id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,200 | gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable._process_params | def _process_params(self, params):
"""
Process params names or values as needed using filters
"""
new_params = OrderedDict()
for param_name, param_value in sorted(params.items()):
param_value = params[param_name]
ParamClass = AirtableParams._get(param_name)
new_params.update(ParamClass(param_value).to_param_dict())
return new_params | python | def _process_params(self, params):
"""
Process params names or values as needed using filters
"""
new_params = OrderedDict()
for param_name, param_value in sorted(params.items()):
param_value = params[param_name]
ParamClass = AirtableParams._get(param_name)
new_params.update(ParamClass(param_value).to_param_dict())
return new_params | [
"def",
"_process_params",
"(",
"self",
",",
"params",
")",
":",
"new_params",
"=",
"OrderedDict",
"(",
")",
"for",
"param_name",
",",
"param_value",
"in",
"sorted",
"(",
"params",
".",
"items",
"(",
")",
")",
":",
"param_value",
"=",
"params",
"[",
"param_name",
"]",
"ParamClass",
"=",
"AirtableParams",
".",
"_get",
"(",
"param_name",
")",
"new_params",
".",
"update",
"(",
"ParamClass",
"(",
"param_value",
")",
".",
"to_param_dict",
"(",
")",
")",
"return",
"new_params"
] | Process params names or values as needed using filters | [
"Process",
"params",
"names",
"or",
"values",
"as",
"needed",
"using",
"filters"
] | 48b2d806178085b52a31817571e5a1fc3dce4045 | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L141-L150 |
4,201 | gtalarico/airtable-python-wrapper | airtable/airtable.py | Airtable._batch_request | def _batch_request(self, func, iterable):
""" Internal Function to limit batch calls to API limit """
responses = []
for item in iterable:
responses.append(func(item))
time.sleep(self.API_LIMIT)
return responses | python | def _batch_request(self, func, iterable):
""" Internal Function to limit batch calls to API limit """
responses = []
for item in iterable:
responses.append(func(item))
time.sleep(self.API_LIMIT)
return responses | [
"def",
"_batch_request",
"(",
"self",
",",
"func",
",",
"iterable",
")",
":",
"responses",
"=",
"[",
"]",
"for",
"item",
"in",
"iterable",
":",
"responses",
".",
"append",
"(",
"func",
"(",
"item",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"API_LIMIT",
")",
"return",
"responses"
] | Internal Function to limit batch calls to API limit | [
"Internal",
"Function",
"to",
"limit",
"batch",
"calls",
"to",
"API",
"limit"
] | 48b2d806178085b52a31817571e5a1fc3dce4045 | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L372-L378 |
4,202 | siznax/wptools | wptools/category.py | WPToolsCategory._add_members | def _add_members(self, catmembers):
"""
Adds category members and subcategories to data
"""
members = [x for x in catmembers if x['ns'] == 0]
subcats = [x for x in catmembers if x['ns'] == 14]
if 'members' in self.data:
self.data['members'].extend(members)
else:
self.data.update({'members': members})
if subcats:
if 'subcategories' in self.data:
self.data['subcategories'].extend(subcats)
else:
self.data.update({'subcategories': subcats}) | python | def _add_members(self, catmembers):
"""
Adds category members and subcategories to data
"""
members = [x for x in catmembers if x['ns'] == 0]
subcats = [x for x in catmembers if x['ns'] == 14]
if 'members' in self.data:
self.data['members'].extend(members)
else:
self.data.update({'members': members})
if subcats:
if 'subcategories' in self.data:
self.data['subcategories'].extend(subcats)
else:
self.data.update({'subcategories': subcats}) | [
"def",
"_add_members",
"(",
"self",
",",
"catmembers",
")",
":",
"members",
"=",
"[",
"x",
"for",
"x",
"in",
"catmembers",
"if",
"x",
"[",
"'ns'",
"]",
"==",
"0",
"]",
"subcats",
"=",
"[",
"x",
"for",
"x",
"in",
"catmembers",
"if",
"x",
"[",
"'ns'",
"]",
"==",
"14",
"]",
"if",
"'members'",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'members'",
"]",
".",
"extend",
"(",
"members",
")",
"else",
":",
"self",
".",
"data",
".",
"update",
"(",
"{",
"'members'",
":",
"members",
"}",
")",
"if",
"subcats",
":",
"if",
"'subcategories'",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'subcategories'",
"]",
".",
"extend",
"(",
"subcats",
")",
"else",
":",
"self",
".",
"data",
".",
"update",
"(",
"{",
"'subcategories'",
":",
"subcats",
"}",
")"
] | Adds category members and subcategories to data | [
"Adds",
"category",
"members",
"and",
"subcategories",
"to",
"data"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L74-L90 |
4,203 | siznax/wptools | wptools/category.py | WPToolsCategory._query | def _query(self, action, qobj):
"""
Form query to enumerate category
"""
title = self.params.get('title')
pageid = self.params.get('pageid')
if action == 'random':
return qobj.random(namespace=14)
elif action == 'category':
return qobj.category(title, pageid, self._continue_params()) | python | def _query(self, action, qobj):
"""
Form query to enumerate category
"""
title = self.params.get('title')
pageid = self.params.get('pageid')
if action == 'random':
return qobj.random(namespace=14)
elif action == 'category':
return qobj.category(title, pageid, self._continue_params()) | [
"def",
"_query",
"(",
"self",
",",
"action",
",",
"qobj",
")",
":",
"title",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
"pageid",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'pageid'",
")",
"if",
"action",
"==",
"'random'",
":",
"return",
"qobj",
".",
"random",
"(",
"namespace",
"=",
"14",
")",
"elif",
"action",
"==",
"'category'",
":",
"return",
"qobj",
".",
"category",
"(",
"title",
",",
"pageid",
",",
"self",
".",
"_continue_params",
"(",
")",
")"
] | Form query to enumerate category | [
"Form",
"query",
"to",
"enumerate",
"category"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L92-L102 |
4,204 | siznax/wptools | wptools/category.py | WPToolsCategory._set_data | def _set_data(self, action):
"""
Set category member data from API response
"""
data = self._load_response(action)
self._handle_continuations(data, 'category')
if action == 'category':
members = data.get('query').get('categorymembers')
if members:
self._add_members(members)
if action == 'random':
rand = data['query']['random'][0]
data = {'pageid': rand.get('id'),
'title': rand.get('title')}
self.data.update(data)
self.params.update(data) | python | def _set_data(self, action):
"""
Set category member data from API response
"""
data = self._load_response(action)
self._handle_continuations(data, 'category')
if action == 'category':
members = data.get('query').get('categorymembers')
if members:
self._add_members(members)
if action == 'random':
rand = data['query']['random'][0]
data = {'pageid': rand.get('id'),
'title': rand.get('title')}
self.data.update(data)
self.params.update(data) | [
"def",
"_set_data",
"(",
"self",
",",
"action",
")",
":",
"data",
"=",
"self",
".",
"_load_response",
"(",
"action",
")",
"self",
".",
"_handle_continuations",
"(",
"data",
",",
"'category'",
")",
"if",
"action",
"==",
"'category'",
":",
"members",
"=",
"data",
".",
"get",
"(",
"'query'",
")",
".",
"get",
"(",
"'categorymembers'",
")",
"if",
"members",
":",
"self",
".",
"_add_members",
"(",
"members",
")",
"if",
"action",
"==",
"'random'",
":",
"rand",
"=",
"data",
"[",
"'query'",
"]",
"[",
"'random'",
"]",
"[",
"0",
"]",
"data",
"=",
"{",
"'pageid'",
":",
"rand",
".",
"get",
"(",
"'id'",
")",
",",
"'title'",
":",
"rand",
".",
"get",
"(",
"'title'",
")",
"}",
"self",
".",
"data",
".",
"update",
"(",
"data",
")",
"self",
".",
"params",
".",
"update",
"(",
"data",
")"
] | Set category member data from API response | [
"Set",
"category",
"member",
"data",
"from",
"API",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/category.py#L104-L122 |
4,205 | siznax/wptools | wptools/site.py | WPToolsSite._sitelist | def _sitelist(self, matrix):
"""
Returns a list of sites from a SiteMatrix, optionally filtered
by 'domain' param
"""
_list = []
for item in matrix:
sites = []
if isinstance(matrix[item], list):
sites = matrix[item]
elif isinstance(matrix[item], dict):
sites = matrix[item]['site']
for site in sites:
if len(site.keys()) > 4: # closed, fishbowl, private
continue
domain = self.params.get('domain')
if domain:
if domain in site['url']:
_list.append(site['url'])
else:
_list.append(site['url'])
return _list | python | def _sitelist(self, matrix):
"""
Returns a list of sites from a SiteMatrix, optionally filtered
by 'domain' param
"""
_list = []
for item in matrix:
sites = []
if isinstance(matrix[item], list):
sites = matrix[item]
elif isinstance(matrix[item], dict):
sites = matrix[item]['site']
for site in sites:
if len(site.keys()) > 4: # closed, fishbowl, private
continue
domain = self.params.get('domain')
if domain:
if domain in site['url']:
_list.append(site['url'])
else:
_list.append(site['url'])
return _list | [
"def",
"_sitelist",
"(",
"self",
",",
"matrix",
")",
":",
"_list",
"=",
"[",
"]",
"for",
"item",
"in",
"matrix",
":",
"sites",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"matrix",
"[",
"item",
"]",
",",
"list",
")",
":",
"sites",
"=",
"matrix",
"[",
"item",
"]",
"elif",
"isinstance",
"(",
"matrix",
"[",
"item",
"]",
",",
"dict",
")",
":",
"sites",
"=",
"matrix",
"[",
"item",
"]",
"[",
"'site'",
"]",
"for",
"site",
"in",
"sites",
":",
"if",
"len",
"(",
"site",
".",
"keys",
"(",
")",
")",
">",
"4",
":",
"# closed, fishbowl, private",
"continue",
"domain",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'domain'",
")",
"if",
"domain",
":",
"if",
"domain",
"in",
"site",
"[",
"'url'",
"]",
":",
"_list",
".",
"append",
"(",
"site",
"[",
"'url'",
"]",
")",
"else",
":",
"_list",
".",
"append",
"(",
"site",
"[",
"'url'",
"]",
")",
"return",
"_list"
] | Returns a list of sites from a SiteMatrix, optionally filtered
by 'domain' param | [
"Returns",
"a",
"list",
"of",
"sites",
"from",
"a",
"SiteMatrix",
"optionally",
"filtered",
"by",
"domain",
"param"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/site.py#L125-L149 |
4,206 | siznax/wptools | wptools/core.py | handle_wikidata_errors | def handle_wikidata_errors(data, query):
"""
Raises LookupError if wikidata error found
"""
entities = data.get('entities')
if not entities:
raise LookupError(query)
elif '-1' in entities:
raise LookupError(query)
else:
item = list(entities.values())[0]
if 'missing' in item:
errmsg = "wikidata item %s has been deleted" % item['id']
raise LookupError(errmsg) | python | def handle_wikidata_errors(data, query):
"""
Raises LookupError if wikidata error found
"""
entities = data.get('entities')
if not entities:
raise LookupError(query)
elif '-1' in entities:
raise LookupError(query)
else:
item = list(entities.values())[0]
if 'missing' in item:
errmsg = "wikidata item %s has been deleted" % item['id']
raise LookupError(errmsg) | [
"def",
"handle_wikidata_errors",
"(",
"data",
",",
"query",
")",
":",
"entities",
"=",
"data",
".",
"get",
"(",
"'entities'",
")",
"if",
"not",
"entities",
":",
"raise",
"LookupError",
"(",
"query",
")",
"elif",
"'-1'",
"in",
"entities",
":",
"raise",
"LookupError",
"(",
"query",
")",
"else",
":",
"item",
"=",
"list",
"(",
"entities",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"if",
"'missing'",
"in",
"item",
":",
"errmsg",
"=",
"\"wikidata item %s has been deleted\"",
"%",
"item",
"[",
"'id'",
"]",
"raise",
"LookupError",
"(",
"errmsg",
")"
] | Raises LookupError if wikidata error found | [
"Raises",
"LookupError",
"if",
"wikidata",
"error",
"found"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L294-L308 |
4,207 | siznax/wptools | wptools/core.py | prettyprint | def prettyprint(datastr):
"""
Print page data strings to stderr
"""
maxwidth = WPToolsQuery.MAXWIDTH
rpad = WPToolsQuery.RPAD
extent = maxwidth - (rpad + 2)
for line in datastr:
if len(line) >= maxwidth:
line = line[:extent] + '...'
utils.stderr(line) | python | def prettyprint(datastr):
"""
Print page data strings to stderr
"""
maxwidth = WPToolsQuery.MAXWIDTH
rpad = WPToolsQuery.RPAD
extent = maxwidth - (rpad + 2)
for line in datastr:
if len(line) >= maxwidth:
line = line[:extent] + '...'
utils.stderr(line) | [
"def",
"prettyprint",
"(",
"datastr",
")",
":",
"maxwidth",
"=",
"WPToolsQuery",
".",
"MAXWIDTH",
"rpad",
"=",
"WPToolsQuery",
".",
"RPAD",
"extent",
"=",
"maxwidth",
"-",
"(",
"rpad",
"+",
"2",
")",
"for",
"line",
"in",
"datastr",
":",
"if",
"len",
"(",
"line",
")",
">=",
"maxwidth",
":",
"line",
"=",
"line",
"[",
":",
"extent",
"]",
"+",
"'...'",
"utils",
".",
"stderr",
"(",
"line",
")"
] | Print page data strings to stderr | [
"Print",
"page",
"data",
"strings",
"to",
"stderr"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L311-L322 |
4,208 | siznax/wptools | wptools/core.py | WPTools._continue_params | def _continue_params(self):
"""
Returns query string fragment continue parameters
"""
if not self.data.get('continue'):
return
params = []
for item in self.data['continue']:
params.append("&%s=%s" % (item, self.data['continue'][item]))
return ''.join(params) | python | def _continue_params(self):
"""
Returns query string fragment continue parameters
"""
if not self.data.get('continue'):
return
params = []
for item in self.data['continue']:
params.append("&%s=%s" % (item, self.data['continue'][item]))
return ''.join(params) | [
"def",
"_continue_params",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"data",
".",
"get",
"(",
"'continue'",
")",
":",
"return",
"params",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"data",
"[",
"'continue'",
"]",
":",
"params",
".",
"append",
"(",
"\"&%s=%s\"",
"%",
"(",
"item",
",",
"self",
".",
"data",
"[",
"'continue'",
"]",
"[",
"item",
"]",
")",
")",
"return",
"''",
".",
"join",
"(",
"params",
")"
] | Returns query string fragment continue parameters | [
"Returns",
"query",
"string",
"fragment",
"continue",
"parameters"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L107-L118 |
4,209 | siznax/wptools | wptools/core.py | WPTools._handle_continuations | def _handle_continuations(self, response, cache_key):
"""
Select continue params and clear cache or last continue params
"""
rcontinue = response.get('continue')
listen = ['blcontinue', 'cmcontinue', 'plcontinue']
cparams = {}
if rcontinue:
for flag in listen:
if rcontinue.get(flag):
cparams[flag] = rcontinue.get(flag)
if cparams:
self.data['continue'] = cparams
del self.cache[cache_key]
else: # no more continuations
if 'continue' in self.data:
del self.data['continue'] | python | def _handle_continuations(self, response, cache_key):
"""
Select continue params and clear cache or last continue params
"""
rcontinue = response.get('continue')
listen = ['blcontinue', 'cmcontinue', 'plcontinue']
cparams = {}
if rcontinue:
for flag in listen:
if rcontinue.get(flag):
cparams[flag] = rcontinue.get(flag)
if cparams:
self.data['continue'] = cparams
del self.cache[cache_key]
else: # no more continuations
if 'continue' in self.data:
del self.data['continue'] | [
"def",
"_handle_continuations",
"(",
"self",
",",
"response",
",",
"cache_key",
")",
":",
"rcontinue",
"=",
"response",
".",
"get",
"(",
"'continue'",
")",
"listen",
"=",
"[",
"'blcontinue'",
",",
"'cmcontinue'",
",",
"'plcontinue'",
"]",
"cparams",
"=",
"{",
"}",
"if",
"rcontinue",
":",
"for",
"flag",
"in",
"listen",
":",
"if",
"rcontinue",
".",
"get",
"(",
"flag",
")",
":",
"cparams",
"[",
"flag",
"]",
"=",
"rcontinue",
".",
"get",
"(",
"flag",
")",
"if",
"cparams",
":",
"self",
".",
"data",
"[",
"'continue'",
"]",
"=",
"cparams",
"del",
"self",
".",
"cache",
"[",
"cache_key",
"]",
"else",
":",
"# no more continuations",
"if",
"'continue'",
"in",
"self",
".",
"data",
":",
"del",
"self",
".",
"data",
"[",
"'continue'",
"]"
] | Select continue params and clear cache or last continue params | [
"Select",
"continue",
"params",
"and",
"clear",
"cache",
"or",
"last",
"continue",
"params"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L120-L138 |
4,210 | siznax/wptools | wptools/core.py | WPTools._get | def _get(self, action, show, proxy, timeout):
"""
make HTTP request and cache response
"""
silent = self.flags['silent']
if action in self.cache:
if action != 'imageinfo' and action != 'labels':
utils.stderr("+ %s results in cache" % action, silent)
return
else:
self.cache[action] = {}
if self.flags.get('skip') and action in self.flags['skip']:
if not self.flags['silent']:
utils.stderr("+ skipping %s" % action)
return
if 'requests' not in self.data:
self.data['requests'] = []
if len(self.data['requests']) >= self.REQUEST_LIMIT:
raise StopIteration("Hit REQUEST_LIMIT = %d" % self.REQUEST_LIMIT)
if self.data['requests'] and self.REQUEST_DELAY:
utils.stderr("REQUEST_DELAY = %d seconds" % self.REQUEST_DELAY)
sleep(self.REQUEST_DELAY)
# make the request
qobj = WPToolsQuery(lang=self.params['lang'],
variant=self.params.get('variant'),
wiki=self.params.get('wiki'),
endpoint=self.params.get('endpoint'))
qstr = self._query(action, qobj)
req = self._request(proxy, timeout)
response = req.get(qstr, qobj.status)
self.cache[action]['query'] = qstr
self.cache[action]['response'] = response
self.cache[action]['info'] = req.info
self.data['requests'].append(action)
self._set_data(action)
if show and not self.flags.get('silent'):
self.show() | python | def _get(self, action, show, proxy, timeout):
"""
make HTTP request and cache response
"""
silent = self.flags['silent']
if action in self.cache:
if action != 'imageinfo' and action != 'labels':
utils.stderr("+ %s results in cache" % action, silent)
return
else:
self.cache[action] = {}
if self.flags.get('skip') and action in self.flags['skip']:
if not self.flags['silent']:
utils.stderr("+ skipping %s" % action)
return
if 'requests' not in self.data:
self.data['requests'] = []
if len(self.data['requests']) >= self.REQUEST_LIMIT:
raise StopIteration("Hit REQUEST_LIMIT = %d" % self.REQUEST_LIMIT)
if self.data['requests'] and self.REQUEST_DELAY:
utils.stderr("REQUEST_DELAY = %d seconds" % self.REQUEST_DELAY)
sleep(self.REQUEST_DELAY)
# make the request
qobj = WPToolsQuery(lang=self.params['lang'],
variant=self.params.get('variant'),
wiki=self.params.get('wiki'),
endpoint=self.params.get('endpoint'))
qstr = self._query(action, qobj)
req = self._request(proxy, timeout)
response = req.get(qstr, qobj.status)
self.cache[action]['query'] = qstr
self.cache[action]['response'] = response
self.cache[action]['info'] = req.info
self.data['requests'].append(action)
self._set_data(action)
if show and not self.flags.get('silent'):
self.show() | [
"def",
"_get",
"(",
"self",
",",
"action",
",",
"show",
",",
"proxy",
",",
"timeout",
")",
":",
"silent",
"=",
"self",
".",
"flags",
"[",
"'silent'",
"]",
"if",
"action",
"in",
"self",
".",
"cache",
":",
"if",
"action",
"!=",
"'imageinfo'",
"and",
"action",
"!=",
"'labels'",
":",
"utils",
".",
"stderr",
"(",
"\"+ %s results in cache\"",
"%",
"action",
",",
"silent",
")",
"return",
"else",
":",
"self",
".",
"cache",
"[",
"action",
"]",
"=",
"{",
"}",
"if",
"self",
".",
"flags",
".",
"get",
"(",
"'skip'",
")",
"and",
"action",
"in",
"self",
".",
"flags",
"[",
"'skip'",
"]",
":",
"if",
"not",
"self",
".",
"flags",
"[",
"'silent'",
"]",
":",
"utils",
".",
"stderr",
"(",
"\"+ skipping %s\"",
"%",
"action",
")",
"return",
"if",
"'requests'",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'requests'",
"]",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'requests'",
"]",
")",
">=",
"self",
".",
"REQUEST_LIMIT",
":",
"raise",
"StopIteration",
"(",
"\"Hit REQUEST_LIMIT = %d\"",
"%",
"self",
".",
"REQUEST_LIMIT",
")",
"if",
"self",
".",
"data",
"[",
"'requests'",
"]",
"and",
"self",
".",
"REQUEST_DELAY",
":",
"utils",
".",
"stderr",
"(",
"\"REQUEST_DELAY = %d seconds\"",
"%",
"self",
".",
"REQUEST_DELAY",
")",
"sleep",
"(",
"self",
".",
"REQUEST_DELAY",
")",
"# make the request",
"qobj",
"=",
"WPToolsQuery",
"(",
"lang",
"=",
"self",
".",
"params",
"[",
"'lang'",
"]",
",",
"variant",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'variant'",
")",
",",
"wiki",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'wiki'",
")",
",",
"endpoint",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'endpoint'",
")",
")",
"qstr",
"=",
"self",
".",
"_query",
"(",
"action",
",",
"qobj",
")",
"req",
"=",
"self",
".",
"_request",
"(",
"proxy",
",",
"timeout",
")",
"response",
"=",
"req",
".",
"get",
"(",
"qstr",
",",
"qobj",
".",
"status",
")",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'query'",
"]",
"=",
"qstr",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'response'",
"]",
"=",
"response",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'info'",
"]",
"=",
"req",
".",
"info",
"self",
".",
"data",
"[",
"'requests'",
"]",
".",
"append",
"(",
"action",
")",
"self",
".",
"_set_data",
"(",
"action",
")",
"if",
"show",
"and",
"not",
"self",
".",
"flags",
".",
"get",
"(",
"'silent'",
")",
":",
"self",
".",
"show",
"(",
")"
] | make HTTP request and cache response | [
"make",
"HTTP",
"request",
"and",
"cache",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L140-L186 |
4,211 | siznax/wptools | wptools/core.py | WPTools._load_response | def _load_response(self, action):
"""
returns API reponse from cache or raises ValueError
"""
_query = self.cache[action]['query'].replace('&format=json', '')
response = self.cache[action]['response']
if not response:
raise ValueError("Empty response: %s" % self.params)
try:
data = utils.json_loads(response)
except ValueError:
raise ValueError(_query)
if data.get('warnings'):
if 'WARNINGS' in self.data:
self.data['WARNINGS'].update(data['warnings'])
else:
self.data['WARNINGS'] = data['warnings']
if data.get('error'):
utils.stderr("API error: %s" % data.get('error'))
raise LookupError(_query)
if 'query' in action and data.get('query'):
if data['query'].get('pages'):
if data['query']['pages'][0].get('missing'):
raise LookupError(_query)
if action == 'parse' and not data.get('parse'):
raise LookupError(_query)
if action == 'wikidata':
handle_wikidata_errors(data, _query)
return data | python | def _load_response(self, action):
"""
returns API reponse from cache or raises ValueError
"""
_query = self.cache[action]['query'].replace('&format=json', '')
response = self.cache[action]['response']
if not response:
raise ValueError("Empty response: %s" % self.params)
try:
data = utils.json_loads(response)
except ValueError:
raise ValueError(_query)
if data.get('warnings'):
if 'WARNINGS' in self.data:
self.data['WARNINGS'].update(data['warnings'])
else:
self.data['WARNINGS'] = data['warnings']
if data.get('error'):
utils.stderr("API error: %s" % data.get('error'))
raise LookupError(_query)
if 'query' in action and data.get('query'):
if data['query'].get('pages'):
if data['query']['pages'][0].get('missing'):
raise LookupError(_query)
if action == 'parse' and not data.get('parse'):
raise LookupError(_query)
if action == 'wikidata':
handle_wikidata_errors(data, _query)
return data | [
"def",
"_load_response",
"(",
"self",
",",
"action",
")",
":",
"_query",
"=",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'query'",
"]",
".",
"replace",
"(",
"'&format=json'",
",",
"''",
")",
"response",
"=",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'response'",
"]",
"if",
"not",
"response",
":",
"raise",
"ValueError",
"(",
"\"Empty response: %s\"",
"%",
"self",
".",
"params",
")",
"try",
":",
"data",
"=",
"utils",
".",
"json_loads",
"(",
"response",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"_query",
")",
"if",
"data",
".",
"get",
"(",
"'warnings'",
")",
":",
"if",
"'WARNINGS'",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'WARNINGS'",
"]",
".",
"update",
"(",
"data",
"[",
"'warnings'",
"]",
")",
"else",
":",
"self",
".",
"data",
"[",
"'WARNINGS'",
"]",
"=",
"data",
"[",
"'warnings'",
"]",
"if",
"data",
".",
"get",
"(",
"'error'",
")",
":",
"utils",
".",
"stderr",
"(",
"\"API error: %s\"",
"%",
"data",
".",
"get",
"(",
"'error'",
")",
")",
"raise",
"LookupError",
"(",
"_query",
")",
"if",
"'query'",
"in",
"action",
"and",
"data",
".",
"get",
"(",
"'query'",
")",
":",
"if",
"data",
"[",
"'query'",
"]",
".",
"get",
"(",
"'pages'",
")",
":",
"if",
"data",
"[",
"'query'",
"]",
"[",
"'pages'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'missing'",
")",
":",
"raise",
"LookupError",
"(",
"_query",
")",
"if",
"action",
"==",
"'parse'",
"and",
"not",
"data",
".",
"get",
"(",
"'parse'",
")",
":",
"raise",
"LookupError",
"(",
"_query",
")",
"if",
"action",
"==",
"'wikidata'",
":",
"handle_wikidata_errors",
"(",
"data",
",",
"_query",
")",
"return",
"data"
] | returns API reponse from cache or raises ValueError | [
"returns",
"API",
"reponse",
"from",
"cache",
"or",
"raises",
"ValueError"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L188-L224 |
4,212 | siznax/wptools | wptools/core.py | WPTools._request | def _request(self, proxy, timeout):
"""
Returns WPToolsRequest object
"""
return request.WPToolsRequest(self.flags['silent'],
self.flags['verbose'],
proxy, timeout) | python | def _request(self, proxy, timeout):
"""
Returns WPToolsRequest object
"""
return request.WPToolsRequest(self.flags['silent'],
self.flags['verbose'],
proxy, timeout) | [
"def",
"_request",
"(",
"self",
",",
"proxy",
",",
"timeout",
")",
":",
"return",
"request",
".",
"WPToolsRequest",
"(",
"self",
".",
"flags",
"[",
"'silent'",
"]",
",",
"self",
".",
"flags",
"[",
"'verbose'",
"]",
",",
"proxy",
",",
"timeout",
")"
] | Returns WPToolsRequest object | [
"Returns",
"WPToolsRequest",
"object"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L232-L238 |
4,213 | siznax/wptools | wptools/core.py | WPTools.info | def info(self, action=None):
"""
returns cached request info for given action,
or list of cached actions
"""
if action in self.cache:
return self.cache[action]['info']
return self.cache.keys() or None | python | def info(self, action=None):
"""
returns cached request info for given action,
or list of cached actions
"""
if action in self.cache:
return self.cache[action]['info']
return self.cache.keys() or None | [
"def",
"info",
"(",
"self",
",",
"action",
"=",
"None",
")",
":",
"if",
"action",
"in",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
"[",
"action",
"]",
"[",
"'info'",
"]",
"return",
"self",
".",
"cache",
".",
"keys",
"(",
")",
"or",
"None"
] | returns cached request info for given action,
or list of cached actions | [
"returns",
"cached",
"request",
"info",
"for",
"given",
"action",
"or",
"list",
"of",
"cached",
"actions"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L246-L253 |
4,214 | siznax/wptools | wptools/core.py | WPTools.show | def show(self):
"""
Pretty-print instance data
"""
if not self.data:
return
if self.data.get('continue'):
return
ptitle = self.params.get('title')
dtitle = self.data.get('title')
pageid = self.params.get('pageid')
seed = dtitle or ptitle or pageid
if utils.is_text(seed):
seed = seed.replace('_', ' ')
prettyprint(self._build_showstr(seed)) | python | def show(self):
"""
Pretty-print instance data
"""
if not self.data:
return
if self.data.get('continue'):
return
ptitle = self.params.get('title')
dtitle = self.data.get('title')
pageid = self.params.get('pageid')
seed = dtitle or ptitle or pageid
if utils.is_text(seed):
seed = seed.replace('_', ' ')
prettyprint(self._build_showstr(seed)) | [
"def",
"show",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"return",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'continue'",
")",
":",
"return",
"ptitle",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
"dtitle",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"pageid",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'pageid'",
")",
"seed",
"=",
"dtitle",
"or",
"ptitle",
"or",
"pageid",
"if",
"utils",
".",
"is_text",
"(",
"seed",
")",
":",
"seed",
"=",
"seed",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
"prettyprint",
"(",
"self",
".",
"_build_showstr",
"(",
"seed",
")",
")"
] | Pretty-print instance data | [
"Pretty",
"-",
"print",
"instance",
"data"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L273-L291 |
4,215 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._get_entity_prop | def _get_entity_prop(self, entity, prop):
"""
returns Wikidata entity property value
"""
variant = self.params.get('variant')
lang = self.params.get('lang')
if entity.get(prop):
ent = entity[prop]
try:
return ent[variant or lang].get('value')
except AttributeError:
return ent.get('value') | python | def _get_entity_prop(self, entity, prop):
"""
returns Wikidata entity property value
"""
variant = self.params.get('variant')
lang = self.params.get('lang')
if entity.get(prop):
ent = entity[prop]
try:
return ent[variant or lang].get('value')
except AttributeError:
return ent.get('value') | [
"def",
"_get_entity_prop",
"(",
"self",
",",
"entity",
",",
"prop",
")",
":",
"variant",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'variant'",
")",
"lang",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'lang'",
")",
"if",
"entity",
".",
"get",
"(",
"prop",
")",
":",
"ent",
"=",
"entity",
"[",
"prop",
"]",
"try",
":",
"return",
"ent",
"[",
"variant",
"or",
"lang",
"]",
".",
"get",
"(",
"'value'",
")",
"except",
"AttributeError",
":",
"return",
"ent",
".",
"get",
"(",
"'value'",
")"
] | returns Wikidata entity property value | [
"returns",
"Wikidata",
"entity",
"property",
"value"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L49-L61 |
4,216 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._marshal_claims | def _marshal_claims(self, query_claims):
"""
set Wikidata entities from query claims
"""
claims = reduce_claims(query_claims)
# self.data['claimq'] = query_claims
self.data['claims'] = claims
entities = set()
for eid in claims:
if self.user_labels:
if eid in self.user_labels or eid == 'P31':
entities.add(eid) # P (property)
else:
continue # get only wanted entities
else:
entities.add(eid) # P (property)
for val in claims[eid]:
if utils.is_text(val) and re.match(r'^Q\d+$', val):
entities.add(val) # Q (item)
self.data['entities'] = list(entities) | python | def _marshal_claims(self, query_claims):
"""
set Wikidata entities from query claims
"""
claims = reduce_claims(query_claims)
# self.data['claimq'] = query_claims
self.data['claims'] = claims
entities = set()
for eid in claims:
if self.user_labels:
if eid in self.user_labels or eid == 'P31':
entities.add(eid) # P (property)
else:
continue # get only wanted entities
else:
entities.add(eid) # P (property)
for val in claims[eid]:
if utils.is_text(val) and re.match(r'^Q\d+$', val):
entities.add(val) # Q (item)
self.data['entities'] = list(entities) | [
"def",
"_marshal_claims",
"(",
"self",
",",
"query_claims",
")",
":",
"claims",
"=",
"reduce_claims",
"(",
"query_claims",
")",
"# self.data['claimq'] = query_claims",
"self",
".",
"data",
"[",
"'claims'",
"]",
"=",
"claims",
"entities",
"=",
"set",
"(",
")",
"for",
"eid",
"in",
"claims",
":",
"if",
"self",
".",
"user_labels",
":",
"if",
"eid",
"in",
"self",
".",
"user_labels",
"or",
"eid",
"==",
"'P31'",
":",
"entities",
".",
"add",
"(",
"eid",
")",
"# P (property)",
"else",
":",
"continue",
"# get only wanted entities",
"else",
":",
"entities",
".",
"add",
"(",
"eid",
")",
"# P (property)",
"for",
"val",
"in",
"claims",
"[",
"eid",
"]",
":",
"if",
"utils",
".",
"is_text",
"(",
"val",
")",
"and",
"re",
".",
"match",
"(",
"r'^Q\\d+$'",
",",
"val",
")",
":",
"entities",
".",
"add",
"(",
"val",
")",
"# Q (item)",
"self",
".",
"data",
"[",
"'entities'",
"]",
"=",
"list",
"(",
"entities",
")"
] | set Wikidata entities from query claims | [
"set",
"Wikidata",
"entities",
"from",
"query",
"claims"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L63-L85 |
4,217 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._pop_entities | def _pop_entities(self, limit=50):
"""
returns up to limit entities and pops them off the list
"""
pop = self.data['entities'][:limit]
del self.data['entities'][:limit]
return pop | python | def _pop_entities(self, limit=50):
"""
returns up to limit entities and pops them off the list
"""
pop = self.data['entities'][:limit]
del self.data['entities'][:limit]
return pop | [
"def",
"_pop_entities",
"(",
"self",
",",
"limit",
"=",
"50",
")",
":",
"pop",
"=",
"self",
".",
"data",
"[",
"'entities'",
"]",
"[",
":",
"limit",
"]",
"del",
"self",
".",
"data",
"[",
"'entities'",
"]",
"[",
":",
"limit",
"]",
"return",
"pop"
] | returns up to limit entities and pops them off the list | [
"returns",
"up",
"to",
"limit",
"entities",
"and",
"pops",
"them",
"off",
"the",
"list"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L87-L93 |
4,218 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._query | def _query(self, action, qobj):
"""
returns wikidata query string
"""
if action == 'labels':
return qobj.labels(self._pop_entities())
elif action == 'wikidata':
return qobj.wikidata(self.params.get('title'),
self.params.get('wikibase')) | python | def _query(self, action, qobj):
"""
returns wikidata query string
"""
if action == 'labels':
return qobj.labels(self._pop_entities())
elif action == 'wikidata':
return qobj.wikidata(self.params.get('title'),
self.params.get('wikibase')) | [
"def",
"_query",
"(",
"self",
",",
"action",
",",
"qobj",
")",
":",
"if",
"action",
"==",
"'labels'",
":",
"return",
"qobj",
".",
"labels",
"(",
"self",
".",
"_pop_entities",
"(",
")",
")",
"elif",
"action",
"==",
"'wikidata'",
":",
"return",
"qobj",
".",
"wikidata",
"(",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
",",
"self",
".",
"params",
".",
"get",
"(",
"'wikibase'",
")",
")"
] | returns wikidata query string | [
"returns",
"wikidata",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L103-L111 |
4,219 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._set_title | def _set_title(self, item):
"""
attempt to set title from wikidata
"""
title = None
lang = self.params['lang']
label = self.data['label']
if item.get('sitelinks'):
for link in item['sitelinks']:
if link == "%swiki" % lang:
title = item['sitelinks'][link]['title']
self.data['title'] = title.replace(' ', '_')
if not self.data.get('title') and label:
self.data['title'] = label.replace(' ', '_')
if self.data.get('title') and not self.params.get('title'):
self.params['title'] = self.data['title'] | python | def _set_title(self, item):
"""
attempt to set title from wikidata
"""
title = None
lang = self.params['lang']
label = self.data['label']
if item.get('sitelinks'):
for link in item['sitelinks']:
if link == "%swiki" % lang:
title = item['sitelinks'][link]['title']
self.data['title'] = title.replace(' ', '_')
if not self.data.get('title') and label:
self.data['title'] = label.replace(' ', '_')
if self.data.get('title') and not self.params.get('title'):
self.params['title'] = self.data['title'] | [
"def",
"_set_title",
"(",
"self",
",",
"item",
")",
":",
"title",
"=",
"None",
"lang",
"=",
"self",
".",
"params",
"[",
"'lang'",
"]",
"label",
"=",
"self",
".",
"data",
"[",
"'label'",
"]",
"if",
"item",
".",
"get",
"(",
"'sitelinks'",
")",
":",
"for",
"link",
"in",
"item",
"[",
"'sitelinks'",
"]",
":",
"if",
"link",
"==",
"\"%swiki\"",
"%",
"lang",
":",
"title",
"=",
"item",
"[",
"'sitelinks'",
"]",
"[",
"link",
"]",
"[",
"'title'",
"]",
"self",
".",
"data",
"[",
"'title'",
"]",
"=",
"title",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"if",
"not",
"self",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"and",
"label",
":",
"self",
".",
"data",
"[",
"'title'",
"]",
"=",
"label",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"and",
"not",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
":",
"self",
".",
"params",
"[",
"'title'",
"]",
"=",
"self",
".",
"data",
"[",
"'title'",
"]"
] | attempt to set title from wikidata | [
"attempt",
"to",
"set",
"title",
"from",
"wikidata"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L135-L153 |
4,220 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._update_images | def _update_images(self):
"""
add images from Wikidata
"""
wd_images = self.data['claims'].get('P18') # image
if wd_images:
if not isinstance(wd_images, list):
wd_images = [wd_images]
if 'image' not in self.data:
self.data['image'] = []
for img_file in wd_images:
self.data['image'].append({'file': img_file,
'kind': 'wikidata-image'}) | python | def _update_images(self):
"""
add images from Wikidata
"""
wd_images = self.data['claims'].get('P18') # image
if wd_images:
if not isinstance(wd_images, list):
wd_images = [wd_images]
if 'image' not in self.data:
self.data['image'] = []
for img_file in wd_images:
self.data['image'].append({'file': img_file,
'kind': 'wikidata-image'}) | [
"def",
"_update_images",
"(",
"self",
")",
":",
"wd_images",
"=",
"self",
".",
"data",
"[",
"'claims'",
"]",
".",
"get",
"(",
"'P18'",
")",
"# image",
"if",
"wd_images",
":",
"if",
"not",
"isinstance",
"(",
"wd_images",
",",
"list",
")",
":",
"wd_images",
"=",
"[",
"wd_images",
"]",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
"=",
"[",
"]",
"for",
"img_file",
"in",
"wd_images",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"{",
"'file'",
":",
"img_file",
",",
"'kind'",
":",
"'wikidata-image'",
"}",
")"
] | add images from Wikidata | [
"add",
"images",
"from",
"Wikidata"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L190-L205 |
4,221 | siznax/wptools | wptools/wikidata.py | WPToolsWikidata._update_wikidata | def _update_wikidata(self):
"""
set wikidata from claims and labels
"""
claims = self.data['claims']
for ent in claims:
plabel = self.data['labels'].get(ent) # P (property) label
if plabel:
plabel = "%s (%s)" % (plabel, ent)
claim = []
for item in claims[ent]:
ilabel = item
if utils.is_text(item) and re.match(r'^Q\d+$', item):
ilabel = self.data['labels'].get(item) # Q (item) label
if ilabel:
ilabel = "%s (%s)" % (ilabel, item)
if len(claims[ent]) == 1:
claim = ilabel
else:
claim.append(ilabel)
if plabel and ilabel:
self.data['wikidata'][plabel] = claim | python | def _update_wikidata(self):
"""
set wikidata from claims and labels
"""
claims = self.data['claims']
for ent in claims:
plabel = self.data['labels'].get(ent) # P (property) label
if plabel:
plabel = "%s (%s)" % (plabel, ent)
claim = []
for item in claims[ent]:
ilabel = item
if utils.is_text(item) and re.match(r'^Q\d+$', item):
ilabel = self.data['labels'].get(item) # Q (item) label
if ilabel:
ilabel = "%s (%s)" % (ilabel, item)
if len(claims[ent]) == 1:
claim = ilabel
else:
claim.append(ilabel)
if plabel and ilabel:
self.data['wikidata'][plabel] = claim | [
"def",
"_update_wikidata",
"(",
"self",
")",
":",
"claims",
"=",
"self",
".",
"data",
"[",
"'claims'",
"]",
"for",
"ent",
"in",
"claims",
":",
"plabel",
"=",
"self",
".",
"data",
"[",
"'labels'",
"]",
".",
"get",
"(",
"ent",
")",
"# P (property) label",
"if",
"plabel",
":",
"plabel",
"=",
"\"%s (%s)\"",
"%",
"(",
"plabel",
",",
"ent",
")",
"claim",
"=",
"[",
"]",
"for",
"item",
"in",
"claims",
"[",
"ent",
"]",
":",
"ilabel",
"=",
"item",
"if",
"utils",
".",
"is_text",
"(",
"item",
")",
"and",
"re",
".",
"match",
"(",
"r'^Q\\d+$'",
",",
"item",
")",
":",
"ilabel",
"=",
"self",
".",
"data",
"[",
"'labels'",
"]",
".",
"get",
"(",
"item",
")",
"# Q (item) label",
"if",
"ilabel",
":",
"ilabel",
"=",
"\"%s (%s)\"",
"%",
"(",
"ilabel",
",",
"item",
")",
"if",
"len",
"(",
"claims",
"[",
"ent",
"]",
")",
"==",
"1",
":",
"claim",
"=",
"ilabel",
"else",
":",
"claim",
".",
"append",
"(",
"ilabel",
")",
"if",
"plabel",
"and",
"ilabel",
":",
"self",
".",
"data",
"[",
"'wikidata'",
"]",
"[",
"plabel",
"]",
"=",
"claim"
] | set wikidata from claims and labels | [
"set",
"wikidata",
"from",
"claims",
"and",
"labels"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L223-L249 |
4,222 | siznax/wptools | scripts/wptool.py | _html_image | def _html_image(page):
"""
returns HTML img tag
"""
source = _image(page)
if not source:
return
alt = page.data.get('label') or page.data.get('title')
img = "<img src=\"%s\"" % source
img += " alt=\"%s\" title=\"%s\" " % (alt, alt)
img += "align=\"right\" width=\"240\">"
return img | python | def _html_image(page):
"""
returns HTML img tag
"""
source = _image(page)
if not source:
return
alt = page.data.get('label') or page.data.get('title')
img = "<img src=\"%s\"" % source
img += " alt=\"%s\" title=\"%s\" " % (alt, alt)
img += "align=\"right\" width=\"240\">"
return img | [
"def",
"_html_image",
"(",
"page",
")",
":",
"source",
"=",
"_image",
"(",
"page",
")",
"if",
"not",
"source",
":",
"return",
"alt",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'label'",
")",
"or",
"page",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"img",
"=",
"\"<img src=\\\"%s\\\"\"",
"%",
"source",
"img",
"+=",
"\" alt=\\\"%s\\\" title=\\\"%s\\\" \"",
"%",
"(",
"alt",
",",
"alt",
")",
"img",
"+=",
"\"align=\\\"right\\\" width=\\\"240\\\">\"",
"return",
"img"
] | returns HTML img tag | [
"returns",
"HTML",
"img",
"tag"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L19-L30 |
4,223 | siznax/wptools | scripts/wptool.py | _html_title | def _html_title(page):
"""
returns Wiki-linked HTML title
"""
link = "<a href=\"%s\">%s</a>" % (page.data.get('url'),
page.data.get('title'))
desc = page.data.get('description')
if desc:
link += "—<i>%s</i>" % desc
else:
link += "—<i>description</i>"
if link:
return "<p>%s</p>" % link | python | def _html_title(page):
"""
returns Wiki-linked HTML title
"""
link = "<a href=\"%s\">%s</a>" % (page.data.get('url'),
page.data.get('title'))
desc = page.data.get('description')
if desc:
link += "—<i>%s</i>" % desc
else:
link += "—<i>description</i>"
if link:
return "<p>%s</p>" % link | [
"def",
"_html_title",
"(",
"page",
")",
":",
"link",
"=",
"\"<a href=\\\"%s\\\">%s</a>\"",
"%",
"(",
"page",
".",
"data",
".",
"get",
"(",
"'url'",
")",
",",
"page",
".",
"data",
".",
"get",
"(",
"'title'",
")",
")",
"desc",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'description'",
")",
"if",
"desc",
":",
"link",
"+=",
"\"—<i>%s</i>\"",
"%",
"desc",
"else",
":",
"link",
"+=",
"\"—<i>description</i>\"",
"if",
"link",
":",
"return",
"\"<p>%s</p>\"",
"%",
"link"
] | returns Wiki-linked HTML title | [
"returns",
"Wiki",
"-",
"linked",
"HTML",
"title"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L33-L45 |
4,224 | siznax/wptools | scripts/wptool.py | _page_html | def _page_html(page):
"""
returns assembled HTML output
"""
out = []
out.append(_html_title(page))
out.append(_html_image(page))
out.append(page.data.get('extract'))
return "\n".join([x for x in out if x]) | python | def _page_html(page):
"""
returns assembled HTML output
"""
out = []
out.append(_html_title(page))
out.append(_html_image(page))
out.append(page.data.get('extract'))
return "\n".join([x for x in out if x]) | [
"def",
"_page_html",
"(",
"page",
")",
":",
"out",
"=",
"[",
"]",
"out",
".",
"append",
"(",
"_html_title",
"(",
"page",
")",
")",
"out",
".",
"append",
"(",
"_html_image",
"(",
"page",
")",
")",
"out",
".",
"append",
"(",
"page",
".",
"data",
".",
"get",
"(",
"'extract'",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"x",
"for",
"x",
"in",
"out",
"if",
"x",
"]",
")"
] | returns assembled HTML output | [
"returns",
"assembled",
"HTML",
"output"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L57-L65 |
4,225 | siznax/wptools | scripts/wptool.py | _page_text | def _page_text(page, nowrap=False):
"""
returns assembled text output
"""
title = page.data['title']
title = "%s\n%s" % (title, "=" * len(title))
desc = page.data.get('description')
if desc:
desc = "_%s_" % desc
img = _text_image(page)
pars = page.data.get('extext')
if pars:
# pars = pars.replace(' * ', '\n * ')
pars = re.sub(r'[ ]+\*[ ]+', '* ', pars)
if pars and not nowrap:
parlist = []
for par in pars.split("\n\n"):
parlist.append("\n".join(textwrap.wrap(par)))
disambiguation = page.data.get('disambiguation')
if disambiguation:
parlist.append(' * ' + "\n * ".join(page.data.get('links')))
pars = "\n\n".join(parlist)
url = '<%s>' % page.data['url']
txt = []
txt.append(title)
txt.append(desc)
txt.append(url)
txt.append(pars)
txt.append(img)
return "\n\n".join([x for x in txt if x]) | python | def _page_text(page, nowrap=False):
"""
returns assembled text output
"""
title = page.data['title']
title = "%s\n%s" % (title, "=" * len(title))
desc = page.data.get('description')
if desc:
desc = "_%s_" % desc
img = _text_image(page)
pars = page.data.get('extext')
if pars:
# pars = pars.replace(' * ', '\n * ')
pars = re.sub(r'[ ]+\*[ ]+', '* ', pars)
if pars and not nowrap:
parlist = []
for par in pars.split("\n\n"):
parlist.append("\n".join(textwrap.wrap(par)))
disambiguation = page.data.get('disambiguation')
if disambiguation:
parlist.append(' * ' + "\n * ".join(page.data.get('links')))
pars = "\n\n".join(parlist)
url = '<%s>' % page.data['url']
txt = []
txt.append(title)
txt.append(desc)
txt.append(url)
txt.append(pars)
txt.append(img)
return "\n\n".join([x for x in txt if x]) | [
"def",
"_page_text",
"(",
"page",
",",
"nowrap",
"=",
"False",
")",
":",
"title",
"=",
"page",
".",
"data",
"[",
"'title'",
"]",
"title",
"=",
"\"%s\\n%s\"",
"%",
"(",
"title",
",",
"\"=\"",
"*",
"len",
"(",
"title",
")",
")",
"desc",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'description'",
")",
"if",
"desc",
":",
"desc",
"=",
"\"_%s_\"",
"%",
"desc",
"img",
"=",
"_text_image",
"(",
"page",
")",
"pars",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'extext'",
")",
"if",
"pars",
":",
"# pars = pars.replace(' * ', '\\n * ')",
"pars",
"=",
"re",
".",
"sub",
"(",
"r'[ ]+\\*[ ]+'",
",",
"'* '",
",",
"pars",
")",
"if",
"pars",
"and",
"not",
"nowrap",
":",
"parlist",
"=",
"[",
"]",
"for",
"par",
"in",
"pars",
".",
"split",
"(",
"\"\\n\\n\"",
")",
":",
"parlist",
".",
"append",
"(",
"\"\\n\"",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"par",
")",
")",
")",
"disambiguation",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'disambiguation'",
")",
"if",
"disambiguation",
":",
"parlist",
".",
"append",
"(",
"' * '",
"+",
"\"\\n * \"",
".",
"join",
"(",
"page",
".",
"data",
".",
"get",
"(",
"'links'",
")",
")",
")",
"pars",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"parlist",
")",
"url",
"=",
"'<%s>'",
"%",
"page",
".",
"data",
"[",
"'url'",
"]",
"txt",
"=",
"[",
"]",
"txt",
".",
"append",
"(",
"title",
")",
"txt",
".",
"append",
"(",
"desc",
")",
"txt",
".",
"append",
"(",
"url",
")",
"txt",
".",
"append",
"(",
"pars",
")",
"txt",
".",
"append",
"(",
"img",
")",
"return",
"\"\\n\\n\"",
".",
"join",
"(",
"[",
"x",
"for",
"x",
"in",
"txt",
"if",
"x",
"]",
")"
] | returns assembled text output | [
"returns",
"assembled",
"text",
"output"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L68-L107 |
4,226 | siznax/wptools | scripts/wptool.py | _safe_exit | def _safe_exit(start, output):
"""
exit without breaking pipes
"""
try:
sys.stdout.write(output)
sys.stdout.flush()
except TypeError: # python3
sys.stdout.write(str(output, 'utf-8'))
sys.stdout.flush()
except IOError:
pass
seconds = time.time() - start
print("\n\n%5.3f seconds" % (seconds), file=sys.stderr) | python | def _safe_exit(start, output):
"""
exit without breaking pipes
"""
try:
sys.stdout.write(output)
sys.stdout.flush()
except TypeError: # python3
sys.stdout.write(str(output, 'utf-8'))
sys.stdout.flush()
except IOError:
pass
seconds = time.time() - start
print("\n\n%5.3f seconds" % (seconds), file=sys.stderr) | [
"def",
"_safe_exit",
"(",
"start",
",",
"output",
")",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"output",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"except",
"TypeError",
":",
"# python3",
"sys",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"output",
",",
"'utf-8'",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"except",
"IOError",
":",
"pass",
"seconds",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start",
"print",
"(",
"\"\\n\\n%5.3f seconds\"",
"%",
"(",
"seconds",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | exit without breaking pipes | [
"exit",
"without",
"breaking",
"pipes"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L110-L124 |
4,227 | siznax/wptools | scripts/wptool.py | _text_image | def _text_image(page):
"""
returns text image URL
"""
img = None
alt = page.data.get('label') or page.data.get('title')
source = _image(page)
if source:
img = "" % (alt, source)
return img | python | def _text_image(page):
"""
returns text image URL
"""
img = None
alt = page.data.get('label') or page.data.get('title')
source = _image(page)
if source:
img = "" % (alt, source)
return img | [
"def",
"_text_image",
"(",
"page",
")",
":",
"img",
"=",
"None",
"alt",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'label'",
")",
"or",
"page",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"source",
"=",
"_image",
"(",
"page",
")",
"if",
"source",
":",
"img",
"=",
"\"\"",
"%",
"(",
"alt",
",",
"source",
")",
"return",
"img"
] | returns text image URL | [
"returns",
"text",
"image",
"URL"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L127-L136 |
4,228 | siznax/wptools | scripts/wptool.py | get | def get(args):
"""
invoke wptools and assemble selected output
"""
html = args.H
lang = args.l
nowrap = args.n
query = args.q
silent = args.s
title = args.t
verbose = args.v
wiki = args.w
if query:
qobj = WPToolsQuery(lang=lang, wiki=wiki)
if title:
return qobj.query(title)
return qobj.random()
page = wptools.page(title, lang=lang, silent=silent,
verbose=verbose, wiki=wiki)
try:
page.get_query()
except (StandardError, ValueError, LookupError):
return "NOT_FOUND"
if not page.data.get('extext'):
out = page.cache['query']['query']
out = _page_text(page, nowrap)
if html:
out = _page_html(page)
try:
return out.encode('utf-8')
except KeyError:
return out | python | def get(args):
"""
invoke wptools and assemble selected output
"""
html = args.H
lang = args.l
nowrap = args.n
query = args.q
silent = args.s
title = args.t
verbose = args.v
wiki = args.w
if query:
qobj = WPToolsQuery(lang=lang, wiki=wiki)
if title:
return qobj.query(title)
return qobj.random()
page = wptools.page(title, lang=lang, silent=silent,
verbose=verbose, wiki=wiki)
try:
page.get_query()
except (StandardError, ValueError, LookupError):
return "NOT_FOUND"
if not page.data.get('extext'):
out = page.cache['query']['query']
out = _page_text(page, nowrap)
if html:
out = _page_html(page)
try:
return out.encode('utf-8')
except KeyError:
return out | [
"def",
"get",
"(",
"args",
")",
":",
"html",
"=",
"args",
".",
"H",
"lang",
"=",
"args",
".",
"l",
"nowrap",
"=",
"args",
".",
"n",
"query",
"=",
"args",
".",
"q",
"silent",
"=",
"args",
".",
"s",
"title",
"=",
"args",
".",
"t",
"verbose",
"=",
"args",
".",
"v",
"wiki",
"=",
"args",
".",
"w",
"if",
"query",
":",
"qobj",
"=",
"WPToolsQuery",
"(",
"lang",
"=",
"lang",
",",
"wiki",
"=",
"wiki",
")",
"if",
"title",
":",
"return",
"qobj",
".",
"query",
"(",
"title",
")",
"return",
"qobj",
".",
"random",
"(",
")",
"page",
"=",
"wptools",
".",
"page",
"(",
"title",
",",
"lang",
"=",
"lang",
",",
"silent",
"=",
"silent",
",",
"verbose",
"=",
"verbose",
",",
"wiki",
"=",
"wiki",
")",
"try",
":",
"page",
".",
"get_query",
"(",
")",
"except",
"(",
"StandardError",
",",
"ValueError",
",",
"LookupError",
")",
":",
"return",
"\"NOT_FOUND\"",
"if",
"not",
"page",
".",
"data",
".",
"get",
"(",
"'extext'",
")",
":",
"out",
"=",
"page",
".",
"cache",
"[",
"'query'",
"]",
"[",
"'query'",
"]",
"out",
"=",
"_page_text",
"(",
"page",
",",
"nowrap",
")",
"if",
"html",
":",
"out",
"=",
"_page_html",
"(",
"page",
")",
"try",
":",
"return",
"out",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
"KeyError",
":",
"return",
"out"
] | invoke wptools and assemble selected output | [
"invoke",
"wptools",
"and",
"assemble",
"selected",
"output"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L139-L177 |
4,229 | siznax/wptools | scripts/wptool.py | main | def main(args):
"""
invoke wptools and exit safely
"""
start = time.time()
output = get(args)
_safe_exit(start, output) | python | def main(args):
"""
invoke wptools and exit safely
"""
start = time.time()
output = get(args)
_safe_exit(start, output) | [
"def",
"main",
"(",
"args",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"output",
"=",
"get",
"(",
"args",
")",
"_safe_exit",
"(",
"start",
",",
"output",
")"
] | invoke wptools and exit safely | [
"invoke",
"wptools",
"and",
"exit",
"safely"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L213-L219 |
4,230 | siznax/wptools | wptools/page.py | WPToolsPage.__insert_image_info | def __insert_image_info(self, title, _from, info):
"""
Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikidata,
etc.), because some sources reference the same image file. We
match API imageinfo response data to existing image filenames
by API title or normalized "from" title. So, some imageinfo
data will be applied to more than one image "kind" (source) if
they share the same filename.
"""
for img in self.data['image']:
if 'url' not in img:
if title == img['file']: # matching title/file
img.update(info)
elif _from == img['file']: # matching from/file
img.update(info) | python | def __insert_image_info(self, title, _from, info):
"""
Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikidata,
etc.), because some sources reference the same image file. We
match API imageinfo response data to existing image filenames
by API title or normalized "from" title. So, some imageinfo
data will be applied to more than one image "kind" (source) if
they share the same filename.
"""
for img in self.data['image']:
if 'url' not in img:
if title == img['file']: # matching title/file
img.update(info)
elif _from == img['file']: # matching from/file
img.update(info) | [
"def",
"__insert_image_info",
"(",
"self",
",",
"title",
",",
"_from",
",",
"info",
")",
":",
"for",
"img",
"in",
"self",
".",
"data",
"[",
"'image'",
"]",
":",
"if",
"'url'",
"not",
"in",
"img",
":",
"if",
"title",
"==",
"img",
"[",
"'file'",
"]",
":",
"# matching title/file",
"img",
".",
"update",
"(",
"info",
")",
"elif",
"_from",
"==",
"img",
"[",
"'file'",
"]",
":",
"# matching from/file",
"img",
".",
"update",
"(",
"info",
")"
] | Insert API image INFO into matching image dict
We make one imageinfo request containing only unique image
filenames. We reduce duplication by asking for image data per
file, instead of per "kind" or source (Wikipedia, Wikidata,
etc.), because some sources reference the same image file. We
match API imageinfo response data to existing image filenames
by API title or normalized "from" title. So, some imageinfo
data will be applied to more than one image "kind" (source) if
they share the same filename. | [
"Insert",
"API",
"image",
"INFO",
"into",
"matching",
"image",
"dict"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L84-L102 |
4,231 | siznax/wptools | wptools/page.py | WPToolsPage.__pull_image_info | def __pull_image_info(self, title, imageinfo, normalized):
"""
Pull image INFO from API response and insert
"""
for info in imageinfo:
info.update({'title': title})
# get API normalized "from" filename for matching
_from = None
for norm in normalized:
if title == norm['to']:
_from = norm['from']
# let's put all "metadata" in one member
info['metadata'] = {}
extmetadata = info.get('extmetadata')
if extmetadata:
info['metadata'].update(extmetadata)
del info['extmetadata']
self.__insert_image_info(title, _from, info) | python | def __pull_image_info(self, title, imageinfo, normalized):
"""
Pull image INFO from API response and insert
"""
for info in imageinfo:
info.update({'title': title})
# get API normalized "from" filename for matching
_from = None
for norm in normalized:
if title == norm['to']:
_from = norm['from']
# let's put all "metadata" in one member
info['metadata'] = {}
extmetadata = info.get('extmetadata')
if extmetadata:
info['metadata'].update(extmetadata)
del info['extmetadata']
self.__insert_image_info(title, _from, info) | [
"def",
"__pull_image_info",
"(",
"self",
",",
"title",
",",
"imageinfo",
",",
"normalized",
")",
":",
"for",
"info",
"in",
"imageinfo",
":",
"info",
".",
"update",
"(",
"{",
"'title'",
":",
"title",
"}",
")",
"# get API normalized \"from\" filename for matching",
"_from",
"=",
"None",
"for",
"norm",
"in",
"normalized",
":",
"if",
"title",
"==",
"norm",
"[",
"'to'",
"]",
":",
"_from",
"=",
"norm",
"[",
"'from'",
"]",
"# let's put all \"metadata\" in one member",
"info",
"[",
"'metadata'",
"]",
"=",
"{",
"}",
"extmetadata",
"=",
"info",
".",
"get",
"(",
"'extmetadata'",
")",
"if",
"extmetadata",
":",
"info",
"[",
"'metadata'",
"]",
".",
"update",
"(",
"extmetadata",
")",
"del",
"info",
"[",
"'extmetadata'",
"]",
"self",
".",
"__insert_image_info",
"(",
"title",
",",
"_from",
",",
"info",
")"
] | Pull image INFO from API response and insert | [
"Pull",
"image",
"INFO",
"from",
"API",
"response",
"and",
"insert"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L104-L124 |
4,232 | siznax/wptools | wptools/page.py | WPToolsPage._extend_data | def _extend_data(self, datapoint, new_data):
"""
extend or assign new data to datapoint
"""
if new_data:
try:
self.data[datapoint].extend(new_data)
except KeyError:
self.data[datapoint] = new_data | python | def _extend_data(self, datapoint, new_data):
"""
extend or assign new data to datapoint
"""
if new_data:
try:
self.data[datapoint].extend(new_data)
except KeyError:
self.data[datapoint] = new_data | [
"def",
"_extend_data",
"(",
"self",
",",
"datapoint",
",",
"new_data",
")",
":",
"if",
"new_data",
":",
"try",
":",
"self",
".",
"data",
"[",
"datapoint",
"]",
".",
"extend",
"(",
"new_data",
")",
"except",
"KeyError",
":",
"self",
".",
"data",
"[",
"datapoint",
"]",
"=",
"new_data"
] | extend or assign new data to datapoint | [
"extend",
"or",
"assign",
"new",
"data",
"to",
"datapoint"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L126-L134 |
4,233 | siznax/wptools | wptools/page.py | WPToolsPage._missing_imageinfo | def _missing_imageinfo(self):
"""
returns list of image filenames that are missing info
"""
if 'image' not in self.data:
return
missing = []
for img in self.data['image']:
if 'url' not in img:
missing.append(img['file'])
return list(set(missing)) | python | def _missing_imageinfo(self):
"""
returns list of image filenames that are missing info
"""
if 'image' not in self.data:
return
missing = []
for img in self.data['image']:
if 'url' not in img:
missing.append(img['file'])
return list(set(missing)) | [
"def",
"_missing_imageinfo",
"(",
"self",
")",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"return",
"missing",
"=",
"[",
"]",
"for",
"img",
"in",
"self",
".",
"data",
"[",
"'image'",
"]",
":",
"if",
"'url'",
"not",
"in",
"img",
":",
"missing",
".",
"append",
"(",
"img",
"[",
"'file'",
"]",
")",
"return",
"list",
"(",
"set",
"(",
"missing",
")",
")"
] | returns list of image filenames that are missing info | [
"returns",
"list",
"of",
"image",
"filenames",
"that",
"are",
"missing",
"info"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L136-L146 |
4,234 | siznax/wptools | wptools/page.py | WPToolsPage._query | def _query(self, action, qobj):
"""
returns WPToolsQuery string
"""
title = self.params.get('title')
pageid = self.params.get('pageid')
wikibase = self.params.get('wikibase')
qstr = None
if action == 'random':
qstr = qobj.random()
elif action == 'query':
qstr = qobj.query(title, pageid, self._continue_params())
elif action == 'querymore':
qstr = qobj.querymore(title, pageid, self._continue_params())
elif action == 'parse':
qstr = qobj.parse(title, pageid)
elif action == 'imageinfo':
qstr = qobj.imageinfo(self._missing_imageinfo())
elif action == 'labels':
qstr = qobj.labels(self._pop_entities())
elif action == 'wikidata':
qstr = qobj.wikidata(title, wikibase)
elif action == 'restbase':
qstr = qobj.restbase(self.params.get('rest_endpoint'), title)
if qstr is None:
raise ValueError("Unknown action: %s" % action)
return qstr | python | def _query(self, action, qobj):
"""
returns WPToolsQuery string
"""
title = self.params.get('title')
pageid = self.params.get('pageid')
wikibase = self.params.get('wikibase')
qstr = None
if action == 'random':
qstr = qobj.random()
elif action == 'query':
qstr = qobj.query(title, pageid, self._continue_params())
elif action == 'querymore':
qstr = qobj.querymore(title, pageid, self._continue_params())
elif action == 'parse':
qstr = qobj.parse(title, pageid)
elif action == 'imageinfo':
qstr = qobj.imageinfo(self._missing_imageinfo())
elif action == 'labels':
qstr = qobj.labels(self._pop_entities())
elif action == 'wikidata':
qstr = qobj.wikidata(title, wikibase)
elif action == 'restbase':
qstr = qobj.restbase(self.params.get('rest_endpoint'), title)
if qstr is None:
raise ValueError("Unknown action: %s" % action)
return qstr | [
"def",
"_query",
"(",
"self",
",",
"action",
",",
"qobj",
")",
":",
"title",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
"pageid",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'pageid'",
")",
"wikibase",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'wikibase'",
")",
"qstr",
"=",
"None",
"if",
"action",
"==",
"'random'",
":",
"qstr",
"=",
"qobj",
".",
"random",
"(",
")",
"elif",
"action",
"==",
"'query'",
":",
"qstr",
"=",
"qobj",
".",
"query",
"(",
"title",
",",
"pageid",
",",
"self",
".",
"_continue_params",
"(",
")",
")",
"elif",
"action",
"==",
"'querymore'",
":",
"qstr",
"=",
"qobj",
".",
"querymore",
"(",
"title",
",",
"pageid",
",",
"self",
".",
"_continue_params",
"(",
")",
")",
"elif",
"action",
"==",
"'parse'",
":",
"qstr",
"=",
"qobj",
".",
"parse",
"(",
"title",
",",
"pageid",
")",
"elif",
"action",
"==",
"'imageinfo'",
":",
"qstr",
"=",
"qobj",
".",
"imageinfo",
"(",
"self",
".",
"_missing_imageinfo",
"(",
")",
")",
"elif",
"action",
"==",
"'labels'",
":",
"qstr",
"=",
"qobj",
".",
"labels",
"(",
"self",
".",
"_pop_entities",
"(",
")",
")",
"elif",
"action",
"==",
"'wikidata'",
":",
"qstr",
"=",
"qobj",
".",
"wikidata",
"(",
"title",
",",
"wikibase",
")",
"elif",
"action",
"==",
"'restbase'",
":",
"qstr",
"=",
"qobj",
".",
"restbase",
"(",
"self",
".",
"params",
".",
"get",
"(",
"'rest_endpoint'",
")",
",",
"title",
")",
"if",
"qstr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unknown action: %s\"",
"%",
"action",
")",
"return",
"qstr"
] | returns WPToolsQuery string | [
"returns",
"WPToolsQuery",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L163-L193 |
4,235 | siznax/wptools | wptools/page.py | WPToolsPage._set_data | def _set_data(self, action):
"""
marshals response data into page data
"""
if 'query' in action:
self._set_query_data(action)
elif action == 'imageinfo':
self._set_imageinfo_data()
elif action == 'parse':
self._set_parse_data()
elif action == 'random':
self._set_random_data()
elif action == 'labels':
self._set_labels()
elif action == 'wikidata':
self._set_wikidata()
self.get_labels()
elif action == 'restbase':
self._set_restbase_data()
self._update_imageinfo()
self._update_params() | python | def _set_data(self, action):
"""
marshals response data into page data
"""
if 'query' in action:
self._set_query_data(action)
elif action == 'imageinfo':
self._set_imageinfo_data()
elif action == 'parse':
self._set_parse_data()
elif action == 'random':
self._set_random_data()
elif action == 'labels':
self._set_labels()
elif action == 'wikidata':
self._set_wikidata()
self.get_labels()
elif action == 'restbase':
self._set_restbase_data()
self._update_imageinfo()
self._update_params() | [
"def",
"_set_data",
"(",
"self",
",",
"action",
")",
":",
"if",
"'query'",
"in",
"action",
":",
"self",
".",
"_set_query_data",
"(",
"action",
")",
"elif",
"action",
"==",
"'imageinfo'",
":",
"self",
".",
"_set_imageinfo_data",
"(",
")",
"elif",
"action",
"==",
"'parse'",
":",
"self",
".",
"_set_parse_data",
"(",
")",
"elif",
"action",
"==",
"'random'",
":",
"self",
".",
"_set_random_data",
"(",
")",
"elif",
"action",
"==",
"'labels'",
":",
"self",
".",
"_set_labels",
"(",
")",
"elif",
"action",
"==",
"'wikidata'",
":",
"self",
".",
"_set_wikidata",
"(",
")",
"self",
".",
"get_labels",
"(",
")",
"elif",
"action",
"==",
"'restbase'",
":",
"self",
".",
"_set_restbase_data",
"(",
")",
"self",
".",
"_update_imageinfo",
"(",
")",
"self",
".",
"_update_params",
"(",
")"
] | marshals response data into page data | [
"marshals",
"response",
"data",
"into",
"page",
"data"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L195-L216 |
4,236 | siznax/wptools | wptools/page.py | WPToolsPage._set_parse_image | def _set_parse_image(self, infobox):
"""
set image data from action=parse response
"""
image = infobox.get('image')
cover = infobox.get('Cover') or infobox.get('cover')
if image or cover:
if 'image' not in self.data:
self.data['image'] = []
if image and utils.isfilename(image):
self.data['image'].append({'kind': 'parse-image', 'file': image})
if cover and utils.isfilename(cover):
self.data['image'].append({'kind': 'parse-cover', 'file': cover}) | python | def _set_parse_image(self, infobox):
"""
set image data from action=parse response
"""
image = infobox.get('image')
cover = infobox.get('Cover') or infobox.get('cover')
if image or cover:
if 'image' not in self.data:
self.data['image'] = []
if image and utils.isfilename(image):
self.data['image'].append({'kind': 'parse-image', 'file': image})
if cover and utils.isfilename(cover):
self.data['image'].append({'kind': 'parse-cover', 'file': cover}) | [
"def",
"_set_parse_image",
"(",
"self",
",",
"infobox",
")",
":",
"image",
"=",
"infobox",
".",
"get",
"(",
"'image'",
")",
"cover",
"=",
"infobox",
".",
"get",
"(",
"'Cover'",
")",
"or",
"infobox",
".",
"get",
"(",
"'cover'",
")",
"if",
"image",
"or",
"cover",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
"=",
"[",
"]",
"if",
"image",
"and",
"utils",
".",
"isfilename",
"(",
"image",
")",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"{",
"'kind'",
":",
"'parse-image'",
",",
"'file'",
":",
"image",
"}",
")",
"if",
"cover",
"and",
"utils",
".",
"isfilename",
"(",
"cover",
")",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"{",
"'kind'",
":",
"'parse-cover'",
",",
"'file'",
":",
"cover",
"}",
")"
] | set image data from action=parse response | [
"set",
"image",
"data",
"from",
"action",
"=",
"parse",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L274-L289 |
4,237 | siznax/wptools | wptools/page.py | WPToolsPage._set_query_data_fast_1 | def _set_query_data_fast_1(self, page):
"""
set less expensive action=query response data PART 1
"""
self.data['pageid'] = page.get('pageid')
assessments = page.get('pageassessments')
if assessments:
self.data['assessments'] = assessments
extract = page.get('extract')
if extract:
self.data['extract'] = extract
extext = html2text.html2text(extract)
if extext:
self.data['extext'] = extext.strip()
fullurl = page.get('fullurl')
if fullurl:
self.data['url'] = fullurl
self.data['url_raw'] = fullurl + '?action=raw'
length = page.get('length')
if length:
self.data['length'] = length
self._extend_data('links', utils.get_links(page.get('links')))
self._update_data('modified', 'page', page.get('touched'))
pageprops = page.get('pageprops')
if pageprops:
wikibase = pageprops.get('wikibase_item')
if wikibase:
self.data['wikibase'] = wikibase
self.data['wikidata_url'] = utils.wikidata_url(wikibase)
if 'disambiguation' in pageprops:
self.data['disambiguation'] = len(self.data['links']) | python | def _set_query_data_fast_1(self, page):
"""
set less expensive action=query response data PART 1
"""
self.data['pageid'] = page.get('pageid')
assessments = page.get('pageassessments')
if assessments:
self.data['assessments'] = assessments
extract = page.get('extract')
if extract:
self.data['extract'] = extract
extext = html2text.html2text(extract)
if extext:
self.data['extext'] = extext.strip()
fullurl = page.get('fullurl')
if fullurl:
self.data['url'] = fullurl
self.data['url_raw'] = fullurl + '?action=raw'
length = page.get('length')
if length:
self.data['length'] = length
self._extend_data('links', utils.get_links(page.get('links')))
self._update_data('modified', 'page', page.get('touched'))
pageprops = page.get('pageprops')
if pageprops:
wikibase = pageprops.get('wikibase_item')
if wikibase:
self.data['wikibase'] = wikibase
self.data['wikidata_url'] = utils.wikidata_url(wikibase)
if 'disambiguation' in pageprops:
self.data['disambiguation'] = len(self.data['links']) | [
"def",
"_set_query_data_fast_1",
"(",
"self",
",",
"page",
")",
":",
"self",
".",
"data",
"[",
"'pageid'",
"]",
"=",
"page",
".",
"get",
"(",
"'pageid'",
")",
"assessments",
"=",
"page",
".",
"get",
"(",
"'pageassessments'",
")",
"if",
"assessments",
":",
"self",
".",
"data",
"[",
"'assessments'",
"]",
"=",
"assessments",
"extract",
"=",
"page",
".",
"get",
"(",
"'extract'",
")",
"if",
"extract",
":",
"self",
".",
"data",
"[",
"'extract'",
"]",
"=",
"extract",
"extext",
"=",
"html2text",
".",
"html2text",
"(",
"extract",
")",
"if",
"extext",
":",
"self",
".",
"data",
"[",
"'extext'",
"]",
"=",
"extext",
".",
"strip",
"(",
")",
"fullurl",
"=",
"page",
".",
"get",
"(",
"'fullurl'",
")",
"if",
"fullurl",
":",
"self",
".",
"data",
"[",
"'url'",
"]",
"=",
"fullurl",
"self",
".",
"data",
"[",
"'url_raw'",
"]",
"=",
"fullurl",
"+",
"'?action=raw'",
"length",
"=",
"page",
".",
"get",
"(",
"'length'",
")",
"if",
"length",
":",
"self",
".",
"data",
"[",
"'length'",
"]",
"=",
"length",
"self",
".",
"_extend_data",
"(",
"'links'",
",",
"utils",
".",
"get_links",
"(",
"page",
".",
"get",
"(",
"'links'",
")",
")",
")",
"self",
".",
"_update_data",
"(",
"'modified'",
",",
"'page'",
",",
"page",
".",
"get",
"(",
"'touched'",
")",
")",
"pageprops",
"=",
"page",
".",
"get",
"(",
"'pageprops'",
")",
"if",
"pageprops",
":",
"wikibase",
"=",
"pageprops",
".",
"get",
"(",
"'wikibase_item'",
")",
"if",
"wikibase",
":",
"self",
".",
"data",
"[",
"'wikibase'",
"]",
"=",
"wikibase",
"self",
".",
"data",
"[",
"'wikidata_url'",
"]",
"=",
"utils",
".",
"wikidata_url",
"(",
"wikibase",
")",
"if",
"'disambiguation'",
"in",
"pageprops",
":",
"self",
".",
"data",
"[",
"'disambiguation'",
"]",
"=",
"len",
"(",
"self",
".",
"data",
"[",
"'links'",
"]",
")"
] | set less expensive action=query response data PART 1 | [
"set",
"less",
"expensive",
"action",
"=",
"query",
"response",
"data",
"PART",
"1"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L311-L349 |
4,238 | siznax/wptools | wptools/page.py | WPToolsPage._set_query_data_fast_2 | def _set_query_data_fast_2(self, page):
"""
set less expensive action=query response data PART 2
"""
self.data['pageid'] = page.get('pageid')
redirects = page.get('redirects')
if redirects:
self.data['redirects'] = redirects
terms = page.get('terms')
if terms:
if terms.get('alias'):
self.data['aliases'] = terms['alias']
if terms.get('description'):
self.data['description'] = next(iter(terms['description']),
None)
if terms.get('label'):
self.data['label'] = next(iter(terms['label']), None)
title = page.get('title')
self.data['title'] = title
if not self.params.get('title'):
self.params['title'] = title
watchers = page.get('watchers')
if watchers:
self.data['watchers'] = watchers
self._set_query_image(page) | python | def _set_query_data_fast_2(self, page):
"""
set less expensive action=query response data PART 2
"""
self.data['pageid'] = page.get('pageid')
redirects = page.get('redirects')
if redirects:
self.data['redirects'] = redirects
terms = page.get('terms')
if terms:
if terms.get('alias'):
self.data['aliases'] = terms['alias']
if terms.get('description'):
self.data['description'] = next(iter(terms['description']),
None)
if terms.get('label'):
self.data['label'] = next(iter(terms['label']), None)
title = page.get('title')
self.data['title'] = title
if not self.params.get('title'):
self.params['title'] = title
watchers = page.get('watchers')
if watchers:
self.data['watchers'] = watchers
self._set_query_image(page) | [
"def",
"_set_query_data_fast_2",
"(",
"self",
",",
"page",
")",
":",
"self",
".",
"data",
"[",
"'pageid'",
"]",
"=",
"page",
".",
"get",
"(",
"'pageid'",
")",
"redirects",
"=",
"page",
".",
"get",
"(",
"'redirects'",
")",
"if",
"redirects",
":",
"self",
".",
"data",
"[",
"'redirects'",
"]",
"=",
"redirects",
"terms",
"=",
"page",
".",
"get",
"(",
"'terms'",
")",
"if",
"terms",
":",
"if",
"terms",
".",
"get",
"(",
"'alias'",
")",
":",
"self",
".",
"data",
"[",
"'aliases'",
"]",
"=",
"terms",
"[",
"'alias'",
"]",
"if",
"terms",
".",
"get",
"(",
"'description'",
")",
":",
"self",
".",
"data",
"[",
"'description'",
"]",
"=",
"next",
"(",
"iter",
"(",
"terms",
"[",
"'description'",
"]",
")",
",",
"None",
")",
"if",
"terms",
".",
"get",
"(",
"'label'",
")",
":",
"self",
".",
"data",
"[",
"'label'",
"]",
"=",
"next",
"(",
"iter",
"(",
"terms",
"[",
"'label'",
"]",
")",
",",
"None",
")",
"title",
"=",
"page",
".",
"get",
"(",
"'title'",
")",
"self",
".",
"data",
"[",
"'title'",
"]",
"=",
"title",
"if",
"not",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
":",
"self",
".",
"params",
"[",
"'title'",
"]",
"=",
"title",
"watchers",
"=",
"page",
".",
"get",
"(",
"'watchers'",
")",
"if",
"watchers",
":",
"self",
".",
"data",
"[",
"'watchers'",
"]",
"=",
"watchers",
"self",
".",
"_set_query_image",
"(",
"page",
")"
] | set less expensive action=query response data PART 2 | [
"set",
"less",
"expensive",
"action",
"=",
"query",
"response",
"data",
"PART",
"2"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L351-L381 |
4,239 | siznax/wptools | wptools/page.py | WPToolsPage._set_query_data_slow | def _set_query_data_slow(self, page):
"""
set more expensive action=query response data
"""
categories = page.get('categories')
if categories:
self.data['categories'] = [x['title'] for x in categories]
if page.get('contributors'):
contributors = page.get('contributors') or 0
anoncontributors = page.get('anoncontributors') or 0
if isinstance(contributors, list):
contributors = len(contributors)
self.data['contributors'] = contributors + anoncontributors
files = page.get('images') # really, these are FILES
if files:
self.data['files'] = [x['title'] for x in files]
languages = page.get('langlinks')
if languages:
self.data['languages'] = languages
pageviews = page.get('pageviews')
if pageviews:
values = [x for x in pageviews.values() if x]
if values:
self.data['views'] = int(sum(values) / len(values))
else:
self.data['views'] = 0 | python | def _set_query_data_slow(self, page):
"""
set more expensive action=query response data
"""
categories = page.get('categories')
if categories:
self.data['categories'] = [x['title'] for x in categories]
if page.get('contributors'):
contributors = page.get('contributors') or 0
anoncontributors = page.get('anoncontributors') or 0
if isinstance(contributors, list):
contributors = len(contributors)
self.data['contributors'] = contributors + anoncontributors
files = page.get('images') # really, these are FILES
if files:
self.data['files'] = [x['title'] for x in files]
languages = page.get('langlinks')
if languages:
self.data['languages'] = languages
pageviews = page.get('pageviews')
if pageviews:
values = [x for x in pageviews.values() if x]
if values:
self.data['views'] = int(sum(values) / len(values))
else:
self.data['views'] = 0 | [
"def",
"_set_query_data_slow",
"(",
"self",
",",
"page",
")",
":",
"categories",
"=",
"page",
".",
"get",
"(",
"'categories'",
")",
"if",
"categories",
":",
"self",
".",
"data",
"[",
"'categories'",
"]",
"=",
"[",
"x",
"[",
"'title'",
"]",
"for",
"x",
"in",
"categories",
"]",
"if",
"page",
".",
"get",
"(",
"'contributors'",
")",
":",
"contributors",
"=",
"page",
".",
"get",
"(",
"'contributors'",
")",
"or",
"0",
"anoncontributors",
"=",
"page",
".",
"get",
"(",
"'anoncontributors'",
")",
"or",
"0",
"if",
"isinstance",
"(",
"contributors",
",",
"list",
")",
":",
"contributors",
"=",
"len",
"(",
"contributors",
")",
"self",
".",
"data",
"[",
"'contributors'",
"]",
"=",
"contributors",
"+",
"anoncontributors",
"files",
"=",
"page",
".",
"get",
"(",
"'images'",
")",
"# really, these are FILES",
"if",
"files",
":",
"self",
".",
"data",
"[",
"'files'",
"]",
"=",
"[",
"x",
"[",
"'title'",
"]",
"for",
"x",
"in",
"files",
"]",
"languages",
"=",
"page",
".",
"get",
"(",
"'langlinks'",
")",
"if",
"languages",
":",
"self",
".",
"data",
"[",
"'languages'",
"]",
"=",
"languages",
"pageviews",
"=",
"page",
".",
"get",
"(",
"'pageviews'",
")",
"if",
"pageviews",
":",
"values",
"=",
"[",
"x",
"for",
"x",
"in",
"pageviews",
".",
"values",
"(",
")",
"if",
"x",
"]",
"if",
"values",
":",
"self",
".",
"data",
"[",
"'views'",
"]",
"=",
"int",
"(",
"sum",
"(",
"values",
")",
"/",
"len",
"(",
"values",
")",
")",
"else",
":",
"self",
".",
"data",
"[",
"'views'",
"]",
"=",
"0"
] | set more expensive action=query response data | [
"set",
"more",
"expensive",
"action",
"=",
"query",
"response",
"data"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L383-L412 |
4,240 | siznax/wptools | wptools/page.py | WPToolsPage._set_query_image | def _set_query_image(self, page):
"""
set image data from action=query response
"""
pageimage = page.get('pageimage')
thumbnail = page.get('thumbnail')
if pageimage or thumbnail:
if 'image' not in self.data:
self.data['image'] = []
if pageimage:
self.data['image'].append({
'kind': 'query-pageimage',
'file': pageimage})
if thumbnail:
qthumb = {'kind': 'query-thumbnail'}
qthumb.update(thumbnail)
qthumb['url'] = thumbnail.get('source')
del qthumb['source']
qthumb['file'] = qthumb['url'].split('/')[-2]
self.data['image'].append(qthumb) | python | def _set_query_image(self, page):
"""
set image data from action=query response
"""
pageimage = page.get('pageimage')
thumbnail = page.get('thumbnail')
if pageimage or thumbnail:
if 'image' not in self.data:
self.data['image'] = []
if pageimage:
self.data['image'].append({
'kind': 'query-pageimage',
'file': pageimage})
if thumbnail:
qthumb = {'kind': 'query-thumbnail'}
qthumb.update(thumbnail)
qthumb['url'] = thumbnail.get('source')
del qthumb['source']
qthumb['file'] = qthumb['url'].split('/')[-2]
self.data['image'].append(qthumb) | [
"def",
"_set_query_image",
"(",
"self",
",",
"page",
")",
":",
"pageimage",
"=",
"page",
".",
"get",
"(",
"'pageimage'",
")",
"thumbnail",
"=",
"page",
".",
"get",
"(",
"'thumbnail'",
")",
"if",
"pageimage",
"or",
"thumbnail",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
"=",
"[",
"]",
"if",
"pageimage",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"{",
"'kind'",
":",
"'query-pageimage'",
",",
"'file'",
":",
"pageimage",
"}",
")",
"if",
"thumbnail",
":",
"qthumb",
"=",
"{",
"'kind'",
":",
"'query-thumbnail'",
"}",
"qthumb",
".",
"update",
"(",
"thumbnail",
")",
"qthumb",
"[",
"'url'",
"]",
"=",
"thumbnail",
".",
"get",
"(",
"'source'",
")",
"del",
"qthumb",
"[",
"'source'",
"]",
"qthumb",
"[",
"'file'",
"]",
"=",
"qthumb",
"[",
"'url'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"2",
"]",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"qthumb",
")"
] | set image data from action=query response | [
"set",
"image",
"data",
"from",
"action",
"=",
"query",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L414-L436 |
4,241 | siznax/wptools | wptools/page.py | WPToolsPage._set_random_data | def _set_random_data(self):
"""
sets page data from random request
"""
rdata = self._load_response('random')
rdata = rdata['query']['random'][0]
pageid = rdata.get('id')
title = rdata.get('title')
self.data.update({'pageid': pageid,
'title': title}) | python | def _set_random_data(self):
"""
sets page data from random request
"""
rdata = self._load_response('random')
rdata = rdata['query']['random'][0]
pageid = rdata.get('id')
title = rdata.get('title')
self.data.update({'pageid': pageid,
'title': title}) | [
"def",
"_set_random_data",
"(",
"self",
")",
":",
"rdata",
"=",
"self",
".",
"_load_response",
"(",
"'random'",
")",
"rdata",
"=",
"rdata",
"[",
"'query'",
"]",
"[",
"'random'",
"]",
"[",
"0",
"]",
"pageid",
"=",
"rdata",
".",
"get",
"(",
"'id'",
")",
"title",
"=",
"rdata",
".",
"get",
"(",
"'title'",
")",
"self",
".",
"data",
".",
"update",
"(",
"{",
"'pageid'",
":",
"pageid",
",",
"'title'",
":",
"title",
"}",
")"
] | sets page data from random request | [
"sets",
"page",
"data",
"from",
"random",
"request"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L438-L449 |
4,242 | siznax/wptools | wptools/page.py | WPToolsPage._update_data | def _update_data(self, datapoint, key, new_data):
"""
update or assign new data to datapoint
"""
if new_data:
try:
self.data[datapoint].update({key: new_data})
except KeyError:
self.data[datapoint] = {key: new_data} | python | def _update_data(self, datapoint, key, new_data):
"""
update or assign new data to datapoint
"""
if new_data:
try:
self.data[datapoint].update({key: new_data})
except KeyError:
self.data[datapoint] = {key: new_data} | [
"def",
"_update_data",
"(",
"self",
",",
"datapoint",
",",
"key",
",",
"new_data",
")",
":",
"if",
"new_data",
":",
"try",
":",
"self",
".",
"data",
"[",
"datapoint",
"]",
".",
"update",
"(",
"{",
"key",
":",
"new_data",
"}",
")",
"except",
"KeyError",
":",
"self",
".",
"data",
"[",
"datapoint",
"]",
"=",
"{",
"key",
":",
"new_data",
"}"
] | update or assign new data to datapoint | [
"update",
"or",
"assign",
"new",
"data",
"to",
"datapoint"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L451-L459 |
4,243 | siznax/wptools | wptools/page.py | WPToolsPage._update_params | def _update_params(self):
"""
update params from response data
"""
if self.data.get('title'):
self.params['title'] = self.data.get('title')
if self.data.get('pageid'):
self.params['pageid'] = self.data.get('pageid')
if self.data.get('wikibase'):
self.params['wikibase'] = self.data.get('wikibase') | python | def _update_params(self):
"""
update params from response data
"""
if self.data.get('title'):
self.params['title'] = self.data.get('title')
if self.data.get('pageid'):
self.params['pageid'] = self.data.get('pageid')
if self.data.get('wikibase'):
self.params['wikibase'] = self.data.get('wikibase') | [
"def",
"_update_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'title'",
")",
":",
"self",
".",
"params",
"[",
"'title'",
"]",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'pageid'",
")",
":",
"self",
".",
"params",
"[",
"'pageid'",
"]",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'pageid'",
")",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'wikibase'",
")",
":",
"self",
".",
"params",
"[",
"'wikibase'",
"]",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'wikibase'",
")"
] | update params from response data | [
"update",
"params",
"from",
"response",
"data"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L472-L481 |
4,244 | siznax/wptools | wptools/page.py | WPToolsPage.skip_action | def skip_action(self, action):
"""
append action to skip flag
"""
if 'skip' not in self.flags:
self.flags['skip'] = []
self.flags['skip'].append(action) | python | def skip_action(self, action):
"""
append action to skip flag
"""
if 'skip' not in self.flags:
self.flags['skip'] = []
self.flags['skip'].append(action) | [
"def",
"skip_action",
"(",
"self",
",",
"action",
")",
":",
"if",
"'skip'",
"not",
"in",
"self",
".",
"flags",
":",
"self",
".",
"flags",
"[",
"'skip'",
"]",
"=",
"[",
"]",
"self",
".",
"flags",
"[",
"'skip'",
"]",
".",
"append",
"(",
"action",
")"
] | append action to skip flag | [
"append",
"action",
"to",
"skip",
"flag"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L483-L489 |
4,245 | siznax/wptools | wptools/page.py | WPToolsPage.images | def images(self, fields=None, token=None):
"""
Returns image info keys for kind containing token
Args:
- fields: <list> image info values wanted
- token: <str> substring to match image kind
EXAMPLES
Get all available image info:
>>> page.images()
Get all image kinds:
>>> page.images('kind')
Get only "query" (kind) image info
>>> page.images(token='query')
Get only file, url fields from "wikidata" images
>>> page.images(['file', 'url'], token='wikidata')
"""
if 'image' not in self.data:
return
out = []
for img in self.data['image']:
if token and token not in img['kind']:
continue
info = {}
for key in img:
if fields and key not in fields:
continue
info.update({key: img[key]})
if info:
out.append(info)
return out | python | def images(self, fields=None, token=None):
"""
Returns image info keys for kind containing token
Args:
- fields: <list> image info values wanted
- token: <str> substring to match image kind
EXAMPLES
Get all available image info:
>>> page.images()
Get all image kinds:
>>> page.images('kind')
Get only "query" (kind) image info
>>> page.images(token='query')
Get only file, url fields from "wikidata" images
>>> page.images(['file', 'url'], token='wikidata')
"""
if 'image' not in self.data:
return
out = []
for img in self.data['image']:
if token and token not in img['kind']:
continue
info = {}
for key in img:
if fields and key not in fields:
continue
info.update({key: img[key]})
if info:
out.append(info)
return out | [
"def",
"images",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"return",
"out",
"=",
"[",
"]",
"for",
"img",
"in",
"self",
".",
"data",
"[",
"'image'",
"]",
":",
"if",
"token",
"and",
"token",
"not",
"in",
"img",
"[",
"'kind'",
"]",
":",
"continue",
"info",
"=",
"{",
"}",
"for",
"key",
"in",
"img",
":",
"if",
"fields",
"and",
"key",
"not",
"in",
"fields",
":",
"continue",
"info",
".",
"update",
"(",
"{",
"key",
":",
"img",
"[",
"key",
"]",
"}",
")",
"if",
"info",
":",
"out",
".",
"append",
"(",
"info",
")",
"return",
"out"
] | Returns image info keys for kind containing token
Args:
- fields: <list> image info values wanted
- token: <str> substring to match image kind
EXAMPLES
Get all available image info:
>>> page.images()
Get all image kinds:
>>> page.images('kind')
Get only "query" (kind) image info
>>> page.images(token='query')
Get only file, url fields from "wikidata" images
>>> page.images(['file', 'url'], token='wikidata') | [
"Returns",
"image",
"info",
"keys",
"for",
"kind",
"containing",
"token"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L700-L738 |
4,246 | siznax/wptools | wptools/request.py | WPToolsRequest.get | def get(self, url, status):
"""
in favor of python-requests for speed
"""
# consistently faster than requests by 3x
#
# r = requests.get(url,
# headers={'User-Agent': self.user_agent})
# return r.text
crl = self.cobj
try:
crl.setopt(pycurl.URL, url)
except UnicodeEncodeError:
crl.setopt(pycurl.URL, url.encode('utf-8'))
if not self.silent:
print(status, file=sys.stderr)
if self.DISABLED:
print("Requests DISABLED", file=sys.stderr)
else:
return self.curl_perform(crl) | python | def get(self, url, status):
"""
in favor of python-requests for speed
"""
# consistently faster than requests by 3x
#
# r = requests.get(url,
# headers={'User-Agent': self.user_agent})
# return r.text
crl = self.cobj
try:
crl.setopt(pycurl.URL, url)
except UnicodeEncodeError:
crl.setopt(pycurl.URL, url.encode('utf-8'))
if not self.silent:
print(status, file=sys.stderr)
if self.DISABLED:
print("Requests DISABLED", file=sys.stderr)
else:
return self.curl_perform(crl) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"status",
")",
":",
"# consistently faster than requests by 3x",
"#",
"# r = requests.get(url,",
"# headers={'User-Agent': self.user_agent})",
"# return r.text",
"crl",
"=",
"self",
".",
"cobj",
"try",
":",
"crl",
".",
"setopt",
"(",
"pycurl",
".",
"URL",
",",
"url",
")",
"except",
"UnicodeEncodeError",
":",
"crl",
".",
"setopt",
"(",
"pycurl",
".",
"URL",
",",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"not",
"self",
".",
"silent",
":",
"print",
"(",
"status",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"self",
".",
"DISABLED",
":",
"print",
"(",
"\"Requests DISABLED\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"return",
"self",
".",
"curl_perform",
"(",
"crl",
")"
] | in favor of python-requests for speed | [
"in",
"favor",
"of",
"python",
"-",
"requests",
"for",
"speed"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/request.py#L52-L76 |
4,247 | siznax/wptools | wptools/request.py | WPToolsRequest.curl_perform | def curl_perform(self, crl):
"""
performs HTTP GET and returns body of response
"""
bfr = BytesIO()
crl.setopt(crl.WRITEFUNCTION, bfr.write)
crl.perform()
info = curl_info(crl)
if info:
if self.verbose and not self.silent:
for item in sorted(info):
print(" %s: %s" % (item, info[item]), file=sys.stderr)
self.info = info
body = bfr.getvalue()
bfr.close()
return body | python | def curl_perform(self, crl):
"""
performs HTTP GET and returns body of response
"""
bfr = BytesIO()
crl.setopt(crl.WRITEFUNCTION, bfr.write)
crl.perform()
info = curl_info(crl)
if info:
if self.verbose and not self.silent:
for item in sorted(info):
print(" %s: %s" % (item, info[item]), file=sys.stderr)
self.info = info
body = bfr.getvalue()
bfr.close()
return body | [
"def",
"curl_perform",
"(",
"self",
",",
"crl",
")",
":",
"bfr",
"=",
"BytesIO",
"(",
")",
"crl",
".",
"setopt",
"(",
"crl",
".",
"WRITEFUNCTION",
",",
"bfr",
".",
"write",
")",
"crl",
".",
"perform",
"(",
")",
"info",
"=",
"curl_info",
"(",
"crl",
")",
"if",
"info",
":",
"if",
"self",
".",
"verbose",
"and",
"not",
"self",
".",
"silent",
":",
"for",
"item",
"in",
"sorted",
"(",
"info",
")",
":",
"print",
"(",
"\" %s: %s\"",
"%",
"(",
"item",
",",
"info",
"[",
"item",
"]",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"self",
".",
"info",
"=",
"info",
"body",
"=",
"bfr",
".",
"getvalue",
"(",
")",
"bfr",
".",
"close",
"(",
")",
"return",
"body"
] | performs HTTP GET and returns body of response | [
"performs",
"HTTP",
"GET",
"and",
"returns",
"body",
"of",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/request.py#L78-L93 |
4,248 | siznax/wptools | wptools/query.py | safequote_restbase | def safequote_restbase(title):
"""
Safequote restbase title possibly having slash in title
"""
try:
return quote(title.encode('utf-8'), safe='')
except UnicodeDecodeError:
return quote(title, safe='') | python | def safequote_restbase(title):
"""
Safequote restbase title possibly having slash in title
"""
try:
return quote(title.encode('utf-8'), safe='')
except UnicodeDecodeError:
return quote(title, safe='') | [
"def",
"safequote_restbase",
"(",
"title",
")",
":",
"try",
":",
"return",
"quote",
"(",
"title",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"''",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"quote",
"(",
"title",
",",
"safe",
"=",
"''",
")"
] | Safequote restbase title possibly having slash in title | [
"Safequote",
"restbase",
"title",
"possibly",
"having",
"slash",
"in",
"title"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L416-L423 |
4,249 | siznax/wptools | wptools/query.py | WPToolsQuery.category | def category(self, title, pageid=None, cparams=None, namespace=None):
"""
Returns category query string
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='categorymembers')
status = pageid or title
query += "&cmlimit=500"
if namespace is not None:
query += "&cmnamespace=%d" % namespace
if title and pageid:
title = None
if title:
query += "&cmtitle=" + safequote(title)
if pageid:
query += "&cmpageid=%d" % pageid
if cparams:
query += cparams
status += ' (%s)' % cparams
self.set_status('categorymembers', status)
return query | python | def category(self, title, pageid=None, cparams=None, namespace=None):
"""
Returns category query string
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='categorymembers')
status = pageid or title
query += "&cmlimit=500"
if namespace is not None:
query += "&cmnamespace=%d" % namespace
if title and pageid:
title = None
if title:
query += "&cmtitle=" + safequote(title)
if pageid:
query += "&cmpageid=%d" % pageid
if cparams:
query += cparams
status += ' (%s)' % cparams
self.set_status('categorymembers', status)
return query | [
"def",
"category",
"(",
"self",
",",
"title",
",",
"pageid",
"=",
"None",
",",
"cparams",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"LIST",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LIST",
"=",
"'categorymembers'",
")",
"status",
"=",
"pageid",
"or",
"title",
"query",
"+=",
"\"&cmlimit=500\"",
"if",
"namespace",
"is",
"not",
"None",
":",
"query",
"+=",
"\"&cmnamespace=%d\"",
"%",
"namespace",
"if",
"title",
"and",
"pageid",
":",
"title",
"=",
"None",
"if",
"title",
":",
"query",
"+=",
"\"&cmtitle=\"",
"+",
"safequote",
"(",
"title",
")",
"if",
"pageid",
":",
"query",
"+=",
"\"&cmpageid=%d\"",
"%",
"pageid",
"if",
"cparams",
":",
"query",
"+=",
"cparams",
"status",
"+=",
"' (%s)'",
"%",
"cparams",
"self",
".",
"set_status",
"(",
"'categorymembers'",
",",
"status",
")",
"return",
"query"
] | Returns category query string | [
"Returns",
"category",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L129-L159 |
4,250 | siznax/wptools | wptools/query.py | WPToolsQuery.labels | def labels(self, qids):
"""
Returns Wikidata labels query string
"""
if len(qids) > 50:
raise ValueError("The limit is 50.")
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.variant or self.lang,
PROPS='labels')
qids = '|'.join(qids)
query += "&ids=%s" % qids
self.set_status('labels', qids)
return query | python | def labels(self, qids):
"""
Returns Wikidata labels query string
"""
if len(qids) > 50:
raise ValueError("The limit is 50.")
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.variant or self.lang,
PROPS='labels')
qids = '|'.join(qids)
query += "&ids=%s" % qids
self.set_status('labels', qids)
return query | [
"def",
"labels",
"(",
"self",
",",
"qids",
")",
":",
"if",
"len",
"(",
"qids",
")",
">",
"50",
":",
"raise",
"ValueError",
"(",
"\"The limit is 50.\"",
")",
"self",
".",
"domain",
"=",
"'www.wikidata.org'",
"self",
".",
"uri",
"=",
"self",
".",
"wiki_uri",
"(",
"self",
".",
"domain",
")",
"query",
"=",
"self",
".",
"WIKIDATA",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LANG",
"=",
"self",
".",
"variant",
"or",
"self",
".",
"lang",
",",
"PROPS",
"=",
"'labels'",
")",
"qids",
"=",
"'|'",
".",
"join",
"(",
"qids",
")",
"query",
"+=",
"\"&ids=%s\"",
"%",
"qids",
"self",
".",
"set_status",
"(",
"'labels'",
",",
"qids",
")",
"return",
"query"
] | Returns Wikidata labels query string | [
"Returns",
"Wikidata",
"labels",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L161-L182 |
4,251 | siznax/wptools | wptools/query.py | WPToolsQuery.imageinfo | def imageinfo(self, files):
"""
Returns imageinfo query string
"""
files = '|'.join([safequote(x) for x in files])
self.set_status('imageinfo', files)
return self.IMAGEINFO.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
FILES=files) | python | def imageinfo(self, files):
"""
Returns imageinfo query string
"""
files = '|'.join([safequote(x) for x in files])
self.set_status('imageinfo', files)
return self.IMAGEINFO.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
FILES=files) | [
"def",
"imageinfo",
"(",
"self",
",",
"files",
")",
":",
"files",
"=",
"'|'",
".",
"join",
"(",
"[",
"safequote",
"(",
"x",
")",
"for",
"x",
"in",
"files",
"]",
")",
"self",
".",
"set_status",
"(",
"'imageinfo'",
",",
"files",
")",
"return",
"self",
".",
"IMAGEINFO",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"FILES",
"=",
"files",
")"
] | Returns imageinfo query string | [
"Returns",
"imageinfo",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L184-L195 |
4,252 | siznax/wptools | wptools/query.py | WPToolsQuery.parse | def parse(self, title, pageid=None):
"""
Returns Mediawiki action=parse query string
"""
qry = self.PARSE.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
PAGE=safequote(title) or pageid)
if pageid and not title:
qry = qry.replace('&page=', '&pageid=').replace('&redirects', '')
if self.variant:
qry += '&variant=' + self.variant
self.set_status('parse', pageid or title)
return qry | python | def parse(self, title, pageid=None):
"""
Returns Mediawiki action=parse query string
"""
qry = self.PARSE.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
PAGE=safequote(title) or pageid)
if pageid and not title:
qry = qry.replace('&page=', '&pageid=').replace('&redirects', '')
if self.variant:
qry += '&variant=' + self.variant
self.set_status('parse', pageid or title)
return qry | [
"def",
"parse",
"(",
"self",
",",
"title",
",",
"pageid",
"=",
"None",
")",
":",
"qry",
"=",
"self",
".",
"PARSE",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"PAGE",
"=",
"safequote",
"(",
"title",
")",
"or",
"pageid",
")",
"if",
"pageid",
"and",
"not",
"title",
":",
"qry",
"=",
"qry",
".",
"replace",
"(",
"'&page='",
",",
"'&pageid='",
")",
".",
"replace",
"(",
"'&redirects'",
",",
"''",
")",
"if",
"self",
".",
"variant",
":",
"qry",
"+=",
"'&variant='",
"+",
"self",
".",
"variant",
"self",
".",
"set_status",
"(",
"'parse'",
",",
"pageid",
"or",
"title",
")",
"return",
"qry"
] | Returns Mediawiki action=parse query string | [
"Returns",
"Mediawiki",
"action",
"=",
"parse",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L197-L214 |
4,253 | siznax/wptools | wptools/query.py | WPToolsQuery.query | def query(self, titles, pageids=None, cparams=None):
"""
Returns MediaWiki action=query query string
"""
query = self.QUERY.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
TITLES=safequote(titles) or pageids)
status = titles or pageids
if pageids and not titles:
query = query.replace('&titles=', '&pageids=')
if cparams:
query += cparams
status += " (%s)" % cparams
if self.variant:
query += '&variant=' + self.variant
self.set_status('query', status)
return query | python | def query(self, titles, pageids=None, cparams=None):
"""
Returns MediaWiki action=query query string
"""
query = self.QUERY.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
TITLES=safequote(titles) or pageids)
status = titles or pageids
if pageids and not titles:
query = query.replace('&titles=', '&pageids=')
if cparams:
query += cparams
status += " (%s)" % cparams
if self.variant:
query += '&variant=' + self.variant
self.set_status('query', status)
return query | [
"def",
"query",
"(",
"self",
",",
"titles",
",",
"pageids",
"=",
"None",
",",
"cparams",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"QUERY",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"TITLES",
"=",
"safequote",
"(",
"titles",
")",
"or",
"pageids",
")",
"status",
"=",
"titles",
"or",
"pageids",
"if",
"pageids",
"and",
"not",
"titles",
":",
"query",
"=",
"query",
".",
"replace",
"(",
"'&titles='",
",",
"'&pageids='",
")",
"if",
"cparams",
":",
"query",
"+=",
"cparams",
"status",
"+=",
"\" (%s)\"",
"%",
"cparams",
"if",
"self",
".",
"variant",
":",
"query",
"+=",
"'&variant='",
"+",
"self",
".",
"variant",
"self",
".",
"set_status",
"(",
"'query'",
",",
"status",
")",
"return",
"query"
] | Returns MediaWiki action=query query string | [
"Returns",
"MediaWiki",
"action",
"=",
"query",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L216-L238 |
4,254 | siznax/wptools | wptools/query.py | WPToolsQuery.random | def random(self, namespace=0):
"""
Returns query string for random page
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='random')
query += "&rnlimit=1&rnnamespace=%d" % namespace
emoji = [
u'\U0001f32f', # burrito or wrap
u'\U0001f355', # slice of pizza
u'\U0001f35c', # steaming bowl of ramen
u'\U0001f363', # sushi
u'\U0001f369', # doughnut
u'\U0001f36a', # cookie
u'\U0001f36d', # lollipop
u'\U0001f370', # strawberry shortcake
]
action = 'random'
if namespace:
action = 'random:%d' % namespace
self.set_status(action, random.choice(emoji))
return query | python | def random(self, namespace=0):
"""
Returns query string for random page
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='random')
query += "&rnlimit=1&rnnamespace=%d" % namespace
emoji = [
u'\U0001f32f', # burrito or wrap
u'\U0001f355', # slice of pizza
u'\U0001f35c', # steaming bowl of ramen
u'\U0001f363', # sushi
u'\U0001f369', # doughnut
u'\U0001f36a', # cookie
u'\U0001f36d', # lollipop
u'\U0001f370', # strawberry shortcake
]
action = 'random'
if namespace:
action = 'random:%d' % namespace
self.set_status(action, random.choice(emoji))
return query | [
"def",
"random",
"(",
"self",
",",
"namespace",
"=",
"0",
")",
":",
"query",
"=",
"self",
".",
"LIST",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LIST",
"=",
"'random'",
")",
"query",
"+=",
"\"&rnlimit=1&rnnamespace=%d\"",
"%",
"namespace",
"emoji",
"=",
"[",
"u'\\U0001f32f'",
",",
"# burrito or wrap",
"u'\\U0001f355'",
",",
"# slice of pizza",
"u'\\U0001f35c'",
",",
"# steaming bowl of ramen",
"u'\\U0001f363'",
",",
"# sushi",
"u'\\U0001f369'",
",",
"# doughnut",
"u'\\U0001f36a'",
",",
"# cookie",
"u'\\U0001f36d'",
",",
"# lollipop",
"u'\\U0001f370'",
",",
"# strawberry shortcake",
"]",
"action",
"=",
"'random'",
"if",
"namespace",
":",
"action",
"=",
"'random:%d'",
"%",
"namespace",
"self",
".",
"set_status",
"(",
"action",
",",
"random",
".",
"choice",
"(",
"emoji",
")",
")",
"return",
"query"
] | Returns query string for random page | [
"Returns",
"query",
"string",
"for",
"random",
"page"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L266-L293 |
4,255 | siznax/wptools | wptools/query.py | WPToolsQuery.restbase | def restbase(self, endpoint, title):
"""
Returns RESTBase query string
"""
if not endpoint:
raise ValueError("invalid endpoint: %s" % endpoint)
route = endpoint
if title and endpoint != '/page/':
route = endpoint + safequote_restbase(title)
self.set_status('restbase', route)
return "%s/api/rest_v1/%s" % (self.uri, route[1:]) | python | def restbase(self, endpoint, title):
"""
Returns RESTBase query string
"""
if not endpoint:
raise ValueError("invalid endpoint: %s" % endpoint)
route = endpoint
if title and endpoint != '/page/':
route = endpoint + safequote_restbase(title)
self.set_status('restbase', route)
return "%s/api/rest_v1/%s" % (self.uri, route[1:]) | [
"def",
"restbase",
"(",
"self",
",",
"endpoint",
",",
"title",
")",
":",
"if",
"not",
"endpoint",
":",
"raise",
"ValueError",
"(",
"\"invalid endpoint: %s\"",
"%",
"endpoint",
")",
"route",
"=",
"endpoint",
"if",
"title",
"and",
"endpoint",
"!=",
"'/page/'",
":",
"route",
"=",
"endpoint",
"+",
"safequote_restbase",
"(",
"title",
")",
"self",
".",
"set_status",
"(",
"'restbase'",
",",
"route",
")",
"return",
"\"%s/api/rest_v1/%s\"",
"%",
"(",
"self",
".",
"uri",
",",
"route",
"[",
"1",
":",
"]",
")"
] | Returns RESTBase query string | [
"Returns",
"RESTBase",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L295-L308 |
4,256 | siznax/wptools | wptools/query.py | WPToolsQuery.site | def site(self, action):
"""
Returns site query
"""
query = None
viewdays = 7
hostpath = self.uri + self.endpoint
if action == 'siteinfo':
query = hostpath + (
'?action=query'
'&meta=siteinfo|siteviews'
'&siprop=general|statistics'
'&list=mostviewed&pvimlimit=max')
query += '&pvisdays=%d' % viewdays # meta=siteviews
self.set_status('query', 'siteinfo|siteviews|mostviewed')
elif action == 'sitematrix':
query = hostpath + '?action=sitematrix'
self.set_status('sitematrix', 'all')
elif action == 'sitevisitors':
query = hostpath + (
'?action=query'
'&meta=siteviews&pvismetric=uniques')
query += '&pvisdays=%d' % viewdays # meta=siteviews
self.set_status('query', 'siteviews:uniques')
if not query:
raise ValueError("Could not form query")
query += '&format=json&formatversion=2'
return query | python | def site(self, action):
"""
Returns site query
"""
query = None
viewdays = 7
hostpath = self.uri + self.endpoint
if action == 'siteinfo':
query = hostpath + (
'?action=query'
'&meta=siteinfo|siteviews'
'&siprop=general|statistics'
'&list=mostviewed&pvimlimit=max')
query += '&pvisdays=%d' % viewdays # meta=siteviews
self.set_status('query', 'siteinfo|siteviews|mostviewed')
elif action == 'sitematrix':
query = hostpath + '?action=sitematrix'
self.set_status('sitematrix', 'all')
elif action == 'sitevisitors':
query = hostpath + (
'?action=query'
'&meta=siteviews&pvismetric=uniques')
query += '&pvisdays=%d' % viewdays # meta=siteviews
self.set_status('query', 'siteviews:uniques')
if not query:
raise ValueError("Could not form query")
query += '&format=json&formatversion=2'
return query | [
"def",
"site",
"(",
"self",
",",
"action",
")",
":",
"query",
"=",
"None",
"viewdays",
"=",
"7",
"hostpath",
"=",
"self",
".",
"uri",
"+",
"self",
".",
"endpoint",
"if",
"action",
"==",
"'siteinfo'",
":",
"query",
"=",
"hostpath",
"+",
"(",
"'?action=query'",
"'&meta=siteinfo|siteviews'",
"'&siprop=general|statistics'",
"'&list=mostviewed&pvimlimit=max'",
")",
"query",
"+=",
"'&pvisdays=%d'",
"%",
"viewdays",
"# meta=siteviews",
"self",
".",
"set_status",
"(",
"'query'",
",",
"'siteinfo|siteviews|mostviewed'",
")",
"elif",
"action",
"==",
"'sitematrix'",
":",
"query",
"=",
"hostpath",
"+",
"'?action=sitematrix'",
"self",
".",
"set_status",
"(",
"'sitematrix'",
",",
"'all'",
")",
"elif",
"action",
"==",
"'sitevisitors'",
":",
"query",
"=",
"hostpath",
"+",
"(",
"'?action=query'",
"'&meta=siteviews&pvismetric=uniques'",
")",
"query",
"+=",
"'&pvisdays=%d'",
"%",
"viewdays",
"# meta=siteviews",
"self",
".",
"set_status",
"(",
"'query'",
",",
"'siteviews:uniques'",
")",
"if",
"not",
"query",
":",
"raise",
"ValueError",
"(",
"\"Could not form query\"",
")",
"query",
"+=",
"'&format=json&formatversion=2'",
"return",
"query"
] | Returns site query | [
"Returns",
"site",
"query"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L329-L360 |
4,257 | siznax/wptools | wptools/query.py | WPToolsQuery.wikidata | def wikidata(self, title, wikibase=None):
"""
Returns Wikidata query string
"""
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.variant or self.lang,
PROPS="aliases|info|claims|descriptions|labels|sitelinks")
if wikibase:
query += "&ids=%s" % wikibase
elif title:
title = safequote(title)
query += "&sites=%swiki" % self.lang
query += "&titles=%s" % title
self.set_status('wikidata', wikibase or title)
return query | python | def wikidata(self, title, wikibase=None):
"""
Returns Wikidata query string
"""
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.variant or self.lang,
PROPS="aliases|info|claims|descriptions|labels|sitelinks")
if wikibase:
query += "&ids=%s" % wikibase
elif title:
title = safequote(title)
query += "&sites=%swiki" % self.lang
query += "&titles=%s" % title
self.set_status('wikidata', wikibase or title)
return query | [
"def",
"wikidata",
"(",
"self",
",",
"title",
",",
"wikibase",
"=",
"None",
")",
":",
"self",
".",
"domain",
"=",
"'www.wikidata.org'",
"self",
".",
"uri",
"=",
"self",
".",
"wiki_uri",
"(",
"self",
".",
"domain",
")",
"query",
"=",
"self",
".",
"WIKIDATA",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LANG",
"=",
"self",
".",
"variant",
"or",
"self",
".",
"lang",
",",
"PROPS",
"=",
"\"aliases|info|claims|descriptions|labels|sitelinks\"",
")",
"if",
"wikibase",
":",
"query",
"+=",
"\"&ids=%s\"",
"%",
"wikibase",
"elif",
"title",
":",
"title",
"=",
"safequote",
"(",
"title",
")",
"query",
"+=",
"\"&sites=%swiki\"",
"%",
"self",
".",
"lang",
"query",
"+=",
"\"&titles=%s\"",
"%",
"title",
"self",
".",
"set_status",
"(",
"'wikidata'",
",",
"wikibase",
"or",
"title",
")",
"return",
"query"
] | Returns Wikidata query string | [
"Returns",
"Wikidata",
"query",
"string"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L370-L392 |
4,258 | siznax/wptools | wptools/restbase.py | WPToolsRESTBase._handle_response | def _handle_response(self):
"""
returns RESTBase response if appropriate
"""
content = self.cache['restbase']['info']['content-type']
if content.startswith('text/html'):
html = self.cache['restbase']['response']
if isinstance(html, bytes):
html = html.decode('utf-8')
self.data['html'] = html
return
response = self._load_response('restbase')
http_status = self.cache['restbase']['info']['status']
if http_status == 404:
raise LookupError(self.cache['restbase']['query'])
if self.params.get('endpoint') == '/page/':
msg = "RESTBase /page/ entry points: %s" % response.get('items')
utils.stderr(msg)
del self.cache['restbase']
return
return response | python | def _handle_response(self):
"""
returns RESTBase response if appropriate
"""
content = self.cache['restbase']['info']['content-type']
if content.startswith('text/html'):
html = self.cache['restbase']['response']
if isinstance(html, bytes):
html = html.decode('utf-8')
self.data['html'] = html
return
response = self._load_response('restbase')
http_status = self.cache['restbase']['info']['status']
if http_status == 404:
raise LookupError(self.cache['restbase']['query'])
if self.params.get('endpoint') == '/page/':
msg = "RESTBase /page/ entry points: %s" % response.get('items')
utils.stderr(msg)
del self.cache['restbase']
return
return response | [
"def",
"_handle_response",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"cache",
"[",
"'restbase'",
"]",
"[",
"'info'",
"]",
"[",
"'content-type'",
"]",
"if",
"content",
".",
"startswith",
"(",
"'text/html'",
")",
":",
"html",
"=",
"self",
".",
"cache",
"[",
"'restbase'",
"]",
"[",
"'response'",
"]",
"if",
"isinstance",
"(",
"html",
",",
"bytes",
")",
":",
"html",
"=",
"html",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"data",
"[",
"'html'",
"]",
"=",
"html",
"return",
"response",
"=",
"self",
".",
"_load_response",
"(",
"'restbase'",
")",
"http_status",
"=",
"self",
".",
"cache",
"[",
"'restbase'",
"]",
"[",
"'info'",
"]",
"[",
"'status'",
"]",
"if",
"http_status",
"==",
"404",
":",
"raise",
"LookupError",
"(",
"self",
".",
"cache",
"[",
"'restbase'",
"]",
"[",
"'query'",
"]",
")",
"if",
"self",
".",
"params",
".",
"get",
"(",
"'endpoint'",
")",
"==",
"'/page/'",
":",
"msg",
"=",
"\"RESTBase /page/ entry points: %s\"",
"%",
"response",
".",
"get",
"(",
"'items'",
")",
"utils",
".",
"stderr",
"(",
"msg",
")",
"del",
"self",
".",
"cache",
"[",
"'restbase'",
"]",
"return",
"return",
"response"
] | returns RESTBase response if appropriate | [
"returns",
"RESTBase",
"response",
"if",
"appropriate"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/restbase.py#L41-L65 |
4,259 | siznax/wptools | wptools/restbase.py | WPToolsRESTBase._query | def _query(self, action, qobj):
"""
returns WPToolsQuery string from action
"""
return qobj.restbase(self.params['rest_endpoint'],
self.params.get('title')) | python | def _query(self, action, qobj):
"""
returns WPToolsQuery string from action
"""
return qobj.restbase(self.params['rest_endpoint'],
self.params.get('title')) | [
"def",
"_query",
"(",
"self",
",",
"action",
",",
"qobj",
")",
":",
"return",
"qobj",
".",
"restbase",
"(",
"self",
".",
"params",
"[",
"'rest_endpoint'",
"]",
",",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
")"
] | returns WPToolsQuery string from action | [
"returns",
"WPToolsQuery",
"string",
"from",
"action"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/restbase.py#L67-L72 |
4,260 | siznax/wptools | wptools/restbase.py | WPToolsRESTBase._unpack_images | def _unpack_images(self, rdata):
"""
Set image data from RESTBase response
"""
image = rdata.get('image') # /page/mobile-sections-lead
originalimage = rdata.get('originalimage') # /page/summary
thumbnail = rdata.get('thumbnail') # /page/summary
if image or originalimage or thumbnail:
if 'image' not in self.data:
self.data['image'] = []
def file_url(info):
"""
put image source in url and set file key
"""
if 'source' in info:
info['url'] = info['source']
info['file'] = info['source'].split('/')[-1]
del info['source']
return info
if image:
img = {'kind': 'restbase-image'}
img.update(image)
self.data['image'].append(file_url(img))
if originalimage:
img = {'kind': 'restbase-original'}
img.update(originalimage)
self.data['image'].append(file_url(img))
if thumbnail:
img = {'kind': 'restbase-thumb'}
img.update(thumbnail)
self.data['image'].append(file_url(img)) | python | def _unpack_images(self, rdata):
"""
Set image data from RESTBase response
"""
image = rdata.get('image') # /page/mobile-sections-lead
originalimage = rdata.get('originalimage') # /page/summary
thumbnail = rdata.get('thumbnail') # /page/summary
if image or originalimage or thumbnail:
if 'image' not in self.data:
self.data['image'] = []
def file_url(info):
"""
put image source in url and set file key
"""
if 'source' in info:
info['url'] = info['source']
info['file'] = info['source'].split('/')[-1]
del info['source']
return info
if image:
img = {'kind': 'restbase-image'}
img.update(image)
self.data['image'].append(file_url(img))
if originalimage:
img = {'kind': 'restbase-original'}
img.update(originalimage)
self.data['image'].append(file_url(img))
if thumbnail:
img = {'kind': 'restbase-thumb'}
img.update(thumbnail)
self.data['image'].append(file_url(img)) | [
"def",
"_unpack_images",
"(",
"self",
",",
"rdata",
")",
":",
"image",
"=",
"rdata",
".",
"get",
"(",
"'image'",
")",
"# /page/mobile-sections-lead",
"originalimage",
"=",
"rdata",
".",
"get",
"(",
"'originalimage'",
")",
"# /page/summary",
"thumbnail",
"=",
"rdata",
".",
"get",
"(",
"'thumbnail'",
")",
"# /page/summary",
"if",
"image",
"or",
"originalimage",
"or",
"thumbnail",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"'image'",
"]",
"=",
"[",
"]",
"def",
"file_url",
"(",
"info",
")",
":",
"\"\"\"\n put image source in url and set file key\n \"\"\"",
"if",
"'source'",
"in",
"info",
":",
"info",
"[",
"'url'",
"]",
"=",
"info",
"[",
"'source'",
"]",
"info",
"[",
"'file'",
"]",
"=",
"info",
"[",
"'source'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"del",
"info",
"[",
"'source'",
"]",
"return",
"info",
"if",
"image",
":",
"img",
"=",
"{",
"'kind'",
":",
"'restbase-image'",
"}",
"img",
".",
"update",
"(",
"image",
")",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"file_url",
"(",
"img",
")",
")",
"if",
"originalimage",
":",
"img",
"=",
"{",
"'kind'",
":",
"'restbase-original'",
"}",
"img",
".",
"update",
"(",
"originalimage",
")",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"file_url",
"(",
"img",
")",
")",
"if",
"thumbnail",
":",
"img",
"=",
"{",
"'kind'",
":",
"'restbase-thumb'",
"}",
"img",
".",
"update",
"(",
"thumbnail",
")",
"self",
".",
"data",
"[",
"'image'",
"]",
".",
"append",
"(",
"file_url",
"(",
"img",
")",
")"
] | Set image data from RESTBase response | [
"Set",
"image",
"data",
"from",
"RESTBase",
"response"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/restbase.py#L120-L155 |
4,261 | siznax/wptools | wptools/utils.py | is_text | def is_text(obj, name=None):
"""
returns True if object is text-like
"""
try: # python2
ans = isinstance(obj, basestring)
except NameError: # python3
ans = isinstance(obj, str)
if name:
print("is_text: (%s) %s = %s" % (ans, name, obj.__class__),
file=sys.stderr)
return ans | python | def is_text(obj, name=None):
"""
returns True if object is text-like
"""
try: # python2
ans = isinstance(obj, basestring)
except NameError: # python3
ans = isinstance(obj, str)
if name:
print("is_text: (%s) %s = %s" % (ans, name, obj.__class__),
file=sys.stderr)
return ans | [
"def",
"is_text",
"(",
"obj",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"# python2",
"ans",
"=",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"except",
"NameError",
":",
"# python3",
"ans",
"=",
"isinstance",
"(",
"obj",
",",
"str",
")",
"if",
"name",
":",
"print",
"(",
"\"is_text: (%s) %s = %s\"",
"%",
"(",
"ans",
",",
"name",
",",
"obj",
".",
"__class__",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"ans"
] | returns True if object is text-like | [
"returns",
"True",
"if",
"object",
"is",
"text",
"-",
"like"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L67-L78 |
4,262 | siznax/wptools | wptools/utils.py | json_loads | def json_loads(data):
"""
python-version-safe json.loads
"""
try:
return json.loads(data, encoding='utf-8')
except TypeError:
return json.loads(data.decode('utf-8')) | python | def json_loads(data):
"""
python-version-safe json.loads
"""
try:
return json.loads(data, encoding='utf-8')
except TypeError:
return json.loads(data.decode('utf-8')) | [
"def",
"json_loads",
"(",
"data",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"data",
",",
"encoding",
"=",
"'utf-8'",
")",
"except",
"TypeError",
":",
"return",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | python-version-safe json.loads | [
"python",
"-",
"version",
"-",
"safe",
"json",
".",
"loads"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L90-L97 |
4,263 | siznax/wptools | wptools/utils.py | stderr | def stderr(msg, silent=False):
"""
write msg to stderr if not silent
"""
if not silent:
print(msg, file=sys.stderr) | python | def stderr(msg, silent=False):
"""
write msg to stderr if not silent
"""
if not silent:
print(msg, file=sys.stderr) | [
"def",
"stderr",
"(",
"msg",
",",
"silent",
"=",
"False",
")",
":",
"if",
"not",
"silent",
":",
"print",
"(",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | write msg to stderr if not silent | [
"write",
"msg",
"to",
"stderr",
"if",
"not",
"silent"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L110-L115 |
4,264 | siznax/wptools | wptools/utils.py | template_to_dict | def template_to_dict(tree, debug=0, find=False):
"""
returns wikitext template as dict
debug = 1
prints minimal debug info to stdout
debug > 1
compares _iter() versus _find() results
find = True
sets values from _find() algorithm (default _iter())
"""
# you can compare (most) raw Infobox wikitext like this:
# https://en.wikipedia.org/wiki/TITLE?action=raw§ion=0
obj = defaultdict(str)
errors = []
for item in tree:
try:
name = item.findtext('name').strip()
if debug:
template_to_dict_debug(name, item, debug)
find_val = template_to_dict_find(item, debug) # DEPRECATED
iter_val = template_to_dict_iter(item, debug)
value = iter_val
if find:
value = find_val
if name and value:
obj[name] = value.strip()
except AttributeError:
if isinstance(item, lxml.etree.ElementBase):
name = item.tag.strip()
text = item.text.strip()
if item.tag == 'title':
obj['infobox'] = text
else:
obj[name] = text
except:
errors.append(lxml.etree.tostring(item))
if errors:
obj['errors'] = errors
return dict(obj) | python | def template_to_dict(tree, debug=0, find=False):
"""
returns wikitext template as dict
debug = 1
prints minimal debug info to stdout
debug > 1
compares _iter() versus _find() results
find = True
sets values from _find() algorithm (default _iter())
"""
# you can compare (most) raw Infobox wikitext like this:
# https://en.wikipedia.org/wiki/TITLE?action=raw§ion=0
obj = defaultdict(str)
errors = []
for item in tree:
try:
name = item.findtext('name').strip()
if debug:
template_to_dict_debug(name, item, debug)
find_val = template_to_dict_find(item, debug) # DEPRECATED
iter_val = template_to_dict_iter(item, debug)
value = iter_val
if find:
value = find_val
if name and value:
obj[name] = value.strip()
except AttributeError:
if isinstance(item, lxml.etree.ElementBase):
name = item.tag.strip()
text = item.text.strip()
if item.tag == 'title':
obj['infobox'] = text
else:
obj[name] = text
except:
errors.append(lxml.etree.tostring(item))
if errors:
obj['errors'] = errors
return dict(obj) | [
"def",
"template_to_dict",
"(",
"tree",
",",
"debug",
"=",
"0",
",",
"find",
"=",
"False",
")",
":",
"# you can compare (most) raw Infobox wikitext like this:",
"# https://en.wikipedia.org/wiki/TITLE?action=raw§ion=0",
"obj",
"=",
"defaultdict",
"(",
"str",
")",
"errors",
"=",
"[",
"]",
"for",
"item",
"in",
"tree",
":",
"try",
":",
"name",
"=",
"item",
".",
"findtext",
"(",
"'name'",
")",
".",
"strip",
"(",
")",
"if",
"debug",
":",
"template_to_dict_debug",
"(",
"name",
",",
"item",
",",
"debug",
")",
"find_val",
"=",
"template_to_dict_find",
"(",
"item",
",",
"debug",
")",
"# DEPRECATED",
"iter_val",
"=",
"template_to_dict_iter",
"(",
"item",
",",
"debug",
")",
"value",
"=",
"iter_val",
"if",
"find",
":",
"value",
"=",
"find_val",
"if",
"name",
"and",
"value",
":",
"obj",
"[",
"name",
"]",
"=",
"value",
".",
"strip",
"(",
")",
"except",
"AttributeError",
":",
"if",
"isinstance",
"(",
"item",
",",
"lxml",
".",
"etree",
".",
"ElementBase",
")",
":",
"name",
"=",
"item",
".",
"tag",
".",
"strip",
"(",
")",
"text",
"=",
"item",
".",
"text",
".",
"strip",
"(",
")",
"if",
"item",
".",
"tag",
"==",
"'title'",
":",
"obj",
"[",
"'infobox'",
"]",
"=",
"text",
"else",
":",
"obj",
"[",
"name",
"]",
"=",
"text",
"except",
":",
"errors",
".",
"append",
"(",
"lxml",
".",
"etree",
".",
"tostring",
"(",
"item",
")",
")",
"if",
"errors",
":",
"obj",
"[",
"'errors'",
"]",
"=",
"errors",
"return",
"dict",
"(",
"obj",
")"
] | returns wikitext template as dict
debug = 1
prints minimal debug info to stdout
debug > 1
compares _iter() versus _find() results
find = True
sets values from _find() algorithm (default _iter()) | [
"returns",
"wikitext",
"template",
"as",
"dict"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L118-L168 |
4,265 | siznax/wptools | wptools/utils.py | template_to_dict_debug | def template_to_dict_debug(name, item, debug):
"""
Print debug statements to compare algorithms
"""
if debug == 1:
print("\n%s = " % name)
elif debug > 1:
print("\n%s" % name)
print("=" * 64)
print(lxml.etree.tostring(item))
print() | python | def template_to_dict_debug(name, item, debug):
"""
Print debug statements to compare algorithms
"""
if debug == 1:
print("\n%s = " % name)
elif debug > 1:
print("\n%s" % name)
print("=" * 64)
print(lxml.etree.tostring(item))
print() | [
"def",
"template_to_dict_debug",
"(",
"name",
",",
"item",
",",
"debug",
")",
":",
"if",
"debug",
"==",
"1",
":",
"print",
"(",
"\"\\n%s = \"",
"%",
"name",
")",
"elif",
"debug",
">",
"1",
":",
"print",
"(",
"\"\\n%s\"",
"%",
"name",
")",
"print",
"(",
"\"=\"",
"*",
"64",
")",
"print",
"(",
"lxml",
".",
"etree",
".",
"tostring",
"(",
"item",
")",
")",
"print",
"(",
")"
] | Print debug statements to compare algorithms | [
"Print",
"debug",
"statements",
"to",
"compare",
"algorithms"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L202-L212 |
4,266 | siznax/wptools | wptools/utils.py | template_to_dict_iter_debug | def template_to_dict_iter_debug(elm):
"""
Print expanded element on stdout for debugging
"""
if elm.text is not None:
print(" <%s>%s</%s>" % (elm.tag, elm.text, elm.tag), end='')
if elm.tail is not None:
print(elm.tail)
else:
print()
else:
if elm.tail is not None:
print(" <%s>%s" % (elm.tag, elm.tail))
else:
print(" <%s>" % elm.tag) | python | def template_to_dict_iter_debug(elm):
"""
Print expanded element on stdout for debugging
"""
if elm.text is not None:
print(" <%s>%s</%s>" % (elm.tag, elm.text, elm.tag), end='')
if elm.tail is not None:
print(elm.tail)
else:
print()
else:
if elm.tail is not None:
print(" <%s>%s" % (elm.tag, elm.tail))
else:
print(" <%s>" % elm.tag) | [
"def",
"template_to_dict_iter_debug",
"(",
"elm",
")",
":",
"if",
"elm",
".",
"text",
"is",
"not",
"None",
":",
"print",
"(",
"\" <%s>%s</%s>\"",
"%",
"(",
"elm",
".",
"tag",
",",
"elm",
".",
"text",
",",
"elm",
".",
"tag",
")",
",",
"end",
"=",
"''",
")",
"if",
"elm",
".",
"tail",
"is",
"not",
"None",
":",
"print",
"(",
"elm",
".",
"tail",
")",
"else",
":",
"print",
"(",
")",
"else",
":",
"if",
"elm",
".",
"tail",
"is",
"not",
"None",
":",
"print",
"(",
"\" <%s>%s\"",
"%",
"(",
"elm",
".",
"tag",
",",
"elm",
".",
"tail",
")",
")",
"else",
":",
"print",
"(",
"\" <%s>\"",
"%",
"elm",
".",
"tag",
")"
] | Print expanded element on stdout for debugging | [
"Print",
"expanded",
"element",
"on",
"stdout",
"for",
"debugging"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L280-L294 |
4,267 | siznax/wptools | wptools/utils.py | template_to_text | def template_to_text(tmpl, debug=0):
"""
convert parse tree template to text
"""
tarr = []
for item in tmpl.itertext():
tarr.append(item)
text = "{{%s}}" % "|".join(tarr).strip()
if debug > 1:
print("+ template_to_text:")
print(" %s" % text)
return text | python | def template_to_text(tmpl, debug=0):
"""
convert parse tree template to text
"""
tarr = []
for item in tmpl.itertext():
tarr.append(item)
text = "{{%s}}" % "|".join(tarr).strip()
if debug > 1:
print("+ template_to_text:")
print(" %s" % text)
return text | [
"def",
"template_to_text",
"(",
"tmpl",
",",
"debug",
"=",
"0",
")",
":",
"tarr",
"=",
"[",
"]",
"for",
"item",
"in",
"tmpl",
".",
"itertext",
"(",
")",
":",
"tarr",
".",
"append",
"(",
"item",
")",
"text",
"=",
"\"{{%s}}\"",
"%",
"\"|\"",
".",
"join",
"(",
"tarr",
")",
".",
"strip",
"(",
")",
"if",
"debug",
">",
"1",
":",
"print",
"(",
"\"+ template_to_text:\"",
")",
"print",
"(",
"\" %s\"",
"%",
"text",
")",
"return",
"text"
] | convert parse tree template to text | [
"convert",
"parse",
"tree",
"template",
"to",
"text"
] | 100eaea585c34aa9ad87a9eda8982bb4898f6ec9 | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L297-L311 |
4,268 | phaethon/kamene | kamene/contrib/igmpv3.py | IGMPv3gr.post_build | def post_build(self, p, pay):
"""Called implicitly before a packet is sent.
"""
p += pay
if self.auxdlen != 0:
print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).")
print(" Subsequent Group Records are lost!")
return p | python | def post_build(self, p, pay):
"""Called implicitly before a packet is sent.
"""
p += pay
if self.auxdlen != 0:
print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).")
print(" Subsequent Group Records are lost!")
return p | [
"def",
"post_build",
"(",
"self",
",",
"p",
",",
"pay",
")",
":",
"p",
"+=",
"pay",
"if",
"self",
".",
"auxdlen",
"!=",
"0",
":",
"print",
"(",
"\"NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).\"",
")",
"print",
"(",
"\" Subsequent Group Records are lost!\"",
")",
"return",
"p"
] | Called implicitly before a packet is sent. | [
"Called",
"implicitly",
"before",
"a",
"packet",
"is",
"sent",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmpv3.py#L55-L62 |
4,269 | phaethon/kamene | kamene/contrib/igmpv3.py | IGMPv3.post_build | def post_build(self, p, pay):
"""Called implicitly before a packet is sent to compute and place IGMPv3 checksum.
Parameters:
self The instantiation of an IGMPv3 class
p The IGMPv3 message in hex in network byte order
pay Additional payload for the IGMPv3 message
"""
p += pay
if self.type in [0, 0x31, 0x32, 0x22]: # for these, field is reserved (0)
p = p[:1]+chr(0)+p[2:]
if self.chksum is None:
ck = checksum(p[:2]+p[4:])
p = p[:2]+ck.to_bytes(2, 'big')+p[4:]
return p | python | def post_build(self, p, pay):
"""Called implicitly before a packet is sent to compute and place IGMPv3 checksum.
Parameters:
self The instantiation of an IGMPv3 class
p The IGMPv3 message in hex in network byte order
pay Additional payload for the IGMPv3 message
"""
p += pay
if self.type in [0, 0x31, 0x32, 0x22]: # for these, field is reserved (0)
p = p[:1]+chr(0)+p[2:]
if self.chksum is None:
ck = checksum(p[:2]+p[4:])
p = p[:2]+ck.to_bytes(2, 'big')+p[4:]
return p | [
"def",
"post_build",
"(",
"self",
",",
"p",
",",
"pay",
")",
":",
"p",
"+=",
"pay",
"if",
"self",
".",
"type",
"in",
"[",
"0",
",",
"0x31",
",",
"0x32",
",",
"0x22",
"]",
":",
"# for these, field is reserved (0)",
"p",
"=",
"p",
"[",
":",
"1",
"]",
"+",
"chr",
"(",
"0",
")",
"+",
"p",
"[",
"2",
":",
"]",
"if",
"self",
".",
"chksum",
"is",
"None",
":",
"ck",
"=",
"checksum",
"(",
"p",
"[",
":",
"2",
"]",
"+",
"p",
"[",
"4",
":",
"]",
")",
"p",
"=",
"p",
"[",
":",
"2",
"]",
"+",
"ck",
".",
"to_bytes",
"(",
"2",
",",
"'big'",
")",
"+",
"p",
"[",
"4",
":",
"]",
"return",
"p"
] | Called implicitly before a packet is sent to compute and place IGMPv3 checksum.
Parameters:
self The instantiation of an IGMPv3 class
p The IGMPv3 message in hex in network byte order
pay Additional payload for the IGMPv3 message | [
"Called",
"implicitly",
"before",
"a",
"packet",
"is",
"sent",
"to",
"compute",
"and",
"place",
"IGMPv3",
"checksum",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmpv3.py#L144-L158 |
4,270 | phaethon/kamene | kamene/contrib/igmpv3.py | IGMPv3.mysummary | def mysummary(self):
"""Display a summary of the IGMPv3 object."""
if isinstance(self.underlayer, IP):
return self.underlayer.sprintf("IGMPv3: %IP.src% > %IP.dst% %IGMPv3.type% %IGMPv3.gaddr%")
else:
return self.sprintf("IGMPv3 %IGMPv3.type% %IGMPv3.gaddr%") | python | def mysummary(self):
"""Display a summary of the IGMPv3 object."""
if isinstance(self.underlayer, IP):
return self.underlayer.sprintf("IGMPv3: %IP.src% > %IP.dst% %IGMPv3.type% %IGMPv3.gaddr%")
else:
return self.sprintf("IGMPv3 %IGMPv3.type% %IGMPv3.gaddr%") | [
"def",
"mysummary",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"underlayer",
",",
"IP",
")",
":",
"return",
"self",
".",
"underlayer",
".",
"sprintf",
"(",
"\"IGMPv3: %IP.src% > %IP.dst% %IGMPv3.type% %IGMPv3.gaddr%\"",
")",
"else",
":",
"return",
"self",
".",
"sprintf",
"(",
"\"IGMPv3 %IGMPv3.type% %IGMPv3.gaddr%\"",
")"
] | Display a summary of the IGMPv3 object. | [
"Display",
"a",
"summary",
"of",
"the",
"IGMPv3",
"object",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmpv3.py#L161-L167 |
4,271 | phaethon/kamene | kamene/contrib/igmpv3.py | IGMPv3.adjust_ether | def adjust_ether (self, ip=None, ether=None):
"""Called to explicitely fixup an associated Ethernet header
The function adjusts the ethernet header destination MAC address based on
the destination IP address.
"""
# The rules are:
# 1. send to the group mac address address corresponding to the IP.dst
if ip != None and ip.haslayer(IP) and ether != None and ether.haslayer(Ether):
iplong = atol(ip.dst)
ether.dst = "01:00:5e:%02x:%02x:%02x" % ( (iplong>>16)&0x7F, (iplong>>8)&0xFF, (iplong)&0xFF )
# print "igmpize ip " + ip.dst + " as mac " + ether.dst
return True
else:
return False | python | def adjust_ether (self, ip=None, ether=None):
"""Called to explicitely fixup an associated Ethernet header
The function adjusts the ethernet header destination MAC address based on
the destination IP address.
"""
# The rules are:
# 1. send to the group mac address address corresponding to the IP.dst
if ip != None and ip.haslayer(IP) and ether != None and ether.haslayer(Ether):
iplong = atol(ip.dst)
ether.dst = "01:00:5e:%02x:%02x:%02x" % ( (iplong>>16)&0x7F, (iplong>>8)&0xFF, (iplong)&0xFF )
# print "igmpize ip " + ip.dst + " as mac " + ether.dst
return True
else:
return False | [
"def",
"adjust_ether",
"(",
"self",
",",
"ip",
"=",
"None",
",",
"ether",
"=",
"None",
")",
":",
"# The rules are:",
"# 1. send to the group mac address address corresponding to the IP.dst",
"if",
"ip",
"!=",
"None",
"and",
"ip",
".",
"haslayer",
"(",
"IP",
")",
"and",
"ether",
"!=",
"None",
"and",
"ether",
".",
"haslayer",
"(",
"Ether",
")",
":",
"iplong",
"=",
"atol",
"(",
"ip",
".",
"dst",
")",
"ether",
".",
"dst",
"=",
"\"01:00:5e:%02x:%02x:%02x\"",
"%",
"(",
"(",
"iplong",
">>",
"16",
")",
"&",
"0x7F",
",",
"(",
"iplong",
">>",
"8",
")",
"&",
"0xFF",
",",
"(",
"iplong",
")",
"&",
"0xFF",
")",
"# print \"igmpize ip \" + ip.dst + \" as mac \" + ether.dst ",
"return",
"True",
"else",
":",
"return",
"False"
] | Called to explicitely fixup an associated Ethernet header
The function adjusts the ethernet header destination MAC address based on
the destination IP address. | [
"Called",
"to",
"explicitely",
"fixup",
"an",
"associated",
"Ethernet",
"header"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmpv3.py#L208-L222 |
4,272 | phaethon/kamene | kamene/contrib/igmpv3.py | IGMPv3.adjust_ip | def adjust_ip (self, ip=None):
"""Called to explicitely fixup an associated IP header
The function adjusts the IP header based on conformance rules
and the group address encoded in the IGMP message.
The rules are:
1. Send General Group Query to 224.0.0.1 (all systems)
2. Send Leave Group to 224.0.0.2 (all routers)
3a.Otherwise send the packet to the group address
3b.Send reports/joins to the group address
4. ttl = 1 (RFC 2236, section 2)
5. send the packet with the router alert IP option (RFC 2236, section 2)
"""
if ip != None and ip.haslayer(IP):
if (self.type == 0x11):
if (self.gaddr == "0.0.0.0"):
ip.dst = "224.0.0.1" # IP rule 1
retCode = True
elif isValidMCAddr(self.gaddr):
ip.dst = self.gaddr # IP rule 3a
retCode = True
else:
print("Warning: Using invalid Group Address")
retCode = False
elif ((self.type == 0x17) and isValidMCAddr(self.gaddr)):
ip.dst = "224.0.0.2" # IP rule 2
retCode = True
elif ((self.type == 0x12) or (self.type == 0x16)) and (isValidMCAddr(self.gaddr)):
ip.dst = self.gaddr # IP rule 3b
retCode = True
else:
print("Warning: Using invalid IGMP Type")
retCode = False
else:
print("Warning: No IGMP Group Address set")
retCode = False
if retCode == True:
ip.ttl=1 # IP Rule 4
ip.options=[IPOption_Router_Alert()] # IP rule 5
return retCode | python | def adjust_ip (self, ip=None):
"""Called to explicitely fixup an associated IP header
The function adjusts the IP header based on conformance rules
and the group address encoded in the IGMP message.
The rules are:
1. Send General Group Query to 224.0.0.1 (all systems)
2. Send Leave Group to 224.0.0.2 (all routers)
3a.Otherwise send the packet to the group address
3b.Send reports/joins to the group address
4. ttl = 1 (RFC 2236, section 2)
5. send the packet with the router alert IP option (RFC 2236, section 2)
"""
if ip != None and ip.haslayer(IP):
if (self.type == 0x11):
if (self.gaddr == "0.0.0.0"):
ip.dst = "224.0.0.1" # IP rule 1
retCode = True
elif isValidMCAddr(self.gaddr):
ip.dst = self.gaddr # IP rule 3a
retCode = True
else:
print("Warning: Using invalid Group Address")
retCode = False
elif ((self.type == 0x17) and isValidMCAddr(self.gaddr)):
ip.dst = "224.0.0.2" # IP rule 2
retCode = True
elif ((self.type == 0x12) or (self.type == 0x16)) and (isValidMCAddr(self.gaddr)):
ip.dst = self.gaddr # IP rule 3b
retCode = True
else:
print("Warning: Using invalid IGMP Type")
retCode = False
else:
print("Warning: No IGMP Group Address set")
retCode = False
if retCode == True:
ip.ttl=1 # IP Rule 4
ip.options=[IPOption_Router_Alert()] # IP rule 5
return retCode | [
"def",
"adjust_ip",
"(",
"self",
",",
"ip",
"=",
"None",
")",
":",
"if",
"ip",
"!=",
"None",
"and",
"ip",
".",
"haslayer",
"(",
"IP",
")",
":",
"if",
"(",
"self",
".",
"type",
"==",
"0x11",
")",
":",
"if",
"(",
"self",
".",
"gaddr",
"==",
"\"0.0.0.0\"",
")",
":",
"ip",
".",
"dst",
"=",
"\"224.0.0.1\"",
"# IP rule 1",
"retCode",
"=",
"True",
"elif",
"isValidMCAddr",
"(",
"self",
".",
"gaddr",
")",
":",
"ip",
".",
"dst",
"=",
"self",
".",
"gaddr",
"# IP rule 3a",
"retCode",
"=",
"True",
"else",
":",
"print",
"(",
"\"Warning: Using invalid Group Address\"",
")",
"retCode",
"=",
"False",
"elif",
"(",
"(",
"self",
".",
"type",
"==",
"0x17",
")",
"and",
"isValidMCAddr",
"(",
"self",
".",
"gaddr",
")",
")",
":",
"ip",
".",
"dst",
"=",
"\"224.0.0.2\"",
"# IP rule 2",
"retCode",
"=",
"True",
"elif",
"(",
"(",
"self",
".",
"type",
"==",
"0x12",
")",
"or",
"(",
"self",
".",
"type",
"==",
"0x16",
")",
")",
"and",
"(",
"isValidMCAddr",
"(",
"self",
".",
"gaddr",
")",
")",
":",
"ip",
".",
"dst",
"=",
"self",
".",
"gaddr",
"# IP rule 3b",
"retCode",
"=",
"True",
"else",
":",
"print",
"(",
"\"Warning: Using invalid IGMP Type\"",
")",
"retCode",
"=",
"False",
"else",
":",
"print",
"(",
"\"Warning: No IGMP Group Address set\"",
")",
"retCode",
"=",
"False",
"if",
"retCode",
"==",
"True",
":",
"ip",
".",
"ttl",
"=",
"1",
"# IP Rule 4",
"ip",
".",
"options",
"=",
"[",
"IPOption_Router_Alert",
"(",
")",
"]",
"# IP rule 5",
"return",
"retCode"
] | Called to explicitely fixup an associated IP header
The function adjusts the IP header based on conformance rules
and the group address encoded in the IGMP message.
The rules are:
1. Send General Group Query to 224.0.0.1 (all systems)
2. Send Leave Group to 224.0.0.2 (all routers)
3a.Otherwise send the packet to the group address
3b.Send reports/joins to the group address
4. ttl = 1 (RFC 2236, section 2)
5. send the packet with the router alert IP option (RFC 2236, section 2) | [
"Called",
"to",
"explicitely",
"fixup",
"an",
"associated",
"IP",
"header"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmpv3.py#L225-L264 |
4,273 | phaethon/kamene | kamene/contrib/ospf.py | ospf_lsa_checksum | def ospf_lsa_checksum(lsa):
""" Fletcher checksum for OSPF LSAs, returned as a 2 byte string.
Give the whole LSA packet as argument.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B.
"""
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/>
CHKSUM_OFFSET = 16
if len(lsa) < CHKSUM_OFFSET:
raise Exception("LSA Packet too short (%s bytes)" % len(lsa))
c0 = c1 = 0
# Calculation is done with checksum set to zero
lsa = lsa[:CHKSUM_OFFSET] + lsa[CHKSUM_OFFSET + 2:]
for char in lsa[2:]: # leave out age
c0 += char
c1 += c0
c0 %= 255
c1 %= 255
x = ((len(lsa) - CHKSUM_OFFSET - 1) * c0 - c1) % 255
if (x <= 0):
x += 255
y = 510 - c0 - x
if (y > 255):
y -= 255
checksum = (x << 8) + y
return checksum | python | def ospf_lsa_checksum(lsa):
""" Fletcher checksum for OSPF LSAs, returned as a 2 byte string.
Give the whole LSA packet as argument.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B.
"""
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/>
CHKSUM_OFFSET = 16
if len(lsa) < CHKSUM_OFFSET:
raise Exception("LSA Packet too short (%s bytes)" % len(lsa))
c0 = c1 = 0
# Calculation is done with checksum set to zero
lsa = lsa[:CHKSUM_OFFSET] + lsa[CHKSUM_OFFSET + 2:]
for char in lsa[2:]: # leave out age
c0 += char
c1 += c0
c0 %= 255
c1 %= 255
x = ((len(lsa) - CHKSUM_OFFSET - 1) * c0 - c1) % 255
if (x <= 0):
x += 255
y = 510 - c0 - x
if (y > 255):
y -= 255
checksum = (x << 8) + y
return checksum | [
"def",
"ospf_lsa_checksum",
"(",
"lsa",
")",
":",
"# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/>",
"CHKSUM_OFFSET",
"=",
"16",
"if",
"len",
"(",
"lsa",
")",
"<",
"CHKSUM_OFFSET",
":",
"raise",
"Exception",
"(",
"\"LSA Packet too short (%s bytes)\"",
"%",
"len",
"(",
"lsa",
")",
")",
"c0",
"=",
"c1",
"=",
"0",
"# Calculation is done with checksum set to zero",
"lsa",
"=",
"lsa",
"[",
":",
"CHKSUM_OFFSET",
"]",
"+",
"lsa",
"[",
"CHKSUM_OFFSET",
"+",
"2",
":",
"]",
"for",
"char",
"in",
"lsa",
"[",
"2",
":",
"]",
":",
"# leave out age",
"c0",
"+=",
"char",
"c1",
"+=",
"c0",
"c0",
"%=",
"255",
"c1",
"%=",
"255",
"x",
"=",
"(",
"(",
"len",
"(",
"lsa",
")",
"-",
"CHKSUM_OFFSET",
"-",
"1",
")",
"*",
"c0",
"-",
"c1",
")",
"%",
"255",
"if",
"(",
"x",
"<=",
"0",
")",
":",
"x",
"+=",
"255",
"y",
"=",
"510",
"-",
"c0",
"-",
"x",
"if",
"(",
"y",
">",
"255",
")",
":",
"y",
"-=",
"255",
"checksum",
"=",
"(",
"x",
"<<",
"8",
")",
"+",
"y",
"return",
"checksum"
] | Fletcher checksum for OSPF LSAs, returned as a 2 byte string.
Give the whole LSA packet as argument.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. | [
"Fletcher",
"checksum",
"for",
"OSPF",
"LSAs",
"returned",
"as",
"a",
"2",
"byte",
"string",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/ospf.py#L208-L243 |
4,274 | phaethon/kamene | kamene/contrib/ospf.py | _LSAGuessPayloadClass | def _LSAGuessPayloadClass(p, **kargs):
""" Guess the correct LSA class for a given payload """
# This is heavily based on scapy-cdp.py by Nicolas Bareil and Arnaud Ebalard
# XXX: This only works if all payload
cls = conf.raw_layer
if len(p) >= 4:
typ = p[3]
clsname = _OSPF_LSclasses.get(typ, "Raw")
cls = globals()[clsname]
return cls(p, **kargs) | python | def _LSAGuessPayloadClass(p, **kargs):
""" Guess the correct LSA class for a given payload """
# This is heavily based on scapy-cdp.py by Nicolas Bareil and Arnaud Ebalard
# XXX: This only works if all payload
cls = conf.raw_layer
if len(p) >= 4:
typ = p[3]
clsname = _OSPF_LSclasses.get(typ, "Raw")
cls = globals()[clsname]
return cls(p, **kargs) | [
"def",
"_LSAGuessPayloadClass",
"(",
"p",
",",
"*",
"*",
"kargs",
")",
":",
"# This is heavily based on scapy-cdp.py by Nicolas Bareil and Arnaud Ebalard",
"# XXX: This only works if all payload",
"cls",
"=",
"conf",
".",
"raw_layer",
"if",
"len",
"(",
"p",
")",
">=",
"4",
":",
"typ",
"=",
"p",
"[",
"3",
"]",
"clsname",
"=",
"_OSPF_LSclasses",
".",
"get",
"(",
"typ",
",",
"\"Raw\"",
")",
"cls",
"=",
"globals",
"(",
")",
"[",
"clsname",
"]",
"return",
"cls",
"(",
"p",
",",
"*",
"*",
"kargs",
")"
] | Guess the correct LSA class for a given payload | [
"Guess",
"the",
"correct",
"LSA",
"class",
"for",
"a",
"given",
"payload"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/ospf.py#L283-L292 |
4,275 | phaethon/kamene | kamene/modules/geoip.py | locate_ip | def locate_ip(ip):
"""Get geographic coordinates from IP using geoip database"""
ip=map(int,ip.split("."))
ip = ip[3]+(ip[2]<<8)+(ip[1]<<16)+(ip[0]<<24)
cloc = country_loc_kdb.get_base()
db = IP_country_kdb.get_base()
d=0
f=len(db)-1
while (f-d) > 1:
guess = (d+f)/2
if ip > db[guess][0]:
d = guess
else:
f = guess
s,e,c = db[guess]
if s <= ip and ip <= e:
return cloc.get(c,None) | python | def locate_ip(ip):
"""Get geographic coordinates from IP using geoip database"""
ip=map(int,ip.split("."))
ip = ip[3]+(ip[2]<<8)+(ip[1]<<16)+(ip[0]<<24)
cloc = country_loc_kdb.get_base()
db = IP_country_kdb.get_base()
d=0
f=len(db)-1
while (f-d) > 1:
guess = (d+f)/2
if ip > db[guess][0]:
d = guess
else:
f = guess
s,e,c = db[guess]
if s <= ip and ip <= e:
return cloc.get(c,None) | [
"def",
"locate_ip",
"(",
"ip",
")",
":",
"ip",
"=",
"map",
"(",
"int",
",",
"ip",
".",
"split",
"(",
"\".\"",
")",
")",
"ip",
"=",
"ip",
"[",
"3",
"]",
"+",
"(",
"ip",
"[",
"2",
"]",
"<<",
"8",
")",
"+",
"(",
"ip",
"[",
"1",
"]",
"<<",
"16",
")",
"+",
"(",
"ip",
"[",
"0",
"]",
"<<",
"24",
")",
"cloc",
"=",
"country_loc_kdb",
".",
"get_base",
"(",
")",
"db",
"=",
"IP_country_kdb",
".",
"get_base",
"(",
")",
"d",
"=",
"0",
"f",
"=",
"len",
"(",
"db",
")",
"-",
"1",
"while",
"(",
"f",
"-",
"d",
")",
">",
"1",
":",
"guess",
"=",
"(",
"d",
"+",
"f",
")",
"/",
"2",
"if",
"ip",
">",
"db",
"[",
"guess",
"]",
"[",
"0",
"]",
":",
"d",
"=",
"guess",
"else",
":",
"f",
"=",
"guess",
"s",
",",
"e",
",",
"c",
"=",
"db",
"[",
"guess",
"]",
"if",
"s",
"<=",
"ip",
"and",
"ip",
"<=",
"e",
":",
"return",
"cloc",
".",
"get",
"(",
"c",
",",
"None",
")"
] | Get geographic coordinates from IP using geoip database | [
"Get",
"geographic",
"coordinates",
"from",
"IP",
"using",
"geoip",
"database"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/modules/geoip.py#L52-L70 |
4,276 | phaethon/kamene | kamene/layers/inet6.py | AS_resolver6._resolve_one | def _resolve_one(self, ip):
"""
overloaded version to provide a Whois resolution on the
embedded IPv4 address if the address is 6to4 or Teredo.
Otherwise, the native IPv6 address is passed.
"""
if in6_isaddr6to4(ip): # for 6to4, use embedded @
tmp = inet_pton(socket.AF_INET6, ip)
addr = inet_ntop(socket.AF_INET, tmp[2:6])
elif in6_isaddrTeredo(ip): # for Teredo, use mapped address
addr = teredoAddrExtractInfo(ip)[2]
else:
addr = ip
_, asn, desc = AS_resolver_riswhois._resolve_one(self, addr)
return ip,asn,desc | python | def _resolve_one(self, ip):
"""
overloaded version to provide a Whois resolution on the
embedded IPv4 address if the address is 6to4 or Teredo.
Otherwise, the native IPv6 address is passed.
"""
if in6_isaddr6to4(ip): # for 6to4, use embedded @
tmp = inet_pton(socket.AF_INET6, ip)
addr = inet_ntop(socket.AF_INET, tmp[2:6])
elif in6_isaddrTeredo(ip): # for Teredo, use mapped address
addr = teredoAddrExtractInfo(ip)[2]
else:
addr = ip
_, asn, desc = AS_resolver_riswhois._resolve_one(self, addr)
return ip,asn,desc | [
"def",
"_resolve_one",
"(",
"self",
",",
"ip",
")",
":",
"if",
"in6_isaddr6to4",
"(",
"ip",
")",
":",
"# for 6to4, use embedded @",
"tmp",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"ip",
")",
"addr",
"=",
"inet_ntop",
"(",
"socket",
".",
"AF_INET",
",",
"tmp",
"[",
"2",
":",
"6",
"]",
")",
"elif",
"in6_isaddrTeredo",
"(",
"ip",
")",
":",
"# for Teredo, use mapped address",
"addr",
"=",
"teredoAddrExtractInfo",
"(",
"ip",
")",
"[",
"2",
"]",
"else",
":",
"addr",
"=",
"ip",
"_",
",",
"asn",
",",
"desc",
"=",
"AS_resolver_riswhois",
".",
"_resolve_one",
"(",
"self",
",",
"addr",
")",
"return",
"ip",
",",
"asn",
",",
"desc"
] | overloaded version to provide a Whois resolution on the
embedded IPv4 address if the address is 6to4 or Teredo.
Otherwise, the native IPv6 address is passed. | [
"overloaded",
"version",
"to",
"provide",
"a",
"Whois",
"resolution",
"on",
"the",
"embedded",
"IPv4",
"address",
"if",
"the",
"address",
"is",
"6to4",
"or",
"Teredo",
".",
"Otherwise",
"the",
"native",
"IPv6",
"address",
"is",
"passed",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/inet6.py#L2882-L2899 |
4,277 | phaethon/kamene | kamene/utils6.py | in6_6to4ExtractAddr | def in6_6to4ExtractAddr(addr):
"""
Extract IPv4 address embbeded in 6to4 address. Passed address must be
a 6to4 addrees. None is returned on error.
"""
try:
addr = inet_pton(socket.AF_INET6, addr)
except:
return None
if addr[:2] != b" \x02":
return None
return inet_ntop(socket.AF_INET, addr[2:6]) | python | def in6_6to4ExtractAddr(addr):
"""
Extract IPv4 address embbeded in 6to4 address. Passed address must be
a 6to4 addrees. None is returned on error.
"""
try:
addr = inet_pton(socket.AF_INET6, addr)
except:
return None
if addr[:2] != b" \x02":
return None
return inet_ntop(socket.AF_INET, addr[2:6]) | [
"def",
"in6_6to4ExtractAddr",
"(",
"addr",
")",
":",
"try",
":",
"addr",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"addr",
")",
"except",
":",
"return",
"None",
"if",
"addr",
"[",
":",
"2",
"]",
"!=",
"b\" \\x02\"",
":",
"return",
"None",
"return",
"inet_ntop",
"(",
"socket",
".",
"AF_INET",
",",
"addr",
"[",
"2",
":",
"6",
"]",
")"
] | Extract IPv4 address embbeded in 6to4 address. Passed address must be
a 6to4 addrees. None is returned on error. | [
"Extract",
"IPv4",
"address",
"embbeded",
"in",
"6to4",
"address",
".",
"Passed",
"address",
"must",
"be",
"a",
"6to4",
"addrees",
".",
"None",
"is",
"returned",
"on",
"error",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils6.py#L386-L397 |
4,278 | phaethon/kamene | kamene/utils6.py | in6_getLocalUniquePrefix | def in6_getLocalUniquePrefix():
"""
Returns a pseudo-randomly generated Local Unique prefix. Function
follows recommandation of Section 3.2.2 of RFC 4193 for prefix
generation.
"""
# Extracted from RFC 1305 (NTP) :
# NTP timestamps are represented as a 64-bit unsigned fixed-point number,
# in seconds relative to 0h on 1 January 1900. The integer part is in the
# first 32 bits and the fraction part in the last 32 bits.
# epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0)
# x = time.time()
# from time import gmtime, strftime, gmtime, mktime
# delta = mktime(gmtime(0)) - mktime(self.epoch)
# x = x-delta
tod = time.time() # time of day. Will bother with epoch later
i = int(tod)
j = int((tod - i)*(2**32))
tod = struct.pack("!II", i,j)
# TODO: Add some check regarding system address gathering
rawmac = get_if_raw_hwaddr(conf.iface6)
mac = b":".join(map(lambda x: b"%.02x" % ord(x), list(rawmac)))
# construct modified EUI-64 ID
eui64 = inet_pton(socket.AF_INET6, '::' + in6_mactoifaceid(mac))[8:]
import sha
globalid = sha.new(tod+eui64).digest()[:5]
return inet_ntop(socket.AF_INET6, b'\xfd' + globalid + b'\x00'*10) | python | def in6_getLocalUniquePrefix():
"""
Returns a pseudo-randomly generated Local Unique prefix. Function
follows recommandation of Section 3.2.2 of RFC 4193 for prefix
generation.
"""
# Extracted from RFC 1305 (NTP) :
# NTP timestamps are represented as a 64-bit unsigned fixed-point number,
# in seconds relative to 0h on 1 January 1900. The integer part is in the
# first 32 bits and the fraction part in the last 32 bits.
# epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0)
# x = time.time()
# from time import gmtime, strftime, gmtime, mktime
# delta = mktime(gmtime(0)) - mktime(self.epoch)
# x = x-delta
tod = time.time() # time of day. Will bother with epoch later
i = int(tod)
j = int((tod - i)*(2**32))
tod = struct.pack("!II", i,j)
# TODO: Add some check regarding system address gathering
rawmac = get_if_raw_hwaddr(conf.iface6)
mac = b":".join(map(lambda x: b"%.02x" % ord(x), list(rawmac)))
# construct modified EUI-64 ID
eui64 = inet_pton(socket.AF_INET6, '::' + in6_mactoifaceid(mac))[8:]
import sha
globalid = sha.new(tod+eui64).digest()[:5]
return inet_ntop(socket.AF_INET6, b'\xfd' + globalid + b'\x00'*10) | [
"def",
"in6_getLocalUniquePrefix",
"(",
")",
":",
"# Extracted from RFC 1305 (NTP) :",
"# NTP timestamps are represented as a 64-bit unsigned fixed-point number, ",
"# in seconds relative to 0h on 1 January 1900. The integer part is in the ",
"# first 32 bits and the fraction part in the last 32 bits.",
"# epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0) ",
"# x = time.time()",
"# from time import gmtime, strftime, gmtime, mktime",
"# delta = mktime(gmtime(0)) - mktime(self.epoch)",
"# x = x-delta",
"tod",
"=",
"time",
".",
"time",
"(",
")",
"# time of day. Will bother with epoch later",
"i",
"=",
"int",
"(",
"tod",
")",
"j",
"=",
"int",
"(",
"(",
"tod",
"-",
"i",
")",
"*",
"(",
"2",
"**",
"32",
")",
")",
"tod",
"=",
"struct",
".",
"pack",
"(",
"\"!II\"",
",",
"i",
",",
"j",
")",
"# TODO: Add some check regarding system address gathering",
"rawmac",
"=",
"get_if_raw_hwaddr",
"(",
"conf",
".",
"iface6",
")",
"mac",
"=",
"b\":\"",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"b\"%.02x\"",
"%",
"ord",
"(",
"x",
")",
",",
"list",
"(",
"rawmac",
")",
")",
")",
"# construct modified EUI-64 ID",
"eui64",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"'::'",
"+",
"in6_mactoifaceid",
"(",
"mac",
")",
")",
"[",
"8",
":",
"]",
"import",
"sha",
"globalid",
"=",
"sha",
".",
"new",
"(",
"tod",
"+",
"eui64",
")",
".",
"digest",
"(",
")",
"[",
":",
"5",
"]",
"return",
"inet_ntop",
"(",
"socket",
".",
"AF_INET6",
",",
"b'\\xfd'",
"+",
"globalid",
"+",
"b'\\x00'",
"*",
"10",
")"
] | Returns a pseudo-randomly generated Local Unique prefix. Function
follows recommandation of Section 3.2.2 of RFC 4193 for prefix
generation. | [
"Returns",
"a",
"pseudo",
"-",
"randomly",
"generated",
"Local",
"Unique",
"prefix",
".",
"Function",
"follows",
"recommandation",
"of",
"Section",
"3",
".",
"2",
".",
"2",
"of",
"RFC",
"4193",
"for",
"prefix",
"generation",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils6.py#L400-L428 |
4,279 | phaethon/kamene | kamene/utils6.py | in6_getnsmac | def in6_getnsmac(a): # return multicast Ethernet address associated with multicast v6 destination
"""
Return the multicast mac address associated with provided
IPv6 address. Passed address must be in network format.
"""
a = struct.unpack('16B', a)[-4:]
mac = '33:33:'
mac += (':'.join(map(lambda x: '%.2x' %x, a)))
return mac | python | def in6_getnsmac(a): # return multicast Ethernet address associated with multicast v6 destination
"""
Return the multicast mac address associated with provided
IPv6 address. Passed address must be in network format.
"""
a = struct.unpack('16B', a)[-4:]
mac = '33:33:'
mac += (':'.join(map(lambda x: '%.2x' %x, a)))
return mac | [
"def",
"in6_getnsmac",
"(",
"a",
")",
":",
"# return multicast Ethernet address associated with multicast v6 destination",
"a",
"=",
"struct",
".",
"unpack",
"(",
"'16B'",
",",
"a",
")",
"[",
"-",
"4",
":",
"]",
"mac",
"=",
"'33:33:'",
"mac",
"+=",
"(",
"':'",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"'%.2x'",
"%",
"x",
",",
"a",
")",
")",
")",
"return",
"mac"
] | Return the multicast mac address associated with provided
IPv6 address. Passed address must be in network format. | [
"Return",
"the",
"multicast",
"mac",
"address",
"associated",
"with",
"provided",
"IPv6",
"address",
".",
"Passed",
"address",
"must",
"be",
"in",
"network",
"format",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils6.py#L646-L655 |
4,280 | phaethon/kamene | kamene/arch/windows/__init__.py | _where | def _where(filename, dirs=[], env="PATH"):
"""Find file in current dir or system path"""
if not isinstance(dirs, list):
dirs = [dirs]
if glob(filename):
return filename
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
for path in paths:
for match in glob(os.path.join(path, filename)):
if match:
return os.path.normpath(match)
raise IOError("File not found: %s" % filename) | python | def _where(filename, dirs=[], env="PATH"):
"""Find file in current dir or system path"""
if not isinstance(dirs, list):
dirs = [dirs]
if glob(filename):
return filename
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
for path in paths:
for match in glob(os.path.join(path, filename)):
if match:
return os.path.normpath(match)
raise IOError("File not found: %s" % filename) | [
"def",
"_where",
"(",
"filename",
",",
"dirs",
"=",
"[",
"]",
",",
"env",
"=",
"\"PATH\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"dirs",
",",
"list",
")",
":",
"dirs",
"=",
"[",
"dirs",
"]",
"if",
"glob",
"(",
"filename",
")",
":",
"return",
"filename",
"paths",
"=",
"[",
"os",
".",
"curdir",
"]",
"+",
"os",
".",
"environ",
"[",
"env",
"]",
".",
"split",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
"+",
"dirs",
"for",
"path",
"in",
"paths",
":",
"for",
"match",
"in",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
":",
"if",
"match",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"match",
")",
"raise",
"IOError",
"(",
"\"File not found: %s\"",
"%",
"filename",
")"
] | Find file in current dir or system path | [
"Find",
"file",
"in",
"current",
"dir",
"or",
"system",
"path"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/arch/windows/__init__.py#L30-L41 |
4,281 | phaethon/kamene | kamene/arch/windows/__init__.py | win_find_exe | def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
"""Find executable in current dir, system path or given ProgramFiles subdir"""
for fn in [filename, filename+".exe"]:
try:
if installsubdir is None:
path = _where(fn)
else:
path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
except IOError:
path = filename
else:
break
return path | python | def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
"""Find executable in current dir, system path or given ProgramFiles subdir"""
for fn in [filename, filename+".exe"]:
try:
if installsubdir is None:
path = _where(fn)
else:
path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
except IOError:
path = filename
else:
break
return path | [
"def",
"win_find_exe",
"(",
"filename",
",",
"installsubdir",
"=",
"None",
",",
"env",
"=",
"\"ProgramFiles\"",
")",
":",
"for",
"fn",
"in",
"[",
"filename",
",",
"filename",
"+",
"\".exe\"",
"]",
":",
"try",
":",
"if",
"installsubdir",
"is",
"None",
":",
"path",
"=",
"_where",
"(",
"fn",
")",
"else",
":",
"path",
"=",
"_where",
"(",
"fn",
",",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"env",
"]",
",",
"installsubdir",
")",
"]",
")",
"except",
"IOError",
":",
"path",
"=",
"filename",
"else",
":",
"break",
"return",
"path"
] | Find executable in current dir, system path or given ProgramFiles subdir | [
"Find",
"executable",
"in",
"current",
"dir",
"system",
"path",
"or",
"given",
"ProgramFiles",
"subdir"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/arch/windows/__init__.py#L43-L55 |
4,282 | phaethon/kamene | kamene/arch/windows/__init__.py | NetworkInterface.init_loopback | def init_loopback(self, data):
"""Just initialize the object for our Pseudo Loopback"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
self.mac = data["mac"]
self.guid = data["guid"]
self.ip = "127.0.0.1" | python | def init_loopback(self, data):
"""Just initialize the object for our Pseudo Loopback"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
self.mac = data["mac"]
self.guid = data["guid"]
self.ip = "127.0.0.1" | [
"def",
"init_loopback",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"self",
".",
"description",
"=",
"data",
"[",
"'description'",
"]",
"self",
".",
"win_index",
"=",
"data",
"[",
"'win_index'",
"]",
"self",
".",
"mac",
"=",
"data",
"[",
"\"mac\"",
"]",
"self",
".",
"guid",
"=",
"data",
"[",
"\"guid\"",
"]",
"self",
".",
"ip",
"=",
"\"127.0.0.1\""
] | Just initialize the object for our Pseudo Loopback | [
"Just",
"initialize",
"the",
"object",
"for",
"our",
"Pseudo",
"Loopback"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/arch/windows/__init__.py#L120-L127 |
4,283 | phaethon/kamene | kamene/arch/windows/__init__.py | NetworkInterface.update | def update(self, data):
"""Update info about network interface according to given dnet dictionary"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
# Other attributes are optional
if conf.use_winpcapy:
self._update_pcapdata()
try:
self.ip = socket.inet_ntoa(get_if_raw_addr(data['guid']))
except (KeyError, AttributeError, NameError):
pass
try:
self.mac = data['mac']
except KeyError:
pass | python | def update(self, data):
"""Update info about network interface according to given dnet dictionary"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
# Other attributes are optional
if conf.use_winpcapy:
self._update_pcapdata()
try:
self.ip = socket.inet_ntoa(get_if_raw_addr(data['guid']))
except (KeyError, AttributeError, NameError):
pass
try:
self.mac = data['mac']
except KeyError:
pass | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"self",
".",
"description",
"=",
"data",
"[",
"'description'",
"]",
"self",
".",
"win_index",
"=",
"data",
"[",
"'win_index'",
"]",
"# Other attributes are optional",
"if",
"conf",
".",
"use_winpcapy",
":",
"self",
".",
"_update_pcapdata",
"(",
")",
"try",
":",
"self",
".",
"ip",
"=",
"socket",
".",
"inet_ntoa",
"(",
"get_if_raw_addr",
"(",
"data",
"[",
"'guid'",
"]",
")",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
",",
"NameError",
")",
":",
"pass",
"try",
":",
"self",
".",
"mac",
"=",
"data",
"[",
"'mac'",
"]",
"except",
"KeyError",
":",
"pass"
] | Update info about network interface according to given dnet dictionary | [
"Update",
"info",
"about",
"network",
"interface",
"according",
"to",
"given",
"dnet",
"dictionary"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/arch/windows/__init__.py#L129-L144 |
4,284 | phaethon/kamene | kamene/arch/windows/__init__.py | NetworkInterfaceDict.pcap_name | def pcap_name(self, devname):
"""Return pcap device name for given Windows device name."""
try:
pcap_name = self.data[devname].pcap_name
except KeyError:
raise ValueError("Unknown network interface %r" % devname)
else:
return pcap_name | python | def pcap_name(self, devname):
"""Return pcap device name for given Windows device name."""
try:
pcap_name = self.data[devname].pcap_name
except KeyError:
raise ValueError("Unknown network interface %r" % devname)
else:
return pcap_name | [
"def",
"pcap_name",
"(",
"self",
",",
"devname",
")",
":",
"try",
":",
"pcap_name",
"=",
"self",
".",
"data",
"[",
"devname",
"]",
".",
"pcap_name",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Unknown network interface %r\"",
"%",
"devname",
")",
"else",
":",
"return",
"pcap_name"
] | Return pcap device name for given Windows device name. | [
"Return",
"pcap",
"device",
"name",
"for",
"given",
"Windows",
"device",
"name",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/arch/windows/__init__.py#L175-L183 |
4,285 | phaethon/kamene | kamene/layers/dns.py | bitmap2RRlist | def bitmap2RRlist(bitmap):
"""
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
"""
# RFC 4034, 4.1.2. The Type Bit Maps Field
RRlist = []
while bitmap:
if len(bitmap) < 2:
warning("bitmap too short (%i)" % len(bitmap))
return
#window_block = ord(bitmap[0]) # window number
window_block = (bitmap[0]) # window number
offset = 256*window_block # offset of the Ressource Record
#bitmap_len = ord(bitmap[0]) # length of the bitmap in bytes
bitmap_len = (bitmap[1]) # length of the bitmap in bytes
if bitmap_len <= 0 or bitmap_len > 32:
warning("bitmap length is no valid (%i)" % bitmap_len)
return
tmp_bitmap = bitmap[2:2+bitmap_len]
# Let's compare each bit of tmp_bitmap and compute the real RR value
for b in range(len(tmp_bitmap)):
v = 128
for i in range(8):
#if ord(tmp_bitmap[b]) & v:
if (tmp_bitmap[b]) & v:
# each of the RR is encoded as a bit
RRlist += [ offset + b*8 + i ]
v = v >> 1
# Next block if any
bitmap = bitmap[2+bitmap_len:]
return RRlist | python | def bitmap2RRlist(bitmap):
"""
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
"""
# RFC 4034, 4.1.2. The Type Bit Maps Field
RRlist = []
while bitmap:
if len(bitmap) < 2:
warning("bitmap too short (%i)" % len(bitmap))
return
#window_block = ord(bitmap[0]) # window number
window_block = (bitmap[0]) # window number
offset = 256*window_block # offset of the Ressource Record
#bitmap_len = ord(bitmap[0]) # length of the bitmap in bytes
bitmap_len = (bitmap[1]) # length of the bitmap in bytes
if bitmap_len <= 0 or bitmap_len > 32:
warning("bitmap length is no valid (%i)" % bitmap_len)
return
tmp_bitmap = bitmap[2:2+bitmap_len]
# Let's compare each bit of tmp_bitmap and compute the real RR value
for b in range(len(tmp_bitmap)):
v = 128
for i in range(8):
#if ord(tmp_bitmap[b]) & v:
if (tmp_bitmap[b]) & v:
# each of the RR is encoded as a bit
RRlist += [ offset + b*8 + i ]
v = v >> 1
# Next block if any
bitmap = bitmap[2+bitmap_len:]
return RRlist | [
"def",
"bitmap2RRlist",
"(",
"bitmap",
")",
":",
"# RFC 4034, 4.1.2. The Type Bit Maps Field",
"RRlist",
"=",
"[",
"]",
"while",
"bitmap",
":",
"if",
"len",
"(",
"bitmap",
")",
"<",
"2",
":",
"warning",
"(",
"\"bitmap too short (%i)\"",
"%",
"len",
"(",
"bitmap",
")",
")",
"return",
"#window_block = ord(bitmap[0]) # window number",
"window_block",
"=",
"(",
"bitmap",
"[",
"0",
"]",
")",
"# window number",
"offset",
"=",
"256",
"*",
"window_block",
"# offset of the Ressource Record",
"#bitmap_len = ord(bitmap[0]) # length of the bitmap in bytes",
"bitmap_len",
"=",
"(",
"bitmap",
"[",
"1",
"]",
")",
"# length of the bitmap in bytes",
"if",
"bitmap_len",
"<=",
"0",
"or",
"bitmap_len",
">",
"32",
":",
"warning",
"(",
"\"bitmap length is no valid (%i)\"",
"%",
"bitmap_len",
")",
"return",
"tmp_bitmap",
"=",
"bitmap",
"[",
"2",
":",
"2",
"+",
"bitmap_len",
"]",
"# Let's compare each bit of tmp_bitmap and compute the real RR value",
"for",
"b",
"in",
"range",
"(",
"len",
"(",
"tmp_bitmap",
")",
")",
":",
"v",
"=",
"128",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"#if ord(tmp_bitmap[b]) & v:",
"if",
"(",
"tmp_bitmap",
"[",
"b",
"]",
")",
"&",
"v",
":",
"# each of the RR is encoded as a bit",
"RRlist",
"+=",
"[",
"offset",
"+",
"b",
"*",
"8",
"+",
"i",
"]",
"v",
"=",
"v",
">>",
"1",
"# Next block if any",
"bitmap",
"=",
"bitmap",
"[",
"2",
"+",
"bitmap_len",
":",
"]",
"return",
"RRlist"
] | Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list. | [
"Decode",
"the",
"Type",
"Bit",
"Maps",
"field",
"of",
"the",
"NSEC",
"Resource",
"Record",
"into",
"an",
"integer",
"list",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/dns.py#L376-L416 |
4,286 | phaethon/kamene | kamene/contrib/gtp.py | IE_Dispatcher | def IE_Dispatcher(s):
"""Choose the correct Information Element class."""
if len(s) < 1:
return Raw(s)
# Get the IE type
ietype = ord(s[0])
cls = ietypecls.get(ietype, Raw)
# if ietype greater than 128 are TLVs
if cls == Raw and ietype & 128 == 128:
cls = IE_NotImplementedTLV
return cls(s) | python | def IE_Dispatcher(s):
"""Choose the correct Information Element class."""
if len(s) < 1:
return Raw(s)
# Get the IE type
ietype = ord(s[0])
cls = ietypecls.get(ietype, Raw)
# if ietype greater than 128 are TLVs
if cls == Raw and ietype & 128 == 128:
cls = IE_NotImplementedTLV
return cls(s) | [
"def",
"IE_Dispatcher",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
"<",
"1",
":",
"return",
"Raw",
"(",
"s",
")",
"# Get the IE type",
"ietype",
"=",
"ord",
"(",
"s",
"[",
"0",
"]",
")",
"cls",
"=",
"ietypecls",
".",
"get",
"(",
"ietype",
",",
"Raw",
")",
"# if ietype greater than 128 are TLVs",
"if",
"cls",
"==",
"Raw",
"and",
"ietype",
"&",
"128",
"==",
"128",
":",
"cls",
"=",
"IE_NotImplementedTLV",
"return",
"cls",
"(",
"s",
")"
] | Choose the correct Information Element class. | [
"Choose",
"the",
"correct",
"Information",
"Element",
"class",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gtp.py#L399-L413 |
4,287 | phaethon/kamene | kamene/plist.py | PacketList.filter | def filter(self, func):
"""Returns a packet list filtered by a truth function"""
return self.__class__(list(filter(func,self.res)),
name="filtered %s"%self.listname) | python | def filter(self, func):
"""Returns a packet list filtered by a truth function"""
return self.__class__(list(filter(func,self.res)),
name="filtered %s"%self.listname) | [
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"filter",
"(",
"func",
",",
"self",
".",
"res",
")",
")",
",",
"name",
"=",
"\"filtered %s\"",
"%",
"self",
".",
"listname",
")"
] | Returns a packet list filtered by a truth function | [
"Returns",
"a",
"packet",
"list",
"filtered",
"by",
"a",
"truth",
"function"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/plist.py#L133-L136 |
4,288 | phaethon/kamene | kamene/plist.py | PacketList.multiplot | def multiplot(self, f, lfilter=None, **kargs):
"""Uses a function that returns a label and a value for this label, then plots all the values label by label"""
d = defaultdict(list)
for i in self.res:
if lfilter and not lfilter(i):
continue
k, v = f(i)
d[k].append(v)
figure = plt.figure()
ax = figure.add_axes(plt.axes())
for i in d:
ax.plot(d[i], **kargs)
return figure | python | def multiplot(self, f, lfilter=None, **kargs):
"""Uses a function that returns a label and a value for this label, then plots all the values label by label"""
d = defaultdict(list)
for i in self.res:
if lfilter and not lfilter(i):
continue
k, v = f(i)
d[k].append(v)
figure = plt.figure()
ax = figure.add_axes(plt.axes())
for i in d:
ax.plot(d[i], **kargs)
return figure | [
"def",
"multiplot",
"(",
"self",
",",
"f",
",",
"lfilter",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"i",
"in",
"self",
".",
"res",
":",
"if",
"lfilter",
"and",
"not",
"lfilter",
"(",
"i",
")",
":",
"continue",
"k",
",",
"v",
"=",
"f",
"(",
"i",
")",
"d",
"[",
"k",
"]",
".",
"append",
"(",
"v",
")",
"figure",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"figure",
".",
"add_axes",
"(",
"plt",
".",
"axes",
"(",
")",
")",
"for",
"i",
"in",
"d",
":",
"ax",
".",
"plot",
"(",
"d",
"[",
"i",
"]",
",",
"*",
"*",
"kargs",
")",
"return",
"figure"
] | Uses a function that returns a label and a value for this label, then plots all the values label by label | [
"Uses",
"a",
"function",
"that",
"returns",
"a",
"label",
"and",
"a",
"value",
"for",
"this",
"label",
"then",
"plots",
"all",
"the",
"values",
"label",
"by",
"label"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/plist.py#L151-L165 |
4,289 | phaethon/kamene | kamene/plist.py | SndRcvList.filter | def filter(self, func):
"""Returns a SndRcv list filtered by a truth function"""
return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.listname) | python | def filter(self, func):
"""Returns a SndRcv list filtered by a truth function"""
return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.listname) | [
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"res",
"if",
"func",
"(",
"*",
"i",
")",
"]",
",",
"name",
"=",
"'filtered %s'",
"%",
"self",
".",
"listname",
")"
] | Returns a SndRcv list filtered by a truth function | [
"Returns",
"a",
"SndRcv",
"list",
"filtered",
"by",
"a",
"truth",
"function"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/plist.py#L504-L506 |
4,290 | phaethon/kamene | kamene/contrib/ppi.py | _PPIGuessPayloadClass | def _PPIGuessPayloadClass(p, **kargs):
""" This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer, and
the remainder of p is added as Raw's payload. If there is no
payload, the remainder of p is added as out's payload.
"""
if len(p) >= 4:
t,pfh_len = struct.unpack("<HH", p[:4])
# Find out if the value t is in the dict _ppi_types.
# If not, return the default TLV class
cls = getPPIType(t, "default")
pfh_len += 4
out = cls(p[:pfh_len], **kargs)
if (out.payload):
out.payload = conf.raw_layer(out.payload.load)
if (len(p) > pfh_len):
out.payload.payload = conf.padding_layer(p[pfh_len:])
elif (len(p) > pfh_len):
out.payload = conf.padding_layer(p[pfh_len:])
else:
out = conf.raw_layer(p, **kargs)
return out | python | def _PPIGuessPayloadClass(p, **kargs):
""" This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer, and
the remainder of p is added as Raw's payload. If there is no
payload, the remainder of p is added as out's payload.
"""
if len(p) >= 4:
t,pfh_len = struct.unpack("<HH", p[:4])
# Find out if the value t is in the dict _ppi_types.
# If not, return the default TLV class
cls = getPPIType(t, "default")
pfh_len += 4
out = cls(p[:pfh_len], **kargs)
if (out.payload):
out.payload = conf.raw_layer(out.payload.load)
if (len(p) > pfh_len):
out.payload.payload = conf.padding_layer(p[pfh_len:])
elif (len(p) > pfh_len):
out.payload = conf.padding_layer(p[pfh_len:])
else:
out = conf.raw_layer(p, **kargs)
return out | [
"def",
"_PPIGuessPayloadClass",
"(",
"p",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"len",
"(",
"p",
")",
">=",
"4",
":",
"t",
",",
"pfh_len",
"=",
"struct",
".",
"unpack",
"(",
"\"<HH\"",
",",
"p",
"[",
":",
"4",
"]",
")",
"# Find out if the value t is in the dict _ppi_types.\r",
"# If not, return the default TLV class\r",
"cls",
"=",
"getPPIType",
"(",
"t",
",",
"\"default\"",
")",
"pfh_len",
"+=",
"4",
"out",
"=",
"cls",
"(",
"p",
"[",
":",
"pfh_len",
"]",
",",
"*",
"*",
"kargs",
")",
"if",
"(",
"out",
".",
"payload",
")",
":",
"out",
".",
"payload",
"=",
"conf",
".",
"raw_layer",
"(",
"out",
".",
"payload",
".",
"load",
")",
"if",
"(",
"len",
"(",
"p",
")",
">",
"pfh_len",
")",
":",
"out",
".",
"payload",
".",
"payload",
"=",
"conf",
".",
"padding_layer",
"(",
"p",
"[",
"pfh_len",
":",
"]",
")",
"elif",
"(",
"len",
"(",
"p",
")",
">",
"pfh_len",
")",
":",
"out",
".",
"payload",
"=",
"conf",
".",
"padding_layer",
"(",
"p",
"[",
"pfh_len",
":",
"]",
")",
"else",
":",
"out",
"=",
"conf",
".",
"raw_layer",
"(",
"p",
",",
"*",
"*",
"kargs",
")",
"return",
"out"
] | This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer, and
the remainder of p is added as Raw's payload. If there is no
payload, the remainder of p is added as out's payload. | [
"This",
"function",
"tells",
"the",
"PacketListField",
"how",
"it",
"should",
"extract",
"the",
"TLVs",
"from",
"the",
"payload",
".",
"We",
"pass",
"cls",
"only",
"the",
"length",
"string",
"pfh_len",
"says",
"it",
"needs",
".",
"If",
"a",
"payload",
"is",
"returned",
"that",
"means",
"part",
"of",
"the",
"sting",
"was",
"unused",
".",
"This",
"converts",
"to",
"a",
"Raw",
"layer",
"and",
"the",
"remainder",
"of",
"p",
"is",
"added",
"as",
"Raw",
"s",
"payload",
".",
"If",
"there",
"is",
"no",
"payload",
"the",
"remainder",
"of",
"p",
"is",
"added",
"as",
"out",
"s",
"payload",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/ppi.py#L38-L62 |
4,291 | phaethon/kamene | kamene/fields.py | Field.i2b | def i2b(self, pkt, x):
"""Convert internal value to internal value"""
if type(x) is str:
x = bytes([ ord(i) for i in x ])
return x | python | def i2b(self, pkt, x):
"""Convert internal value to internal value"""
if type(x) is str:
x = bytes([ ord(i) for i in x ])
return x | [
"def",
"i2b",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"x",
"=",
"bytes",
"(",
"[",
"ord",
"(",
"i",
")",
"for",
"i",
"in",
"x",
"]",
")",
"return",
"x"
] | Convert internal value to internal value | [
"Convert",
"internal",
"value",
"to",
"internal",
"value"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/fields.py#L45-L49 |
4,292 | phaethon/kamene | kamene/fields.py | Field.randval | def randval(self):
"""Return a volatile object whose value is both random and suitable for this field"""
fmtt = self.fmt[-1]
if fmtt in "BHIQ":
return {"B":RandByte,"H":RandShort,"I":RandInt, "Q":RandLong}[fmtt]()
elif fmtt == "s":
if self.fmt[0] in "0123456789":
l = int(self.fmt[:-1])
else:
l = int(self.fmt[1:-1])
return RandBin(l)
else:
warning("no random class for [%s] (fmt=%s)." % (self.name, self.fmt)) | python | def randval(self):
"""Return a volatile object whose value is both random and suitable for this field"""
fmtt = self.fmt[-1]
if fmtt in "BHIQ":
return {"B":RandByte,"H":RandShort,"I":RandInt, "Q":RandLong}[fmtt]()
elif fmtt == "s":
if self.fmt[0] in "0123456789":
l = int(self.fmt[:-1])
else:
l = int(self.fmt[1:-1])
return RandBin(l)
else:
warning("no random class for [%s] (fmt=%s)." % (self.name, self.fmt)) | [
"def",
"randval",
"(",
"self",
")",
":",
"fmtt",
"=",
"self",
".",
"fmt",
"[",
"-",
"1",
"]",
"if",
"fmtt",
"in",
"\"BHIQ\"",
":",
"return",
"{",
"\"B\"",
":",
"RandByte",
",",
"\"H\"",
":",
"RandShort",
",",
"\"I\"",
":",
"RandInt",
",",
"\"Q\"",
":",
"RandLong",
"}",
"[",
"fmtt",
"]",
"(",
")",
"elif",
"fmtt",
"==",
"\"s\"",
":",
"if",
"self",
".",
"fmt",
"[",
"0",
"]",
"in",
"\"0123456789\"",
":",
"l",
"=",
"int",
"(",
"self",
".",
"fmt",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"l",
"=",
"int",
"(",
"self",
".",
"fmt",
"[",
"1",
":",
"-",
"1",
"]",
")",
"return",
"RandBin",
"(",
"l",
")",
"else",
":",
"warning",
"(",
"\"no random class for [%s] (fmt=%s).\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"fmt",
")",
")"
] | Return a volatile object whose value is both random and suitable for this field | [
"Return",
"a",
"volatile",
"object",
"whose",
"value",
"is",
"both",
"random",
"and",
"suitable",
"for",
"this",
"field"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/fields.py#L93-L105 |
4,293 | phaethon/kamene | kamene/utils.py | str2bytes | def str2bytes(x):
"""Convert input argument to bytes"""
if type(x) is bytes:
return x
elif type(x) is str:
return bytes([ ord(i) for i in x ])
else:
return str2bytes(str(x)) | python | def str2bytes(x):
"""Convert input argument to bytes"""
if type(x) is bytes:
return x
elif type(x) is str:
return bytes([ ord(i) for i in x ])
else:
return str2bytes(str(x)) | [
"def",
"str2bytes",
"(",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"bytes",
":",
"return",
"x",
"elif",
"type",
"(",
"x",
")",
"is",
"str",
":",
"return",
"bytes",
"(",
"[",
"ord",
"(",
"i",
")",
"for",
"i",
"in",
"x",
"]",
")",
"else",
":",
"return",
"str2bytes",
"(",
"str",
"(",
"x",
")",
")"
] | Convert input argument to bytes | [
"Convert",
"input",
"argument",
"to",
"bytes"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L41-L48 |
4,294 | phaethon/kamene | kamene/utils.py | is_private_addr | def is_private_addr(x):
"""Returns True if the IPv4 Address is an RFC 1918 private address."""
paddrs = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']
found = False
for ipr in paddrs:
try:
if ipaddress.ip_address(x) in ipaddress.ip_network(ipr):
found = True
continue
except:
break
return found | python | def is_private_addr(x):
"""Returns True if the IPv4 Address is an RFC 1918 private address."""
paddrs = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']
found = False
for ipr in paddrs:
try:
if ipaddress.ip_address(x) in ipaddress.ip_network(ipr):
found = True
continue
except:
break
return found | [
"def",
"is_private_addr",
"(",
"x",
")",
":",
"paddrs",
"=",
"[",
"'10.0.0.0/8'",
",",
"'172.16.0.0/12'",
",",
"'192.168.0.0/16'",
"]",
"found",
"=",
"False",
"for",
"ipr",
"in",
"paddrs",
":",
"try",
":",
"if",
"ipaddress",
".",
"ip_address",
"(",
"x",
")",
"in",
"ipaddress",
".",
"ip_network",
"(",
"ipr",
")",
":",
"found",
"=",
"True",
"continue",
"except",
":",
"break",
"return",
"found"
] | Returns True if the IPv4 Address is an RFC 1918 private address. | [
"Returns",
"True",
"if",
"the",
"IPv4",
"Address",
"is",
"an",
"RFC",
"1918",
"private",
"address",
"."
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L96-L107 |
4,295 | phaethon/kamene | kamene/utils.py | corrupt_bytes | def corrupt_bytes(s, p=0.01, n=None):
"""Corrupt a given percentage or number of bytes from bytes"""
s = bytes(s)
s = array.array("B",s)
l = len(s)
if n is None:
n = max(1,int(l*p))
for i in random.sample(range(l), n):
s[i] = (s[i]+random.randint(1,255))%256
return s.tobytes() | python | def corrupt_bytes(s, p=0.01, n=None):
"""Corrupt a given percentage or number of bytes from bytes"""
s = bytes(s)
s = array.array("B",s)
l = len(s)
if n is None:
n = max(1,int(l*p))
for i in random.sample(range(l), n):
s[i] = (s[i]+random.randint(1,255))%256
return s.tobytes() | [
"def",
"corrupt_bytes",
"(",
"s",
",",
"p",
"=",
"0.01",
",",
"n",
"=",
"None",
")",
":",
"s",
"=",
"bytes",
"(",
"s",
")",
"s",
"=",
"array",
".",
"array",
"(",
"\"B\"",
",",
"s",
")",
"l",
"=",
"len",
"(",
"s",
")",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"l",
"*",
"p",
")",
")",
"for",
"i",
"in",
"random",
".",
"sample",
"(",
"range",
"(",
"l",
")",
",",
"n",
")",
":",
"s",
"[",
"i",
"]",
"=",
"(",
"s",
"[",
"i",
"]",
"+",
"random",
".",
"randint",
"(",
"1",
",",
"255",
")",
")",
"%",
"256",
"return",
"s",
".",
"tobytes",
"(",
")"
] | Corrupt a given percentage or number of bytes from bytes | [
"Corrupt",
"a",
"given",
"percentage",
"or",
"number",
"of",
"bytes",
"from",
"bytes"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L516-L525 |
4,296 | phaethon/kamene | kamene/utils.py | wireshark | def wireshark(pktlist, *args):
"""Run wireshark on a list of packets"""
fname = get_temp_file()
wrpcap(fname, pktlist)
subprocess.Popen([conf.prog.wireshark, "-r", fname] + list(args)) | python | def wireshark(pktlist, *args):
"""Run wireshark on a list of packets"""
fname = get_temp_file()
wrpcap(fname, pktlist)
subprocess.Popen([conf.prog.wireshark, "-r", fname] + list(args)) | [
"def",
"wireshark",
"(",
"pktlist",
",",
"*",
"args",
")",
":",
"fname",
"=",
"get_temp_file",
"(",
")",
"wrpcap",
"(",
"fname",
",",
"pktlist",
")",
"subprocess",
".",
"Popen",
"(",
"[",
"conf",
".",
"prog",
".",
"wireshark",
",",
"\"-r\"",
",",
"fname",
"]",
"+",
"list",
"(",
"args",
")",
")"
] | Run wireshark on a list of packets | [
"Run",
"wireshark",
"on",
"a",
"list",
"of",
"packets"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L1003-L1007 |
4,297 | phaethon/kamene | kamene/utils.py | tdecode | def tdecode(pkt, *args):
"""Run tshark to decode and display the packet. If no args defined uses -V"""
if not args:
args = [ "-V" ]
fname = get_temp_file()
wrpcap(fname,[pkt])
subprocess.call(["tshark", "-r", fname] + list(args)) | python | def tdecode(pkt, *args):
"""Run tshark to decode and display the packet. If no args defined uses -V"""
if not args:
args = [ "-V" ]
fname = get_temp_file()
wrpcap(fname,[pkt])
subprocess.call(["tshark", "-r", fname] + list(args)) | [
"def",
"tdecode",
"(",
"pkt",
",",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"[",
"\"-V\"",
"]",
"fname",
"=",
"get_temp_file",
"(",
")",
"wrpcap",
"(",
"fname",
",",
"[",
"pkt",
"]",
")",
"subprocess",
".",
"call",
"(",
"[",
"\"tshark\"",
",",
"\"-r\"",
",",
"fname",
"]",
"+",
"list",
"(",
"args",
")",
")"
] | Run tshark to decode and display the packet. If no args defined uses -V | [
"Run",
"tshark",
"to",
"decode",
"and",
"display",
"the",
"packet",
".",
"If",
"no",
"args",
"defined",
"uses",
"-",
"V"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L1010-L1016 |
4,298 | phaethon/kamene | kamene/utils.py | hexedit | def hexedit(x):
"""Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit"""
x = bytes(x)
fname = get_temp_file()
with open(fname,"wb") as f:
f.write(x)
subprocess.call([conf.prog.hexedit, fname])
with open(fname, "rb") as f:
x = f.read()
return x | python | def hexedit(x):
"""Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit"""
x = bytes(x)
fname = get_temp_file()
with open(fname,"wb") as f:
f.write(x)
subprocess.call([conf.prog.hexedit, fname])
with open(fname, "rb") as f:
x = f.read()
return x | [
"def",
"hexedit",
"(",
"x",
")",
":",
"x",
"=",
"bytes",
"(",
"x",
")",
"fname",
"=",
"get_temp_file",
"(",
")",
"with",
"open",
"(",
"fname",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"x",
")",
"subprocess",
".",
"call",
"(",
"[",
"conf",
".",
"prog",
".",
"hexedit",
",",
"fname",
"]",
")",
"with",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
"as",
"f",
":",
"x",
"=",
"f",
".",
"read",
"(",
")",
"return",
"x"
] | Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit | [
"Run",
"external",
"hex",
"editor",
"on",
"a",
"packet",
"or",
"bytes",
".",
"Set",
"editor",
"in",
"conf",
".",
"prog",
".",
"hexedit"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L1019-L1028 |
4,299 | phaethon/kamene | kamene/utils.py | RawPcapWriter._write_packet | def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
"""writes a single packet to the pcap file
"""
if caplen is None:
caplen = len(packet)
if wirelen is None:
wirelen = caplen
if sec is None or usec is None:
t=time.time()
it = int(t)
if sec is None:
sec = it
if usec is None:
usec = int(round((t-it)*1000000))
self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen))
self.f.write(packet)
if self.gz and self.sync:
self.f.flush() | python | def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
"""writes a single packet to the pcap file
"""
if caplen is None:
caplen = len(packet)
if wirelen is None:
wirelen = caplen
if sec is None or usec is None:
t=time.time()
it = int(t)
if sec is None:
sec = it
if usec is None:
usec = int(round((t-it)*1000000))
self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen))
self.f.write(packet)
if self.gz and self.sync:
self.f.flush() | [
"def",
"_write_packet",
"(",
"self",
",",
"packet",
",",
"sec",
"=",
"None",
",",
"usec",
"=",
"None",
",",
"caplen",
"=",
"None",
",",
"wirelen",
"=",
"None",
")",
":",
"if",
"caplen",
"is",
"None",
":",
"caplen",
"=",
"len",
"(",
"packet",
")",
"if",
"wirelen",
"is",
"None",
":",
"wirelen",
"=",
"caplen",
"if",
"sec",
"is",
"None",
"or",
"usec",
"is",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"it",
"=",
"int",
"(",
"t",
")",
"if",
"sec",
"is",
"None",
":",
"sec",
"=",
"it",
"if",
"usec",
"is",
"None",
":",
"usec",
"=",
"int",
"(",
"round",
"(",
"(",
"t",
"-",
"it",
")",
"*",
"1000000",
")",
")",
"self",
".",
"f",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"self",
".",
"endian",
"+",
"\"IIII\"",
",",
"sec",
",",
"usec",
",",
"caplen",
",",
"wirelen",
")",
")",
"self",
".",
"f",
".",
"write",
"(",
"packet",
")",
"if",
"self",
".",
"gz",
"and",
"self",
".",
"sync",
":",
"self",
".",
"f",
".",
"flush",
"(",
")"
] | writes a single packet to the pcap file | [
"writes",
"a",
"single",
"packet",
"to",
"the",
"pcap",
"file"
] | 11d4064844f4f68ac5d7546f5633ac7d02082914 | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L905-L922 |
Subsets and Splits