partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | GoldenCheetahClient._request_activity_data | Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') | goldencheetahlib/client.py | def _request_activity_data(self, athlete, filename):
"""Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\')
"""
response = self._get_request(self._activity_endpoint(athlete, filename)).json()
activity = pd.DataFrame(response['RIDE']['SAMPLES'])
activity = activity.rename(columns=ACTIVITY_COLUMN_TRANSLATION)
activity.index = pd.to_timedelta(activity.time, unit='s')
activity.drop('time', axis=1, inplace=True)
return activity[[i for i in ACTIVITY_COLUMN_ORDER if i in activity.columns]] | def _request_activity_data(self, athlete, filename):
"""Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\')
"""
response = self._get_request(self._activity_endpoint(athlete, filename)).json()
activity = pd.DataFrame(response['RIDE']['SAMPLES'])
activity = activity.rename(columns=ACTIVITY_COLUMN_TRANSLATION)
activity.index = pd.to_timedelta(activity.time, unit='s')
activity.drop('time', axis=1, inplace=True)
return activity[[i for i in ACTIVITY_COLUMN_ORDER if i in activity.columns]] | [
"Actually",
"do",
"the",
"request",
"for",
"activity",
"filename",
"This",
"call",
"is",
"slow",
"and",
"therefore",
"this",
"method",
"is",
"memory",
"cached",
"."
] | AartGoossens/goldencheetahlib | python | https://github.com/AartGoossens/goldencheetahlib/blob/ebe57de7d94280674c8440a81f53ac02f0b4eb43/goldencheetahlib/client.py#L112-L128 | [
"def",
"_request_activity_data",
"(",
"self",
",",
"athlete",
",",
"filename",
")",
":",
"response",
"=",
"self",
".",
"_get_request",
"(",
"self",
".",
"_activity_endpoint",
"(",
"athlete",
",",
"filename",
")",
")",
".",
"json",
"(",
")",
"activity",
"=",
"pd",
".",
"DataFrame",
"(",
"response",
"[",
"'RIDE'",
"]",
"[",
"'SAMPLES'",
"]",
")",
"activity",
"=",
"activity",
".",
"rename",
"(",
"columns",
"=",
"ACTIVITY_COLUMN_TRANSLATION",
")",
"activity",
".",
"index",
"=",
"pd",
".",
"to_timedelta",
"(",
"activity",
".",
"time",
",",
"unit",
"=",
"'s'",
")",
"activity",
".",
"drop",
"(",
"'time'",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"return",
"activity",
"[",
"[",
"i",
"for",
"i",
"in",
"ACTIVITY_COLUMN_ORDER",
"if",
"i",
"in",
"activity",
".",
"columns",
"]",
"]"
] | ebe57de7d94280674c8440a81f53ac02f0b4eb43 |
test | GoldenCheetahClient._athlete_endpoint | Construct athlete endpoint from host and athlete name
Keyword arguments:
athlete -- Full athlete name | goldencheetahlib/client.py | def _athlete_endpoint(self, athlete):
"""Construct athlete endpoint from host and athlete name
Keyword arguments:
athlete -- Full athlete name
"""
return '{host}{athlete}'.format(
host=self.host,
athlete=quote_plus(athlete)
) | def _athlete_endpoint(self, athlete):
"""Construct athlete endpoint from host and athlete name
Keyword arguments:
athlete -- Full athlete name
"""
return '{host}{athlete}'.format(
host=self.host,
athlete=quote_plus(athlete)
) | [
"Construct",
"athlete",
"endpoint",
"from",
"host",
"and",
"athlete",
"name"
] | AartGoossens/goldencheetahlib | python | https://github.com/AartGoossens/goldencheetahlib/blob/ebe57de7d94280674c8440a81f53ac02f0b4eb43/goldencheetahlib/client.py#L130-L139 | [
"def",
"_athlete_endpoint",
"(",
"self",
",",
"athlete",
")",
":",
"return",
"'{host}{athlete}'",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"athlete",
"=",
"quote_plus",
"(",
"athlete",
")",
")"
] | ebe57de7d94280674c8440a81f53ac02f0b4eb43 |
test | GoldenCheetahClient._activity_endpoint | Construct activity endpoint from host, athlete name and filename
Keyword arguments:
athlete -- Full athlete name
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') | goldencheetahlib/client.py | def _activity_endpoint(self, athlete, filename):
"""Construct activity endpoint from host, athlete name and filename
Keyword arguments:
athlete -- Full athlete name
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\')
"""
return '{host}{athlete}/activity/{filename}'.format(
host=self.host,
athlete=quote_plus(athlete),
filename=filename
) | def _activity_endpoint(self, athlete, filename):
"""Construct activity endpoint from host, athlete name and filename
Keyword arguments:
athlete -- Full athlete name
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\')
"""
return '{host}{athlete}/activity/{filename}'.format(
host=self.host,
athlete=quote_plus(athlete),
filename=filename
) | [
"Construct",
"activity",
"endpoint",
"from",
"host",
"athlete",
"name",
"and",
"filename"
] | AartGoossens/goldencheetahlib | python | https://github.com/AartGoossens/goldencheetahlib/blob/ebe57de7d94280674c8440a81f53ac02f0b4eb43/goldencheetahlib/client.py#L141-L152 | [
"def",
"_activity_endpoint",
"(",
"self",
",",
"athlete",
",",
"filename",
")",
":",
"return",
"'{host}{athlete}/activity/{filename}'",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"athlete",
"=",
"quote_plus",
"(",
"athlete",
")",
",",
"filename",
"=",
"filename",
")"
] | ebe57de7d94280674c8440a81f53ac02f0b4eb43 |
test | GoldenCheetahClient._get_request | Do actual GET request to GC REST API
Also validates responses.
Keyword arguments:
endpoint -- full endpoint for GET request | goldencheetahlib/client.py | def _get_request(self, endpoint):
"""Do actual GET request to GC REST API
Also validates responses.
Keyword arguments:
endpoint -- full endpoint for GET request
"""
try:
response = requests.get(endpoint)
except requests.exceptions.RequestException:
raise GoldenCheetahNotAvailable(endpoint)
if response.text.startswith('unknown athlete'):
match = re.match(
pattern='unknown athlete (?P<athlete>.+)',
string=response.text)
raise AthleteDoesNotExist(
athlete=match.groupdict()['athlete'])
elif response.text == 'file not found':
match = re.match(
pattern='.+/activity/(?P<filename>.+)',
string=endpoint)
raise ActivityDoesNotExist(
filename=match.groupdict()['filename'])
return response | def _get_request(self, endpoint):
"""Do actual GET request to GC REST API
Also validates responses.
Keyword arguments:
endpoint -- full endpoint for GET request
"""
try:
response = requests.get(endpoint)
except requests.exceptions.RequestException:
raise GoldenCheetahNotAvailable(endpoint)
if response.text.startswith('unknown athlete'):
match = re.match(
pattern='unknown athlete (?P<athlete>.+)',
string=response.text)
raise AthleteDoesNotExist(
athlete=match.groupdict()['athlete'])
elif response.text == 'file not found':
match = re.match(
pattern='.+/activity/(?P<filename>.+)',
string=endpoint)
raise ActivityDoesNotExist(
filename=match.groupdict()['filename'])
return response | [
"Do",
"actual",
"GET",
"request",
"to",
"GC",
"REST",
"API",
"Also",
"validates",
"responses",
"."
] | AartGoossens/goldencheetahlib | python | https://github.com/AartGoossens/goldencheetahlib/blob/ebe57de7d94280674c8440a81f53ac02f0b4eb43/goldencheetahlib/client.py#L155-L181 | [
"def",
"_get_request",
"(",
"self",
",",
"endpoint",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"endpoint",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
":",
"raise",
"GoldenCheetahNotAvailable",
"(",
"endpoint",
")",
"if",
"response",
".",
"text",
".",
"startswith",
"(",
"'unknown athlete'",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
"=",
"'unknown athlete (?P<athlete>.+)'",
",",
"string",
"=",
"response",
".",
"text",
")",
"raise",
"AthleteDoesNotExist",
"(",
"athlete",
"=",
"match",
".",
"groupdict",
"(",
")",
"[",
"'athlete'",
"]",
")",
"elif",
"response",
".",
"text",
"==",
"'file not found'",
":",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
"=",
"'.+/activity/(?P<filename>.+)'",
",",
"string",
"=",
"endpoint",
")",
"raise",
"ActivityDoesNotExist",
"(",
"filename",
"=",
"match",
".",
"groupdict",
"(",
")",
"[",
"'filename'",
"]",
")",
"return",
"response"
] | ebe57de7d94280674c8440a81f53ac02f0b4eb43 |
test | get_version | Return package version as listed in `__version__` in `init.py`. | setup.py | def get_version():
"""
Return package version as listed in `__version__` in `init.py`.
"""
with open(os.path.join(os.path.dirname(__file__), 'argparsetree', '__init__.py')) as init_py:
return re.search('__version__ = [\'"]([^\'"]+)[\'"]', init_py.read()).group(1) | def get_version():
"""
Return package version as listed in `__version__` in `init.py`.
"""
with open(os.path.join(os.path.dirname(__file__), 'argparsetree', '__init__.py')) as init_py:
return re.search('__version__ = [\'"]([^\'"]+)[\'"]', init_py.read()).group(1) | [
"Return",
"package",
"version",
"as",
"listed",
"in",
"__version__",
"in",
"init",
".",
"py",
"."
] | wildfish/argparsetree | python | https://github.com/wildfish/argparsetree/blob/424fb13847c4788cad7084233d008d14e17b901c/setup.py#L16-L21 | [
"def",
"get_version",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'argparsetree'",
",",
"'__init__.py'",
")",
")",
"as",
"init_py",
":",
"return",
"re",
".",
"search",
"(",
"'__version__ = [\\'\"]([^\\'\"]+)[\\'\"]'",
",",
"init_py",
".",
"read",
"(",
")",
")",
".",
"group",
"(",
"1",
")"
] | 424fb13847c4788cad7084233d008d14e17b901c |
test | Happy.create | Creates a Heroku app-setup build.
:param tarball_url: URL of a tarball containing an ``app.json``.
:param env: (optional) Dict containing environment variable overrides.
:param app_name: (optional) Name of the Heroku app to create.
:returns: A tuple with ``(build_id, app_name)``. | happy/__init__.py | def create(self, tarball_url, env=None, app_name=None):
"""Creates a Heroku app-setup build.
:param tarball_url: URL of a tarball containing an ``app.json``.
:param env: (optional) Dict containing environment variable overrides.
:param app_name: (optional) Name of the Heroku app to create.
:returns: A tuple with ``(build_id, app_name)``.
"""
data = self._api.create_build(
tarball_url=tarball_url,
env=env,
app_name=app_name,
)
return (data['id'], data['app']['name']) | def create(self, tarball_url, env=None, app_name=None):
"""Creates a Heroku app-setup build.
:param tarball_url: URL of a tarball containing an ``app.json``.
:param env: (optional) Dict containing environment variable overrides.
:param app_name: (optional) Name of the Heroku app to create.
:returns: A tuple with ``(build_id, app_name)``.
"""
data = self._api.create_build(
tarball_url=tarball_url,
env=env,
app_name=app_name,
)
return (data['id'], data['app']['name']) | [
"Creates",
"a",
"Heroku",
"app",
"-",
"setup",
"build",
"."
] | grampajoe/happy | python | https://github.com/grampajoe/happy/blob/707e056eb033ea010d181f5fab8d44e129ea9906/happy/__init__.py#L18-L32 | [
"def",
"create",
"(",
"self",
",",
"tarball_url",
",",
"env",
"=",
"None",
",",
"app_name",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"_api",
".",
"create_build",
"(",
"tarball_url",
"=",
"tarball_url",
",",
"env",
"=",
"env",
",",
"app_name",
"=",
"app_name",
",",
")",
"return",
"(",
"data",
"[",
"'id'",
"]",
",",
"data",
"[",
"'app'",
"]",
"[",
"'name'",
"]",
")"
] | 707e056eb033ea010d181f5fab8d44e129ea9906 |
test | url_with_auth | if view is string based, must be a full path | djapiauth/utility.py | def url_with_auth(regex, view, kwargs=None, name=None, prefix=''):
"""
if view is string based, must be a full path
"""
from djapiauth.auth import api_auth
if isinstance(view, six.string_types): # view is a string, must be full path
return url(regex, api_auth(import_by_path(prefix + "." + view if prefix else view)))
elif isinstance(view, (list, tuple)): # include
return url(regex, view, name, prefix, **kwargs)
else: # view is an object
return url(regex, api_auth(view)) | def url_with_auth(regex, view, kwargs=None, name=None, prefix=''):
"""
if view is string based, must be a full path
"""
from djapiauth.auth import api_auth
if isinstance(view, six.string_types): # view is a string, must be full path
return url(regex, api_auth(import_by_path(prefix + "." + view if prefix else view)))
elif isinstance(view, (list, tuple)): # include
return url(regex, view, name, prefix, **kwargs)
else: # view is an object
return url(regex, api_auth(view)) | [
"if",
"view",
"is",
"string",
"based",
"must",
"be",
"a",
"full",
"path"
] | feifangit/dj-api-auth | python | https://github.com/feifangit/dj-api-auth/blob/9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b/djapiauth/utility.py#L72-L82 | [
"def",
"url_with_auth",
"(",
"regex",
",",
"view",
",",
"kwargs",
"=",
"None",
",",
"name",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"from",
"djapiauth",
".",
"auth",
"import",
"api_auth",
"if",
"isinstance",
"(",
"view",
",",
"six",
".",
"string_types",
")",
":",
"# view is a string, must be full path",
"return",
"url",
"(",
"regex",
",",
"api_auth",
"(",
"import_by_path",
"(",
"prefix",
"+",
"\".\"",
"+",
"view",
"if",
"prefix",
"else",
"view",
")",
")",
")",
"elif",
"isinstance",
"(",
"view",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# include",
"return",
"url",
"(",
"regex",
",",
"view",
",",
"name",
",",
"prefix",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# view is an object",
"return",
"url",
"(",
"regex",
",",
"api_auth",
"(",
"view",
")",
")"
] | 9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b |
test | traverse_urls | urlpattern: urlpattern object
prefix?? : for multiple level urls defined in different urls.py files
prefixre: compiled regex object
prefixnames: regex text
patternFunc: function to process RegexURLPattern
resolverFunc: function to process RegexURLResolver | djapiauth/utility.py | def traverse_urls(urlpattern, prefixre=[], prefixname=[], patternFunc=None, resolverFunc=None):
"""
urlpattern: urlpattern object
prefix?? : for multiple level urls defined in different urls.py files
prefixre: compiled regex object
prefixnames: regex text
patternFunc: function to process RegexURLPattern
resolverFunc: function to process RegexURLResolver
"""
for u in urlpattern:
if isinstance(u, RegexURLResolver): # inspect sub urls
if resolverFunc:
resolverFunc(u, prefixre, prefixname)
traverse_urls(u.url_patterns,
prefixre + [u.regex, ],
prefixname + [u._regex, ],
patternFunc,
resolverFunc)
else:
if patternFunc:
patternFunc(u, prefixre, prefixname) | def traverse_urls(urlpattern, prefixre=[], prefixname=[], patternFunc=None, resolverFunc=None):
"""
urlpattern: urlpattern object
prefix?? : for multiple level urls defined in different urls.py files
prefixre: compiled regex object
prefixnames: regex text
patternFunc: function to process RegexURLPattern
resolverFunc: function to process RegexURLResolver
"""
for u in urlpattern:
if isinstance(u, RegexURLResolver): # inspect sub urls
if resolverFunc:
resolverFunc(u, prefixre, prefixname)
traverse_urls(u.url_patterns,
prefixre + [u.regex, ],
prefixname + [u._regex, ],
patternFunc,
resolverFunc)
else:
if patternFunc:
patternFunc(u, prefixre, prefixname) | [
"urlpattern",
":",
"urlpattern",
"object"
] | feifangit/dj-api-auth | python | https://github.com/feifangit/dj-api-auth/blob/9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b/djapiauth/utility.py#L90-L113 | [
"def",
"traverse_urls",
"(",
"urlpattern",
",",
"prefixre",
"=",
"[",
"]",
",",
"prefixname",
"=",
"[",
"]",
",",
"patternFunc",
"=",
"None",
",",
"resolverFunc",
"=",
"None",
")",
":",
"for",
"u",
"in",
"urlpattern",
":",
"if",
"isinstance",
"(",
"u",
",",
"RegexURLResolver",
")",
":",
"# inspect sub urls",
"if",
"resolverFunc",
":",
"resolverFunc",
"(",
"u",
",",
"prefixre",
",",
"prefixname",
")",
"traverse_urls",
"(",
"u",
".",
"url_patterns",
",",
"prefixre",
"+",
"[",
"u",
".",
"regex",
",",
"]",
",",
"prefixname",
"+",
"[",
"u",
".",
"_regex",
",",
"]",
",",
"patternFunc",
",",
"resolverFunc",
")",
"else",
":",
"if",
"patternFunc",
":",
"patternFunc",
"(",
"u",
",",
"prefixre",
",",
"prefixname",
")"
] | 9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b |
test | title | returns a random title
.. code-block:: python
>>> d.title()
u'Mrs.'
>>> d.title(['es'])
u'El Sr.'
>>> d.title(None, [GENDER_FEMALE])
u'Mrs.'
:param languages: list of allowed languages. ['en'] if None
:param genders: list of allowed genders. (GENDER_FEMALE, GENDER_MALE) if None | sample_data_utils/people.py | def title(languages=None, genders=None):
"""
returns a random title
.. code-block:: python
>>> d.title()
u'Mrs.'
>>> d.title(['es'])
u'El Sr.'
>>> d.title(None, [GENDER_FEMALE])
u'Mrs.'
:param languages: list of allowed languages. ['en'] if None
:param genders: list of allowed genders. (GENDER_FEMALE, GENDER_MALE) if None
"""
languages = languages or ['en']
genders = genders or (GENDER_FEMALE, GENDER_MALE)
choices = _get_titles(languages)
gender = {'m':0, 'f':1}[random.choice(genders)]
return random.choice(choices)[gender] | def title(languages=None, genders=None):
"""
returns a random title
.. code-block:: python
>>> d.title()
u'Mrs.'
>>> d.title(['es'])
u'El Sr.'
>>> d.title(None, [GENDER_FEMALE])
u'Mrs.'
:param languages: list of allowed languages. ['en'] if None
:param genders: list of allowed genders. (GENDER_FEMALE, GENDER_MALE) if None
"""
languages = languages or ['en']
genders = genders or (GENDER_FEMALE, GENDER_MALE)
choices = _get_titles(languages)
gender = {'m':0, 'f':1}[random.choice(genders)]
return random.choice(choices)[gender] | [
"returns",
"a",
"random",
"title"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/people.py#L32-L54 | [
"def",
"title",
"(",
"languages",
"=",
"None",
",",
"genders",
"=",
"None",
")",
":",
"languages",
"=",
"languages",
"or",
"[",
"'en'",
"]",
"genders",
"=",
"genders",
"or",
"(",
"GENDER_FEMALE",
",",
"GENDER_MALE",
")",
"choices",
"=",
"_get_titles",
"(",
"languages",
")",
"gender",
"=",
"{",
"'m'",
":",
"0",
",",
"'f'",
":",
"1",
"}",
"[",
"random",
".",
"choice",
"(",
"genders",
")",
"]",
"return",
"random",
".",
"choice",
"(",
"choices",
")",
"[",
"gender",
"]"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | person | returns a random tuple representing person information
.. code-block:: python
>>> d.person()
(u'Derren', u'Powell', 'm')
>>> d.person(genders=['f'])
(u'Marge', u'Rodriguez', u'Mrs.', 'f')
>>> d.person(['es'],['m'])
(u'Jacinto', u'Delgado', u'El Sr.', 'm')
:param language:
:param genders: | sample_data_utils/people.py | def person(languages=None, genders=None):
"""
returns a random tuple representing person information
.. code-block:: python
>>> d.person()
(u'Derren', u'Powell', 'm')
>>> d.person(genders=['f'])
(u'Marge', u'Rodriguez', u'Mrs.', 'f')
>>> d.person(['es'],['m'])
(u'Jacinto', u'Delgado', u'El Sr.', 'm')
:param language:
:param genders:
"""
languages = languages or ['en']
genders = genders or (GENDER_FEMALE, GENDER_MALE)
lang = random.choice(languages)
g = random.choice(genders)
t = title([lang], [g])
return first_name([lang], [g]), last_name([lang]), t, g | def person(languages=None, genders=None):
"""
returns a random tuple representing person information
.. code-block:: python
>>> d.person()
(u'Derren', u'Powell', 'm')
>>> d.person(genders=['f'])
(u'Marge', u'Rodriguez', u'Mrs.', 'f')
>>> d.person(['es'],['m'])
(u'Jacinto', u'Delgado', u'El Sr.', 'm')
:param language:
:param genders:
"""
languages = languages or ['en']
genders = genders or (GENDER_FEMALE, GENDER_MALE)
lang = random.choice(languages)
g = random.choice(genders)
t = title([lang], [g])
return first_name([lang], [g]), last_name([lang]), t, g | [
"returns",
"a",
"random",
"tuple",
"representing",
"person",
"information"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/people.py#L64-L87 | [
"def",
"person",
"(",
"languages",
"=",
"None",
",",
"genders",
"=",
"None",
")",
":",
"languages",
"=",
"languages",
"or",
"[",
"'en'",
"]",
"genders",
"=",
"genders",
"or",
"(",
"GENDER_FEMALE",
",",
"GENDER_MALE",
")",
"lang",
"=",
"random",
".",
"choice",
"(",
"languages",
")",
"g",
"=",
"random",
".",
"choice",
"(",
"genders",
")",
"t",
"=",
"title",
"(",
"[",
"lang",
"]",
",",
"[",
"g",
"]",
")",
"return",
"first_name",
"(",
"[",
"lang",
"]",
",",
"[",
"g",
"]",
")",
",",
"last_name",
"(",
"[",
"lang",
"]",
")",
",",
"t",
",",
"g"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | first_name | return a random first name
:return:
>>> from mock import patch
>>> with patch('%s._get_firstnamess' % __name__, lambda *args: ['aaa']):
... first_name()
'Aaa' | sample_data_utils/people.py | def first_name(languages=None, genders=None):
"""
return a random first name
:return:
>>> from mock import patch
>>> with patch('%s._get_firstnamess' % __name__, lambda *args: ['aaa']):
... first_name()
'Aaa'
"""
choices = []
languages = languages or ['en']
genders = genders or [GENDER_MALE, GENDER_FEMALE]
for lang in languages:
for gender in genders:
samples = _get_firstnames(lang, gender)
choices.extend(samples)
return random.choice(choices).title() | def first_name(languages=None, genders=None):
"""
return a random first name
:return:
>>> from mock import patch
>>> with patch('%s._get_firstnamess' % __name__, lambda *args: ['aaa']):
... first_name()
'Aaa'
"""
choices = []
languages = languages or ['en']
genders = genders or [GENDER_MALE, GENDER_FEMALE]
for lang in languages:
for gender in genders:
samples = _get_firstnames(lang, gender)
choices.extend(samples)
return random.choice(choices).title() | [
"return",
"a",
"random",
"first",
"name",
":",
"return",
":"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/people.py#L98-L115 | [
"def",
"first_name",
"(",
"languages",
"=",
"None",
",",
"genders",
"=",
"None",
")",
":",
"choices",
"=",
"[",
"]",
"languages",
"=",
"languages",
"or",
"[",
"'en'",
"]",
"genders",
"=",
"genders",
"or",
"[",
"GENDER_MALE",
",",
"GENDER_FEMALE",
"]",
"for",
"lang",
"in",
"languages",
":",
"for",
"gender",
"in",
"genders",
":",
"samples",
"=",
"_get_firstnames",
"(",
"lang",
",",
"gender",
")",
"choices",
".",
"extend",
"(",
"samples",
")",
"return",
"random",
".",
"choice",
"(",
"choices",
")",
".",
"title",
"(",
")"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | last_name | return a random last name
>>> from mock import patch
>>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']):
... last_name()
'Aaa'
>>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]):
... last_name(['it'])
'It_Lastname' | sample_data_utils/people.py | def last_name(languages=None):
"""
return a random last name
>>> from mock import patch
>>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']):
... last_name()
'Aaa'
>>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]):
... last_name(['it'])
'It_Lastname'
"""
choices = []
languages = languages or ['en']
for lang in languages:
samples = _get_lastnames(lang)
choices.extend(samples)
return random.choice(choices).title() | def last_name(languages=None):
"""
return a random last name
>>> from mock import patch
>>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']):
... last_name()
'Aaa'
>>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]):
... last_name(['it'])
'It_Lastname'
"""
choices = []
languages = languages or ['en']
for lang in languages:
samples = _get_lastnames(lang)
choices.extend(samples)
return random.choice(choices).title() | [
"return",
"a",
"random",
"last",
"name"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/people.py#L118-L135 | [
"def",
"last_name",
"(",
"languages",
"=",
"None",
")",
":",
"choices",
"=",
"[",
"]",
"languages",
"=",
"languages",
"or",
"[",
"'en'",
"]",
"for",
"lang",
"in",
"languages",
":",
"samples",
"=",
"_get_lastnames",
"(",
"lang",
")",
"choices",
".",
"extend",
"(",
"samples",
")",
"return",
"random",
".",
"choice",
"(",
"choices",
")",
".",
"title",
"(",
")"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | lookup_color | Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF' | GChartWrapper/GChart.py | def lookup_color(color):
"""
Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF'
"""
if color is None: return
color = color.lower()
if color in COLOR_MAP:
return COLOR_MAP[color]
return color | def lookup_color(color):
"""
Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF'
"""
if color is None: return
color = color.lower()
if color in COLOR_MAP:
return COLOR_MAP[color]
return color | [
"Returns",
"the",
"hex",
"color",
"for",
"any",
"valid",
"css",
"color",
"name",
">>>",
"lookup_color",
"(",
"aliceblue",
")",
"F0F8FF"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L45-L56 | [
"def",
"lookup_color",
"(",
"color",
")",
":",
"if",
"color",
"is",
"None",
":",
"return",
"color",
"=",
"color",
".",
"lower",
"(",
")",
"if",
"color",
"in",
"COLOR_MAP",
":",
"return",
"COLOR_MAP",
"[",
"color",
"]",
"return",
"color"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | color_args | Color a list of arguments on particular indexes
>>> c = color_args([None,'blue'], 1)
>>> c.next()
None
>>> c.next()
'0000FF' | GChartWrapper/GChart.py | def color_args(args, *indexes):
"""
Color a list of arguments on particular indexes
>>> c = color_args([None,'blue'], 1)
>>> c.next()
None
>>> c.next()
'0000FF'
"""
for i,arg in enumerate(args):
if i in indexes:
yield lookup_color(arg)
else:
yield arg | def color_args(args, *indexes):
"""
Color a list of arguments on particular indexes
>>> c = color_args([None,'blue'], 1)
>>> c.next()
None
>>> c.next()
'0000FF'
"""
for i,arg in enumerate(args):
if i in indexes:
yield lookup_color(arg)
else:
yield arg | [
"Color",
"a",
"list",
"of",
"arguments",
"on",
"particular",
"indexes",
">>>",
"c",
"=",
"color_args",
"(",
"[",
"None",
"blue",
"]",
"1",
")",
">>>",
"c",
".",
"next",
"()",
"None",
">>>",
"c",
".",
"next",
"()",
"0000FF"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L58-L72 | [
"def",
"color_args",
"(",
"args",
",",
"*",
"indexes",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"i",
"in",
"indexes",
":",
"yield",
"lookup_color",
"(",
"arg",
")",
"else",
":",
"yield",
"arg"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.tick | Add tick marks in order of axes by width
APIPARAM: chxtc <axis index>,<length of tick mark> | GChartWrapper/GChart.py | def tick(self, index, length):
"""
Add tick marks in order of axes by width
APIPARAM: chxtc <axis index>,<length of tick mark>
"""
assert int(length) <= 25, 'Width cannot be more than 25'
self.data['ticks'].append('%s,%d'%(index,length))
return self.parent | def tick(self, index, length):
"""
Add tick marks in order of axes by width
APIPARAM: chxtc <axis index>,<length of tick mark>
"""
assert int(length) <= 25, 'Width cannot be more than 25'
self.data['ticks'].append('%s,%d'%(index,length))
return self.parent | [
"Add",
"tick",
"marks",
"in",
"order",
"of",
"axes",
"by",
"width",
"APIPARAM",
":",
"chxtc",
"<axis",
"index",
">",
"<length",
"of",
"tick",
"mark",
">"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L99-L106 | [
"def",
"tick",
"(",
"self",
",",
"index",
",",
"length",
")",
":",
"assert",
"int",
"(",
"length",
")",
"<=",
"25",
",",
"'Width cannot be more than 25'",
"self",
".",
"data",
"[",
"'ticks'",
"]",
".",
"append",
"(",
"'%s,%d'",
"%",
"(",
"index",
",",
"length",
")",
")",
"return",
"self",
".",
"parent"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.type | Define the type of axes you wish to use
atype must be one of x,t,y,r
APIPARAM: chxt | GChartWrapper/GChart.py | def type(self, atype):
"""
Define the type of axes you wish to use
atype must be one of x,t,y,r
APIPARAM: chxt
"""
for char in atype:
assert char in 'xtyr', 'Invalid axes type: %s'%char
if not ',' in atype:
atype = ','.join(atype)
self['chxt'] = atype
return self.parent | def type(self, atype):
"""
Define the type of axes you wish to use
atype must be one of x,t,y,r
APIPARAM: chxt
"""
for char in atype:
assert char in 'xtyr', 'Invalid axes type: %s'%char
if not ',' in atype:
atype = ','.join(atype)
self['chxt'] = atype
return self.parent | [
"Define",
"the",
"type",
"of",
"axes",
"you",
"wish",
"to",
"use",
"atype",
"must",
"be",
"one",
"of",
"x",
"t",
"y",
"r",
"APIPARAM",
":",
"chxt"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L108-L119 | [
"def",
"type",
"(",
"self",
",",
"atype",
")",
":",
"for",
"char",
"in",
"atype",
":",
"assert",
"char",
"in",
"'xtyr'",
",",
"'Invalid axes type: %s'",
"%",
"char",
"if",
"not",
"','",
"in",
"atype",
":",
"atype",
"=",
"','",
".",
"join",
"(",
"atype",
")",
"self",
"[",
"'chxt'",
"]",
"=",
"atype",
"return",
"self",
".",
"parent"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.label | Label each axes one at a time
args are of the form <label 1>,...,<label n>
APIPARAM: chxl | GChartWrapper/GChart.py | def label(self, index, *args):
"""
Label each axes one at a time
args are of the form <label 1>,...,<label n>
APIPARAM: chxl
"""
self.data['labels'].append(
str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','')
)
return self.parent | def label(self, index, *args):
"""
Label each axes one at a time
args are of the form <label 1>,...,<label n>
APIPARAM: chxl
"""
self.data['labels'].append(
str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','')
)
return self.parent | [
"Label",
"each",
"axes",
"one",
"at",
"a",
"time",
"args",
"are",
"of",
"the",
"form",
"<label",
"1",
">",
"...",
"<label",
"n",
">",
"APIPARAM",
":",
"chxl"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L122-L131 | [
"def",
"label",
"(",
"self",
",",
"index",
",",
"*",
"args",
")",
":",
"self",
".",
"data",
"[",
"'labels'",
"]",
".",
"append",
"(",
"str",
"(",
"'%s:|%s'",
"%",
"(",
"index",
",",
"'|'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
")",
")",
".",
"replace",
"(",
"'None'",
",",
"''",
")",
")",
"return",
"self",
".",
"parent"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.range | Set the range of each axis, one at a time
args are of the form <start of range>,<end of range>,<interval>
APIPARAM: chxr | GChartWrapper/GChart.py | def range(self, index, *args):
"""
Set the range of each axis, one at a time
args are of the form <start of range>,<end of range>,<interval>
APIPARAM: chxr
"""
self.data['ranges'].append('%s,%s'%(index,
','.join(map(smart_str, args))))
return self.parent | def range(self, index, *args):
"""
Set the range of each axis, one at a time
args are of the form <start of range>,<end of range>,<interval>
APIPARAM: chxr
"""
self.data['ranges'].append('%s,%s'%(index,
','.join(map(smart_str, args))))
return self.parent | [
"Set",
"the",
"range",
"of",
"each",
"axis",
"one",
"at",
"a",
"time",
"args",
"are",
"of",
"the",
"form",
"<start",
"of",
"range",
">",
"<end",
"of",
"range",
">",
"<interval",
">",
"APIPARAM",
":",
"chxr"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L144-L152 | [
"def",
"range",
"(",
"self",
",",
"index",
",",
"*",
"args",
")",
":",
"self",
".",
"data",
"[",
"'ranges'",
"]",
".",
"append",
"(",
"'%s,%s'",
"%",
"(",
"index",
",",
"','",
".",
"join",
"(",
"map",
"(",
"smart_str",
",",
"args",
")",
")",
")",
")",
"return",
"self",
".",
"parent"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.style | Add style to your axis, one at a time
args are of the form::
<axis color>,
<font size>,
<alignment>,
<drawing control>,
<tick mark color>
APIPARAM: chxs | GChartWrapper/GChart.py | def style(self, index, *args):
"""
Add style to your axis, one at a time
args are of the form::
<axis color>,
<font size>,
<alignment>,
<drawing control>,
<tick mark color>
APIPARAM: chxs
"""
args = color_args(args, 0)
self.data['styles'].append(
','.join([str(index)]+list(map(str,args)))
)
return self.parent | def style(self, index, *args):
"""
Add style to your axis, one at a time
args are of the form::
<axis color>,
<font size>,
<alignment>,
<drawing control>,
<tick mark color>
APIPARAM: chxs
"""
args = color_args(args, 0)
self.data['styles'].append(
','.join([str(index)]+list(map(str,args)))
)
return self.parent | [
"Add",
"style",
"to",
"your",
"axis",
"one",
"at",
"a",
"time",
"args",
"are",
"of",
"the",
"form",
"::",
"<axis",
"color",
">",
"<font",
"size",
">",
"<alignment",
">",
"<drawing",
"control",
">",
"<tick",
"mark",
"color",
">",
"APIPARAM",
":",
"chxs"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L154-L169 | [
"def",
"style",
"(",
"self",
",",
"index",
",",
"*",
"args",
")",
":",
"args",
"=",
"color_args",
"(",
"args",
",",
"0",
")",
"self",
".",
"data",
"[",
"'styles'",
"]",
".",
"append",
"(",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"index",
")",
"]",
"+",
"list",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
")",
")",
"return",
"self",
".",
"parent"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | Axes.render | Render the axes data into the dict data | GChartWrapper/GChart.py | def render(self):
"""Render the axes data into the dict data"""
for opt,values in self.data.items():
if opt == 'ticks':
self['chxtc'] = '|'.join(values)
else:
self['chx%s'%opt[0]] = '|'.join(values)
return self | def render(self):
"""Render the axes data into the dict data"""
for opt,values in self.data.items():
if opt == 'ticks':
self['chxtc'] = '|'.join(values)
else:
self['chx%s'%opt[0]] = '|'.join(values)
return self | [
"Render",
"the",
"axes",
"data",
"into",
"the",
"dict",
"data"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L171-L178 | [
"def",
"render",
"(",
"self",
")",
":",
"for",
"opt",
",",
"values",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"opt",
"==",
"'ticks'",
":",
"self",
"[",
"'chxtc'",
"]",
"=",
"'|'",
".",
"join",
"(",
"values",
")",
"else",
":",
"self",
"[",
"'chx%s'",
"%",
"opt",
"[",
"0",
"]",
"]",
"=",
"'|'",
".",
"join",
"(",
"values",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.fromurl | Reverse a chart URL or dict into a GChart instance
>>> G = GChart.fromurl('http://chart.apis.google.com/chart?...')
>>> G
<GChartWrapper.GChart instance at...>
>>> G.image().save('chart.jpg','JPEG') | GChartWrapper/GChart.py | def fromurl(cls, qs):
"""
Reverse a chart URL or dict into a GChart instance
>>> G = GChart.fromurl('http://chart.apis.google.com/chart?...')
>>> G
<GChartWrapper.GChart instance at...>
>>> G.image().save('chart.jpg','JPEG')
"""
if isinstance(qs, dict):
return cls(**qs)
return cls(**dict(parse_qsl(qs[qs.index('?')+1:]))) | def fromurl(cls, qs):
"""
Reverse a chart URL or dict into a GChart instance
>>> G = GChart.fromurl('http://chart.apis.google.com/chart?...')
>>> G
<GChartWrapper.GChart instance at...>
>>> G.image().save('chart.jpg','JPEG')
"""
if isinstance(qs, dict):
return cls(**qs)
return cls(**dict(parse_qsl(qs[qs.index('?')+1:]))) | [
"Reverse",
"a",
"chart",
"URL",
"or",
"dict",
"into",
"a",
"GChart",
"instance",
">>>",
"G",
"=",
"GChart",
".",
"fromurl",
"(",
"http",
":",
"//",
"chart",
".",
"apis",
".",
"google",
".",
"com",
"/",
"chart?",
"...",
")",
">>>",
"G",
"<GChartWrapper",
".",
"GChart",
"instance",
"at",
"...",
">",
">>>",
"G",
".",
"image",
"()",
".",
"save",
"(",
"chart",
".",
"jpg",
"JPEG",
")"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L203-L214 | [
"def",
"fromurl",
"(",
"cls",
",",
"qs",
")",
":",
"if",
"isinstance",
"(",
"qs",
",",
"dict",
")",
":",
"return",
"cls",
"(",
"*",
"*",
"qs",
")",
"return",
"cls",
"(",
"*",
"*",
"dict",
"(",
"parse_qsl",
"(",
"qs",
"[",
"qs",
".",
"index",
"(",
"'?'",
")",
"+",
"1",
":",
"]",
")",
")",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.map | Creates a map of the defined geography with the given country/state codes
Geography choices are africa, asia, europe, middle_east, south_america, and world
ISO country codes can be found at http://code.google.com/apis/chart/isocodes.html
US state codes can be found at http://code.google.com/apis/chart/statecodes.html
APIPARAMS: chtm & chld | GChartWrapper/GChart.py | def map(self, geo, country_codes):
"""
Creates a map of the defined geography with the given country/state codes
Geography choices are africa, asia, europe, middle_east, south_america, and world
ISO country codes can be found at http://code.google.com/apis/chart/isocodes.html
US state codes can be found at http://code.google.com/apis/chart/statecodes.html
APIPARAMS: chtm & chld
"""
assert geo in GEO, 'Geograpic area %s not recognized'%geo
self._geo = geo
self._ld = country_codes
return self | def map(self, geo, country_codes):
"""
Creates a map of the defined geography with the given country/state codes
Geography choices are africa, asia, europe, middle_east, south_america, and world
ISO country codes can be found at http://code.google.com/apis/chart/isocodes.html
US state codes can be found at http://code.google.com/apis/chart/statecodes.html
APIPARAMS: chtm & chld
"""
assert geo in GEO, 'Geograpic area %s not recognized'%geo
self._geo = geo
self._ld = country_codes
return self | [
"Creates",
"a",
"map",
"of",
"the",
"defined",
"geography",
"with",
"the",
"given",
"country",
"/",
"state",
"codes",
"Geography",
"choices",
"are",
"africa",
"asia",
"europe",
"middle_east",
"south_america",
"and",
"world",
"ISO",
"country",
"codes",
"can",
"be",
"found",
"at",
"http",
":",
"//",
"code",
".",
"google",
".",
"com",
"/",
"apis",
"/",
"chart",
"/",
"isocodes",
".",
"html",
"US",
"state",
"codes",
"can",
"be",
"found",
"at",
"http",
":",
"//",
"code",
".",
"google",
".",
"com",
"/",
"apis",
"/",
"chart",
"/",
"statecodes",
".",
"html",
"APIPARAMS",
":",
"chtm",
"&",
"chld"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L219-L230 | [
"def",
"map",
"(",
"self",
",",
"geo",
",",
"country_codes",
")",
":",
"assert",
"geo",
"in",
"GEO",
",",
"'Geograpic area %s not recognized'",
"%",
"geo",
"self",
".",
"_geo",
"=",
"geo",
"self",
".",
"_ld",
"=",
"country_codes",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.scale | Scales the data down to the given size
args must be of the form::
<data set 1 minimum value>,
<data set 1 maximum value>,
<data set n minimum value>,
<data set n maximum value>
will only work with text encoding!
APIPARAM: chds | GChartWrapper/GChart.py | def scale(self, *args):
"""
Scales the data down to the given size
args must be of the form::
<data set 1 minimum value>,
<data set 1 maximum value>,
<data set n minimum value>,
<data set n maximum value>
will only work with text encoding!
APIPARAM: chds
"""
self._scale = [','.join(map(smart_str, args))]
return self | def scale(self, *args):
"""
Scales the data down to the given size
args must be of the form::
<data set 1 minimum value>,
<data set 1 maximum value>,
<data set n minimum value>,
<data set n maximum value>
will only work with text encoding!
APIPARAM: chds
"""
self._scale = [','.join(map(smart_str, args))]
return self | [
"Scales",
"the",
"data",
"down",
"to",
"the",
"given",
"size",
"args",
"must",
"be",
"of",
"the",
"form",
"::",
"<data",
"set",
"1",
"minimum",
"value",
">",
"<data",
"set",
"1",
"maximum",
"value",
">",
"<data",
"set",
"n",
"minimum",
"value",
">",
"<data",
"set",
"n",
"maximum",
"value",
">",
"will",
"only",
"work",
"with",
"text",
"encoding!",
"APIPARAM",
":",
"chds"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L271-L283 | [
"def",
"scale",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_scale",
"=",
"[",
"','",
".",
"join",
"(",
"map",
"(",
"smart_str",
",",
"args",
")",
")",
"]",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.dataset | Update the chart's dataset, can be two dimensional or contain string data | GChartWrapper/GChart.py | def dataset(self, data, series=''):
"""
Update the chart's dataset, can be two dimensional or contain string data
"""
self._dataset = data
self._series = series
return self | def dataset(self, data, series=''):
"""
Update the chart's dataset, can be two dimensional or contain string data
"""
self._dataset = data
self._series = series
return self | [
"Update",
"the",
"chart",
"s",
"dataset",
"can",
"be",
"two",
"dimensional",
"or",
"contain",
"string",
"data"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L285-L291 | [
"def",
"dataset",
"(",
"self",
",",
"data",
",",
"series",
"=",
"''",
")",
":",
"self",
".",
"_dataset",
"=",
"data",
"self",
".",
"_series",
"=",
"series",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.marker | Defines markers one at a time for your graph
args are of the form::
<marker type>,
<color>,
<data set index>,
<data point>,
<size>,
<priority>
see the official developers doc for the complete spec
APIPARAM: chm | GChartWrapper/GChart.py | def marker(self, *args):
"""
Defines markers one at a time for your graph
args are of the form::
<marker type>,
<color>,
<data set index>,
<data point>,
<size>,
<priority>
see the official developers doc for the complete spec
APIPARAM: chm
"""
if len(args[0]) == 1:
assert args[0] in MARKERS, 'Invalid marker type: %s'%args[0]
assert len(args) <= 6, 'Incorrect arguments %s'%str(args)
args = color_args(args, 1)
self.markers.append(','.join(map(str,args)) )
return self | def marker(self, *args):
"""
Defines markers one at a time for your graph
args are of the form::
<marker type>,
<color>,
<data set index>,
<data point>,
<size>,
<priority>
see the official developers doc for the complete spec
APIPARAM: chm
"""
if len(args[0]) == 1:
assert args[0] in MARKERS, 'Invalid marker type: %s'%args[0]
assert len(args) <= 6, 'Incorrect arguments %s'%str(args)
args = color_args(args, 1)
self.markers.append(','.join(map(str,args)) )
return self | [
"Defines",
"markers",
"one",
"at",
"a",
"time",
"for",
"your",
"graph",
"args",
"are",
"of",
"the",
"form",
"::",
"<marker",
"type",
">",
"<color",
">",
"<data",
"set",
"index",
">",
"<data",
"point",
">",
"<size",
">",
"<priority",
">",
"see",
"the",
"official",
"developers",
"doc",
"for",
"the",
"complete",
"spec",
"APIPARAM",
":",
"chm"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L293-L311 | [
"def",
"marker",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
"[",
"0",
"]",
")",
"==",
"1",
":",
"assert",
"args",
"[",
"0",
"]",
"in",
"MARKERS",
",",
"'Invalid marker type: %s'",
"%",
"args",
"[",
"0",
"]",
"assert",
"len",
"(",
"args",
")",
"<=",
"6",
",",
"'Incorrect arguments %s'",
"%",
"str",
"(",
"args",
")",
"args",
"=",
"color_args",
"(",
"args",
",",
"1",
")",
"self",
".",
"markers",
".",
"append",
"(",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.margin | Set margins for chart area
args are of the form::
<left margin>,
<right margin>,
<top margin>,
<bottom margin>|
<legend width>,
<legend height>
APIPARAM: chma | GChartWrapper/GChart.py | def margin(self, left, right, top, bottom, lwidth=0, lheight=0):
"""
Set margins for chart area
args are of the form::
<left margin>,
<right margin>,
<top margin>,
<bottom margin>|
<legend width>,
<legend height>
APIPARAM: chma
"""
self['chma'] = '%d,%d,%d,%d' % (left, right, top, bottom)
if lwidth or lheight:
self['chma'] += '|%d,%d' % (lwidth, lheight)
return self | def margin(self, left, right, top, bottom, lwidth=0, lheight=0):
"""
Set margins for chart area
args are of the form::
<left margin>,
<right margin>,
<top margin>,
<bottom margin>|
<legend width>,
<legend height>
APIPARAM: chma
"""
self['chma'] = '%d,%d,%d,%d' % (left, right, top, bottom)
if lwidth or lheight:
self['chma'] += '|%d,%d' % (lwidth, lheight)
return self | [
"Set",
"margins",
"for",
"chart",
"area",
"args",
"are",
"of",
"the",
"form",
"::",
"<left",
"margin",
">",
"<right",
"margin",
">",
"<top",
"margin",
">",
"<bottom",
"margin",
">",
"|",
"<legend",
"width",
">",
"<legend",
"height",
">",
"APIPARAM",
":",
"chma"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L313-L329 | [
"def",
"margin",
"(",
"self",
",",
"left",
",",
"right",
",",
"top",
",",
"bottom",
",",
"lwidth",
"=",
"0",
",",
"lheight",
"=",
"0",
")",
":",
"self",
"[",
"'chma'",
"]",
"=",
"'%d,%d,%d,%d'",
"%",
"(",
"left",
",",
"right",
",",
"top",
",",
"bottom",
")",
"if",
"lwidth",
"or",
"lheight",
":",
"self",
"[",
"'chma'",
"]",
"+=",
"'|%d,%d'",
"%",
"(",
"lwidth",
",",
"lheight",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.line | Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls | GChartWrapper/GChart.py | def line(self, *args):
"""
Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls
"""
self.lines.append(','.join(['%.1f'%x for x in map(float,args)]))
return self | def line(self, *args):
"""
Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls
"""
self.lines.append(','.join(['%.1f'%x for x in map(float,args)]))
return self | [
"Called",
"one",
"at",
"a",
"time",
"for",
"each",
"dataset",
"args",
"are",
"of",
"the",
"form",
"::",
"<data",
"set",
"n",
"line",
"thickness",
">",
"<length",
"of",
"line",
"segment",
">",
"<length",
"of",
"blank",
"segment",
">",
"APIPARAM",
":",
"chls"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L331-L341 | [
"def",
"line",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"lines",
".",
"append",
"(",
"','",
".",
"join",
"(",
"[",
"'%.1f'",
"%",
"x",
"for",
"x",
"in",
"map",
"(",
"float",
",",
"args",
")",
"]",
")",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.fill | Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf | GChartWrapper/GChart.py | def fill(self, *args):
"""
Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf
"""
a,b = args[:2]
assert a in ('c','bg','a'), 'Fill type must be bg/c/a not %s'%a
assert b in ('s','lg','ls'), 'Fill style must be s/lg/ls not %s'%b
if len(args) == 3:
args = color_args(args, 2)
else:
args = color_args(args, 3,5)
self.fills.append(','.join(map(str,args)))
return self | def fill(self, *args):
"""
Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf
"""
a,b = args[:2]
assert a in ('c','bg','a'), 'Fill type must be bg/c/a not %s'%a
assert b in ('s','lg','ls'), 'Fill style must be s/lg/ls not %s'%b
if len(args) == 3:
args = color_args(args, 2)
else:
args = color_args(args, 3,5)
self.fills.append(','.join(map(str,args)))
return self | [
"Apply",
"a",
"solid",
"fill",
"to",
"your",
"chart",
"args",
"are",
"of",
"the",
"form",
"<fill",
"type",
">",
"<fill",
"style",
">",
"...",
"fill",
"type",
"must",
"be",
"one",
"of",
"c",
"bg",
"a",
"fill",
"style",
"must",
"be",
"one",
"of",
"s",
"lg",
"ls",
"the",
"rest",
"of",
"the",
"args",
"refer",
"to",
"the",
"particular",
"style",
"APIPARAM",
":",
"chf"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L343-L360 | [
"def",
"fill",
"(",
"self",
",",
"*",
"args",
")",
":",
"a",
",",
"b",
"=",
"args",
"[",
":",
"2",
"]",
"assert",
"a",
"in",
"(",
"'c'",
",",
"'bg'",
",",
"'a'",
")",
",",
"'Fill type must be bg/c/a not %s'",
"%",
"a",
"assert",
"b",
"in",
"(",
"'s'",
",",
"'lg'",
",",
"'ls'",
")",
",",
"'Fill style must be s/lg/ls not %s'",
"%",
"b",
"if",
"len",
"(",
"args",
")",
"==",
"3",
":",
"args",
"=",
"color_args",
"(",
"args",
",",
"2",
")",
"else",
":",
"args",
"=",
"color_args",
"(",
"args",
",",
"3",
",",
"5",
")",
"self",
".",
"fills",
".",
"append",
"(",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.grid | Apply a grid to your chart
args are of the form::
<x axis step size>,
<y axis step size>,
<length of line segment>,
<length of blank segment>
<x offset>,
<y offset>
APIPARAM: chg | GChartWrapper/GChart.py | def grid(self, *args):
"""
Apply a grid to your chart
args are of the form::
<x axis step size>,
<y axis step size>,
<length of line segment>,
<length of blank segment>
<x offset>,
<y offset>
APIPARAM: chg
"""
grids = map(str,map(float,args))
self['chg'] = ','.join(grids).replace('None','')
return self | def grid(self, *args):
"""
Apply a grid to your chart
args are of the form::
<x axis step size>,
<y axis step size>,
<length of line segment>,
<length of blank segment>
<x offset>,
<y offset>
APIPARAM: chg
"""
grids = map(str,map(float,args))
self['chg'] = ','.join(grids).replace('None','')
return self | [
"Apply",
"a",
"grid",
"to",
"your",
"chart",
"args",
"are",
"of",
"the",
"form",
"::",
"<x",
"axis",
"step",
"size",
">",
"<y",
"axis",
"step",
"size",
">",
"<length",
"of",
"line",
"segment",
">",
"<length",
"of",
"blank",
"segment",
">",
"<x",
"offset",
">",
"<y",
"offset",
">",
"APIPARAM",
":",
"chg"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L362-L376 | [
"def",
"grid",
"(",
"self",
",",
"*",
"args",
")",
":",
"grids",
"=",
"map",
"(",
"str",
",",
"map",
"(",
"float",
",",
"args",
")",
")",
"self",
"[",
"'chg'",
"]",
"=",
"','",
".",
"join",
"(",
"grids",
")",
".",
"replace",
"(",
"'None'",
",",
"''",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.color | Add a color for each dataset
args are of the form <color 1>,...<color n>
APIPARAM: chco | GChartWrapper/GChart.py | def color(self, *args):
"""
Add a color for each dataset
args are of the form <color 1>,...<color n>
APIPARAM: chco
"""
args = color_args(args, *range(len(args)))
self['chco'] = ','.join(args)
return self | def color(self, *args):
"""
Add a color for each dataset
args are of the form <color 1>,...<color n>
APIPARAM: chco
"""
args = color_args(args, *range(len(args)))
self['chco'] = ','.join(args)
return self | [
"Add",
"a",
"color",
"for",
"each",
"dataset",
"args",
"are",
"of",
"the",
"form",
"<color",
"1",
">",
"...",
"<color",
"n",
">",
"APIPARAM",
":",
"chco"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L378-L386 | [
"def",
"color",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"=",
"color_args",
"(",
"args",
",",
"*",
"range",
"(",
"len",
"(",
"args",
")",
")",
")",
"self",
"[",
"'chco'",
"]",
"=",
"','",
".",
"join",
"(",
"args",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.label | Add a simple label to your chart
call each time for each dataset
APIPARAM: chl | GChartWrapper/GChart.py | def label(self, *args):
"""
Add a simple label to your chart
call each time for each dataset
APIPARAM: chl
"""
if self['cht'] == 'qr':
self['chl'] = ''.join(map(str,args))
else:
self['chl'] = '|'.join(map(str,args))
return self | def label(self, *args):
"""
Add a simple label to your chart
call each time for each dataset
APIPARAM: chl
"""
if self['cht'] == 'qr':
self['chl'] = ''.join(map(str,args))
else:
self['chl'] = '|'.join(map(str,args))
return self | [
"Add",
"a",
"simple",
"label",
"to",
"your",
"chart",
"call",
"each",
"time",
"for",
"each",
"dataset",
"APIPARAM",
":",
"chl"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L396-L406 | [
"def",
"label",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
"[",
"'cht'",
"]",
"==",
"'qr'",
":",
"self",
"[",
"'chl'",
"]",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
"else",
":",
"self",
"[",
"'chl'",
"]",
"=",
"'|'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.legend_pos | Define a position for your legend to occupy
APIPARAM: chdlp | GChartWrapper/GChart.py | def legend_pos(self, pos):
"""
Define a position for your legend to occupy
APIPARAM: chdlp
"""
assert pos in LEGEND_POSITIONS, 'Unknown legend position: %s'%pos
self['chdlp'] = str(pos)
return self | def legend_pos(self, pos):
"""
Define a position for your legend to occupy
APIPARAM: chdlp
"""
assert pos in LEGEND_POSITIONS, 'Unknown legend position: %s'%pos
self['chdlp'] = str(pos)
return self | [
"Define",
"a",
"position",
"for",
"your",
"legend",
"to",
"occupy",
"APIPARAM",
":",
"chdlp"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L417-L424 | [
"def",
"legend_pos",
"(",
"self",
",",
"pos",
")",
":",
"assert",
"pos",
"in",
"LEGEND_POSITIONS",
",",
"'Unknown legend position: %s'",
"%",
"pos",
"self",
"[",
"'chdlp'",
"]",
"=",
"str",
"(",
"pos",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.title | Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts | GChartWrapper/GChart.py | def title(self, title, *args):
"""
Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts
"""
self['chtt'] = title
if args:
args = color_args(args, 0)
self['chts'] = ','.join(map(str,args))
return self | def title(self, title, *args):
"""
Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts
"""
self['chtt'] = title
if args:
args = color_args(args, 0)
self['chts'] = ','.join(map(str,args))
return self | [
"Add",
"a",
"title",
"to",
"your",
"chart",
"args",
"are",
"optional",
"style",
"params",
"of",
"the",
"form",
"<color",
">",
"<font",
"size",
">",
"APIPARAMS",
":",
"chtt",
"chts"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L426-L436 | [
"def",
"title",
"(",
"self",
",",
"title",
",",
"*",
"args",
")",
":",
"self",
"[",
"'chtt'",
"]",
"=",
"title",
"if",
"args",
":",
"args",
"=",
"color_args",
"(",
"args",
",",
"0",
")",
"self",
"[",
"'chts'",
"]",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.size | Set the size of the chart, args are width,height and can be tuple
APIPARAM: chs | GChartWrapper/GChart.py | def size(self,*args):
"""
Set the size of the chart, args are width,height and can be tuple
APIPARAM: chs
"""
if len(args) == 2:
x,y = map(int,args)
else:
x,y = map(int,args[0])
self.check_size(x,y)
self['chs'] = '%dx%d'%(x,y)
return self | def size(self,*args):
"""
Set the size of the chart, args are width,height and can be tuple
APIPARAM: chs
"""
if len(args) == 2:
x,y = map(int,args)
else:
x,y = map(int,args[0])
self.check_size(x,y)
self['chs'] = '%dx%d'%(x,y)
return self | [
"Set",
"the",
"size",
"of",
"the",
"chart",
"args",
"are",
"width",
"height",
"and",
"can",
"be",
"tuple",
"APIPARAM",
":",
"chs"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L438-L449 | [
"def",
"size",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"x",
",",
"y",
"=",
"map",
"(",
"int",
",",
"args",
")",
"else",
":",
"x",
",",
"y",
"=",
"map",
"(",
"int",
",",
"args",
"[",
"0",
"]",
")",
"self",
".",
"check_size",
"(",
"x",
",",
"y",
")",
"self",
"[",
"'chs'",
"]",
"=",
"'%dx%d'",
"%",
"(",
"x",
",",
"y",
")",
"return",
"self"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.render | Renders the chart context and axes into the dict data | GChartWrapper/GChart.py | def render(self):
"""
Renders the chart context and axes into the dict data
"""
self.update(self.axes.render())
encoder = Encoder(self._encoding, None, self._series)
if not 'chs' in self:
self['chs'] = '300x150'
else:
size = self['chs'].split('x')
assert len(size) == 2, 'Invalid size, must be in the format WxH'
self.check_size(*map(int,size))
assert 'cht' in self, 'No chart type defined, use type method'
self['cht'] = self.check_type(self['cht'])
if ('any' in dir(self._dataset) and self._dataset.any()) or self._dataset:
self['chd'] = encoder.encode(self._dataset)
elif not 'choe' in self:
assert 'chd' in self, 'You must have a dataset, or use chd'
if self._scale:
assert self['chd'].startswith('t'),\
'You must use text encoding with chds'
self['chds'] = ','.join(self._scale)
if self._geo and self._ld:
self['chtm'] = self._geo
self['chld'] = self._ld
if self.lines:
self['chls'] = '|'.join(self.lines)
if self.markers:
self['chm'] = '|'.join(self.markers)
if self.fills:
self['chf'] = '|'.join(self.fills) | def render(self):
"""
Renders the chart context and axes into the dict data
"""
self.update(self.axes.render())
encoder = Encoder(self._encoding, None, self._series)
if not 'chs' in self:
self['chs'] = '300x150'
else:
size = self['chs'].split('x')
assert len(size) == 2, 'Invalid size, must be in the format WxH'
self.check_size(*map(int,size))
assert 'cht' in self, 'No chart type defined, use type method'
self['cht'] = self.check_type(self['cht'])
if ('any' in dir(self._dataset) and self._dataset.any()) or self._dataset:
self['chd'] = encoder.encode(self._dataset)
elif not 'choe' in self:
assert 'chd' in self, 'You must have a dataset, or use chd'
if self._scale:
assert self['chd'].startswith('t'),\
'You must use text encoding with chds'
self['chds'] = ','.join(self._scale)
if self._geo and self._ld:
self['chtm'] = self._geo
self['chld'] = self._ld
if self.lines:
self['chls'] = '|'.join(self.lines)
if self.markers:
self['chm'] = '|'.join(self.markers)
if self.fills:
self['chf'] = '|'.join(self.fills) | [
"Renders",
"the",
"chart",
"context",
"and",
"axes",
"into",
"the",
"dict",
"data"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L461-L491 | [
"def",
"render",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
"self",
".",
"axes",
".",
"render",
"(",
")",
")",
"encoder",
"=",
"Encoder",
"(",
"self",
".",
"_encoding",
",",
"None",
",",
"self",
".",
"_series",
")",
"if",
"not",
"'chs'",
"in",
"self",
":",
"self",
"[",
"'chs'",
"]",
"=",
"'300x150'",
"else",
":",
"size",
"=",
"self",
"[",
"'chs'",
"]",
".",
"split",
"(",
"'x'",
")",
"assert",
"len",
"(",
"size",
")",
"==",
"2",
",",
"'Invalid size, must be in the format WxH'",
"self",
".",
"check_size",
"(",
"*",
"map",
"(",
"int",
",",
"size",
")",
")",
"assert",
"'cht'",
"in",
"self",
",",
"'No chart type defined, use type method'",
"self",
"[",
"'cht'",
"]",
"=",
"self",
".",
"check_type",
"(",
"self",
"[",
"'cht'",
"]",
")",
"if",
"(",
"'any'",
"in",
"dir",
"(",
"self",
".",
"_dataset",
")",
"and",
"self",
".",
"_dataset",
".",
"any",
"(",
")",
")",
"or",
"self",
".",
"_dataset",
":",
"self",
"[",
"'chd'",
"]",
"=",
"encoder",
".",
"encode",
"(",
"self",
".",
"_dataset",
")",
"elif",
"not",
"'choe'",
"in",
"self",
":",
"assert",
"'chd'",
"in",
"self",
",",
"'You must have a dataset, or use chd'",
"if",
"self",
".",
"_scale",
":",
"assert",
"self",
"[",
"'chd'",
"]",
".",
"startswith",
"(",
"'t'",
")",
",",
"'You must use text encoding with chds'",
"self",
"[",
"'chds'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
".",
"_scale",
")",
"if",
"self",
".",
"_geo",
"and",
"self",
".",
"_ld",
":",
"self",
"[",
"'chtm'",
"]",
"=",
"self",
".",
"_geo",
"self",
"[",
"'chld'",
"]",
"=",
"self",
".",
"_ld",
"if",
"self",
".",
"lines",
":",
"self",
"[",
"'chls'",
"]",
"=",
"'|'",
".",
"join",
"(",
"self",
".",
"lines",
")",
"if",
"self",
".",
"markers",
":",
"self",
"[",
"'chm'",
"]",
"=",
"'|'",
".",
"join",
"(",
"self",
".",
"markers",
")",
"if",
"self",
".",
"fills",
":",
"self",
"[",
"'chf'",
"]",
"=",
"'|'",
".",
"join",
"(",
"self",
".",
"fills",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.check_type | Check to see if the type is either in TYPES or fits type name
Returns proper type | GChartWrapper/GChart.py | def check_type(self, type):
"""Check to see if the type is either in TYPES or fits type name
Returns proper type
"""
if type in TYPES:
return type
tdict = dict(zip(TYPES,TYPES))
tdict.update({
'line': 'lc',
'bar': 'bvs',
'pie': 'p',
'venn': 'v',
'scater': 's',
'radar': 'r',
'meter': 'gom',
})
assert type in tdict, 'Invalid chart type: %s'%type
return tdict[type] | def check_type(self, type):
"""Check to see if the type is either in TYPES or fits type name
Returns proper type
"""
if type in TYPES:
return type
tdict = dict(zip(TYPES,TYPES))
tdict.update({
'line': 'lc',
'bar': 'bvs',
'pie': 'p',
'venn': 'v',
'scater': 's',
'radar': 'r',
'meter': 'gom',
})
assert type in tdict, 'Invalid chart type: %s'%type
return tdict[type] | [
"Check",
"to",
"see",
"if",
"the",
"type",
"is",
"either",
"in",
"TYPES",
"or",
"fits",
"type",
"name"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L504-L522 | [
"def",
"check_type",
"(",
"self",
",",
"type",
")",
":",
"if",
"type",
"in",
"TYPES",
":",
"return",
"type",
"tdict",
"=",
"dict",
"(",
"zip",
"(",
"TYPES",
",",
"TYPES",
")",
")",
"tdict",
".",
"update",
"(",
"{",
"'line'",
":",
"'lc'",
",",
"'bar'",
":",
"'bvs'",
",",
"'pie'",
":",
"'p'",
",",
"'venn'",
":",
"'v'",
",",
"'scater'",
":",
"'s'",
",",
"'radar'",
":",
"'r'",
",",
"'meter'",
":",
"'gom'",
",",
"}",
")",
"assert",
"type",
"in",
"tdict",
",",
"'Invalid chart type: %s'",
"%",
"type",
"return",
"tdict",
"[",
"type",
"]"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.url | Returns the rendered URL of the chart | GChartWrapper/GChart.py | def url(self):
"""
Returns the rendered URL of the chart
"""
self.render()
return self._apiurl + '&'.join(self._parts()).replace(' ','+') | def url(self):
"""
Returns the rendered URL of the chart
"""
self.render()
return self._apiurl + '&'.join(self._parts()).replace(' ','+') | [
"Returns",
"the",
"rendered",
"URL",
"of",
"the",
"chart"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L550-L555 | [
"def",
"url",
"(",
"self",
")",
":",
"self",
".",
"render",
"(",
")",
"return",
"self",
".",
"_apiurl",
"+",
"'&'",
".",
"join",
"(",
"self",
".",
"_parts",
"(",
")",
")",
".",
"replace",
"(",
"' '",
",",
"'+'",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.show | Shows the chart URL in a webbrowser
Other arguments passed to webbrowser.open | GChartWrapper/GChart.py | def show(self, *args, **kwargs):
"""
Shows the chart URL in a webbrowser
Other arguments passed to webbrowser.open
"""
from webbrowser import open as webopen
return webopen(str(self), *args, **kwargs) | def show(self, *args, **kwargs):
"""
Shows the chart URL in a webbrowser
Other arguments passed to webbrowser.open
"""
from webbrowser import open as webopen
return webopen(str(self), *args, **kwargs) | [
"Shows",
"the",
"chart",
"URL",
"in",
"a",
"webbrowser"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L558-L565 | [
"def",
"show",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"webbrowser",
"import",
"open",
"as",
"webopen",
"return",
"webopen",
"(",
"str",
"(",
"self",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.save | Download the chart from the URL into a filename as a PNG
The filename defaults to the chart title (chtt) if any | GChartWrapper/GChart.py | def save(self, fname=None):
"""
Download the chart from the URL into a filename as a PNG
The filename defaults to the chart title (chtt) if any
"""
if not fname:
fname = self.getname()
assert fname != None, 'You must specify a filename to save to'
if not fname.endswith('.png'):
fname += '.png'
try:
urlretrieve(self.url, fname)
except Exception:
raise IOError('Problem saving %s to file'%fname)
return fname | def save(self, fname=None):
"""
Download the chart from the URL into a filename as a PNG
The filename defaults to the chart title (chtt) if any
"""
if not fname:
fname = self.getname()
assert fname != None, 'You must specify a filename to save to'
if not fname.endswith('.png'):
fname += '.png'
try:
urlretrieve(self.url, fname)
except Exception:
raise IOError('Problem saving %s to file'%fname)
return fname | [
"Download",
"the",
"chart",
"from",
"the",
"URL",
"into",
"a",
"filename",
"as",
"a",
"PNG"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L567-L582 | [
"def",
"save",
"(",
"self",
",",
"fname",
"=",
"None",
")",
":",
"if",
"not",
"fname",
":",
"fname",
"=",
"self",
".",
"getname",
"(",
")",
"assert",
"fname",
"!=",
"None",
",",
"'You must specify a filename to save to'",
"if",
"not",
"fname",
".",
"endswith",
"(",
"'.png'",
")",
":",
"fname",
"+=",
"'.png'",
"try",
":",
"urlretrieve",
"(",
"self",
".",
"url",
",",
"fname",
")",
"except",
"Exception",
":",
"raise",
"IOError",
"(",
"'Problem saving %s to file'",
"%",
"fname",
")",
"return",
"fname"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.img | Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML | GChartWrapper/GChart.py | def img(self, **kwargs):
"""
Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML
"""
safe = 'src="%s" ' % self.url.replace('&','&').replace('<', '<')\
.replace('>', '>').replace('"', '"').replace( "'", ''')
for item in kwargs.items():
if not item[0] in IMGATTRS:
raise AttributeError('Invalid img tag attribute: %s'%item[0])
safe += '%s="%s" '%item
return '<img %s/>'%safe | def img(self, **kwargs):
"""
Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML
"""
safe = 'src="%s" ' % self.url.replace('&','&').replace('<', '<')\
.replace('>', '>').replace('"', '"').replace( "'", ''')
for item in kwargs.items():
if not item[0] in IMGATTRS:
raise AttributeError('Invalid img tag attribute: %s'%item[0])
safe += '%s="%s" '%item
return '<img %s/>'%safe | [
"Returns",
"an",
"XHTML",
"<img",
"/",
">",
"tag",
"of",
"the",
"chart"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L584-L597 | [
"def",
"img",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"safe",
"=",
"'src=\"%s\" '",
"%",
"self",
".",
"url",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
".",
"replace",
"(",
"'>'",
",",
"'>'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'"'",
")",
".",
"replace",
"(",
"\"'\"",
",",
"'''",
")",
"for",
"item",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"item",
"[",
"0",
"]",
"in",
"IMGATTRS",
":",
"raise",
"AttributeError",
"(",
"'Invalid img tag attribute: %s'",
"%",
"item",
"[",
"0",
"]",
")",
"safe",
"+=",
"'%s=\"%s\" '",
"%",
"item",
"return",
"'<img %s/>'",
"%",
"safe"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.urlopen | Grabs readable PNG file pointer | GChartWrapper/GChart.py | def urlopen(self):
"""
Grabs readable PNG file pointer
"""
req = Request(str(self))
try:
return urlopen(req)
except HTTPError:
_print('The server couldn\'t fulfill the request.')
except URLError:
_print('We failed to reach a server.') | def urlopen(self):
"""
Grabs readable PNG file pointer
"""
req = Request(str(self))
try:
return urlopen(req)
except HTTPError:
_print('The server couldn\'t fulfill the request.')
except URLError:
_print('We failed to reach a server.') | [
"Grabs",
"readable",
"PNG",
"file",
"pointer"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L599-L609 | [
"def",
"urlopen",
"(",
"self",
")",
":",
"req",
"=",
"Request",
"(",
"str",
"(",
"self",
")",
")",
"try",
":",
"return",
"urlopen",
"(",
"req",
")",
"except",
"HTTPError",
":",
"_print",
"(",
"'The server couldn\\'t fulfill the request.'",
")",
"except",
"URLError",
":",
"_print",
"(",
"'We failed to reach a server.'",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.image | Returns a PngImageFile instance of the chart
You must have PIL installed for this to work | GChartWrapper/GChart.py | def image(self):
"""
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
"""
try:
try:
import Image
except ImportError:
from PIL import Image
except ImportError:
raise ImportError('You must install PIL to fetch image objects')
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return Image.open(StringIO(self.urlopen().read())) | def image(self):
"""
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
"""
try:
try:
import Image
except ImportError:
from PIL import Image
except ImportError:
raise ImportError('You must install PIL to fetch image objects')
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return Image.open(StringIO(self.urlopen().read())) | [
"Returns",
"a",
"PngImageFile",
"instance",
"of",
"the",
"chart"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L611-L628 | [
"def",
"image",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"import",
"Image",
"except",
"ImportError",
":",
"from",
"PIL",
"import",
"Image",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'You must install PIL to fetch image objects'",
")",
"try",
":",
"from",
"cStringIO",
"import",
"StringIO",
"except",
"ImportError",
":",
"from",
"StringIO",
"import",
"StringIO",
"return",
"Image",
".",
"open",
"(",
"StringIO",
"(",
"self",
".",
"urlopen",
"(",
")",
".",
"read",
"(",
")",
")",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.write | Writes out PNG image data in chunks to file pointer fp
fp must support w or wb | GChartWrapper/GChart.py | def write(self, fp):
"""
Writes out PNG image data in chunks to file pointer fp
fp must support w or wb
"""
urlfp = self.urlopen().fp
while 1:
try:
fp.write(urlfp.next())
except StopIteration:
return | def write(self, fp):
"""
Writes out PNG image data in chunks to file pointer fp
fp must support w or wb
"""
urlfp = self.urlopen().fp
while 1:
try:
fp.write(urlfp.next())
except StopIteration:
return | [
"Writes",
"out",
"PNG",
"image",
"data",
"in",
"chunks",
"to",
"file",
"pointer",
"fp"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L630-L641 | [
"def",
"write",
"(",
"self",
",",
"fp",
")",
":",
"urlfp",
"=",
"self",
".",
"urlopen",
"(",
")",
".",
"fp",
"while",
"1",
":",
"try",
":",
"fp",
".",
"write",
"(",
"urlfp",
".",
"next",
"(",
")",
")",
"except",
"StopIteration",
":",
"return"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | GChart.checksum | Returns the unique SHA1 hexdigest of the chart URL param parts
good for unittesting... | GChartWrapper/GChart.py | def checksum(self):
"""
Returns the unique SHA1 hexdigest of the chart URL param parts
good for unittesting...
"""
self.render()
return new_sha(''.join(sorted(self._parts()))).hexdigest() | def checksum(self):
"""
Returns the unique SHA1 hexdigest of the chart URL param parts
good for unittesting...
"""
self.render()
return new_sha(''.join(sorted(self._parts()))).hexdigest() | [
"Returns",
"the",
"unique",
"SHA1",
"hexdigest",
"of",
"the",
"chart",
"URL",
"param",
"parts"
] | appknox/google-chartwrapper | python | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L643-L650 | [
"def",
"checksum",
"(",
"self",
")",
":",
"self",
".",
"render",
"(",
")",
"return",
"new_sha",
"(",
"''",
".",
"join",
"(",
"sorted",
"(",
"self",
".",
"_parts",
"(",
")",
")",
")",
")",
".",
"hexdigest",
"(",
")"
] | 3769aecbef6c83b6cd93ee72ece478ffe433ac57 |
test | get_codes | >> get_codes()
ISO ISO3 ISO-Numeric fips Country Capital Area(in sq km) Population Continent tld CurrencyCode CurrencyName Phone Postal Code Format Postal Code Regex Languages geonameid neighbours EquivalentFipsCode | sample_data_utils/geo.py | def get_codes():
"""
>> get_codes()
ISO ISO3 ISO-Numeric fips Country Capital Area(in sq km) Population Continent tld CurrencyCode CurrencyName Phone Postal Code Format Postal Code Regex Languages geonameid neighbours EquivalentFipsCode
"""
cache_filename = os.path.join(os.path.dirname(__file__), 'data', 'countryInfo.txt')
data = []
for line in open(cache_filename, 'r'):
if not line.startswith('#'):
data.append(line.split('\t'))
return data | def get_codes():
"""
>> get_codes()
ISO ISO3 ISO-Numeric fips Country Capital Area(in sq km) Population Continent tld CurrencyCode CurrencyName Phone Postal Code Format Postal Code Regex Languages geonameid neighbours EquivalentFipsCode
"""
cache_filename = os.path.join(os.path.dirname(__file__), 'data', 'countryInfo.txt')
data = []
for line in open(cache_filename, 'r'):
if not line.startswith('#'):
data.append(line.split('\t'))
return data | [
">>",
"get_codes",
"()",
"ISO",
"ISO3",
"ISO",
"-",
"Numeric",
"fips",
"Country",
"Capital",
"Area",
"(",
"in",
"sq",
"km",
")",
"Population",
"Continent",
"tld",
"CurrencyCode",
"CurrencyName",
"Phone",
"Postal",
"Code",
"Format",
"Postal",
"Code",
"Regex",
"Languages",
"geonameid",
"neighbours",
"EquivalentFipsCode"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/geo.py#L16-L27 | [
"def",
"get_codes",
"(",
")",
":",
"cache_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'data'",
",",
"'countryInfo.txt'",
")",
"data",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"cache_filename",
",",
"'r'",
")",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"data",
".",
"append",
"(",
"line",
".",
"split",
"(",
"'\\t'",
")",
")",
"return",
"data"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | amount | return a random floating number
:param min: minimum value
:param max: maximum value
:param decimal_places: decimal places
:return: | sample_data_utils/money.py | def amount(min=1, max=sys.maxsize, decimal_places=2):
"""
return a random floating number
:param min: minimum value
:param max: maximum value
:param decimal_places: decimal places
:return:
"""
q = '.%s1' % '0' * (decimal_places - 1)
return decimal.Decimal(uniform(min, max)).quantize(decimal.Decimal(q)) | def amount(min=1, max=sys.maxsize, decimal_places=2):
"""
return a random floating number
:param min: minimum value
:param max: maximum value
:param decimal_places: decimal places
:return:
"""
q = '.%s1' % '0' * (decimal_places - 1)
return decimal.Decimal(uniform(min, max)).quantize(decimal.Decimal(q)) | [
"return",
"a",
"random",
"floating",
"number"
] | saxix/sample-data-utils | python | https://github.com/saxix/sample-data-utils/blob/769f1b46e60def2675a14bd5872047af6d1ea398/sample_data_utils/money.py#L7-L17 | [
"def",
"amount",
"(",
"min",
"=",
"1",
",",
"max",
"=",
"sys",
".",
"maxsize",
",",
"decimal_places",
"=",
"2",
")",
":",
"q",
"=",
"'.%s1'",
"%",
"'0'",
"*",
"(",
"decimal_places",
"-",
"1",
")",
"return",
"decimal",
".",
"Decimal",
"(",
"uniform",
"(",
"min",
",",
"max",
")",
")",
".",
"quantize",
"(",
"decimal",
".",
"Decimal",
"(",
"q",
")",
")"
] | 769f1b46e60def2675a14bd5872047af6d1ea398 |
test | entity_name_decorator | Assign an entity name based on the class immediately inhering from Base.
This is needed because we don't want
entity names to come from any class that simply inherits our classes,
just the ones in our module.
For example, if you create a class Project2 that exists outside of
kalibro_client and inherits from Project, it's entity name should still
be Project. | kalibro_client/base.py | def entity_name_decorator(top_cls):
"""
Assign an entity name based on the class immediately inhering from Base.
This is needed because we don't want
entity names to come from any class that simply inherits our classes,
just the ones in our module.
For example, if you create a class Project2 that exists outside of
kalibro_client and inherits from Project, it's entity name should still
be Project.
"""
class_name = inflection.underscore(top_cls.__name__).lower()
def entity_name(cls):
return class_name
top_cls.entity_name = classmethod(entity_name)
return top_cls | def entity_name_decorator(top_cls):
"""
Assign an entity name based on the class immediately inhering from Base.
This is needed because we don't want
entity names to come from any class that simply inherits our classes,
just the ones in our module.
For example, if you create a class Project2 that exists outside of
kalibro_client and inherits from Project, it's entity name should still
be Project.
"""
class_name = inflection.underscore(top_cls.__name__).lower()
def entity_name(cls):
return class_name
top_cls.entity_name = classmethod(entity_name)
return top_cls | [
"Assign",
"an",
"entity",
"name",
"based",
"on",
"the",
"class",
"immediately",
"inhering",
"from",
"Base",
"."
] | mezuro/kalibro_client_py | python | https://github.com/mezuro/kalibro_client_py/blob/841881acadf2ff8c06444f0bc34d541c0772edc0/kalibro_client/base.py#L139-L158 | [
"def",
"entity_name_decorator",
"(",
"top_cls",
")",
":",
"class_name",
"=",
"inflection",
".",
"underscore",
"(",
"top_cls",
".",
"__name__",
")",
".",
"lower",
"(",
")",
"def",
"entity_name",
"(",
"cls",
")",
":",
"return",
"class_name",
"top_cls",
".",
"entity_name",
"=",
"classmethod",
"(",
"entity_name",
")",
"return",
"top_cls"
] | 841881acadf2ff8c06444f0bc34d541c0772edc0 |
test | LessOrEqual.eval | Apply the less or equal algorithm on the ordered list of metadata
statements
:param orig: Start values
:return: | src/fedoidcmsg/operator.py | def eval(self, orig):
"""
Apply the less or equal algorithm on the ordered list of metadata
statements
:param orig: Start values
:return:
"""
_le = {}
_err = []
for k, v in self.sup_items():
if k in DoNotCompare:
continue
if k in orig:
if is_lesser(orig[k], v):
_le[k] = orig[k]
else:
_err.append({'claim': k, 'policy': orig[k], 'err': v,
'signer': self.iss})
else:
_le[k] = v
for k, v in orig.items():
if k in DoNotCompare:
continue
if k not in _le:
_le[k] = v
self.le = _le
self.err = _err | def eval(self, orig):
"""
Apply the less or equal algorithm on the ordered list of metadata
statements
:param orig: Start values
:return:
"""
_le = {}
_err = []
for k, v in self.sup_items():
if k in DoNotCompare:
continue
if k in orig:
if is_lesser(orig[k], v):
_le[k] = orig[k]
else:
_err.append({'claim': k, 'policy': orig[k], 'err': v,
'signer': self.iss})
else:
_le[k] = v
for k, v in orig.items():
if k in DoNotCompare:
continue
if k not in _le:
_le[k] = v
self.le = _le
self.err = _err | [
"Apply",
"the",
"less",
"or",
"equal",
"algorithm",
"on",
"the",
"ordered",
"list",
"of",
"metadata",
"statements",
":",
"param",
"orig",
":",
"Start",
"values",
":",
"return",
":"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L88-L117 | [
"def",
"eval",
"(",
"self",
",",
"orig",
")",
":",
"_le",
"=",
"{",
"}",
"_err",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"sup_items",
"(",
")",
":",
"if",
"k",
"in",
"DoNotCompare",
":",
"continue",
"if",
"k",
"in",
"orig",
":",
"if",
"is_lesser",
"(",
"orig",
"[",
"k",
"]",
",",
"v",
")",
":",
"_le",
"[",
"k",
"]",
"=",
"orig",
"[",
"k",
"]",
"else",
":",
"_err",
".",
"append",
"(",
"{",
"'claim'",
":",
"k",
",",
"'policy'",
":",
"orig",
"[",
"k",
"]",
",",
"'err'",
":",
"v",
",",
"'signer'",
":",
"self",
".",
"iss",
"}",
")",
"else",
":",
"_le",
"[",
"k",
"]",
"=",
"v",
"for",
"k",
",",
"v",
"in",
"orig",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"DoNotCompare",
":",
"continue",
"if",
"k",
"not",
"in",
"_le",
":",
"_le",
"[",
"k",
"]",
"=",
"v",
"self",
".",
"le",
"=",
"_le",
"self",
".",
"err",
"=",
"_err"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | LessOrEqual.unprotected_and_protected_claims | This is both verified and self asserted information. As expected
verified information beats self-asserted so if there is both
self-asserted and verified values for a claim then only the verified
will be returned. | src/fedoidcmsg/operator.py | def unprotected_and_protected_claims(self):
"""
This is both verified and self asserted information. As expected
verified information beats self-asserted so if there is both
self-asserted and verified values for a claim then only the verified
will be returned.
"""
if self.sup:
res = {}
for k, v in self.le.items():
if k not in self.sup.le:
res[k] = v
else:
res[k] = self.sup.le[k]
return res
else:
return self.le | def unprotected_and_protected_claims(self):
"""
This is both verified and self asserted information. As expected
verified information beats self-asserted so if there is both
self-asserted and verified values for a claim then only the verified
will be returned.
"""
if self.sup:
res = {}
for k, v in self.le.items():
if k not in self.sup.le:
res[k] = v
else:
res[k] = self.sup.le[k]
return res
else:
return self.le | [
"This",
"is",
"both",
"verified",
"and",
"self",
"asserted",
"information",
".",
"As",
"expected",
"verified",
"information",
"beats",
"self",
"-",
"asserted",
"so",
"if",
"there",
"is",
"both",
"self",
"-",
"asserted",
"and",
"verified",
"values",
"for",
"a",
"claim",
"then",
"only",
"the",
"verified",
"will",
"be",
"returned",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L126-L142 | [
"def",
"unprotected_and_protected_claims",
"(",
"self",
")",
":",
"if",
"self",
".",
"sup",
":",
"res",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"le",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"sup",
".",
"le",
":",
"res",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"res",
"[",
"k",
"]",
"=",
"self",
".",
"sup",
".",
"le",
"[",
"k",
"]",
"return",
"res",
"else",
":",
"return",
"self",
".",
"le"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.signing_keys_as_jwks | Build a JWKS from the signing keys belonging to the self signer
:return: Dictionary | src/fedoidcmsg/operator.py | def signing_keys_as_jwks(self):
"""
Build a JWKS from the signing keys belonging to the self signer
:return: Dictionary
"""
_l = [x.serialize() for x in self.self_signer.keyjar.get_signing_key()]
if not _l:
_l = [x.serialize() for x in
self.self_signer.keyjar.get_signing_key(owner=self.iss)]
return {'keys': _l} | def signing_keys_as_jwks(self):
"""
Build a JWKS from the signing keys belonging to the self signer
:return: Dictionary
"""
_l = [x.serialize() for x in self.self_signer.keyjar.get_signing_key()]
if not _l:
_l = [x.serialize() for x in
self.self_signer.keyjar.get_signing_key(owner=self.iss)]
return {'keys': _l} | [
"Build",
"a",
"JWKS",
"from",
"the",
"signing",
"keys",
"belonging",
"to",
"the",
"self",
"signer"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L202-L212 | [
"def",
"signing_keys_as_jwks",
"(",
"self",
")",
":",
"_l",
"=",
"[",
"x",
".",
"serialize",
"(",
")",
"for",
"x",
"in",
"self",
".",
"self_signer",
".",
"keyjar",
".",
"get_signing_key",
"(",
")",
"]",
"if",
"not",
"_l",
":",
"_l",
"=",
"[",
"x",
".",
"serialize",
"(",
")",
"for",
"x",
"in",
"self",
".",
"self_signer",
".",
"keyjar",
".",
"get_signing_key",
"(",
"owner",
"=",
"self",
".",
"iss",
")",
"]",
"return",
"{",
"'keys'",
":",
"_l",
"}"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator._unpack | :param ms_dict: Metadata statement as a dictionary
:param keyjar: A keyjar with the necessary FO keys
:param cls: What class to map the metadata into
:param jwt_ms: Metadata statement as a JWS
:param liss: List of FO issuer IDs
:return: ParseInfo instance | src/fedoidcmsg/operator.py | def _unpack(self, ms_dict, keyjar, cls, jwt_ms=None, liss=None):
"""
:param ms_dict: Metadata statement as a dictionary
:param keyjar: A keyjar with the necessary FO keys
:param cls: What class to map the metadata into
:param jwt_ms: Metadata statement as a JWS
:param liss: List of FO issuer IDs
:return: ParseInfo instance
"""
if liss is None:
liss = []
_pr = ParseInfo()
_pr.input = ms_dict
ms_flag = False
if 'metadata_statements' in ms_dict:
ms_flag = True
for iss, _ms in ms_dict['metadata_statements'].items():
if liss and iss not in liss:
continue
_pr = self._ums(_pr, _ms, keyjar)
if 'metadata_statement_uris' in ms_dict:
ms_flag = True
if self.httpcli:
for iss, url in ms_dict['metadata_statement_uris'].items():
if liss and iss not in liss:
continue
rsp = self.httpcli(method='GET', url=url,
verify=self.verify_ssl)
if rsp.status_code == 200:
_pr = self._ums(_pr, rsp.text, keyjar)
else:
raise ParseError(
'Could not fetch jws from {}'.format(url))
for _ms in _pr.parsed_statement:
if _ms: # can be None
loaded = False
try:
keyjar.import_jwks_as_json(_ms['signing_keys'],
ms_dict['iss'])
except KeyError:
pass
except TypeError:
try:
keyjar.import_jwks(_ms['signing_keys'], ms_dict['iss'])
except Exception as err:
logger.error(err)
raise
else:
loaded = True
else:
loaded = True
if loaded:
logger.debug(
'Loaded signing keys belonging to {} into the '
'keyjar'.format(ms_dict['iss']))
if ms_flag is True and not _pr.parsed_statement:
return _pr
if jwt_ms:
logger.debug("verifying signed JWT: {}".format(jwt_ms))
try:
_pr.result = cls().from_jwt(jwt_ms, keyjar=keyjar)
except MissingSigningKey:
if 'signing_keys' in ms_dict:
try:
_pr.result = self.self_signed(ms_dict, jwt_ms, cls)
except MissingSigningKey as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
except (JWSException, BadSignature, KeyError) as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
else:
_pr.result = ms_dict
if _pr.result and _pr.parsed_statement:
_prr = _pr.result
_res = {}
for x in _pr.parsed_statement:
if x:
_res[get_fo(x)] = x
_msg = Message(**_res)
logger.debug('Resulting metadata statement: {}'.format(_msg))
_pr.result['metadata_statements'] = _msg
return _pr | def _unpack(self, ms_dict, keyjar, cls, jwt_ms=None, liss=None):
"""
:param ms_dict: Metadata statement as a dictionary
:param keyjar: A keyjar with the necessary FO keys
:param cls: What class to map the metadata into
:param jwt_ms: Metadata statement as a JWS
:param liss: List of FO issuer IDs
:return: ParseInfo instance
"""
if liss is None:
liss = []
_pr = ParseInfo()
_pr.input = ms_dict
ms_flag = False
if 'metadata_statements' in ms_dict:
ms_flag = True
for iss, _ms in ms_dict['metadata_statements'].items():
if liss and iss not in liss:
continue
_pr = self._ums(_pr, _ms, keyjar)
if 'metadata_statement_uris' in ms_dict:
ms_flag = True
if self.httpcli:
for iss, url in ms_dict['metadata_statement_uris'].items():
if liss and iss not in liss:
continue
rsp = self.httpcli(method='GET', url=url,
verify=self.verify_ssl)
if rsp.status_code == 200:
_pr = self._ums(_pr, rsp.text, keyjar)
else:
raise ParseError(
'Could not fetch jws from {}'.format(url))
for _ms in _pr.parsed_statement:
if _ms: # can be None
loaded = False
try:
keyjar.import_jwks_as_json(_ms['signing_keys'],
ms_dict['iss'])
except KeyError:
pass
except TypeError:
try:
keyjar.import_jwks(_ms['signing_keys'], ms_dict['iss'])
except Exception as err:
logger.error(err)
raise
else:
loaded = True
else:
loaded = True
if loaded:
logger.debug(
'Loaded signing keys belonging to {} into the '
'keyjar'.format(ms_dict['iss']))
if ms_flag is True and not _pr.parsed_statement:
return _pr
if jwt_ms:
logger.debug("verifying signed JWT: {}".format(jwt_ms))
try:
_pr.result = cls().from_jwt(jwt_ms, keyjar=keyjar)
except MissingSigningKey:
if 'signing_keys' in ms_dict:
try:
_pr.result = self.self_signed(ms_dict, jwt_ms, cls)
except MissingSigningKey as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
except (JWSException, BadSignature, KeyError) as err:
logger.error('Encountered: {}'.format(err))
_pr.error[jwt_ms] = err
else:
_pr.result = ms_dict
if _pr.result and _pr.parsed_statement:
_prr = _pr.result
_res = {}
for x in _pr.parsed_statement:
if x:
_res[get_fo(x)] = x
_msg = Message(**_res)
logger.debug('Resulting metadata statement: {}'.format(_msg))
_pr.result['metadata_statements'] = _msg
return _pr | [
":",
"param",
"ms_dict",
":",
"Metadata",
"statement",
"as",
"a",
"dictionary",
":",
"param",
"keyjar",
":",
"A",
"keyjar",
"with",
"the",
"necessary",
"FO",
"keys",
":",
"param",
"cls",
":",
"What",
"class",
"to",
"map",
"the",
"metadata",
"into",
":",
"param",
"jwt_ms",
":",
"Metadata",
"statement",
"as",
"a",
"JWS",
":",
"param",
"liss",
":",
"List",
"of",
"FO",
"issuer",
"IDs",
":",
"return",
":",
"ParseInfo",
"instance"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L237-L329 | [
"def",
"_unpack",
"(",
"self",
",",
"ms_dict",
",",
"keyjar",
",",
"cls",
",",
"jwt_ms",
"=",
"None",
",",
"liss",
"=",
"None",
")",
":",
"if",
"liss",
"is",
"None",
":",
"liss",
"=",
"[",
"]",
"_pr",
"=",
"ParseInfo",
"(",
")",
"_pr",
".",
"input",
"=",
"ms_dict",
"ms_flag",
"=",
"False",
"if",
"'metadata_statements'",
"in",
"ms_dict",
":",
"ms_flag",
"=",
"True",
"for",
"iss",
",",
"_ms",
"in",
"ms_dict",
"[",
"'metadata_statements'",
"]",
".",
"items",
"(",
")",
":",
"if",
"liss",
"and",
"iss",
"not",
"in",
"liss",
":",
"continue",
"_pr",
"=",
"self",
".",
"_ums",
"(",
"_pr",
",",
"_ms",
",",
"keyjar",
")",
"if",
"'metadata_statement_uris'",
"in",
"ms_dict",
":",
"ms_flag",
"=",
"True",
"if",
"self",
".",
"httpcli",
":",
"for",
"iss",
",",
"url",
"in",
"ms_dict",
"[",
"'metadata_statement_uris'",
"]",
".",
"items",
"(",
")",
":",
"if",
"liss",
"and",
"iss",
"not",
"in",
"liss",
":",
"continue",
"rsp",
"=",
"self",
".",
"httpcli",
"(",
"method",
"=",
"'GET'",
",",
"url",
"=",
"url",
",",
"verify",
"=",
"self",
".",
"verify_ssl",
")",
"if",
"rsp",
".",
"status_code",
"==",
"200",
":",
"_pr",
"=",
"self",
".",
"_ums",
"(",
"_pr",
",",
"rsp",
".",
"text",
",",
"keyjar",
")",
"else",
":",
"raise",
"ParseError",
"(",
"'Could not fetch jws from {}'",
".",
"format",
"(",
"url",
")",
")",
"for",
"_ms",
"in",
"_pr",
".",
"parsed_statement",
":",
"if",
"_ms",
":",
"# can be None",
"loaded",
"=",
"False",
"try",
":",
"keyjar",
".",
"import_jwks_as_json",
"(",
"_ms",
"[",
"'signing_keys'",
"]",
",",
"ms_dict",
"[",
"'iss'",
"]",
")",
"except",
"KeyError",
":",
"pass",
"except",
"TypeError",
":",
"try",
":",
"keyjar",
".",
"import_jwks",
"(",
"_ms",
"[",
"'signing_keys'",
"]",
",",
"ms_dict",
"[",
"'iss'",
"]",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"err",
")",
"raise",
"else",
":",
"loaded",
"=",
"True",
"else",
":",
"loaded",
"=",
"True",
"if",
"loaded",
":",
"logger",
".",
"debug",
"(",
"'Loaded signing keys belonging to {} into the '",
"'keyjar'",
".",
"format",
"(",
"ms_dict",
"[",
"'iss'",
"]",
")",
")",
"if",
"ms_flag",
"is",
"True",
"and",
"not",
"_pr",
".",
"parsed_statement",
":",
"return",
"_pr",
"if",
"jwt_ms",
":",
"logger",
".",
"debug",
"(",
"\"verifying signed JWT: {}\"",
".",
"format",
"(",
"jwt_ms",
")",
")",
"try",
":",
"_pr",
".",
"result",
"=",
"cls",
"(",
")",
".",
"from_jwt",
"(",
"jwt_ms",
",",
"keyjar",
"=",
"keyjar",
")",
"except",
"MissingSigningKey",
":",
"if",
"'signing_keys'",
"in",
"ms_dict",
":",
"try",
":",
"_pr",
".",
"result",
"=",
"self",
".",
"self_signed",
"(",
"ms_dict",
",",
"jwt_ms",
",",
"cls",
")",
"except",
"MissingSigningKey",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Encountered: {}'",
".",
"format",
"(",
"err",
")",
")",
"_pr",
".",
"error",
"[",
"jwt_ms",
"]",
"=",
"err",
"except",
"(",
"JWSException",
",",
"BadSignature",
",",
"KeyError",
")",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Encountered: {}'",
".",
"format",
"(",
"err",
")",
")",
"_pr",
".",
"error",
"[",
"jwt_ms",
"]",
"=",
"err",
"else",
":",
"_pr",
".",
"result",
"=",
"ms_dict",
"if",
"_pr",
".",
"result",
"and",
"_pr",
".",
"parsed_statement",
":",
"_prr",
"=",
"_pr",
".",
"result",
"_res",
"=",
"{",
"}",
"for",
"x",
"in",
"_pr",
".",
"parsed_statement",
":",
"if",
"x",
":",
"_res",
"[",
"get_fo",
"(",
"x",
")",
"]",
"=",
"x",
"_msg",
"=",
"Message",
"(",
"*",
"*",
"_res",
")",
"logger",
".",
"debug",
"(",
"'Resulting metadata statement: {}'",
".",
"format",
"(",
"_msg",
")",
")",
"_pr",
".",
"result",
"[",
"'metadata_statements'",
"]",
"=",
"_msg",
"return",
"_pr"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.unpack_metadata_statement | Starting with a signed JWT or a JSON document unpack and verify all
the separate metadata statements.
:param ms_dict: Metadata statement as a dictionary
:param jwt_ms: Metadata statement as JWT
:param keyjar: Keys that should be used to verify the signature of the
document
:param cls: What type (Class) of metadata statement this is
:param liss: list of FO identifiers that matters. The rest will be
ignored
:return: A ParseInfo instance | src/fedoidcmsg/operator.py | def unpack_metadata_statement(self, ms_dict=None, jwt_ms='', keyjar=None,
cls=ClientMetadataStatement, liss=None):
"""
Starting with a signed JWT or a JSON document unpack and verify all
the separate metadata statements.
:param ms_dict: Metadata statement as a dictionary
:param jwt_ms: Metadata statement as JWT
:param keyjar: Keys that should be used to verify the signature of the
document
:param cls: What type (Class) of metadata statement this is
:param liss: list of FO identifiers that matters. The rest will be
ignored
:return: A ParseInfo instance
"""
if not keyjar:
if self.jwks_bundle:
keyjar = self.jwks_bundle.as_keyjar()
else:
keyjar = KeyJar()
if jwt_ms:
try:
ms_dict = unfurl(jwt_ms)
except JWSException as err:
logger.error('Could not unfurl jwt_ms due to {}'.format(err))
raise
if ms_dict:
return self._unpack(ms_dict, keyjar, cls, jwt_ms, liss)
else:
raise AttributeError('Need one of ms_dict or jwt_ms') | def unpack_metadata_statement(self, ms_dict=None, jwt_ms='', keyjar=None,
cls=ClientMetadataStatement, liss=None):
"""
Starting with a signed JWT or a JSON document unpack and verify all
the separate metadata statements.
:param ms_dict: Metadata statement as a dictionary
:param jwt_ms: Metadata statement as JWT
:param keyjar: Keys that should be used to verify the signature of the
document
:param cls: What type (Class) of metadata statement this is
:param liss: list of FO identifiers that matters. The rest will be
ignored
:return: A ParseInfo instance
"""
if not keyjar:
if self.jwks_bundle:
keyjar = self.jwks_bundle.as_keyjar()
else:
keyjar = KeyJar()
if jwt_ms:
try:
ms_dict = unfurl(jwt_ms)
except JWSException as err:
logger.error('Could not unfurl jwt_ms due to {}'.format(err))
raise
if ms_dict:
return self._unpack(ms_dict, keyjar, cls, jwt_ms, liss)
else:
raise AttributeError('Need one of ms_dict or jwt_ms') | [
"Starting",
"with",
"a",
"signed",
"JWT",
"or",
"a",
"JSON",
"document",
"unpack",
"and",
"verify",
"all",
"the",
"separate",
"metadata",
"statements",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L331-L363 | [
"def",
"unpack_metadata_statement",
"(",
"self",
",",
"ms_dict",
"=",
"None",
",",
"jwt_ms",
"=",
"''",
",",
"keyjar",
"=",
"None",
",",
"cls",
"=",
"ClientMetadataStatement",
",",
"liss",
"=",
"None",
")",
":",
"if",
"not",
"keyjar",
":",
"if",
"self",
".",
"jwks_bundle",
":",
"keyjar",
"=",
"self",
".",
"jwks_bundle",
".",
"as_keyjar",
"(",
")",
"else",
":",
"keyjar",
"=",
"KeyJar",
"(",
")",
"if",
"jwt_ms",
":",
"try",
":",
"ms_dict",
"=",
"unfurl",
"(",
"jwt_ms",
")",
"except",
"JWSException",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Could not unfurl jwt_ms due to {}'",
".",
"format",
"(",
"err",
")",
")",
"raise",
"if",
"ms_dict",
":",
"return",
"self",
".",
"_unpack",
"(",
"ms_dict",
",",
"keyjar",
",",
"cls",
",",
"jwt_ms",
",",
"liss",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"'Need one of ms_dict or jwt_ms'",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.pack_metadata_statement | Given a MetadataStatement instance create a signed JWT.
:param metadata: Original metadata statement as a MetadataStatement
instance
:param receiver: Receiver (audience) of the JWT
:param iss: Issuer ID if different from default
:param lifetime: jWT signature life time
:param sign_alg: JWT signature algorithm
:return: A JWT | src/fedoidcmsg/operator.py | def pack_metadata_statement(self, metadata, receiver='', iss='', lifetime=0,
sign_alg=''):
"""
Given a MetadataStatement instance create a signed JWT.
:param metadata: Original metadata statement as a MetadataStatement
instance
:param receiver: Receiver (audience) of the JWT
:param iss: Issuer ID if different from default
:param lifetime: jWT signature life time
:param sign_alg: JWT signature algorithm
:return: A JWT
"""
return self.self_signer.sign(metadata, receiver=receiver, iss=iss,
lifetime=lifetime, sign_alg=sign_alg) | def pack_metadata_statement(self, metadata, receiver='', iss='', lifetime=0,
sign_alg=''):
"""
Given a MetadataStatement instance create a signed JWT.
:param metadata: Original metadata statement as a MetadataStatement
instance
:param receiver: Receiver (audience) of the JWT
:param iss: Issuer ID if different from default
:param lifetime: jWT signature life time
:param sign_alg: JWT signature algorithm
:return: A JWT
"""
return self.self_signer.sign(metadata, receiver=receiver, iss=iss,
lifetime=lifetime, sign_alg=sign_alg) | [
"Given",
"a",
"MetadataStatement",
"instance",
"create",
"a",
"signed",
"JWT",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L365-L380 | [
"def",
"pack_metadata_statement",
"(",
"self",
",",
"metadata",
",",
"receiver",
"=",
"''",
",",
"iss",
"=",
"''",
",",
"lifetime",
"=",
"0",
",",
"sign_alg",
"=",
"''",
")",
":",
"return",
"self",
".",
"self_signer",
".",
"sign",
"(",
"metadata",
",",
"receiver",
"=",
"receiver",
",",
"iss",
"=",
"iss",
",",
"lifetime",
"=",
"lifetime",
",",
"sign_alg",
"=",
"sign_alg",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.evaluate_metadata_statement | Computes the resulting metadata statement from a compounded metadata
statement.
If something goes wrong during the evaluation an exception is raised
:param metadata: The compounded metadata statement as a dictionary
:return: A list of :py:class:`fedoidc.operator.LessOrEqual`
instances, one per FO. | src/fedoidcmsg/operator.py | def evaluate_metadata_statement(self, metadata, keyjar=None):
"""
Computes the resulting metadata statement from a compounded metadata
statement.
If something goes wrong during the evaluation an exception is raised
:param metadata: The compounded metadata statement as a dictionary
:return: A list of :py:class:`fedoidc.operator.LessOrEqual`
instances, one per FO.
"""
# start from the innermost metadata statement and work outwards
res = dict([(k, v) for k, v in metadata.items() if k not in IgnoreKeys])
les = []
if 'metadata_statements' in metadata:
for fo, ms in metadata['metadata_statements'].items():
if isinstance(ms, str):
ms = json.loads(ms)
for _le in self.evaluate_metadata_statement(ms):
if isinstance(ms, Message):
le = LessOrEqual(sup=_le, **ms.to_dict())
else: # Must be a dict
le = LessOrEqual(sup=_le, **ms)
if le.is_expired():
logger.error(
'This metadata statement has expired: {}'.format(ms)
)
logger.info('My time: {}'.format(utc_time_sans_frac()))
continue
le.eval(res)
les.append(le)
return les
else: # this is the innermost
try:
_iss = metadata['iss']
except:
le = LessOrEqual()
le.eval(res)
else:
le = LessOrEqual(iss=_iss, exp=metadata['exp'])
le.eval(res)
les.append(le)
return les | def evaluate_metadata_statement(self, metadata, keyjar=None):
"""
Computes the resulting metadata statement from a compounded metadata
statement.
If something goes wrong during the evaluation an exception is raised
:param metadata: The compounded metadata statement as a dictionary
:return: A list of :py:class:`fedoidc.operator.LessOrEqual`
instances, one per FO.
"""
# start from the innermost metadata statement and work outwards
res = dict([(k, v) for k, v in metadata.items() if k not in IgnoreKeys])
les = []
if 'metadata_statements' in metadata:
for fo, ms in metadata['metadata_statements'].items():
if isinstance(ms, str):
ms = json.loads(ms)
for _le in self.evaluate_metadata_statement(ms):
if isinstance(ms, Message):
le = LessOrEqual(sup=_le, **ms.to_dict())
else: # Must be a dict
le = LessOrEqual(sup=_le, **ms)
if le.is_expired():
logger.error(
'This metadata statement has expired: {}'.format(ms)
)
logger.info('My time: {}'.format(utc_time_sans_frac()))
continue
le.eval(res)
les.append(le)
return les
else: # this is the innermost
try:
_iss = metadata['iss']
except:
le = LessOrEqual()
le.eval(res)
else:
le = LessOrEqual(iss=_iss, exp=metadata['exp'])
le.eval(res)
les.append(le)
return les | [
"Computes",
"the",
"resulting",
"metadata",
"statement",
"from",
"a",
"compounded",
"metadata",
"statement",
".",
"If",
"something",
"goes",
"wrong",
"during",
"the",
"evaluation",
"an",
"exception",
"is",
"raised"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L382-L428 | [
"def",
"evaluate_metadata_statement",
"(",
"self",
",",
"metadata",
",",
"keyjar",
"=",
"None",
")",
":",
"# start from the innermost metadata statement and work outwards",
"res",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"metadata",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"IgnoreKeys",
"]",
")",
"les",
"=",
"[",
"]",
"if",
"'metadata_statements'",
"in",
"metadata",
":",
"for",
"fo",
",",
"ms",
"in",
"metadata",
"[",
"'metadata_statements'",
"]",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"ms",
",",
"str",
")",
":",
"ms",
"=",
"json",
".",
"loads",
"(",
"ms",
")",
"for",
"_le",
"in",
"self",
".",
"evaluate_metadata_statement",
"(",
"ms",
")",
":",
"if",
"isinstance",
"(",
"ms",
",",
"Message",
")",
":",
"le",
"=",
"LessOrEqual",
"(",
"sup",
"=",
"_le",
",",
"*",
"*",
"ms",
".",
"to_dict",
"(",
")",
")",
"else",
":",
"# Must be a dict",
"le",
"=",
"LessOrEqual",
"(",
"sup",
"=",
"_le",
",",
"*",
"*",
"ms",
")",
"if",
"le",
".",
"is_expired",
"(",
")",
":",
"logger",
".",
"error",
"(",
"'This metadata statement has expired: {}'",
".",
"format",
"(",
"ms",
")",
")",
"logger",
".",
"info",
"(",
"'My time: {}'",
".",
"format",
"(",
"utc_time_sans_frac",
"(",
")",
")",
")",
"continue",
"le",
".",
"eval",
"(",
"res",
")",
"les",
".",
"append",
"(",
"le",
")",
"return",
"les",
"else",
":",
"# this is the innermost",
"try",
":",
"_iss",
"=",
"metadata",
"[",
"'iss'",
"]",
"except",
":",
"le",
"=",
"LessOrEqual",
"(",
")",
"le",
".",
"eval",
"(",
"res",
")",
"else",
":",
"le",
"=",
"LessOrEqual",
"(",
"iss",
"=",
"_iss",
",",
"exp",
"=",
"metadata",
"[",
"'exp'",
"]",
")",
"le",
".",
"eval",
"(",
"res",
")",
"les",
".",
"append",
"(",
"le",
")",
"return",
"les"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.correct_usage | Remove MS paths that are marked to be used for another usage
:param metadata: Metadata statement as dictionary
:param federation_usage: In which context this is expected to used.
:return: Filtered Metadata statement. | src/fedoidcmsg/operator.py | def correct_usage(self, metadata, federation_usage):
"""
Remove MS paths that are marked to be used for another usage
:param metadata: Metadata statement as dictionary
:param federation_usage: In which context this is expected to used.
:return: Filtered Metadata statement.
"""
if 'metadata_statements' in metadata:
_msl = {}
for fo, ms in metadata['metadata_statements'].items():
if not isinstance(ms, Message):
ms = json.loads(ms)
if self.correct_usage(ms, federation_usage=federation_usage):
_msl[fo] = ms
if _msl:
metadata['metadata_statements'] = Message(**_msl)
return metadata
else:
return None
else: # this is the innermost
try:
assert federation_usage == metadata['federation_usage']
except KeyError:
pass
except AssertionError:
return None
return metadata | def correct_usage(self, metadata, federation_usage):
"""
Remove MS paths that are marked to be used for another usage
:param metadata: Metadata statement as dictionary
:param federation_usage: In which context this is expected to used.
:return: Filtered Metadata statement.
"""
if 'metadata_statements' in metadata:
_msl = {}
for fo, ms in metadata['metadata_statements'].items():
if not isinstance(ms, Message):
ms = json.loads(ms)
if self.correct_usage(ms, federation_usage=federation_usage):
_msl[fo] = ms
if _msl:
metadata['metadata_statements'] = Message(**_msl)
return metadata
else:
return None
else: # this is the innermost
try:
assert federation_usage == metadata['federation_usage']
except KeyError:
pass
except AssertionError:
return None
return metadata | [
"Remove",
"MS",
"paths",
"that",
"are",
"marked",
"to",
"be",
"used",
"for",
"another",
"usage"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L430-L459 | [
"def",
"correct_usage",
"(",
"self",
",",
"metadata",
",",
"federation_usage",
")",
":",
"if",
"'metadata_statements'",
"in",
"metadata",
":",
"_msl",
"=",
"{",
"}",
"for",
"fo",
",",
"ms",
"in",
"metadata",
"[",
"'metadata_statements'",
"]",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"ms",
",",
"Message",
")",
":",
"ms",
"=",
"json",
".",
"loads",
"(",
"ms",
")",
"if",
"self",
".",
"correct_usage",
"(",
"ms",
",",
"federation_usage",
"=",
"federation_usage",
")",
":",
"_msl",
"[",
"fo",
"]",
"=",
"ms",
"if",
"_msl",
":",
"metadata",
"[",
"'metadata_statements'",
"]",
"=",
"Message",
"(",
"*",
"*",
"_msl",
")",
"return",
"metadata",
"else",
":",
"return",
"None",
"else",
":",
"# this is the innermost",
"try",
":",
"assert",
"federation_usage",
"==",
"metadata",
"[",
"'federation_usage'",
"]",
"except",
"KeyError",
":",
"pass",
"except",
"AssertionError",
":",
"return",
"None",
"return",
"metadata"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Operator.extend_with_ms | Add signed metadata statements to a request
:param req: The request
:param sms_dict: A dictionary with FO IDs as keys and signed metadata
statements (sms) or uris pointing to sms as values.
:return: The updated request | src/fedoidcmsg/operator.py | def extend_with_ms(self, req, sms_dict):
"""
Add signed metadata statements to a request
:param req: The request
:param sms_dict: A dictionary with FO IDs as keys and signed metadata
statements (sms) or uris pointing to sms as values.
:return: The updated request
"""
_ms_uri = {}
_ms = {}
for fo, sms in sms_dict.items():
if sms.startswith('http://') or sms.startswith('https://'):
_ms_uri[fo] = sms
else:
_ms[fo] = sms
if _ms:
req['metadata_statements'] = Message(**_ms)
if _ms_uri:
req['metadata_statement_uris'] = Message(**_ms_uri)
return req | def extend_with_ms(self, req, sms_dict):
"""
Add signed metadata statements to a request
:param req: The request
:param sms_dict: A dictionary with FO IDs as keys and signed metadata
statements (sms) or uris pointing to sms as values.
:return: The updated request
"""
_ms_uri = {}
_ms = {}
for fo, sms in sms_dict.items():
if sms.startswith('http://') or sms.startswith('https://'):
_ms_uri[fo] = sms
else:
_ms[fo] = sms
if _ms:
req['metadata_statements'] = Message(**_ms)
if _ms_uri:
req['metadata_statement_uris'] = Message(**_ms_uri)
return req | [
"Add",
"signed",
"metadata",
"statements",
"to",
"a",
"request"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/operator.py#L461-L482 | [
"def",
"extend_with_ms",
"(",
"self",
",",
"req",
",",
"sms_dict",
")",
":",
"_ms_uri",
"=",
"{",
"}",
"_ms",
"=",
"{",
"}",
"for",
"fo",
",",
"sms",
"in",
"sms_dict",
".",
"items",
"(",
")",
":",
"if",
"sms",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"sms",
".",
"startswith",
"(",
"'https://'",
")",
":",
"_ms_uri",
"[",
"fo",
"]",
"=",
"sms",
"else",
":",
"_ms",
"[",
"fo",
"]",
"=",
"sms",
"if",
"_ms",
":",
"req",
"[",
"'metadata_statements'",
"]",
"=",
"Message",
"(",
"*",
"*",
"_ms",
")",
"if",
"_ms_uri",
":",
"req",
"[",
"'metadata_statement_uris'",
"]",
"=",
"Message",
"(",
"*",
"*",
"_ms_uri",
")",
"return",
"req"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | parse_args | Parses command line args using argparse library | concordance/drivers/runner.py | def parse_args():
"""
Parses command line args using argparse library
"""
usage = "Usage: create_concordance <infile> [<outfile>]"
description = "Simple Concordance Generator"
argparser = argparse.ArgumentParser(
usage=usage, description=description)
argparser.add_argument(
'infile', type=argparse.FileType('r'),
help="File read in to create concordance")
argparser.add_argument(
'outfile', nargs='?', type=argparse.FileType('w'),
default=sys.stdout, help="File to write concordance to. "
"Default is stdout")
argparser.add_argument(
'--word', nargs="?", const=str, help="Display a word in concordance")
args = argparser.parse_args()
return args | def parse_args():
"""
Parses command line args using argparse library
"""
usage = "Usage: create_concordance <infile> [<outfile>]"
description = "Simple Concordance Generator"
argparser = argparse.ArgumentParser(
usage=usage, description=description)
argparser.add_argument(
'infile', type=argparse.FileType('r'),
help="File read in to create concordance")
argparser.add_argument(
'outfile', nargs='?', type=argparse.FileType('w'),
default=sys.stdout, help="File to write concordance to. "
"Default is stdout")
argparser.add_argument(
'--word', nargs="?", const=str, help="Display a word in concordance")
args = argparser.parse_args()
return args | [
"Parses",
"command",
"line",
"args",
"using",
"argparse",
"library"
] | bucknerns/concordance | python | https://github.com/bucknerns/concordance/blob/a4f39b60e7f8ec64741dd7a603105734bd9cca72/concordance/drivers/runner.py#L19-L40 | [
"def",
"parse_args",
"(",
")",
":",
"usage",
"=",
"\"Usage: create_concordance <infile> [<outfile>]\"",
"description",
"=",
"\"Simple Concordance Generator\"",
"argparser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"usage",
",",
"description",
"=",
"description",
")",
"argparser",
".",
"add_argument",
"(",
"'infile'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"help",
"=",
"\"File read in to create concordance\"",
")",
"argparser",
".",
"add_argument",
"(",
"'outfile'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'w'",
")",
",",
"default",
"=",
"sys",
".",
"stdout",
",",
"help",
"=",
"\"File to write concordance to. \"",
"\"Default is stdout\"",
")",
"argparser",
".",
"add_argument",
"(",
"'--word'",
",",
"nargs",
"=",
"\"?\"",
",",
"const",
"=",
"str",
",",
"help",
"=",
"\"Display a word in concordance\"",
")",
"args",
"=",
"argparser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | a4f39b60e7f8ec64741dd7a603105734bd9cca72 |
test | addCommandLineArgs | Add logging option to an ArgumentParser. | nicfit/logger.py | def addCommandLineArgs(arg_parser):
"""Add logging option to an ArgumentParser."""
arg_parser.register("action", "log_levels", LogLevelAction)
arg_parser.register("action", "log_files", LogFileAction)
arg_parser.register("action", "log_help", LogHelpAction)
group = arg_parser.add_argument_group("Logging options")
group.add_argument(
"-l", "--log-level", dest="log_levels",
action="log_levels", metavar="LOGGER:LEVEL", default=[],
help="Set log levels for individual loggers. See --help-logging for "
"complete details.")
group.add_argument(
"-L", "--log-file", dest="log_files",
action="log_files", metavar="LOGGER:FILE", default=[],
help="Set log the output file for individual loggers. "
" See --help-logging for complete details.")
group.add_argument("--help-logging", action="log_help",
help=argparse.SUPPRESS) | def addCommandLineArgs(arg_parser):
"""Add logging option to an ArgumentParser."""
arg_parser.register("action", "log_levels", LogLevelAction)
arg_parser.register("action", "log_files", LogFileAction)
arg_parser.register("action", "log_help", LogHelpAction)
group = arg_parser.add_argument_group("Logging options")
group.add_argument(
"-l", "--log-level", dest="log_levels",
action="log_levels", metavar="LOGGER:LEVEL", default=[],
help="Set log levels for individual loggers. See --help-logging for "
"complete details.")
group.add_argument(
"-L", "--log-file", dest="log_files",
action="log_files", metavar="LOGGER:FILE", default=[],
help="Set log the output file for individual loggers. "
" See --help-logging for complete details.")
group.add_argument("--help-logging", action="log_help",
help=argparse.SUPPRESS) | [
"Add",
"logging",
"option",
"to",
"an",
"ArgumentParser",
"."
] | nicfit/nicfit.py | python | https://github.com/nicfit/nicfit.py/blob/8313f8edbc5e7361ddad496d6d818324b5236c7a/nicfit/logger.py#L102-L122 | [
"def",
"addCommandLineArgs",
"(",
"arg_parser",
")",
":",
"arg_parser",
".",
"register",
"(",
"\"action\"",
",",
"\"log_levels\"",
",",
"LogLevelAction",
")",
"arg_parser",
".",
"register",
"(",
"\"action\"",
",",
"\"log_files\"",
",",
"LogFileAction",
")",
"arg_parser",
".",
"register",
"(",
"\"action\"",
",",
"\"log_help\"",
",",
"LogHelpAction",
")",
"group",
"=",
"arg_parser",
".",
"add_argument_group",
"(",
"\"Logging options\"",
")",
"group",
".",
"add_argument",
"(",
"\"-l\"",
",",
"\"--log-level\"",
",",
"dest",
"=",
"\"log_levels\"",
",",
"action",
"=",
"\"log_levels\"",
",",
"metavar",
"=",
"\"LOGGER:LEVEL\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Set log levels for individual loggers. See --help-logging for \"",
"\"complete details.\"",
")",
"group",
".",
"add_argument",
"(",
"\"-L\"",
",",
"\"--log-file\"",
",",
"dest",
"=",
"\"log_files\"",
",",
"action",
"=",
"\"log_files\"",
",",
"metavar",
"=",
"\"LOGGER:FILE\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Set log the output file for individual loggers. \"",
"\" See --help-logging for complete details.\"",
")",
"group",
".",
"add_argument",
"(",
"\"--help-logging\"",
",",
"action",
"=",
"\"log_help\"",
",",
"help",
"=",
"argparse",
".",
"SUPPRESS",
")"
] | 8313f8edbc5e7361ddad496d6d818324b5236c7a |
test | applyLoggingOpts | Apply logging options produced by LogLevelAction and LogFileAction.
More often then not this function is not needed, the actions have already
been taken during the parse, but it can be used in the case they need to be
applied again (e.g. when command line opts take precedence but were
overridded by a fileConfig, etc.). | nicfit/logger.py | def applyLoggingOpts(log_levels, log_files):
"""Apply logging options produced by LogLevelAction and LogFileAction.
More often then not this function is not needed, the actions have already
been taken during the parse, but it can be used in the case they need to be
applied again (e.g. when command line opts take precedence but were
overridded by a fileConfig, etc.).
"""
for l, lvl in log_levels:
l.setLevel(lvl)
for l, hdl in log_files:
for h in l.handlers:
l.removeHandler(h)
l.addHandler(hdl) | def applyLoggingOpts(log_levels, log_files):
"""Apply logging options produced by LogLevelAction and LogFileAction.
More often then not this function is not needed, the actions have already
been taken during the parse, but it can be used in the case they need to be
applied again (e.g. when command line opts take precedence but were
overridded by a fileConfig, etc.).
"""
for l, lvl in log_levels:
l.setLevel(lvl)
for l, hdl in log_files:
for h in l.handlers:
l.removeHandler(h)
l.addHandler(hdl) | [
"Apply",
"logging",
"options",
"produced",
"by",
"LogLevelAction",
"and",
"LogFileAction",
"."
] | nicfit/nicfit.py | python | https://github.com/nicfit/nicfit.py/blob/8313f8edbc5e7361ddad496d6d818324b5236c7a/nicfit/logger.py#L125-L138 | [
"def",
"applyLoggingOpts",
"(",
"log_levels",
",",
"log_files",
")",
":",
"for",
"l",
",",
"lvl",
"in",
"log_levels",
":",
"l",
".",
"setLevel",
"(",
"lvl",
")",
"for",
"l",
",",
"hdl",
"in",
"log_files",
":",
"for",
"h",
"in",
"l",
".",
"handlers",
":",
"l",
".",
"removeHandler",
"(",
"h",
")",
"l",
".",
"addHandler",
"(",
"hdl",
")"
] | 8313f8edbc5e7361ddad496d6d818324b5236c7a |
test | Logger.verbose | Log msg at 'verbose' level, debug < verbose < info | nicfit/logger.py | def verbose(self, msg, *args, **kwargs):
"""Log msg at 'verbose' level, debug < verbose < info"""
self.log(logging.VERBOSE, msg, *args, **kwargs) | def verbose(self, msg, *args, **kwargs):
"""Log msg at 'verbose' level, debug < verbose < info"""
self.log(logging.VERBOSE, msg, *args, **kwargs) | [
"Log",
"msg",
"at",
"verbose",
"level",
"debug",
"<",
"verbose",
"<",
"info"
] | nicfit/nicfit.py | python | https://github.com/nicfit/nicfit.py/blob/8313f8edbc5e7361ddad496d6d818324b5236c7a/nicfit/logger.py#L24-L26 | [
"def",
"verbose",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"logging",
".",
"VERBOSE",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 8313f8edbc5e7361ddad496d6d818324b5236c7a |
test | SduBkjws._aodata | 生成用于post的数据
:param echo: a int to check is response is write
:type echo: int
:param columns: 所有columns列名组成的list
:type columns: list
:param xnxq: str
:type xnxq: string
:param final_exam: 是否期末考试
:rtype: bool
:return: a valid data for post to get data | sdu_bkjws/__init__.py | def _aodata(echo, columns, xnxq=None, final_exam=False):
"""
生成用于post的数据
:param echo: a int to check is response is write
:type echo: int
:param columns: 所有columns列名组成的list
:type columns: list
:param xnxq: str
:type xnxq: string
:param final_exam: 是否期末考试
:rtype: bool
:return: a valid data for post to get data
"""
ao_data = [{"name": "sEcho", "value": echo},
{"name": "iColumns", "value": len(columns)},
{"name": "sColumns", "value": ""},
{"name": "iDisplayStart", "value": 0},
{"name": "iDisplayLength", "value": -1},
]
if xnxq:
if final_exam:
ao_data.append(
{"name": "ksrwid", "value": "000000005bf6cb6f015bfac609410d4b"})
ao_data.append({"name": "xnxq", "value": xnxq})
for index, value in enumerate(columns):
ao_data.append(
{"name": "mDataProp_{}".format(index), "value": value})
ao_data.append(
{"name": "bSortable_{}".format(index), "value": False})
return urlencode({"aoData": ao_data}) | def _aodata(echo, columns, xnxq=None, final_exam=False):
"""
生成用于post的数据
:param echo: a int to check is response is write
:type echo: int
:param columns: 所有columns列名组成的list
:type columns: list
:param xnxq: str
:type xnxq: string
:param final_exam: 是否期末考试
:rtype: bool
:return: a valid data for post to get data
"""
ao_data = [{"name": "sEcho", "value": echo},
{"name": "iColumns", "value": len(columns)},
{"name": "sColumns", "value": ""},
{"name": "iDisplayStart", "value": 0},
{"name": "iDisplayLength", "value": -1},
]
if xnxq:
if final_exam:
ao_data.append(
{"name": "ksrwid", "value": "000000005bf6cb6f015bfac609410d4b"})
ao_data.append({"name": "xnxq", "value": xnxq})
for index, value in enumerate(columns):
ao_data.append(
{"name": "mDataProp_{}".format(index), "value": value})
ao_data.append(
{"name": "bSortable_{}".format(index), "value": False})
return urlencode({"aoData": ao_data}) | [
"生成用于post的数据"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L54-L86 | [
"def",
"_aodata",
"(",
"echo",
",",
"columns",
",",
"xnxq",
"=",
"None",
",",
"final_exam",
"=",
"False",
")",
":",
"ao_data",
"=",
"[",
"{",
"\"name\"",
":",
"\"sEcho\"",
",",
"\"value\"",
":",
"echo",
"}",
",",
"{",
"\"name\"",
":",
"\"iColumns\"",
",",
"\"value\"",
":",
"len",
"(",
"columns",
")",
"}",
",",
"{",
"\"name\"",
":",
"\"sColumns\"",
",",
"\"value\"",
":",
"\"\"",
"}",
",",
"{",
"\"name\"",
":",
"\"iDisplayStart\"",
",",
"\"value\"",
":",
"0",
"}",
",",
"{",
"\"name\"",
":",
"\"iDisplayLength\"",
",",
"\"value\"",
":",
"-",
"1",
"}",
",",
"]",
"if",
"xnxq",
":",
"if",
"final_exam",
":",
"ao_data",
".",
"append",
"(",
"{",
"\"name\"",
":",
"\"ksrwid\"",
",",
"\"value\"",
":",
"\"000000005bf6cb6f015bfac609410d4b\"",
"}",
")",
"ao_data",
".",
"append",
"(",
"{",
"\"name\"",
":",
"\"xnxq\"",
",",
"\"value\"",
":",
"xnxq",
"}",
")",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"columns",
")",
":",
"ao_data",
".",
"append",
"(",
"{",
"\"name\"",
":",
"\"mDataProp_{}\"",
".",
"format",
"(",
"index",
")",
",",
"\"value\"",
":",
"value",
"}",
")",
"ao_data",
".",
"append",
"(",
"{",
"\"name\"",
":",
"\"bSortable_{}\"",
".",
"format",
"(",
"index",
")",
",",
"\"value\"",
":",
"False",
"}",
")",
"return",
"urlencode",
"(",
"{",
"\"aoData\"",
":",
"ao_data",
"}",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.login | 登陆系统,返回一个requests的session对象
:return: session with login cookies
:rtype: requests.sessions.Session | sdu_bkjws/__init__.py | def login(self):
"""
登陆系统,返回一个requests的session对象
:return: session with login cookies
:rtype: requests.sessions.Session
"""
if not hasattr(self, 'session'):
self.last_connect = time.time()
s = requests.session()
s.get('http://bkjws.sdu.edu.cn')
data = {
'j_username': self.student_id,
'j_password': self.password_md5
}
r6 = s.post('http://bkjws.sdu.edu.cn/b/ajaxLogin', headers={
'user-agent': self._ua},
data=data)
if r6.text == '"success"':
return s
else:
s.close()
raise AuthFailure(r6.text) | def login(self):
"""
登陆系统,返回一个requests的session对象
:return: session with login cookies
:rtype: requests.sessions.Session
"""
if not hasattr(self, 'session'):
self.last_connect = time.time()
s = requests.session()
s.get('http://bkjws.sdu.edu.cn')
data = {
'j_username': self.student_id,
'j_password': self.password_md5
}
r6 = s.post('http://bkjws.sdu.edu.cn/b/ajaxLogin', headers={
'user-agent': self._ua},
data=data)
if r6.text == '"success"':
return s
else:
s.close()
raise AuthFailure(r6.text) | [
"登陆系统",
"返回一个requests的session对象"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L110-L133 | [
"def",
"login",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'session'",
")",
":",
"self",
".",
"last_connect",
"=",
"time",
".",
"time",
"(",
")",
"s",
"=",
"requests",
".",
"session",
"(",
")",
"s",
".",
"get",
"(",
"'http://bkjws.sdu.edu.cn'",
")",
"data",
"=",
"{",
"'j_username'",
":",
"self",
".",
"student_id",
",",
"'j_password'",
":",
"self",
".",
"password_md5",
"}",
"r6",
"=",
"s",
".",
"post",
"(",
"'http://bkjws.sdu.edu.cn/b/ajaxLogin'",
",",
"headers",
"=",
"{",
"'user-agent'",
":",
"self",
".",
"_ua",
"}",
",",
"data",
"=",
"data",
")",
"if",
"r6",
".",
"text",
"==",
"'\"success\"'",
":",
"return",
"s",
"else",
":",
"s",
".",
"close",
"(",
")",
"raise",
"AuthFailure",
"(",
"r6",
".",
"text",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.get_lesson | 获取课表,返回一个列表,包含所有课表对象
:return: list of lessons
:rtype: list[dict] | sdu_bkjws/__init__.py | def get_lesson(self):
"""
获取课表,返回一个列表,包含所有课表对象
:return: list of lessons
:rtype: list[dict]
"""
html = self._get('http://bkjws.sdu.edu.cn/f/xk/xs/bxqkb')
soup = BeautifulSoup(html, "html.parser")
s = soup.find('table',
attrs={"class": "table table-striped table-bordered table-hover",
"id": "ysjddDataTableId"})
tr_box = s.find_all('tr')
c = list()
for les in tr_box[1:]:
td_box = les.find_all('td')
c.append({"lesson_num_long": td_box[1].text,
"lesson_name": td_box[2].text,
"lesson_num_short": td_box[3].text,
"credit": td_box[4].text,
"school": td_box[6].text,
"teacher": td_box[7].text,
"weeks": td_box[8].text,
"days": td_box[9].text,
"times": td_box[10].text,
"place": td_box[11].text})
self._lessons = c
return c | def get_lesson(self):
"""
获取课表,返回一个列表,包含所有课表对象
:return: list of lessons
:rtype: list[dict]
"""
html = self._get('http://bkjws.sdu.edu.cn/f/xk/xs/bxqkb')
soup = BeautifulSoup(html, "html.parser")
s = soup.find('table',
attrs={"class": "table table-striped table-bordered table-hover",
"id": "ysjddDataTableId"})
tr_box = s.find_all('tr')
c = list()
for les in tr_box[1:]:
td_box = les.find_all('td')
c.append({"lesson_num_long": td_box[1].text,
"lesson_name": td_box[2].text,
"lesson_num_short": td_box[3].text,
"credit": td_box[4].text,
"school": td_box[6].text,
"teacher": td_box[7].text,
"weeks": td_box[8].text,
"days": td_box[9].text,
"times": td_box[10].text,
"place": td_box[11].text})
self._lessons = c
return c | [
"获取课表",
"返回一个列表",
"包含所有课表对象"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L135-L163 | [
"def",
"get_lesson",
"(",
"self",
")",
":",
"html",
"=",
"self",
".",
"_get",
"(",
"'http://bkjws.sdu.edu.cn/f/xk/xs/bxqkb'",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
",",
"\"html.parser\"",
")",
"s",
"=",
"soup",
".",
"find",
"(",
"'table'",
",",
"attrs",
"=",
"{",
"\"class\"",
":",
"\"table table-striped table-bordered table-hover\"",
",",
"\"id\"",
":",
"\"ysjddDataTableId\"",
"}",
")",
"tr_box",
"=",
"s",
".",
"find_all",
"(",
"'tr'",
")",
"c",
"=",
"list",
"(",
")",
"for",
"les",
"in",
"tr_box",
"[",
"1",
":",
"]",
":",
"td_box",
"=",
"les",
".",
"find_all",
"(",
"'td'",
")",
"c",
".",
"append",
"(",
"{",
"\"lesson_num_long\"",
":",
"td_box",
"[",
"1",
"]",
".",
"text",
",",
"\"lesson_name\"",
":",
"td_box",
"[",
"2",
"]",
".",
"text",
",",
"\"lesson_num_short\"",
":",
"td_box",
"[",
"3",
"]",
".",
"text",
",",
"\"credit\"",
":",
"td_box",
"[",
"4",
"]",
".",
"text",
",",
"\"school\"",
":",
"td_box",
"[",
"6",
"]",
".",
"text",
",",
"\"teacher\"",
":",
"td_box",
"[",
"7",
"]",
".",
"text",
",",
"\"weeks\"",
":",
"td_box",
"[",
"8",
"]",
".",
"text",
",",
"\"days\"",
":",
"td_box",
"[",
"9",
"]",
".",
"text",
",",
"\"times\"",
":",
"td_box",
"[",
"10",
"]",
".",
"text",
",",
"\"place\"",
":",
"td_box",
"[",
"11",
"]",
".",
"text",
"}",
")",
"self",
".",
"_lessons",
"=",
"c",
"return",
"c"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.lessons | 返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list | sdu_bkjws/__init__.py | def lessons(self):
"""
返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list
"""
if hasattr(self, '_lessons'):
return self._lessons
else:
self.get_lesson()
return self._lessons | def lessons(self):
"""
返回lessons,如果未调用过``get_lesson()``会自动调用
:return: list of lessons
:rtype: list
"""
if hasattr(self, '_lessons'):
return self._lessons
else:
self.get_lesson()
return self._lessons | [
"返回lessons",
"如果未调用过",
"get_lesson",
"()",
"会自动调用"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L166-L177 | [
"def",
"lessons",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_lessons'",
")",
":",
"return",
"self",
".",
"_lessons",
"else",
":",
"self",
".",
"get_lesson",
"(",
")",
"return",
"self",
".",
"_lessons"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.detail | 个人信息,如果未调用过``get_detail()``会自动调用
:return: information of student
:rtype: dict | sdu_bkjws/__init__.py | def detail(self):
"""
个人信息,如果未调用过``get_detail()``会自动调用
:return: information of student
:rtype: dict
"""
if hasattr(self, '_detail'):
return self._detail
else:
self.get_detail()
return self._detail | def detail(self):
"""
个人信息,如果未调用过``get_detail()``会自动调用
:return: information of student
:rtype: dict
"""
if hasattr(self, '_detail'):
return self._detail
else:
self.get_detail()
return self._detail | [
"个人信息",
"如果未调用过",
"get_detail",
"()",
"会自动调用"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L196-L207 | [
"def",
"detail",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_detail'",
")",
":",
"return",
"self",
".",
"_detail",
"else",
":",
"self",
".",
"get_detail",
"(",
")",
"return",
"self",
".",
"_detail"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.get_detail | 个人信息,同时会把返回值保存在self.detail中
:return: information of student
:rtype: dict | sdu_bkjws/__init__.py | def get_detail(self):
"""
个人信息,同时会把返回值保存在self.detail中
:return: information of student
:rtype: dict
"""
response = self._post("http://bkjws.sdu.edu.cn/b/grxx/xs/xjxx/detail",
data=None)
if response['result'] == 'success':
self._detail = response['object']
return self._detail
else:
self._unexpected(response) | def get_detail(self):
"""
个人信息,同时会把返回值保存在self.detail中
:return: information of student
:rtype: dict
"""
response = self._post("http://bkjws.sdu.edu.cn/b/grxx/xs/xjxx/detail",
data=None)
if response['result'] == 'success':
self._detail = response['object']
return self._detail
else:
self._unexpected(response) | [
"个人信息",
"同时会把返回值保存在self",
".",
"detail中",
":",
"return",
":",
"information",
"of",
"student",
":",
"rtype",
":",
"dict"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L209-L221 | [
"def",
"get_detail",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_post",
"(",
"\"http://bkjws.sdu.edu.cn/b/grxx/xs/xjxx/detail\"",
",",
"data",
"=",
"None",
")",
"if",
"response",
"[",
"'result'",
"]",
"==",
"'success'",
":",
"self",
".",
"_detail",
"=",
"response",
"[",
"'object'",
"]",
"return",
"self",
".",
"_detail",
"else",
":",
"self",
".",
"_unexpected",
"(",
"response",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.get_raw_past_score | 历年成绩查询的原始返回值,请使用get_past_score()
:return: dict of the raw response of past score
:rtype: dict | sdu_bkjws/__init__.py | def get_raw_past_score(self):
"""
历年成绩查询的原始返回值,请使用get_past_score()
:return: dict of the raw response of past score
:rtype: dict
"""
echo = self._echo
response = self._post("http://bkjws.sdu.edu.cn/b/cj/cjcx/xs/lscx",
data=self._aodata(echo,
columns=["xnxq", "kcm", "kxh", "xf", "kssj",
"kscjView", "wfzjd",
"wfzdj",
"kcsx"]))
if self._check_response(response, echo):
self._raw_past_score = response
return self._raw_past_score
else:
self._unexpected(response) | def get_raw_past_score(self):
"""
历年成绩查询的原始返回值,请使用get_past_score()
:return: dict of the raw response of past score
:rtype: dict
"""
echo = self._echo
response = self._post("http://bkjws.sdu.edu.cn/b/cj/cjcx/xs/lscx",
data=self._aodata(echo,
columns=["xnxq", "kcm", "kxh", "xf", "kssj",
"kscjView", "wfzjd",
"wfzdj",
"kcsx"]))
if self._check_response(response, echo):
self._raw_past_score = response
return self._raw_past_score
else:
self._unexpected(response) | [
"历年成绩查询的原始返回值",
"请使用get_past_score",
"()",
":",
"return",
":",
"dict",
"of",
"the",
"raw",
"response",
"of",
"past",
"score",
":",
"rtype",
":",
"dict"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L223-L242 | [
"def",
"get_raw_past_score",
"(",
"self",
")",
":",
"echo",
"=",
"self",
".",
"_echo",
"response",
"=",
"self",
".",
"_post",
"(",
"\"http://bkjws.sdu.edu.cn/b/cj/cjcx/xs/lscx\"",
",",
"data",
"=",
"self",
".",
"_aodata",
"(",
"echo",
",",
"columns",
"=",
"[",
"\"xnxq\"",
",",
"\"kcm\"",
",",
"\"kxh\"",
",",
"\"xf\"",
",",
"\"kssj\"",
",",
"\"kscjView\"",
",",
"\"wfzjd\"",
",",
"\"wfzdj\"",
",",
"\"kcsx\"",
"]",
")",
")",
"if",
"self",
".",
"_check_response",
"(",
"response",
",",
"echo",
")",
":",
"self",
".",
"_raw_past_score",
"=",
"response",
"return",
"self",
".",
"_raw_past_score",
"else",
":",
"self",
".",
"_unexpected",
"(",
"response",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.get_comment_lesson_info | 获取教学评估内所有需要课程
:return: 返回所以有需要进行教学评估的课程
:rtype: list | sdu_bkjws/__init__.py | def get_comment_lesson_info(self): # 获取课程序列
"""
获取教学评估内所有需要课程
:return: 返回所以有需要进行教学评估的课程
:rtype: list
"""
echo = self._echo
response = self._post('http://bkjws.sdu.edu.cn/b/pg/xs/list',
data=self._aodata(echo, ['kch', 'kcm', 'jsm', 'function', 'function']), )
if self._check_response(response, echo=echo):
return response['object']['aaData']
else:
self._unexpected(response) | def get_comment_lesson_info(self): # 获取课程序列
"""
获取教学评估内所有需要课程
:return: 返回所以有需要进行教学评估的课程
:rtype: list
"""
echo = self._echo
response = self._post('http://bkjws.sdu.edu.cn/b/pg/xs/list',
data=self._aodata(echo, ['kch', 'kcm', 'jsm', 'function', 'function']), )
if self._check_response(response, echo=echo):
return response['object']['aaData']
else:
self._unexpected(response) | [
"获取教学评估内所有需要课程"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L379-L392 | [
"def",
"get_comment_lesson_info",
"(",
"self",
")",
":",
"# 获取课程序列",
"echo",
"=",
"self",
".",
"_echo",
"response",
"=",
"self",
".",
"_post",
"(",
"'http://bkjws.sdu.edu.cn/b/pg/xs/list'",
",",
"data",
"=",
"self",
".",
"_aodata",
"(",
"echo",
",",
"[",
"'kch'",
",",
"'kcm'",
",",
"'jsm'",
",",
"'function'",
",",
"'function'",
"]",
")",
",",
")",
"if",
"self",
".",
"_check_response",
"(",
"response",
",",
"echo",
"=",
"echo",
")",
":",
"return",
"response",
"[",
"'object'",
"]",
"[",
"'aaData'",
"]",
"else",
":",
"self",
".",
"_unexpected",
"(",
"response",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | SduBkjws.get_exam_time | 获取考试时间
:param xnxq: 学年学期 格式为 ``开始学年-结束学年-{1|2|3}`` 3为暑期学校 example:``2016-2017-2``
:type xnxq: str
:return: list of exam time
:rtype: list | sdu_bkjws/__init__.py | def get_exam_time(self, xnxq):
"""
获取考试时间
:param xnxq: 学年学期 格式为 ``开始学年-结束学年-{1|2|3}`` 3为暑期学校 example:``2016-2017-2``
:type xnxq: str
:return: list of exam time
:rtype: list
"""
echo = self._echo
response = self._post('http://bkjws.sdu.edu.cn/b/ksap/xs/vksapxs/pageList',
data=self._aodata(echo, xnxq=xnxq,
columns=["function", 'ksmc', 'kcm', 'kch', 'xqmc',
'jxljs', 'sjsj', "ksfsmc",
"ksffmc", "ksbz"]))
if self._check_response(response, echo):
return response['object']['aaData']
else:
self._unexpected(response) | def get_exam_time(self, xnxq):
"""
获取考试时间
:param xnxq: 学年学期 格式为 ``开始学年-结束学年-{1|2|3}`` 3为暑期学校 example:``2016-2017-2``
:type xnxq: str
:return: list of exam time
:rtype: list
"""
echo = self._echo
response = self._post('http://bkjws.sdu.edu.cn/b/ksap/xs/vksapxs/pageList',
data=self._aodata(echo, xnxq=xnxq,
columns=["function", 'ksmc', 'kcm', 'kch', 'xqmc',
'jxljs', 'sjsj', "ksfsmc",
"ksffmc", "ksbz"]))
if self._check_response(response, echo):
return response['object']['aaData']
else:
self._unexpected(response) | [
"获取考试时间"
] | Trim21/sdu_bkjws | python | https://github.com/Trim21/sdu_bkjws/blob/87e74c84e6a20b2abd20905e2381f0a572398f6c/sdu_bkjws/__init__.py#L394-L412 | [
"def",
"get_exam_time",
"(",
"self",
",",
"xnxq",
")",
":",
"echo",
"=",
"self",
".",
"_echo",
"response",
"=",
"self",
".",
"_post",
"(",
"'http://bkjws.sdu.edu.cn/b/ksap/xs/vksapxs/pageList'",
",",
"data",
"=",
"self",
".",
"_aodata",
"(",
"echo",
",",
"xnxq",
"=",
"xnxq",
",",
"columns",
"=",
"[",
"\"function\"",
",",
"'ksmc'",
",",
"'kcm'",
",",
"'kch'",
",",
"'xqmc'",
",",
"'jxljs'",
",",
"'sjsj'",
",",
"\"ksfsmc\"",
",",
"\"ksffmc\"",
",",
"\"ksbz\"",
"]",
")",
")",
"if",
"self",
".",
"_check_response",
"(",
"response",
",",
"echo",
")",
":",
"return",
"response",
"[",
"'object'",
"]",
"[",
"'aaData'",
"]",
"else",
":",
"self",
".",
"_unexpected",
"(",
"response",
")"
] | 87e74c84e6a20b2abd20905e2381f0a572398f6c |
test | _letter_map | Creates a map of letter use in a word.
Args:
word: a string to create a letter map from
Returns:
a dictionary of {letter: integer count of letter in word} | nagaram/anagrams.py | def _letter_map(word):
"""Creates a map of letter use in a word.
Args:
word: a string to create a letter map from
Returns:
a dictionary of {letter: integer count of letter in word}
"""
lmap = {}
for letter in word:
try:
lmap[letter] += 1
except KeyError:
lmap[letter] = 1
return lmap | def _letter_map(word):
"""Creates a map of letter use in a word.
Args:
word: a string to create a letter map from
Returns:
a dictionary of {letter: integer count of letter in word}
"""
lmap = {}
for letter in word:
try:
lmap[letter] += 1
except KeyError:
lmap[letter] = 1
return lmap | [
"Creates",
"a",
"map",
"of",
"letter",
"use",
"in",
"a",
"word",
"."
] | a-tal/nagaram | python | https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/nagaram/anagrams.py#L7-L23 | [
"def",
"_letter_map",
"(",
"word",
")",
":",
"lmap",
"=",
"{",
"}",
"for",
"letter",
"in",
"word",
":",
"try",
":",
"lmap",
"[",
"letter",
"]",
"+=",
"1",
"except",
"KeyError",
":",
"lmap",
"[",
"letter",
"]",
"=",
"1",
"return",
"lmap"
] | 2edcb0ef8cb569ebd1c398be826472b4831d6110 |
test | anagrams_in_word | Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yields:
a tuple of (word, score) that can be made with the input_word | nagaram/anagrams.py | def anagrams_in_word(word, sowpods=False, start="", end=""):
"""Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yields:
a tuple of (word, score) that can be made with the input_word
"""
input_letters, blanks, questions = blank_tiles(word)
for tile in start + end:
input_letters.append(tile)
for word in word_list(sowpods, start, end):
lmap = _letter_map(input_letters)
used_blanks = 0
for letter in word:
if letter in lmap:
lmap[letter] -= 1
if lmap[letter] < 0:
used_blanks += 1
if used_blanks > (blanks + questions):
break
else:
used_blanks += 1
if used_blanks > (blanks + questions):
break
else:
yield (word, word_score(word, input_letters, questions)) | def anagrams_in_word(word, sowpods=False, start="", end=""):
"""Finds anagrams in word.
Args:
word: the string to base our search off of
sowpods: boolean to declare TWL or SOWPODS words file
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yields:
a tuple of (word, score) that can be made with the input_word
"""
input_letters, blanks, questions = blank_tiles(word)
for tile in start + end:
input_letters.append(tile)
for word in word_list(sowpods, start, end):
lmap = _letter_map(input_letters)
used_blanks = 0
for letter in word:
if letter in lmap:
lmap[letter] -= 1
if lmap[letter] < 0:
used_blanks += 1
if used_blanks > (blanks + questions):
break
else:
used_blanks += 1
if used_blanks > (blanks + questions):
break
else:
yield (word, word_score(word, input_letters, questions)) | [
"Finds",
"anagrams",
"in",
"word",
"."
] | a-tal/nagaram | python | https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/nagaram/anagrams.py#L26-L59 | [
"def",
"anagrams_in_word",
"(",
"word",
",",
"sowpods",
"=",
"False",
",",
"start",
"=",
"\"\"",
",",
"end",
"=",
"\"\"",
")",
":",
"input_letters",
",",
"blanks",
",",
"questions",
"=",
"blank_tiles",
"(",
"word",
")",
"for",
"tile",
"in",
"start",
"+",
"end",
":",
"input_letters",
".",
"append",
"(",
"tile",
")",
"for",
"word",
"in",
"word_list",
"(",
"sowpods",
",",
"start",
",",
"end",
")",
":",
"lmap",
"=",
"_letter_map",
"(",
"input_letters",
")",
"used_blanks",
"=",
"0",
"for",
"letter",
"in",
"word",
":",
"if",
"letter",
"in",
"lmap",
":",
"lmap",
"[",
"letter",
"]",
"-=",
"1",
"if",
"lmap",
"[",
"letter",
"]",
"<",
"0",
":",
"used_blanks",
"+=",
"1",
"if",
"used_blanks",
">",
"(",
"blanks",
"+",
"questions",
")",
":",
"break",
"else",
":",
"used_blanks",
"+=",
"1",
"if",
"used_blanks",
">",
"(",
"blanks",
"+",
"questions",
")",
":",
"break",
"else",
":",
"yield",
"(",
"word",
",",
"word_score",
"(",
"word",
",",
"input_letters",
",",
"questions",
")",
")"
] | 2edcb0ef8cb569ebd1c398be826472b4831d6110 |
test | Error.asAMP | Returns the exception's name in an AMP Command friendly format.
For example, given a class named ``ExampleExceptionClass``, returns
``"EXAMPLE_EXCEPTION_CLASS"``. | txampext/errors.py | def asAMP(cls):
"""
Returns the exception's name in an AMP Command friendly format.
For example, given a class named ``ExampleExceptionClass``, returns
``"EXAMPLE_EXCEPTION_CLASS"``.
"""
parts = groupByUpperCase(cls.__name__)
return cls, "_".join(part.upper() for part in parts) | def asAMP(cls):
"""
Returns the exception's name in an AMP Command friendly format.
For example, given a class named ``ExampleExceptionClass``, returns
``"EXAMPLE_EXCEPTION_CLASS"``.
"""
parts = groupByUpperCase(cls.__name__)
return cls, "_".join(part.upper() for part in parts) | [
"Returns",
"the",
"exception",
"s",
"name",
"in",
"an",
"AMP",
"Command",
"friendly",
"format",
"."
] | lvh/txampext | python | https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/errors.py#L12-L20 | [
"def",
"asAMP",
"(",
"cls",
")",
":",
"parts",
"=",
"groupByUpperCase",
"(",
"cls",
".",
"__name__",
")",
"return",
"cls",
",",
"\"_\"",
".",
"join",
"(",
"part",
".",
"upper",
"(",
")",
"for",
"part",
"in",
"parts",
")"
] | a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9 |
test | transform_timeseries_data | Transforms a Go Metrics API metric result into a list of
values for a given window period.
start and end are expected to be Unix timestamps in microseconds. | ci/utils.py | def transform_timeseries_data(timeseries, start, end=None):
"""Transforms a Go Metrics API metric result into a list of
values for a given window period.
start and end are expected to be Unix timestamps in microseconds.
"""
data = []
include = False
for metric, points in timeseries.items():
for point in points:
if point['x'] == start:
include = True
if include:
data.append(point['y'])
if end is not None and point['x'] == end:
return data
return data | def transform_timeseries_data(timeseries, start, end=None):
"""Transforms a Go Metrics API metric result into a list of
values for a given window period.
start and end are expected to be Unix timestamps in microseconds.
"""
data = []
include = False
for metric, points in timeseries.items():
for point in points:
if point['x'] == start:
include = True
if include:
data.append(point['y'])
if end is not None and point['x'] == end:
return data
return data | [
"Transforms",
"a",
"Go",
"Metrics",
"API",
"metric",
"result",
"into",
"a",
"list",
"of",
"values",
"for",
"a",
"given",
"window",
"period",
"."
] | praekeltfoundation/seed-control-interface | python | https://github.com/praekeltfoundation/seed-control-interface/blob/32ddad88b5bc2f8f4d80b848361899da2e081636/ci/utils.py#L13-L29 | [
"def",
"transform_timeseries_data",
"(",
"timeseries",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"include",
"=",
"False",
"for",
"metric",
",",
"points",
"in",
"timeseries",
".",
"items",
"(",
")",
":",
"for",
"point",
"in",
"points",
":",
"if",
"point",
"[",
"'x'",
"]",
"==",
"start",
":",
"include",
"=",
"True",
"if",
"include",
":",
"data",
".",
"append",
"(",
"point",
"[",
"'y'",
"]",
")",
"if",
"end",
"is",
"not",
"None",
"and",
"point",
"[",
"'x'",
"]",
"==",
"end",
":",
"return",
"data",
"return",
"data"
] | 32ddad88b5bc2f8f4d80b848361899da2e081636 |
test | get_last_value_from_timeseries | Gets the most recent non-zero value for a .last metric or zero
for empty data. | ci/utils.py | def get_last_value_from_timeseries(timeseries):
"""Gets the most recent non-zero value for a .last metric or zero
for empty data."""
if not timeseries:
return 0
for metric, points in timeseries.items():
return next((p['y'] for p in reversed(points) if p['y'] > 0), 0) | def get_last_value_from_timeseries(timeseries):
"""Gets the most recent non-zero value for a .last metric or zero
for empty data."""
if not timeseries:
return 0
for metric, points in timeseries.items():
return next((p['y'] for p in reversed(points) if p['y'] > 0), 0) | [
"Gets",
"the",
"most",
"recent",
"non",
"-",
"zero",
"value",
"for",
"a",
".",
"last",
"metric",
"or",
"zero",
"for",
"empty",
"data",
"."
] | praekeltfoundation/seed-control-interface | python | https://github.com/praekeltfoundation/seed-control-interface/blob/32ddad88b5bc2f8f4d80b848361899da2e081636/ci/utils.py#L32-L38 | [
"def",
"get_last_value_from_timeseries",
"(",
"timeseries",
")",
":",
"if",
"not",
"timeseries",
":",
"return",
"0",
"for",
"metric",
",",
"points",
"in",
"timeseries",
".",
"items",
"(",
")",
":",
"return",
"next",
"(",
"(",
"p",
"[",
"'y'",
"]",
"for",
"p",
"in",
"reversed",
"(",
"points",
")",
"if",
"p",
"[",
"'y'",
"]",
">",
"0",
")",
",",
"0",
")"
] | 32ddad88b5bc2f8f4d80b848361899da2e081636 |
test | validate_page_number | Validate the given 1-based page number. | ci/utils.py | def validate_page_number(number):
"""Validate the given 1-based page number."""
try:
number = int(number)
except (TypeError, ValueError):
raise PageNotAnInteger('That page number is not an integer')
if number < 1:
raise EmptyPage('That page number is less than 1')
return number | def validate_page_number(number):
"""Validate the given 1-based page number."""
try:
number = int(number)
except (TypeError, ValueError):
raise PageNotAnInteger('That page number is not an integer')
if number < 1:
raise EmptyPage('That page number is less than 1')
return number | [
"Validate",
"the",
"given",
"1",
"-",
"based",
"page",
"number",
"."
] | praekeltfoundation/seed-control-interface | python | https://github.com/praekeltfoundation/seed-control-interface/blob/32ddad88b5bc2f8f4d80b848361899da2e081636/ci/utils.py#L121-L129 | [
"def",
"validate_page_number",
"(",
"number",
")",
":",
"try",
":",
"number",
"=",
"int",
"(",
"number",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"PageNotAnInteger",
"(",
"'That page number is not an integer'",
")",
"if",
"number",
"<",
"1",
":",
"raise",
"EmptyPage",
"(",
"'That page number is less than 1'",
")",
"return",
"number"
] | 32ddad88b5bc2f8f4d80b848361899da2e081636 |
test | get_page_of_iterator | Get a page from an interator, handling invalid input from the page number
by defaulting to the first page. | ci/utils.py | def get_page_of_iterator(iterator, page_size, page_number):
"""
Get a page from an interator, handling invalid input from the page number
by defaulting to the first page.
"""
try:
page_number = validate_page_number(page_number)
except (PageNotAnInteger, EmptyPage):
page_number = 1
start = (page_number - 1) * page_size
# End 1 more than we need, so that we can see if there's another page
end = (page_number * page_size) + 1
skipped_items = list(islice(iterator, start))
items = list(islice(iterator, end))
if len(items) == 0 and page_number != 1:
items = skipped_items
page_number = 1
has_next = len(items) > page_size
items = items[:page_size]
return NoCountPage(items, page_number, page_size, has_next) | def get_page_of_iterator(iterator, page_size, page_number):
"""
Get a page from an interator, handling invalid input from the page number
by defaulting to the first page.
"""
try:
page_number = validate_page_number(page_number)
except (PageNotAnInteger, EmptyPage):
page_number = 1
start = (page_number - 1) * page_size
# End 1 more than we need, so that we can see if there's another page
end = (page_number * page_size) + 1
skipped_items = list(islice(iterator, start))
items = list(islice(iterator, end))
if len(items) == 0 and page_number != 1:
items = skipped_items
page_number = 1
has_next = len(items) > page_size
items = items[:page_size]
return NoCountPage(items, page_number, page_size, has_next) | [
"Get",
"a",
"page",
"from",
"an",
"interator",
"handling",
"invalid",
"input",
"from",
"the",
"page",
"number",
"by",
"defaulting",
"to",
"the",
"first",
"page",
"."
] | praekeltfoundation/seed-control-interface | python | https://github.com/praekeltfoundation/seed-control-interface/blob/32ddad88b5bc2f8f4d80b848361899da2e081636/ci/utils.py#L162-L185 | [
"def",
"get_page_of_iterator",
"(",
"iterator",
",",
"page_size",
",",
"page_number",
")",
":",
"try",
":",
"page_number",
"=",
"validate_page_number",
"(",
"page_number",
")",
"except",
"(",
"PageNotAnInteger",
",",
"EmptyPage",
")",
":",
"page_number",
"=",
"1",
"start",
"=",
"(",
"page_number",
"-",
"1",
")",
"*",
"page_size",
"# End 1 more than we need, so that we can see if there's another page",
"end",
"=",
"(",
"page_number",
"*",
"page_size",
")",
"+",
"1",
"skipped_items",
"=",
"list",
"(",
"islice",
"(",
"iterator",
",",
"start",
")",
")",
"items",
"=",
"list",
"(",
"islice",
"(",
"iterator",
",",
"end",
")",
")",
"if",
"len",
"(",
"items",
")",
"==",
"0",
"and",
"page_number",
"!=",
"1",
":",
"items",
"=",
"skipped_items",
"page_number",
"=",
"1",
"has_next",
"=",
"len",
"(",
"items",
")",
">",
"page_size",
"items",
"=",
"items",
"[",
":",
"page_size",
"]",
"return",
"NoCountPage",
"(",
"items",
",",
"page_number",
",",
"page_size",
",",
"has_next",
")"
] | 32ddad88b5bc2f8f4d80b848361899da2e081636 |
test | sh | Executes the given command.
returns a 2-tuple with returncode (integer) and OUTPUT (string) | pyque/sh.py | def sh(cmd, escape=True):
""" Executes the given command.
returns a 2-tuple with returncode (integer) and OUTPUT (string)
"""
if escape:
cmd = quote(cmd)
process = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
output, unused_err = process.communicate()
retcode = process.poll()
return (retcode, output) | def sh(cmd, escape=True):
""" Executes the given command.
returns a 2-tuple with returncode (integer) and OUTPUT (string)
"""
if escape:
cmd = quote(cmd)
process = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
output, unused_err = process.communicate()
retcode = process.poll()
return (retcode, output) | [
"Executes",
"the",
"given",
"command",
".",
"returns",
"a",
"2",
"-",
"tuple",
"with",
"returncode",
"(",
"integer",
")",
"and",
"OUTPUT",
"(",
"string",
")"
] | bmaeser/pyque | python | https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/sh.py#L17-L29 | [
"def",
"sh",
"(",
"cmd",
",",
"escape",
"=",
"True",
")",
":",
"if",
"escape",
":",
"cmd",
"=",
"quote",
"(",
"cmd",
")",
"process",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"STDOUT",
",",
"shell",
"=",
"True",
")",
"output",
",",
"unused_err",
"=",
"process",
".",
"communicate",
"(",
")",
"retcode",
"=",
"process",
".",
"poll",
"(",
")",
"return",
"(",
"retcode",
",",
"output",
")"
] | 856dceab8d89cf3771cf21e682466c29a85ae8eb |
test | gzip | Gzip a file
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename. | pyque/sh.py | def gzip(filename):
""" Gzip a file
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename.
"""
## run gzip
retcode, output = sh('gzip %s' % filename)
new_filename = filename+'.gz'
return (retcode, output, new_filename) | def gzip(filename):
""" Gzip a file
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename.
"""
## run gzip
retcode, output = sh('gzip %s' % filename)
new_filename = filename+'.gz'
return (retcode, output, new_filename) | [
"Gzip",
"a",
"file",
"returns",
"a",
"3",
"-",
"tuple",
"with",
"returncode",
"(",
"integer",
")",
"terminal",
"output",
"(",
"string",
")",
"and",
"the",
"new",
"filename",
"."
] | bmaeser/pyque | python | https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/sh.py#L32-L42 | [
"def",
"gzip",
"(",
"filename",
")",
":",
"## run gzip",
"retcode",
",",
"output",
"=",
"sh",
"(",
"'gzip %s'",
"%",
"filename",
")",
"new_filename",
"=",
"filename",
"+",
"'.gz'",
"return",
"(",
"retcode",
",",
"output",
",",
"new_filename",
")"
] | 856dceab8d89cf3771cf21e682466c29a85ae8eb |
test | tar | Create a tar-file or a tar.gz at location: filename.
params:
gzip: if True - gzip the file, default = False
dirs: dirs to be tared
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename. | pyque/sh.py | def tar(filename, dirs=[], gzip=False):
""" Create a tar-file or a tar.gz at location: filename.
params:
gzip: if True - gzip the file, default = False
dirs: dirs to be tared
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename.
"""
if gzip:
cmd = 'tar czvf %s ' % filename
else:
cmd = 'tar cvf %s ' % filename
if type(dirs) != 'list':
dirs = [dirs]
cmd += ' '.join(str(x) for x in dirs)
retcode, output = sh(cmd)
return (retcode, output, filename) | def tar(filename, dirs=[], gzip=False):
""" Create a tar-file or a tar.gz at location: filename.
params:
gzip: if True - gzip the file, default = False
dirs: dirs to be tared
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename.
"""
if gzip:
cmd = 'tar czvf %s ' % filename
else:
cmd = 'tar cvf %s ' % filename
if type(dirs) != 'list':
dirs = [dirs]
cmd += ' '.join(str(x) for x in dirs)
retcode, output = sh(cmd)
return (retcode, output, filename) | [
"Create",
"a",
"tar",
"-",
"file",
"or",
"a",
"tar",
".",
"gz",
"at",
"location",
":",
"filename",
".",
"params",
":",
"gzip",
":",
"if",
"True",
"-",
"gzip",
"the",
"file",
"default",
"=",
"False",
"dirs",
":",
"dirs",
"to",
"be",
"tared",
"returns",
"a",
"3",
"-",
"tuple",
"with",
"returncode",
"(",
"integer",
")",
"terminal",
"output",
"(",
"string",
")",
"and",
"the",
"new",
"filename",
"."
] | bmaeser/pyque | python | https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/sh.py#L44-L64 | [
"def",
"tar",
"(",
"filename",
",",
"dirs",
"=",
"[",
"]",
",",
"gzip",
"=",
"False",
")",
":",
"if",
"gzip",
":",
"cmd",
"=",
"'tar czvf %s '",
"%",
"filename",
"else",
":",
"cmd",
"=",
"'tar cvf %s '",
"%",
"filename",
"if",
"type",
"(",
"dirs",
")",
"!=",
"'list'",
":",
"dirs",
"=",
"[",
"dirs",
"]",
"cmd",
"+=",
"' '",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"dirs",
")",
"retcode",
",",
"output",
"=",
"sh",
"(",
"cmd",
")",
"return",
"(",
"retcode",
",",
"output",
",",
"filename",
")"
] | 856dceab8d89cf3771cf21e682466c29a85ae8eb |
test | chown | alternative to os.chown.
wraps around unix chown
example:
chown('/tmp/test/', bob, bob)
returns 2-tuple: exitcode and terminal output | pyque/sh.py | def chown(path, uid, guid, recursive=True):
""" alternative to os.chown.
wraps around unix chown
example:
chown('/tmp/test/', bob, bob)
returns 2-tuple: exitcode and terminal output
"""
if recursive:
cmd = 'chown -R %s:%s %s' % (uid, guid, path)
else:
cmd = 'chown %s:%s %s' % (uid, guid, path)
return sh(cmd) | def chown(path, uid, guid, recursive=True):
""" alternative to os.chown.
wraps around unix chown
example:
chown('/tmp/test/', bob, bob)
returns 2-tuple: exitcode and terminal output
"""
if recursive:
cmd = 'chown -R %s:%s %s' % (uid, guid, path)
else:
cmd = 'chown %s:%s %s' % (uid, guid, path)
return sh(cmd) | [
"alternative",
"to",
"os",
".",
"chown",
".",
"wraps",
"around",
"unix",
"chown",
"example",
":",
"chown",
"(",
"/",
"tmp",
"/",
"test",
"/",
"bob",
"bob",
")"
] | bmaeser/pyque | python | https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/sh.py#L66-L80 | [
"def",
"chown",
"(",
"path",
",",
"uid",
",",
"guid",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"recursive",
":",
"cmd",
"=",
"'chown -R %s:%s %s'",
"%",
"(",
"uid",
",",
"guid",
",",
"path",
")",
"else",
":",
"cmd",
"=",
"'chown %s:%s %s'",
"%",
"(",
"uid",
",",
"guid",
",",
"path",
")",
"return",
"sh",
"(",
"cmd",
")"
] | 856dceab8d89cf3771cf21e682466c29a85ae8eb |
test | chmod | alternative to os. | pyque/sh.py | def chmod(path, mode, recursive=True):
""" alternative to os.
"""
if recursive:
cmd = 'chmod -R %s %s' % (mode, path)
else:
cmd = 'chmod %s %s' % (mode, path)
return sh(cmd) | def chmod(path, mode, recursive=True):
""" alternative to os.
"""
if recursive:
cmd = 'chmod -R %s %s' % (mode, path)
else:
cmd = 'chmod %s %s' % (mode, path)
return sh(cmd) | [
"alternative",
"to",
"os",
"."
] | bmaeser/pyque | python | https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/sh.py#L82-L91 | [
"def",
"chmod",
"(",
"path",
",",
"mode",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"recursive",
":",
"cmd",
"=",
"'chmod -R %s %s'",
"%",
"(",
"mode",
",",
"path",
")",
"else",
":",
"cmd",
"=",
"'chmod %s %s'",
"%",
"(",
"mode",
",",
"path",
")",
"return",
"sh",
"(",
"cmd",
")"
] | 856dceab8d89cf3771cf21e682466c29a85ae8eb |
test | StackSentinelClient.handle_exception | Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself
:param state: Dictionary of state information associated with the error. This could be form data, cookie data, whatnot. NOTE: sys and machine are added to this dictionary if they are not already included.
:param tags: Any string tags you want associated with the exception report.
:param return_feedback_urls: If True, Stack Sentinel will return feedback URLs you can present to the user for extra debugging information.
:param dry_run: If True, method will not actively send in error information to API. Instead, it will return a request object and payload. Used in unittests. | StackSentinel/__init__.py | def handle_exception(self, exc_info=None, state=None, tags=None, return_feedback_urls=False,
dry_run=False):
"""
Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself
:param state: Dictionary of state information associated with the error. This could be form data, cookie data, whatnot. NOTE: sys and machine are added to this dictionary if they are not already included.
:param tags: Any string tags you want associated with the exception report.
:param return_feedback_urls: If True, Stack Sentinel will return feedback URLs you can present to the user for extra debugging information.
:param dry_run: If True, method will not actively send in error information to API. Instead, it will return a request object and payload. Used in unittests.
"""
if not exc_info:
exc_info = sys.exc_info()
if exc_info is None:
raise StackSentinelError("handle_exception called outside of exception handler")
(etype, value, tb) = exc_info
try:
msg = value.args[0]
except:
msg = repr(value)
if not isinstance(tags, list):
tags = [tags]
limit = None
new_tb = []
n = 0
while tb is not None and (limit is None or n < limit):
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filename = co.co_filename
name = co.co_name
tb = tb.tb_next
n = n + 1
new_tb.append({'line': lineno, 'module': filename, 'method': name})
if state is None:
state = {}
if 'sys' not in state:
try:
state['sys'] = self._get_sys_info()
except Exception as e:
state['sys'] = '<Unable to get sys: %r>' % e
if 'machine' not in state:
try:
state['machine'] = self._get_machine_info()
except Exception as e:
state['machine'] = '<Unable to get machine: %e>' % e
if tags is None:
tags = []
# The joy of Unicode
if sys.version_info.major > 2:
error_type = str(etype.__name__)
error_message = str(value)
else:
error_type = unicode(etype.__name__)
error_message = unicode(value)
send_error_args = dict(error_type=error_type,
error_message=error_message,
traceback=new_tb,
environment=self.environment,
state=state,
tags=self.tags + tags,
return_feedback_urls=return_feedback_urls)
if dry_run:
return send_error_args
else:
return self.send_error(**send_error_args) | def handle_exception(self, exc_info=None, state=None, tags=None, return_feedback_urls=False,
dry_run=False):
"""
Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself
:param state: Dictionary of state information associated with the error. This could be form data, cookie data, whatnot. NOTE: sys and machine are added to this dictionary if they are not already included.
:param tags: Any string tags you want associated with the exception report.
:param return_feedback_urls: If True, Stack Sentinel will return feedback URLs you can present to the user for extra debugging information.
:param dry_run: If True, method will not actively send in error information to API. Instead, it will return a request object and payload. Used in unittests.
"""
if not exc_info:
exc_info = sys.exc_info()
if exc_info is None:
raise StackSentinelError("handle_exception called outside of exception handler")
(etype, value, tb) = exc_info
try:
msg = value.args[0]
except:
msg = repr(value)
if not isinstance(tags, list):
tags = [tags]
limit = None
new_tb = []
n = 0
while tb is not None and (limit is None or n < limit):
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filename = co.co_filename
name = co.co_name
tb = tb.tb_next
n = n + 1
new_tb.append({'line': lineno, 'module': filename, 'method': name})
if state is None:
state = {}
if 'sys' not in state:
try:
state['sys'] = self._get_sys_info()
except Exception as e:
state['sys'] = '<Unable to get sys: %r>' % e
if 'machine' not in state:
try:
state['machine'] = self._get_machine_info()
except Exception as e:
state['machine'] = '<Unable to get machine: %e>' % e
if tags is None:
tags = []
# The joy of Unicode
if sys.version_info.major > 2:
error_type = str(etype.__name__)
error_message = str(value)
else:
error_type = unicode(etype.__name__)
error_message = unicode(value)
send_error_args = dict(error_type=error_type,
error_message=error_message,
traceback=new_tb,
environment=self.environment,
state=state,
tags=self.tags + tags,
return_feedback_urls=return_feedback_urls)
if dry_run:
return send_error_args
else:
return self.send_error(**send_error_args) | [
"Call",
"this",
"method",
"from",
"within",
"a",
"try",
"/",
"except",
"clause",
"to",
"generate",
"a",
"call",
"to",
"Stack",
"Sentinel",
"."
] | StackSentinel/stacksentinel-python | python | https://github.com/StackSentinel/stacksentinel-python/blob/253664ac5ccaeb312f4288580e10061dac65403c/StackSentinel/__init__.py#L113-L190 | [
"def",
"handle_exception",
"(",
"self",
",",
"exc_info",
"=",
"None",
",",
"state",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"return_feedback_urls",
"=",
"False",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"not",
"exc_info",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"exc_info",
"is",
"None",
":",
"raise",
"StackSentinelError",
"(",
"\"handle_exception called outside of exception handler\"",
")",
"(",
"etype",
",",
"value",
",",
"tb",
")",
"=",
"exc_info",
"try",
":",
"msg",
"=",
"value",
".",
"args",
"[",
"0",
"]",
"except",
":",
"msg",
"=",
"repr",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"limit",
"=",
"None",
"new_tb",
"=",
"[",
"]",
"n",
"=",
"0",
"while",
"tb",
"is",
"not",
"None",
"and",
"(",
"limit",
"is",
"None",
"or",
"n",
"<",
"limit",
")",
":",
"f",
"=",
"tb",
".",
"tb_frame",
"lineno",
"=",
"tb",
".",
"tb_lineno",
"co",
"=",
"f",
".",
"f_code",
"filename",
"=",
"co",
".",
"co_filename",
"name",
"=",
"co",
".",
"co_name",
"tb",
"=",
"tb",
".",
"tb_next",
"n",
"=",
"n",
"+",
"1",
"new_tb",
".",
"append",
"(",
"{",
"'line'",
":",
"lineno",
",",
"'module'",
":",
"filename",
",",
"'method'",
":",
"name",
"}",
")",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"{",
"}",
"if",
"'sys'",
"not",
"in",
"state",
":",
"try",
":",
"state",
"[",
"'sys'",
"]",
"=",
"self",
".",
"_get_sys_info",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"state",
"[",
"'sys'",
"]",
"=",
"'<Unable to get sys: %r>'",
"%",
"e",
"if",
"'machine'",
"not",
"in",
"state",
":",
"try",
":",
"state",
"[",
"'machine'",
"]",
"=",
"self",
".",
"_get_machine_info",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"state",
"[",
"'machine'",
"]",
"=",
"'<Unable to get machine: %e>'",
"%",
"e",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"# The joy of Unicode",
"if",
"sys",
".",
"version_info",
".",
"major",
">",
"2",
":",
"error_type",
"=",
"str",
"(",
"etype",
".",
"__name__",
")",
"error_message",
"=",
"str",
"(",
"value",
")",
"else",
":",
"error_type",
"=",
"unicode",
"(",
"etype",
".",
"__name__",
")",
"error_message",
"=",
"unicode",
"(",
"value",
")",
"send_error_args",
"=",
"dict",
"(",
"error_type",
"=",
"error_type",
",",
"error_message",
"=",
"error_message",
",",
"traceback",
"=",
"new_tb",
",",
"environment",
"=",
"self",
".",
"environment",
",",
"state",
"=",
"state",
",",
"tags",
"=",
"self",
".",
"tags",
"+",
"tags",
",",
"return_feedback_urls",
"=",
"return_feedback_urls",
")",
"if",
"dry_run",
":",
"return",
"send_error_args",
"else",
":",
"return",
"self",
".",
"send_error",
"(",
"*",
"*",
"send_error_args",
")"
] | 253664ac5ccaeb312f4288580e10061dac65403c |
test | StackSentinelClient.send_error | Sends error payload to Stack Sentinel API, returning a parsed JSON response. (Parsed as in,
converted into Python dict/list objects)
:param error_type: Type of error generated. (Eg, "TypeError")
:param error_message: Message of error generated (Eg, "cannot concatenate 'str' and 'int' objects")
:param traceback: List of dictionaries. Each dictionary should contain, "line", "method", and "module" keys.
:param environment: Environment the error occurred in (eg, "devel")_
:param state: State of the application when the error happened. Could contain form data, cookies, etc.
:param tags: Arbitrary tags you want associated with the error. list.
:param return_feedback_urls: If True, return payload will offer URLs to send users to collect additional feedback for debugging.
:return: Parsed return value from Stack Sentinel API | StackSentinel/__init__.py | def send_error(self, error_type, error_message, traceback, environment, state, tags=None,
return_feedback_urls=False):
"""
Sends error payload to Stack Sentinel API, returning a parsed JSON response. (Parsed as in,
converted into Python dict/list objects)
:param error_type: Type of error generated. (Eg, "TypeError")
:param error_message: Message of error generated (Eg, "cannot concatenate 'str' and 'int' objects")
:param traceback: List of dictionaries. Each dictionary should contain, "line", "method", and "module" keys.
:param environment: Environment the error occurred in (eg, "devel")_
:param state: State of the application when the error happened. Could contain form data, cookies, etc.
:param tags: Arbitrary tags you want associated with the error. list.
:param return_feedback_urls: If True, return payload will offer URLs to send users to collect additional feedback for debugging.
:return: Parsed return value from Stack Sentinel API
"""
(request, payload) = self._generate_request(environment, error_message, error_type, return_feedback_urls,
state, tags, traceback)
try:
response = urlopen(request)
except HTTPError as e:
if e.code == 400:
raise StackSentinelError(e.read())
else:
raise
if sys.version_info.major > 2:
text_response = response.read().decode(response.headers.get_content_charset() or 'utf8')
else:
encoding = response.headers.get('content-type', '').split('charset=')[-1].strip()
if encoding:
text_response = response.read().decode('utf8', 'replace')
else:
text_response = response.read().decode(encoding)
return json.loads(text_response) | def send_error(self, error_type, error_message, traceback, environment, state, tags=None,
return_feedback_urls=False):
"""
Sends error payload to Stack Sentinel API, returning a parsed JSON response. (Parsed as in,
converted into Python dict/list objects)
:param error_type: Type of error generated. (Eg, "TypeError")
:param error_message: Message of error generated (Eg, "cannot concatenate 'str' and 'int' objects")
:param traceback: List of dictionaries. Each dictionary should contain, "line", "method", and "module" keys.
:param environment: Environment the error occurred in (eg, "devel")_
:param state: State of the application when the error happened. Could contain form data, cookies, etc.
:param tags: Arbitrary tags you want associated with the error. list.
:param return_feedback_urls: If True, return payload will offer URLs to send users to collect additional feedback for debugging.
:return: Parsed return value from Stack Sentinel API
"""
(request, payload) = self._generate_request(environment, error_message, error_type, return_feedback_urls,
state, tags, traceback)
try:
response = urlopen(request)
except HTTPError as e:
if e.code == 400:
raise StackSentinelError(e.read())
else:
raise
if sys.version_info.major > 2:
text_response = response.read().decode(response.headers.get_content_charset() or 'utf8')
else:
encoding = response.headers.get('content-type', '').split('charset=')[-1].strip()
if encoding:
text_response = response.read().decode('utf8', 'replace')
else:
text_response = response.read().decode(encoding)
return json.loads(text_response) | [
"Sends",
"error",
"payload",
"to",
"Stack",
"Sentinel",
"API",
"returning",
"a",
"parsed",
"JSON",
"response",
".",
"(",
"Parsed",
"as",
"in",
"converted",
"into",
"Python",
"dict",
"/",
"list",
"objects",
")"
] | StackSentinel/stacksentinel-python | python | https://github.com/StackSentinel/stacksentinel-python/blob/253664ac5ccaeb312f4288580e10061dac65403c/StackSentinel/__init__.py#L219-L254 | [
"def",
"send_error",
"(",
"self",
",",
"error_type",
",",
"error_message",
",",
"traceback",
",",
"environment",
",",
"state",
",",
"tags",
"=",
"None",
",",
"return_feedback_urls",
"=",
"False",
")",
":",
"(",
"request",
",",
"payload",
")",
"=",
"self",
".",
"_generate_request",
"(",
"environment",
",",
"error_message",
",",
"error_type",
",",
"return_feedback_urls",
",",
"state",
",",
"tags",
",",
"traceback",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"request",
")",
"except",
"HTTPError",
"as",
"e",
":",
"if",
"e",
".",
"code",
"==",
"400",
":",
"raise",
"StackSentinelError",
"(",
"e",
".",
"read",
"(",
")",
")",
"else",
":",
"raise",
"if",
"sys",
".",
"version_info",
".",
"major",
">",
"2",
":",
"text_response",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"response",
".",
"headers",
".",
"get_content_charset",
"(",
")",
"or",
"'utf8'",
")",
"else",
":",
"encoding",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
".",
"split",
"(",
"'charset='",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"if",
"encoding",
":",
"text_response",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf8'",
",",
"'replace'",
")",
"else",
":",
"text_response",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"encoding",
")",
"return",
"json",
".",
"loads",
"(",
"text_response",
")"
] | 253664ac5ccaeb312f4288580e10061dac65403c |
test | make_internal_signing_service | Given configuration initiate an InternalSigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A InternalSigningService instance | src/fedoidcmsg/signing_service.py | def make_internal_signing_service(config, entity_id):
"""
Given configuration initiate an InternalSigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A InternalSigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ_SPECS])
_kj = init_key_jar(**_args)
return InternalSigningService(entity_id, _kj) | def make_internal_signing_service(config, entity_id):
"""
Given configuration initiate an InternalSigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A InternalSigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ_SPECS])
_kj = init_key_jar(**_args)
return InternalSigningService(entity_id, _kj) | [
"Given",
"configuration",
"initiate",
"an",
"InternalSigningService",
"instance"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L306-L318 | [
"def",
"make_internal_signing_service",
"(",
"config",
",",
"entity_id",
")",
":",
"_args",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"config",
".",
"items",
"(",
")",
"if",
"k",
"in",
"KJ_SPECS",
"]",
")",
"_kj",
"=",
"init_key_jar",
"(",
"*",
"*",
"_args",
")",
"return",
"InternalSigningService",
"(",
"entity_id",
",",
"_kj",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | make_signing_service | Given configuration initiate a SigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A SigningService instance | src/fedoidcmsg/signing_service.py | def make_signing_service(config, entity_id):
"""
Given configuration initiate a SigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A SigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ_SPECS])
_kj = init_key_jar(**_args)
if config['type'] == 'internal':
signer = InternalSigningService(entity_id, _kj)
elif config['type'] == 'web':
_kj.issuer_keys[config['iss']] = _kj.issuer_keys['']
del _kj.issuer_keys['']
signer = WebSigningServiceClient(config['iss'], config['url'],
entity_id, _kj)
else:
raise ValueError('Unknown signer type: {}'.format(config['type']))
return signer | def make_signing_service(config, entity_id):
"""
Given configuration initiate a SigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A SigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ_SPECS])
_kj = init_key_jar(**_args)
if config['type'] == 'internal':
signer = InternalSigningService(entity_id, _kj)
elif config['type'] == 'web':
_kj.issuer_keys[config['iss']] = _kj.issuer_keys['']
del _kj.issuer_keys['']
signer = WebSigningServiceClient(config['iss'], config['url'],
entity_id, _kj)
else:
raise ValueError('Unknown signer type: {}'.format(config['type']))
return signer | [
"Given",
"configuration",
"initiate",
"a",
"SigningService",
"instance"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L321-L343 | [
"def",
"make_signing_service",
"(",
"config",
",",
"entity_id",
")",
":",
"_args",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"config",
".",
"items",
"(",
")",
"if",
"k",
"in",
"KJ_SPECS",
"]",
")",
"_kj",
"=",
"init_key_jar",
"(",
"*",
"*",
"_args",
")",
"if",
"config",
"[",
"'type'",
"]",
"==",
"'internal'",
":",
"signer",
"=",
"InternalSigningService",
"(",
"entity_id",
",",
"_kj",
")",
"elif",
"config",
"[",
"'type'",
"]",
"==",
"'web'",
":",
"_kj",
".",
"issuer_keys",
"[",
"config",
"[",
"'iss'",
"]",
"]",
"=",
"_kj",
".",
"issuer_keys",
"[",
"''",
"]",
"del",
"_kj",
".",
"issuer_keys",
"[",
"''",
"]",
"signer",
"=",
"WebSigningServiceClient",
"(",
"config",
"[",
"'iss'",
"]",
",",
"config",
"[",
"'url'",
"]",
",",
"entity_id",
",",
"_kj",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown signer type: {}'",
".",
"format",
"(",
"config",
"[",
"'type'",
"]",
")",
")",
"return",
"signer"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | InternalSigningService.sign | Creates a signed JWT
:param req: Original metadata statement as a
:py:class:`MetadataStatement` instance
:param receiver: The intended audience for the JWS
:param iss: Issuer or the JWT
:param lifetime: Lifetime of the signature
:param sign_alg: Which signature algorithm to use
:param aud: The audience, a list of receivers.
:return: A signed JWT | src/fedoidcmsg/signing_service.py | def sign(self, req, receiver='', iss='', lifetime=0, sign_alg='', aud=None):
"""
Creates a signed JWT
:param req: Original metadata statement as a
:py:class:`MetadataStatement` instance
:param receiver: The intended audience for the JWS
:param iss: Issuer or the JWT
:param lifetime: Lifetime of the signature
:param sign_alg: Which signature algorithm to use
:param aud: The audience, a list of receivers.
:return: A signed JWT
"""
if not sign_alg:
for key_type, s_alg in [('RSA', 'RS256'), ('EC', 'ES256')]:
if self.keyjar.get_signing_key(key_type=key_type):
sign_alg = s_alg
break
if not sign_alg:
raise NoSigningKeys('Could not find any signing keys')
return self.pack(req=req, receiver=receiver, iss=iss, lifetime=lifetime,
sign=True, encrypt=False, sign_alg=sign_alg) | def sign(self, req, receiver='', iss='', lifetime=0, sign_alg='', aud=None):
"""
Creates a signed JWT
:param req: Original metadata statement as a
:py:class:`MetadataStatement` instance
:param receiver: The intended audience for the JWS
:param iss: Issuer or the JWT
:param lifetime: Lifetime of the signature
:param sign_alg: Which signature algorithm to use
:param aud: The audience, a list of receivers.
:return: A signed JWT
"""
if not sign_alg:
for key_type, s_alg in [('RSA', 'RS256'), ('EC', 'ES256')]:
if self.keyjar.get_signing_key(key_type=key_type):
sign_alg = s_alg
break
if not sign_alg:
raise NoSigningKeys('Could not find any signing keys')
return self.pack(req=req, receiver=receiver, iss=iss, lifetime=lifetime,
sign=True, encrypt=False, sign_alg=sign_alg) | [
"Creates",
"a",
"signed",
"JWT"
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L73-L96 | [
"def",
"sign",
"(",
"self",
",",
"req",
",",
"receiver",
"=",
"''",
",",
"iss",
"=",
"''",
",",
"lifetime",
"=",
"0",
",",
"sign_alg",
"=",
"''",
",",
"aud",
"=",
"None",
")",
":",
"if",
"not",
"sign_alg",
":",
"for",
"key_type",
",",
"s_alg",
"in",
"[",
"(",
"'RSA'",
",",
"'RS256'",
")",
",",
"(",
"'EC'",
",",
"'ES256'",
")",
"]",
":",
"if",
"self",
".",
"keyjar",
".",
"get_signing_key",
"(",
"key_type",
"=",
"key_type",
")",
":",
"sign_alg",
"=",
"s_alg",
"break",
"if",
"not",
"sign_alg",
":",
"raise",
"NoSigningKeys",
"(",
"'Could not find any signing keys'",
")",
"return",
"self",
".",
"pack",
"(",
"req",
"=",
"req",
",",
"receiver",
"=",
"receiver",
",",
"iss",
"=",
"iss",
",",
"lifetime",
"=",
"lifetime",
",",
"sign",
"=",
"True",
",",
"encrypt",
"=",
"False",
",",
"sign_alg",
"=",
"sign_alg",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | WebSigningServiceClient.create | Uses POST to send a first metadata statement signing request to
a signing service.
:param req: The metadata statement that the entity wants signed
:return: returns a dictionary with 'sms' and 'loc' as keys. | src/fedoidcmsg/signing_service.py | def create(self, req, **kwargs):
"""
Uses POST to send a first metadata statement signing request to
a signing service.
:param req: The metadata statement that the entity wants signed
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.post(self.url, json=req, **self.req_args())
return self.parse_response(response) | def create(self, req, **kwargs):
"""
Uses POST to send a first metadata statement signing request to
a signing service.
:param req: The metadata statement that the entity wants signed
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.post(self.url, json=req, **self.req_args())
return self.parse_response(response) | [
"Uses",
"POST",
"to",
"send",
"a",
"first",
"metadata",
"statement",
"signing",
"request",
"to",
"a",
"signing",
"service",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L265-L275 | [
"def",
"create",
"(",
"self",
",",
"req",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
",",
"json",
"=",
"req",
",",
"*",
"*",
"self",
".",
"req_args",
"(",
")",
")",
"return",
"self",
".",
"parse_response",
"(",
"response",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | WebSigningServiceClient.update_metadata_statement | Uses PUT to update an earlier accepted and signed metadata statement.
:param location: A URL to which the update request is sent
:param req: The diff between what is registereed with the signing
service and what it should be.
:return: returns a dictionary with 'sms' and 'loc' as keys. | src/fedoidcmsg/signing_service.py | def update_metadata_statement(self, location, req):
"""
Uses PUT to update an earlier accepted and signed metadata statement.
:param location: A URL to which the update request is sent
:param req: The diff between what is registereed with the signing
service and what it should be.
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.put(location, json=req, **self.req_args())
return self.parse_response(response) | def update_metadata_statement(self, location, req):
"""
Uses PUT to update an earlier accepted and signed metadata statement.
:param location: A URL to which the update request is sent
:param req: The diff between what is registereed with the signing
service and what it should be.
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.put(location, json=req, **self.req_args())
return self.parse_response(response) | [
"Uses",
"PUT",
"to",
"update",
"an",
"earlier",
"accepted",
"and",
"signed",
"metadata",
"statement",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L280-L290 | [
"def",
"update_metadata_statement",
"(",
"self",
",",
"location",
",",
"req",
")",
":",
"response",
"=",
"requests",
".",
"put",
"(",
"location",
",",
"json",
"=",
"req",
",",
"*",
"*",
"self",
".",
"req_args",
"(",
")",
")",
"return",
"self",
".",
"parse_response",
"(",
"response",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | WebSigningServiceClient.update_signature | Uses GET to get a newly signed metadata statement.
:param location: A URL to which the request is sent
:return: returns a dictionary with 'sms' and 'loc' as keys. | src/fedoidcmsg/signing_service.py | def update_signature(self, location):
"""
Uses GET to get a newly signed metadata statement.
:param location: A URL to which the request is sent
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.get(location, **self.req_args())
return self.parse_response(response) | def update_signature(self, location):
"""
Uses GET to get a newly signed metadata statement.
:param location: A URL to which the request is sent
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.get(location, **self.req_args())
return self.parse_response(response) | [
"Uses",
"GET",
"to",
"get",
"a",
"newly",
"signed",
"metadata",
"statement",
"."
] | IdentityPython/fedoidcmsg | python | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/signing_service.py#L292-L300 | [
"def",
"update_signature",
"(",
"self",
",",
"location",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"location",
",",
"*",
"*",
"self",
".",
"req_args",
"(",
")",
")",
"return",
"self",
".",
"parse_response",
"(",
"response",
")"
] | d30107be02521fa6cdfe285da3b6b0cdd153c8cc |
test | Package._yield_bundle_contents | Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle. | easywebassets/package.py | def _yield_bundle_contents(self, data):
"""Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle."""
if isinstance(data, list):
contents = data
else:
contents = data.get('contents', [])
if isinstance(contents, six.string_types):
contents = contents,
for content in contents:
if isinstance(content, dict):
content = self._create_bundle(content)
yield content | def _yield_bundle_contents(self, data):
"""Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle."""
if isinstance(data, list):
contents = data
else:
contents = data.get('contents', [])
if isinstance(contents, six.string_types):
contents = contents,
for content in contents:
if isinstance(content, dict):
content = self._create_bundle(content)
yield content | [
"Yield",
"bundle",
"contents",
"from",
"the",
"given",
"dict",
"."
] | frascoweb/easywebassets | python | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L80-L94 | [
"def",
"_yield_bundle_contents",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"contents",
"=",
"data",
"else",
":",
"contents",
"=",
"data",
".",
"get",
"(",
"'contents'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"contents",
",",
"six",
".",
"string_types",
")",
":",
"contents",
"=",
"contents",
",",
"for",
"content",
"in",
"contents",
":",
"if",
"isinstance",
"(",
"content",
",",
"dict",
")",
":",
"content",
"=",
"self",
".",
"_create_bundle",
"(",
"content",
")",
"yield",
"content"
] | 02f84376067c827c84fc1773895bb2784e033949 |
test | Package._create_bundle | Return a bundle initialised by the given dict. | easywebassets/package.py | def _create_bundle(self, data):
"""Return a bundle initialised by the given dict."""
kwargs = {}
filters = None
if isinstance(data, dict):
kwargs.update(
filters=data.get('filters', None),
output=data.get('output', None),
debug=data.get('debug', None),
extra=data.get('extra', {}),
config=data.get('config', {}),
depends=data.get('depends', None))
bundle = Bundle(*list(self._yield_bundle_contents(data)), **kwargs)
return self._auto_filter_bundle(bundle) | def _create_bundle(self, data):
"""Return a bundle initialised by the given dict."""
kwargs = {}
filters = None
if isinstance(data, dict):
kwargs.update(
filters=data.get('filters', None),
output=data.get('output', None),
debug=data.get('debug', None),
extra=data.get('extra', {}),
config=data.get('config', {}),
depends=data.get('depends', None))
bundle = Bundle(*list(self._yield_bundle_contents(data)), **kwargs)
return self._auto_filter_bundle(bundle) | [
"Return",
"a",
"bundle",
"initialised",
"by",
"the",
"given",
"dict",
"."
] | frascoweb/easywebassets | python | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L96-L109 | [
"def",
"_create_bundle",
"(",
"self",
",",
"data",
")",
":",
"kwargs",
"=",
"{",
"}",
"filters",
"=",
"None",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"kwargs",
".",
"update",
"(",
"filters",
"=",
"data",
".",
"get",
"(",
"'filters'",
",",
"None",
")",
",",
"output",
"=",
"data",
".",
"get",
"(",
"'output'",
",",
"None",
")",
",",
"debug",
"=",
"data",
".",
"get",
"(",
"'debug'",
",",
"None",
")",
",",
"extra",
"=",
"data",
".",
"get",
"(",
"'extra'",
",",
"{",
"}",
")",
",",
"config",
"=",
"data",
".",
"get",
"(",
"'config'",
",",
"{",
"}",
")",
",",
"depends",
"=",
"data",
".",
"get",
"(",
"'depends'",
",",
"None",
")",
")",
"bundle",
"=",
"Bundle",
"(",
"*",
"list",
"(",
"self",
".",
"_yield_bundle_contents",
"(",
"data",
")",
")",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_auto_filter_bundle",
"(",
"bundle",
")"
] | 02f84376067c827c84fc1773895bb2784e033949 |
test | Package.urls_for | Returns urls needed to include all assets of asset_type | easywebassets/package.py | def urls_for(self, asset_type, *args, **kwargs):
"""Returns urls needed to include all assets of asset_type
"""
return self.urls_for_depends(asset_type, *args, **kwargs) + \
self.urls_for_self(asset_type, *args, **kwargs) | def urls_for(self, asset_type, *args, **kwargs):
"""Returns urls needed to include all assets of asset_type
"""
return self.urls_for_depends(asset_type, *args, **kwargs) + \
self.urls_for_self(asset_type, *args, **kwargs) | [
"Returns",
"urls",
"needed",
"to",
"include",
"all",
"assets",
"of",
"asset_type"
] | frascoweb/easywebassets | python | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L194-L198 | [
"def",
"urls_for",
"(",
"self",
",",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"urls_for_depends",
"(",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"self",
".",
"urls_for_self",
"(",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 02f84376067c827c84fc1773895bb2784e033949 |
test | Package.html_tags_for | Return html tags for urls of asset_type | easywebassets/package.py | def html_tags_for(self, asset_type, *args, **kwargs):
"""Return html tags for urls of asset_type
"""
html = []
for ref in self.depends:
html.append(self._ref(ref).html_tags_for(asset_type, *args, **kwargs))
if asset_type in self.typed_bundles:
html.append(render_asset_html_tags(asset_type, self.urls_for_self(asset_type, *args, **kwargs)))
return "\n".join(html) | def html_tags_for(self, asset_type, *args, **kwargs):
"""Return html tags for urls of asset_type
"""
html = []
for ref in self.depends:
html.append(self._ref(ref).html_tags_for(asset_type, *args, **kwargs))
if asset_type in self.typed_bundles:
html.append(render_asset_html_tags(asset_type, self.urls_for_self(asset_type, *args, **kwargs)))
return "\n".join(html) | [
"Return",
"html",
"tags",
"for",
"urls",
"of",
"asset_type"
] | frascoweb/easywebassets | python | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L200-L208 | [
"def",
"html_tags_for",
"(",
"self",
",",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"html",
"=",
"[",
"]",
"for",
"ref",
"in",
"self",
".",
"depends",
":",
"html",
".",
"append",
"(",
"self",
".",
"_ref",
"(",
"ref",
")",
".",
"html_tags_for",
"(",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"if",
"asset_type",
"in",
"self",
".",
"typed_bundles",
":",
"html",
".",
"append",
"(",
"render_asset_html_tags",
"(",
"asset_type",
",",
"self",
".",
"urls_for_self",
"(",
"asset_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"html",
")"
] | 02f84376067c827c84fc1773895bb2784e033949 |
test | Package.html_tags | Return all html tags for all asset_type | easywebassets/package.py | def html_tags(self, *args, **kwargs):
"""Return all html tags for all asset_type
"""
html = []
for asset_type in list_asset_types():
html.append(self.html_tags_for(asset_type.name, *args, **kwargs))
return "\n".join(html) | def html_tags(self, *args, **kwargs):
"""Return all html tags for all asset_type
"""
html = []
for asset_type in list_asset_types():
html.append(self.html_tags_for(asset_type.name, *args, **kwargs))
return "\n".join(html) | [
"Return",
"all",
"html",
"tags",
"for",
"all",
"asset_type"
] | frascoweb/easywebassets | python | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L210-L216 | [
"def",
"html_tags",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"html",
"=",
"[",
"]",
"for",
"asset_type",
"in",
"list_asset_types",
"(",
")",
":",
"html",
".",
"append",
"(",
"self",
".",
"html_tags_for",
"(",
"asset_type",
".",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"html",
")"
] | 02f84376067c827c84fc1773895bb2784e033949 |
test | find_version | Uses re to pull out the assigned value to __version__ in filename. | setup.py | def find_version(filename):
"""Uses re to pull out the assigned value to __version__ in filename."""
with io.open(filename, encoding="utf-8") as version_file:
version_match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]',
version_file.read(), re.M)
if version_match:
return version_match.group(1)
return "0.0-version-unknown" | def find_version(filename):
"""Uses re to pull out the assigned value to __version__ in filename."""
with io.open(filename, encoding="utf-8") as version_file:
version_match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]',
version_file.read(), re.M)
if version_match:
return version_match.group(1)
return "0.0-version-unknown" | [
"Uses",
"re",
"to",
"pull",
"out",
"the",
"assigned",
"value",
"to",
"__version__",
"in",
"filename",
"."
] | a-tal/nagaram | python | https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/setup.py#L10-L18 | [
"def",
"find_version",
"(",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"version_file",
":",
"version_match",
"=",
"re",
".",
"search",
"(",
"r'^__version__ = [\\'\"]([^\\'\"]*)[\\'\"]'",
",",
"version_file",
".",
"read",
"(",
")",
",",
"re",
".",
"M",
")",
"if",
"version_match",
":",
"return",
"version_match",
".",
"group",
"(",
"1",
")",
"return",
"\"0.0-version-unknown\""
] | 2edcb0ef8cb569ebd1c398be826472b4831d6110 |
test | protocolise | Given a URL, check to see if there is an assocaited protocol.
If not, set the protocol to HTTP and return the protocolised URL | urlhelp/__init__.py | def protocolise(url):
"""
Given a URL, check to see if there is an assocaited protocol.
If not, set the protocol to HTTP and return the protocolised URL
"""
# Use the regex to match http//localhost/something
protore = re.compile(r'https?:{0,1}/{1,2}')
parsed = urlparse.urlparse(url)
if not parsed.scheme and not protore.search(url):
url = 'http://{0}'.format(url)
return url | def protocolise(url):
"""
Given a URL, check to see if there is an assocaited protocol.
If not, set the protocol to HTTP and return the protocolised URL
"""
# Use the regex to match http//localhost/something
protore = re.compile(r'https?:{0,1}/{1,2}')
parsed = urlparse.urlparse(url)
if not parsed.scheme and not protore.search(url):
url = 'http://{0}'.format(url)
return url | [
"Given",
"a",
"URL",
"check",
"to",
"see",
"if",
"there",
"is",
"an",
"assocaited",
"protocol",
"."
] | davidmiller/urlhelp | python | https://github.com/davidmiller/urlhelp/blob/9cc417a5dc5bd4a7e17ed78a1f1394a6ece9faa5/urlhelp/__init__.py#L21-L32 | [
"def",
"protocolise",
"(",
"url",
")",
":",
"# Use the regex to match http//localhost/something",
"protore",
"=",
"re",
".",
"compile",
"(",
"r'https?:{0,1}/{1,2}'",
")",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"scheme",
"and",
"not",
"protore",
".",
"search",
"(",
"url",
")",
":",
"url",
"=",
"'http://{0}'",
".",
"format",
"(",
"url",
")",
"return",
"url"
] | 9cc417a5dc5bd4a7e17ed78a1f1394a6ece9faa5 |
test | find_links | Find the href destinations of all links at URL
Arguments:
- `url`:
Return: list[str]
Exceptions: None | urlhelp/__init__.py | def find_links(url):
"""
Find the href destinations of all links at URL
Arguments:
- `url`:
Return: list[str]
Exceptions: None
"""
url = protocolise(url)
content = requests.get(url).content
flike = StringIO(content)
root = html.parse(flike).getroot()
atags = root.cssselect('a')
hrefs = [a.attrib['href'] for a in atags]
# !!! This does the wrong thing for bbc.co.uk/index.html
hrefs = [h if h.startswith('http') else '/'.join([url, h]) for h in hrefs ]
return hrefs | def find_links(url):
"""
Find the href destinations of all links at URL
Arguments:
- `url`:
Return: list[str]
Exceptions: None
"""
url = protocolise(url)
content = requests.get(url).content
flike = StringIO(content)
root = html.parse(flike).getroot()
atags = root.cssselect('a')
hrefs = [a.attrib['href'] for a in atags]
# !!! This does the wrong thing for bbc.co.uk/index.html
hrefs = [h if h.startswith('http') else '/'.join([url, h]) for h in hrefs ]
return hrefs | [
"Find",
"the",
"href",
"destinations",
"of",
"all",
"links",
"at",
"URL"
] | davidmiller/urlhelp | python | https://github.com/davidmiller/urlhelp/blob/9cc417a5dc5bd4a7e17ed78a1f1394a6ece9faa5/urlhelp/__init__.py#L34-L52 | [
"def",
"find_links",
"(",
"url",
")",
":",
"url",
"=",
"protocolise",
"(",
"url",
")",
"content",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"content",
"flike",
"=",
"StringIO",
"(",
"content",
")",
"root",
"=",
"html",
".",
"parse",
"(",
"flike",
")",
".",
"getroot",
"(",
")",
"atags",
"=",
"root",
".",
"cssselect",
"(",
"'a'",
")",
"hrefs",
"=",
"[",
"a",
".",
"attrib",
"[",
"'href'",
"]",
"for",
"a",
"in",
"atags",
"]",
"# !!! This does the wrong thing for bbc.co.uk/index.html",
"hrefs",
"=",
"[",
"h",
"if",
"h",
".",
"startswith",
"(",
"'http'",
")",
"else",
"'/'",
".",
"join",
"(",
"[",
"url",
",",
"h",
"]",
")",
"for",
"h",
"in",
"hrefs",
"]",
"return",
"hrefs"
] | 9cc417a5dc5bd4a7e17ed78a1f1394a6ece9faa5 |
test | _connected | Connected to AMP server, start listening locally, and give the AMP
client a reference to the local listening factory. | docs/examples/multiplexing_client.py | def _connected(client):
"""
Connected to AMP server, start listening locally, and give the AMP
client a reference to the local listening factory.
"""
log.msg("Connected to AMP server, starting to listen locally...")
localFactory = multiplexing.ProxyingFactory(client, "hello")
return listeningEndpoint.listen(localFactory) | def _connected(client):
"""
Connected to AMP server, start listening locally, and give the AMP
client a reference to the local listening factory.
"""
log.msg("Connected to AMP server, starting to listen locally...")
localFactory = multiplexing.ProxyingFactory(client, "hello")
return listeningEndpoint.listen(localFactory) | [
"Connected",
"to",
"AMP",
"server",
"start",
"listening",
"locally",
"and",
"give",
"the",
"AMP",
"client",
"a",
"reference",
"to",
"the",
"local",
"listening",
"factory",
"."
] | lvh/txampext | python | https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/docs/examples/multiplexing_client.py#L31-L38 | [
"def",
"_connected",
"(",
"client",
")",
":",
"log",
".",
"msg",
"(",
"\"Connected to AMP server, starting to listen locally...\"",
")",
"localFactory",
"=",
"multiplexing",
".",
"ProxyingFactory",
"(",
"client",
",",
"\"hello\"",
")",
"return",
"listeningEndpoint",
".",
"listen",
"(",
"localFactory",
")"
] | a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9 |
test | Config.getlist | Return the [section] option values as a list.
The list items must be delimited with commas and/or newlines. | nicfit/config.py | def getlist(self, section, option, *, raw=False, vars=None,
fallback=None):
"""Return the [section] option values as a list.
The list items must be delimited with commas and/or newlines.
"""
val = self.get(section, option, raw=raw, vars=vars, fallback=fallback)
values = []
if val:
for line in val.split("\n"):
values += [s.strip() for s in line.split(",")]
return values | def getlist(self, section, option, *, raw=False, vars=None,
fallback=None):
"""Return the [section] option values as a list.
The list items must be delimited with commas and/or newlines.
"""
val = self.get(section, option, raw=raw, vars=vars, fallback=fallback)
values = []
if val:
for line in val.split("\n"):
values += [s.strip() for s in line.split(",")]
return values | [
"Return",
"the",
"[",
"section",
"]",
"option",
"values",
"as",
"a",
"list",
".",
"The",
"list",
"items",
"must",
"be",
"delimited",
"with",
"commas",
"and",
"/",
"or",
"newlines",
"."
] | nicfit/nicfit.py | python | https://github.com/nicfit/nicfit.py/blob/8313f8edbc5e7361ddad496d6d818324b5236c7a/nicfit/config.py#L37-L47 | [
"def",
"getlist",
"(",
"self",
",",
"section",
",",
"option",
",",
"*",
",",
"raw",
"=",
"False",
",",
"vars",
"=",
"None",
",",
"fallback",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"get",
"(",
"section",
",",
"option",
",",
"raw",
"=",
"raw",
",",
"vars",
"=",
"vars",
",",
"fallback",
"=",
"fallback",
")",
"values",
"=",
"[",
"]",
"if",
"val",
":",
"for",
"line",
"in",
"val",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"values",
"+=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"line",
".",
"split",
"(",
"\",\"",
")",
"]",
"return",
"values"
] | 8313f8edbc5e7361ddad496d6d818324b5236c7a |
test | ServiceModules.get_modules | Get modules by project_abspath and packages_scan.
Traverse all files under folder packages_scan which set by customer.
And get all modules name. | ternya/modules.py | def get_modules(self):
"""Get modules by project_abspath and packages_scan.
Traverse all files under folder packages_scan which set by customer.
And get all modules name.
"""
if not self.project_abspath:
raise TypeError("project_abspath can not be empty.")
packages_abspath = self.get_package_abspath()
for package_abspath in packages_abspath:
self.get_module_name(package_abspath)
return self._modules | def get_modules(self):
"""Get modules by project_abspath and packages_scan.
Traverse all files under folder packages_scan which set by customer.
And get all modules name.
"""
if not self.project_abspath:
raise TypeError("project_abspath can not be empty.")
packages_abspath = self.get_package_abspath()
for package_abspath in packages_abspath:
self.get_module_name(package_abspath)
return self._modules | [
"Get",
"modules",
"by",
"project_abspath",
"and",
"packages_scan",
"."
] | ndrlslz/ternya | python | https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/modules.py#L36-L48 | [
"def",
"get_modules",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"project_abspath",
":",
"raise",
"TypeError",
"(",
"\"project_abspath can not be empty.\"",
")",
"packages_abspath",
"=",
"self",
".",
"get_package_abspath",
"(",
")",
"for",
"package_abspath",
"in",
"packages_abspath",
":",
"self",
".",
"get_module_name",
"(",
"package_abspath",
")",
"return",
"self",
".",
"_modules"
] | c05aec10029e645d63ff04313dbcf2644743481f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.