repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
KeplerGO/K2fov | K2fov/greatcircle.py | haversine | def haversine(x):
"""Return the haversine of an angle
haversine(x) = sin(x/2)**2, where x is an angle in radians
"""
y = .5*x
y = np.sin(y)
return y*y | python | def haversine(x):
"""Return the haversine of an angle
haversine(x) = sin(x/2)**2, where x is an angle in radians
"""
y = .5*x
y = np.sin(y)
return y*y | [
"def",
"haversine",
"(",
"x",
")",
":",
"y",
"=",
".5",
"*",
"x",
"y",
"=",
"np",
".",
"sin",
"(",
"y",
")",
"return",
"y",
"*",
"y"
] | Return the haversine of an angle
haversine(x) = sin(x/2)**2, where x is an angle in radians | [
"Return",
"the",
"haversine",
"of",
"an",
"angle"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/greatcircle.py#L73-L80 |
twisted/mantissa | xmantissa/websharing.py | addDefaultShareID | def addDefaultShareID(store, shareID, priority):
"""
Add a default share ID to C{store}, pointing to C{shareID} with a
priority C{priority}. The highest-priority share ID identifies the share
that will be retrieved when a user does not explicitly provide a share ID
in their URL (e.g. /host/users/username/).
@param shareID: A share ID.
@type shareID: C{unicode}
@param priority: The priority of this default. Higher means more
important.
@type priority: C{int}
"""
_DefaultShareID(store=store, shareID=shareID, priority=priority) | python | def addDefaultShareID(store, shareID, priority):
"""
Add a default share ID to C{store}, pointing to C{shareID} with a
priority C{priority}. The highest-priority share ID identifies the share
that will be retrieved when a user does not explicitly provide a share ID
in their URL (e.g. /host/users/username/).
@param shareID: A share ID.
@type shareID: C{unicode}
@param priority: The priority of this default. Higher means more
important.
@type priority: C{int}
"""
_DefaultShareID(store=store, shareID=shareID, priority=priority) | [
"def",
"addDefaultShareID",
"(",
"store",
",",
"shareID",
",",
"priority",
")",
":",
"_DefaultShareID",
"(",
"store",
"=",
"store",
",",
"shareID",
"=",
"shareID",
",",
"priority",
"=",
"priority",
")"
] | Add a default share ID to C{store}, pointing to C{shareID} with a
priority C{priority}. The highest-priority share ID identifies the share
that will be retrieved when a user does not explicitly provide a share ID
in their URL (e.g. /host/users/username/).
@param shareID: A share ID.
@type shareID: C{unicode}
@param priority: The priority of this default. Higher means more
important.
@type priority: C{int} | [
"Add",
"a",
"default",
"share",
"ID",
"to",
"C",
"{",
"store",
"}",
"pointing",
"to",
"C",
"{",
"shareID",
"}",
"with",
"a",
"priority",
"C",
"{",
"priority",
"}",
".",
"The",
"highest",
"-",
"priority",
"share",
"ID",
"identifies",
"the",
"share",
"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L61-L75 |
twisted/mantissa | xmantissa/websharing.py | getDefaultShareID | def getDefaultShareID(store):
"""
Get the highest-priority default share ID for C{store}.
@return: the default share ID, or u'' if one has not been set.
@rtype: C{unicode}
"""
defaultShareID = store.findFirst(
_DefaultShareID, sort=_DefaultShareID.priority.desc)
if defaultShareID is None:
return u''
return defaultShareID.shareID | python | def getDefaultShareID(store):
"""
Get the highest-priority default share ID for C{store}.
@return: the default share ID, or u'' if one has not been set.
@rtype: C{unicode}
"""
defaultShareID = store.findFirst(
_DefaultShareID, sort=_DefaultShareID.priority.desc)
if defaultShareID is None:
return u''
return defaultShareID.shareID | [
"def",
"getDefaultShareID",
"(",
"store",
")",
":",
"defaultShareID",
"=",
"store",
".",
"findFirst",
"(",
"_DefaultShareID",
",",
"sort",
"=",
"_DefaultShareID",
".",
"priority",
".",
"desc",
")",
"if",
"defaultShareID",
"is",
"None",
":",
"return",
"u''",
... | Get the highest-priority default share ID for C{store}.
@return: the default share ID, or u'' if one has not been set.
@rtype: C{unicode} | [
"Get",
"the",
"highest",
"-",
"priority",
"default",
"share",
"ID",
"for",
"C",
"{",
"store",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L79-L90 |
twisted/mantissa | xmantissa/websharing.py | linkTo | def linkTo(sharedProxyOrItem):
"""
Generate the path part of a URL to link to a share item or its proxy.
@param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share}
@return: a URL object, which when converted to a string will look
something like '/users/user@host/shareID'.
@rtype: L{nevow.url.URL}
@raise: L{RuntimeError} if the store that the C{sharedProxyOrItem} is
stored in is not accessible via the web, for example due to the fact
that the store has no L{LoginMethod} objects to indicate who it is
owned by.
"""
if isinstance(sharedProxyOrItem, sharing.SharedProxy):
userStore = sharing.itemFromProxy(sharedProxyOrItem).store
else:
userStore = sharedProxyOrItem.store
appStore = isAppStore(userStore)
if appStore:
# This code-path should be fixed by #2703; PublicWeb is deprecated.
from xmantissa.publicweb import PublicWeb
substore = userStore.parent.getItemByID(userStore.idInParent)
pw = userStore.parent.findUnique(PublicWeb, PublicWeb.application == substore)
path = [pw.prefixURL.encode('ascii')]
else:
for lm in userbase.getLoginMethods(userStore):
if lm.internal:
path = ['users', lm.localpart.encode('ascii')]
break
else:
raise RuntimeError(
"Shared item is in a user store with no"
" internal username -- can't generate a link.")
if (sharedProxyOrItem.shareID == getDefaultShareID(userStore)):
shareID = sharedProxyOrItem.shareID
path.append('')
else:
shareID = None
path.append(sharedProxyOrItem.shareID)
return _ShareURL(shareID, scheme='', netloc='', pathsegs=path) | python | def linkTo(sharedProxyOrItem):
"""
Generate the path part of a URL to link to a share item or its proxy.
@param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share}
@return: a URL object, which when converted to a string will look
something like '/users/user@host/shareID'.
@rtype: L{nevow.url.URL}
@raise: L{RuntimeError} if the store that the C{sharedProxyOrItem} is
stored in is not accessible via the web, for example due to the fact
that the store has no L{LoginMethod} objects to indicate who it is
owned by.
"""
if isinstance(sharedProxyOrItem, sharing.SharedProxy):
userStore = sharing.itemFromProxy(sharedProxyOrItem).store
else:
userStore = sharedProxyOrItem.store
appStore = isAppStore(userStore)
if appStore:
# This code-path should be fixed by #2703; PublicWeb is deprecated.
from xmantissa.publicweb import PublicWeb
substore = userStore.parent.getItemByID(userStore.idInParent)
pw = userStore.parent.findUnique(PublicWeb, PublicWeb.application == substore)
path = [pw.prefixURL.encode('ascii')]
else:
for lm in userbase.getLoginMethods(userStore):
if lm.internal:
path = ['users', lm.localpart.encode('ascii')]
break
else:
raise RuntimeError(
"Shared item is in a user store with no"
" internal username -- can't generate a link.")
if (sharedProxyOrItem.shareID == getDefaultShareID(userStore)):
shareID = sharedProxyOrItem.shareID
path.append('')
else:
shareID = None
path.append(sharedProxyOrItem.shareID)
return _ShareURL(shareID, scheme='', netloc='', pathsegs=path) | [
"def",
"linkTo",
"(",
"sharedProxyOrItem",
")",
":",
"if",
"isinstance",
"(",
"sharedProxyOrItem",
",",
"sharing",
".",
"SharedProxy",
")",
":",
"userStore",
"=",
"sharing",
".",
"itemFromProxy",
"(",
"sharedProxyOrItem",
")",
".",
"store",
"else",
":",
"userS... | Generate the path part of a URL to link to a share item or its proxy.
@param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share}
@return: a URL object, which when converted to a string will look
something like '/users/user@host/shareID'.
@rtype: L{nevow.url.URL}
@raise: L{RuntimeError} if the store that the C{sharedProxyOrItem} is
stored in is not accessible via the web, for example due to the fact
that the store has no L{LoginMethod} objects to indicate who it is
owned by. | [
"Generate",
"the",
"path",
"part",
"of",
"a",
"URL",
"to",
"link",
"to",
"a",
"share",
"item",
"or",
"its",
"proxy",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L166-L208 |
twisted/mantissa | xmantissa/websharing.py | _storeFromUsername | def _storeFromUsername(store, username):
"""
Find the user store of the user with username C{store}
@param store: site-store
@type store: L{axiom.store.Store}
@param username: the name a user signed up with
@type username: C{unicode}
@rtype: L{axiom.store.Store} or C{None}
"""
lm = store.findUnique(
userbase.LoginMethod,
attributes.AND(
userbase.LoginMethod.localpart == username,
userbase.LoginMethod.internal == True),
default=None)
if lm is not None:
return lm.account.avatars.open() | python | def _storeFromUsername(store, username):
"""
Find the user store of the user with username C{store}
@param store: site-store
@type store: L{axiom.store.Store}
@param username: the name a user signed up with
@type username: C{unicode}
@rtype: L{axiom.store.Store} or C{None}
"""
lm = store.findUnique(
userbase.LoginMethod,
attributes.AND(
userbase.LoginMethod.localpart == username,
userbase.LoginMethod.internal == True),
default=None)
if lm is not None:
return lm.account.avatars.open() | [
"def",
"_storeFromUsername",
"(",
"store",
",",
"username",
")",
":",
"lm",
"=",
"store",
".",
"findUnique",
"(",
"userbase",
".",
"LoginMethod",
",",
"attributes",
".",
"AND",
"(",
"userbase",
".",
"LoginMethod",
".",
"localpart",
"==",
"username",
",",
"... | Find the user store of the user with username C{store}
@param store: site-store
@type store: L{axiom.store.Store}
@param username: the name a user signed up with
@type username: C{unicode}
@rtype: L{axiom.store.Store} or C{None} | [
"Find",
"the",
"user",
"store",
"of",
"the",
"user",
"with",
"username",
"C",
"{",
"store",
"}"
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L212-L231 |
twisted/mantissa | xmantissa/websharing.py | _ShareURL.child | def child(self, path):
"""
Override the base implementation to inject the share ID our
constructor was passed.
"""
if self._shareID is not None:
self = url.URL.child(self, self._shareID)
self._shareID = None
return url.URL.child(self, path) | python | def child(self, path):
"""
Override the base implementation to inject the share ID our
constructor was passed.
"""
if self._shareID is not None:
self = url.URL.child(self, self._shareID)
self._shareID = None
return url.URL.child(self, path) | [
"def",
"child",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"_shareID",
"is",
"not",
"None",
":",
"self",
"=",
"url",
".",
"URL",
".",
"child",
"(",
"self",
",",
"self",
".",
"_shareID",
")",
"self",
".",
"_shareID",
"=",
"None",
"retu... | Override the base implementation to inject the share ID our
constructor was passed. | [
"Override",
"the",
"base",
"implementation",
"to",
"inject",
"the",
"share",
"ID",
"our",
"constructor",
"was",
"passed",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L108-L116 |
twisted/mantissa | xmantissa/websharing.py | _ShareURL.cloneURL | def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment):
"""
Override the base implementation to pass along the share ID our
constructor was passed.
"""
return self.__class__(
self._shareID, scheme, netloc, pathsegs, querysegs, fragment) | python | def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment):
"""
Override the base implementation to pass along the share ID our
constructor was passed.
"""
return self.__class__(
self._shareID, scheme, netloc, pathsegs, querysegs, fragment) | [
"def",
"cloneURL",
"(",
"self",
",",
"scheme",
",",
"netloc",
",",
"pathsegs",
",",
"querysegs",
",",
"fragment",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_shareID",
",",
"scheme",
",",
"netloc",
",",
"pathsegs",
",",
"querysegs",... | Override the base implementation to pass along the share ID our
constructor was passed. | [
"Override",
"the",
"base",
"implementation",
"to",
"pass",
"along",
"the",
"share",
"ID",
"our",
"constructor",
"was",
"passed",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L119-L125 |
twisted/mantissa | xmantissa/websharing.py | UserIndexPage.locateChild | def locateChild(self, ctx, segments):
"""
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
"""
store = _storeFromUsername(
self.loginSystem.store, segments[0].decode('utf-8'))
if store is None:
return rend.NotFound
return (SharingIndex(store, self.webViewer), segments[1:]) | python | def locateChild(self, ctx, segments):
"""
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
"""
store = _storeFromUsername(
self.loginSystem.store, segments[0].decode('utf-8'))
if store is None:
return rend.NotFound
return (SharingIndex(store, self.webViewer), segments[1:]) | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"store",
"=",
"_storeFromUsername",
"(",
"self",
".",
"loginSystem",
".",
"store",
",",
"segments",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"store",
"is",
... | Retrieve a L{SharingIndex} for a particular user, or rend.NotFound. | [
"Retrieve",
"a",
"L",
"{",
"SharingIndex",
"}",
"for",
"a",
"particular",
"user",
"or",
"rend",
".",
"NotFound",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L256-L264 |
twisted/mantissa | xmantissa/websharing.py | SharingIndex.locateChild | def locateChild(self, ctx, segments):
"""
Look up a shared item for the role viewing this SharingIndex and return a
L{PublicAthenaLivePage} containing that shared item's fragment to the
user.
These semantics are UNSTABLE. This method is adequate for simple uses,
but it should be expanded in the future to be more consistent with
other resource lookups. In particular, it should allow share
implementors to adapt their shares to L{IResource} directly rather than
L{INavigableFragment}, to allow for simpler child dispatch.
@param segments: a list of strings, the first of which should be the
shareID of the desired item.
@param ctx: unused.
@return: a L{PublicAthenaLivePage} wrapping a customized fragment.
"""
shareID = segments[0].decode('utf-8')
role = self.webViewer.roleIn(self.userStore)
# if there is an empty segment
if shareID == u'':
# then we want to return the default share. if we find one, then
# let's use that
defaultShareID = getDefaultShareID(self.userStore)
try:
sharedItem = role.getShare(defaultShareID)
except sharing.NoSuchShare:
return rend.NotFound
# otherwise the user is trying to access some other share
else:
# let's see if it's a real share
try:
sharedItem = role.getShare(shareID)
# oops it's not
except sharing.NoSuchShare:
return rend.NotFound
return (self.webViewer.wrapModel(sharedItem),
segments[1:]) | python | def locateChild(self, ctx, segments):
"""
Look up a shared item for the role viewing this SharingIndex and return a
L{PublicAthenaLivePage} containing that shared item's fragment to the
user.
These semantics are UNSTABLE. This method is adequate for simple uses,
but it should be expanded in the future to be more consistent with
other resource lookups. In particular, it should allow share
implementors to adapt their shares to L{IResource} directly rather than
L{INavigableFragment}, to allow for simpler child dispatch.
@param segments: a list of strings, the first of which should be the
shareID of the desired item.
@param ctx: unused.
@return: a L{PublicAthenaLivePage} wrapping a customized fragment.
"""
shareID = segments[0].decode('utf-8')
role = self.webViewer.roleIn(self.userStore)
# if there is an empty segment
if shareID == u'':
# then we want to return the default share. if we find one, then
# let's use that
defaultShareID = getDefaultShareID(self.userStore)
try:
sharedItem = role.getShare(defaultShareID)
except sharing.NoSuchShare:
return rend.NotFound
# otherwise the user is trying to access some other share
else:
# let's see if it's a real share
try:
sharedItem = role.getShare(shareID)
# oops it's not
except sharing.NoSuchShare:
return rend.NotFound
return (self.webViewer.wrapModel(sharedItem),
segments[1:]) | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"shareID",
"=",
"segments",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"role",
"=",
"self",
".",
"webViewer",
".",
"roleIn",
"(",
"self",
".",
"userStore",
")",
"# if t... | Look up a shared item for the role viewing this SharingIndex and return a
L{PublicAthenaLivePage} containing that shared item's fragment to the
user.
These semantics are UNSTABLE. This method is adequate for simple uses,
but it should be expanded in the future to be more consistent with
other resource lookups. In particular, it should allow share
implementors to adapt their shares to L{IResource} directly rather than
L{INavigableFragment}, to allow for simpler child dispatch.
@param segments: a list of strings, the first of which should be the
shareID of the desired item.
@param ctx: unused.
@return: a L{PublicAthenaLivePage} wrapping a customized fragment. | [
"Look",
"up",
"a",
"shared",
"item",
"for",
"the",
"role",
"viewing",
"this",
"SharingIndex",
"and",
"return",
"a",
"L",
"{",
"PublicAthenaLivePage",
"}",
"containing",
"that",
"shared",
"item",
"s",
"fragment",
"to",
"the",
"user",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websharing.py#L308-L350 |
weluse/django-nose-selenium | noseselenium/plugins.py | _set_autocommit | def _set_autocommit(connection):
"""Make sure a connection is in autocommit mode."""
if hasattr(connection.connection, "autocommit"):
if callable(connection.connection.autocommit):
connection.connection.autocommit(True)
else:
connection.connection.autocommit = True
elif hasattr(connection.connection, "set_isolation_level"):
connection.connection.set_isolation_level(0) | python | def _set_autocommit(connection):
"""Make sure a connection is in autocommit mode."""
if hasattr(connection.connection, "autocommit"):
if callable(connection.connection.autocommit):
connection.connection.autocommit(True)
else:
connection.connection.autocommit = True
elif hasattr(connection.connection, "set_isolation_level"):
connection.connection.set_isolation_level(0) | [
"def",
"_set_autocommit",
"(",
"connection",
")",
":",
"if",
"hasattr",
"(",
"connection",
".",
"connection",
",",
"\"autocommit\"",
")",
":",
"if",
"callable",
"(",
"connection",
".",
"connection",
".",
"autocommit",
")",
":",
"connection",
".",
"connection",... | Make sure a connection is in autocommit mode. | [
"Make",
"sure",
"a",
"connection",
"is",
"in",
"autocommit",
"mode",
"."
] | train | https://github.com/weluse/django-nose-selenium/blob/19a09b9455545f70271f884649323a38812793e6/noseselenium/plugins.py#L48-L56 |
weluse/django-nose-selenium | noseselenium/plugins.py | _patch_static_handler | def _patch_static_handler(handler):
"""Patch in support for static files serving if supported and enabled.
"""
if django.VERSION[:2] < (1, 3):
return
from django.contrib.staticfiles.handlers import StaticFilesHandler
return StaticFilesHandler(handler) | python | def _patch_static_handler(handler):
"""Patch in support for static files serving if supported and enabled.
"""
if django.VERSION[:2] < (1, 3):
return
from django.contrib.staticfiles.handlers import StaticFilesHandler
return StaticFilesHandler(handler) | [
"def",
"_patch_static_handler",
"(",
"handler",
")",
":",
"if",
"django",
".",
"VERSION",
"[",
":",
"2",
"]",
"<",
"(",
"1",
",",
"3",
")",
":",
"return",
"from",
"django",
".",
"contrib",
".",
"staticfiles",
".",
"handlers",
"import",
"StaticFilesHandle... | Patch in support for static files serving if supported and enabled. | [
"Patch",
"in",
"support",
"for",
"static",
"files",
"serving",
"if",
"supported",
"and",
"enabled",
"."
] | train | https://github.com/weluse/django-nose-selenium/blob/19a09b9455545f70271f884649323a38812793e6/noseselenium/plugins.py#L81-L89 |
weluse/django-nose-selenium | noseselenium/plugins.py | SeleniumPlugin._inject_selenium | def _inject_selenium(self, test):
"""
Injects a selenium instance into the method.
"""
from django.conf import settings
test_case = get_test_case_class(test)
test_case.selenium_plugin_started = True
# Provide some reasonable default values
sel = selenium(
getattr(settings, "SELENIUM_HOST", "localhost"),
int(getattr(settings, "SELENIUM_PORT", 4444)),
getattr(settings, "SELENIUM_BROWSER_COMMAND", "*chrome"),
getattr(settings, "SELENIUM_URL_ROOT", "http://127.0.0.1:8000/"))
try:
sel.start()
except socket.error:
if getattr(settings, "FORCE_SELENIUM_TESTS", False):
raise
else:
raise SkipTest("Selenium server not available.")
else:
test_case.selenium_started = True
# Only works on method test cases, because we obviously need
# self.
if isinstance(test.test, nose.case.MethodTestCase):
test.test.test.im_self.selenium = sel
elif isinstance(test.test, TestCase):
test.test.run.im_self.selenium = sel
else:
raise SkipTest("Test skipped because it's not a method.") | python | def _inject_selenium(self, test):
"""
Injects a selenium instance into the method.
"""
from django.conf import settings
test_case = get_test_case_class(test)
test_case.selenium_plugin_started = True
# Provide some reasonable default values
sel = selenium(
getattr(settings, "SELENIUM_HOST", "localhost"),
int(getattr(settings, "SELENIUM_PORT", 4444)),
getattr(settings, "SELENIUM_BROWSER_COMMAND", "*chrome"),
getattr(settings, "SELENIUM_URL_ROOT", "http://127.0.0.1:8000/"))
try:
sel.start()
except socket.error:
if getattr(settings, "FORCE_SELENIUM_TESTS", False):
raise
else:
raise SkipTest("Selenium server not available.")
else:
test_case.selenium_started = True
# Only works on method test cases, because we obviously need
# self.
if isinstance(test.test, nose.case.MethodTestCase):
test.test.test.im_self.selenium = sel
elif isinstance(test.test, TestCase):
test.test.run.im_self.selenium = sel
else:
raise SkipTest("Test skipped because it's not a method.") | [
"def",
"_inject_selenium",
"(",
"self",
",",
"test",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"test_case",
"=",
"get_test_case_class",
"(",
"test",
")",
"test_case",
".",
"selenium_plugin_started",
"=",
"True",
"# Provide some reasonable defaul... | Injects a selenium instance into the method. | [
"Injects",
"a",
"selenium",
"instance",
"into",
"the",
"method",
"."
] | train | https://github.com/weluse/django-nose-selenium/blob/19a09b9455545f70271f884649323a38812793e6/noseselenium/plugins.py#L138-L170 |
weluse/django-nose-selenium | noseselenium/plugins.py | StoppableWSGIServer.server_bind | def server_bind(self):
"""Bind server to socket. Overrided to store server name and
set timeout.
"""
try:
HTTPServer.server_bind(self)
except Exception as e:
raise WSGIServerException(e)
self.setup_environ()
self.socket.settimeout(1) | python | def server_bind(self):
"""Bind server to socket. Overrided to store server name and
set timeout.
"""
try:
HTTPServer.server_bind(self)
except Exception as e:
raise WSGIServerException(e)
self.setup_environ()
self.socket.settimeout(1) | [
"def",
"server_bind",
"(",
"self",
")",
":",
"try",
":",
"HTTPServer",
".",
"server_bind",
"(",
"self",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"WSGIServerException",
"(",
"e",
")",
"self",
".",
"setup_environ",
"(",
")",
"self",
".",
"socke... | Bind server to socket. Overrided to store server name and
set timeout. | [
"Bind",
"server",
"to",
"socket",
".",
"Overrided",
"to",
"store",
"server",
"name",
"and",
"set",
"timeout",
"."
] | train | https://github.com/weluse/django-nose-selenium/blob/19a09b9455545f70271f884649323a38812793e6/noseselenium/plugins.py#L219-L230 |
vladcalin/gemstone | gemstone/client/structs.py | AsyncMethodCall.result | def result(self, wait=False):
"""
Gets the result of the method call. If the call was successful,
return the result, otherwise, reraise the exception.
:param wait: Block until the result is available, or just get the result.
:raises: RuntimeError when called and the result is not yet available.
"""
if wait:
self._async_resp.wait()
if not self.finished():
raise RuntimeError("Result is not ready yet")
raw_response = self._async_resp.get()
return Result(result=raw_response["result"], error=raw_response["error"],
id=raw_response["id"], method_call=self.request) | python | def result(self, wait=False):
"""
Gets the result of the method call. If the call was successful,
return the result, otherwise, reraise the exception.
:param wait: Block until the result is available, or just get the result.
:raises: RuntimeError when called and the result is not yet available.
"""
if wait:
self._async_resp.wait()
if not self.finished():
raise RuntimeError("Result is not ready yet")
raw_response = self._async_resp.get()
return Result(result=raw_response["result"], error=raw_response["error"],
id=raw_response["id"], method_call=self.request) | [
"def",
"result",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"if",
"wait",
":",
"self",
".",
"_async_resp",
".",
"wait",
"(",
")",
"if",
"not",
"self",
".",
"finished",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Result is not ready yet\"",
"... | Gets the result of the method call. If the call was successful,
return the result, otherwise, reraise the exception.
:param wait: Block until the result is available, or just get the result.
:raises: RuntimeError when called and the result is not yet available. | [
"Gets",
"the",
"result",
"of",
"the",
"method",
"call",
".",
"If",
"the",
"call",
"was",
"successful",
"return",
"the",
"result",
"otherwise",
"reraise",
"the",
"exception",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/client/structs.py#L80-L97 |
rande/python-simple-ioc | ioc/extra/flask/di.py | Extension.post_build | def post_build(self, container_builder, container):
"""
This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered at the jinja2
"""
app = container.get('ioc.extra.flask.app')
app.config.update(container_builder.parameters.get('ioc.extra.flask.app.config'))
if container.has('ioc.extra.jinja2'):
# This must be an instance of jinja.ChoiceLoader
# This code replace the flask specific jinja configuration to use
# the one provided by the ioc.extra.jinja2 code
jinja2 = container.get('ioc.extra.jinja2')
jinja2.loader.loaders.append(app.create_global_jinja_loader())
for name, value in app.jinja_env.globals.items():
if name not in jinja2.globals:
jinja2.globals[name] = value
for name, value in app.jinja_env.filters.items():
if name not in jinja2.filters:
jinja2.filters[name] = value
app.jinja_env = jinja2 | python | def post_build(self, container_builder, container):
"""
This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered at the jinja2
"""
app = container.get('ioc.extra.flask.app')
app.config.update(container_builder.parameters.get('ioc.extra.flask.app.config'))
if container.has('ioc.extra.jinja2'):
# This must be an instance of jinja.ChoiceLoader
# This code replace the flask specific jinja configuration to use
# the one provided by the ioc.extra.jinja2 code
jinja2 = container.get('ioc.extra.jinja2')
jinja2.loader.loaders.append(app.create_global_jinja_loader())
for name, value in app.jinja_env.globals.items():
if name not in jinja2.globals:
jinja2.globals[name] = value
for name, value in app.jinja_env.filters.items():
if name not in jinja2.filters:
jinja2.filters[name] = value
app.jinja_env = jinja2 | [
"def",
"post_build",
"(",
"self",
",",
"container_builder",
",",
"container",
")",
":",
"app",
"=",
"container",
".",
"get",
"(",
"'ioc.extra.flask.app'",
")",
"app",
".",
"config",
".",
"update",
"(",
"container_builder",
".",
"parameters",
".",
"get",
"(",... | This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered at the jinja2 | [
"This",
"method",
"make",
"sure",
"the",
"flask",
"configuration",
"is",
"fine",
"and",
"check",
"the",
"if",
"ioc",
".",
"extra",
".",
"jinja2",
"service",
"is",
"available",
".",
"If",
"so",
"the",
"flask",
"instance",
"will",
"use",
"this",
"service",
... | train | https://github.com/rande/python-simple-ioc/blob/36ddf667c1213a07a53cd4cdd708d02494e5190b/ioc/extra/flask/di.py#L87-L114 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | Mongrel2Handler.start | def start(self):
"""
Start to listen for incoming requests.
"""
assert not self._started
self._listening_stream.on_recv(self._recv_callback)
self._started = True | python | def start(self):
"""
Start to listen for incoming requests.
"""
assert not self._started
self._listening_stream.on_recv(self._recv_callback)
self._started = True | [
"def",
"start",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_started",
"self",
".",
"_listening_stream",
".",
"on_recv",
"(",
"self",
".",
"_recv_callback",
")",
"self",
".",
"_started",
"=",
"True"
] | Start to listen for incoming requests. | [
"Start",
"to",
"listen",
"for",
"incoming",
"requests",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L51-L57 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | Mongrel2Handler._create_listening_stream | def _create_listening_stream(self, pull_addr):
"""
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
"""
sock = self._zmq_context.socket(zmq.PULL)
sock.connect(pull_addr)
stream = ZMQStream(sock, io_loop=self.io_loop)
return stream | python | def _create_listening_stream(self, pull_addr):
"""
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
"""
sock = self._zmq_context.socket(zmq.PULL)
sock.connect(pull_addr)
stream = ZMQStream(sock, io_loop=self.io_loop)
return stream | [
"def",
"_create_listening_stream",
"(",
"self",
",",
"pull_addr",
")",
":",
"sock",
"=",
"self",
".",
"_zmq_context",
".",
"socket",
"(",
"zmq",
".",
"PULL",
")",
"sock",
".",
"connect",
"(",
"pull_addr",
")",
"stream",
"=",
"ZMQStream",
"(",
"sock",
","... | Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests. | [
"Create",
"a",
"stream",
"listening",
"for",
"Requests",
".",
"The",
"self",
".",
"_recv_callback",
"method",
"is",
"asociated",
"with",
"incoming",
"requests",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L59-L68 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | Mongrel2Handler._create_sending_stream | def _create_sending_stream(self, pub_addr):
"""
Create a `ZMQStream` for sending responses back to Mongrel2.
"""
sock = self._zmq_context.socket(zmq.PUB)
sock.setsockopt(zmq.IDENTITY, self.sender_id)
sock.connect(pub_addr)
stream = ZMQStream(sock, io_loop=self.io_loop)
return stream | python | def _create_sending_stream(self, pub_addr):
"""
Create a `ZMQStream` for sending responses back to Mongrel2.
"""
sock = self._zmq_context.socket(zmq.PUB)
sock.setsockopt(zmq.IDENTITY, self.sender_id)
sock.connect(pub_addr)
stream = ZMQStream(sock, io_loop=self.io_loop)
return stream | [
"def",
"_create_sending_stream",
"(",
"self",
",",
"pub_addr",
")",
":",
"sock",
"=",
"self",
".",
"_zmq_context",
".",
"socket",
"(",
"zmq",
".",
"PUB",
")",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"IDENTITY",
",",
"self",
".",
"sender_id",
")",
"... | Create a `ZMQStream` for sending responses back to Mongrel2. | [
"Create",
"a",
"ZMQStream",
"for",
"sending",
"responses",
"back",
"to",
"Mongrel2",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L70-L79 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | Mongrel2Handler._recv_callback | def _recv_callback(self, msg):
"""
Method is called when there is a message coming from a Mongrel2 server.
This message should be a valid Request String.
"""
m2req = MongrelRequest.parse(msg[0])
MongrelConnection(m2req, self._sending_stream, self.request_callback,
no_keep_alive=self.no_keep_alive, xheaders=self.xheaders) | python | def _recv_callback(self, msg):
"""
Method is called when there is a message coming from a Mongrel2 server.
This message should be a valid Request String.
"""
m2req = MongrelRequest.parse(msg[0])
MongrelConnection(m2req, self._sending_stream, self.request_callback,
no_keep_alive=self.no_keep_alive, xheaders=self.xheaders) | [
"def",
"_recv_callback",
"(",
"self",
",",
"msg",
")",
":",
"m2req",
"=",
"MongrelRequest",
".",
"parse",
"(",
"msg",
"[",
"0",
"]",
")",
"MongrelConnection",
"(",
"m2req",
",",
"self",
".",
"_sending_stream",
",",
"self",
".",
"request_callback",
",",
"... | Method is called when there is a message coming from a Mongrel2 server.
This message should be a valid Request String. | [
"Method",
"is",
"called",
"when",
"there",
"is",
"a",
"message",
"coming",
"from",
"a",
"Mongrel2",
"server",
".",
"This",
"message",
"should",
"be",
"a",
"valid",
"Request",
"String",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L81-L88 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | MongrelConnection._begin_request | def _begin_request(self):
"""
Actually start executing this request.
"""
headers = self.m2req.headers
self._request = HTTPRequest(connection=self,
method=headers.get("METHOD"),
uri=self.m2req.path,
version=headers.get("VERSION"),
headers=headers,
remote_ip=headers.get("x-forwarded-for"))
if len(self.m2req.body) > 0:
self._request.body = self.m2req.body
if self.m2req.is_disconnect():
self.finish()
elif headers.get("x-mongrel2-upload-done", None):
# there has been a file upload.
expected = headers.get("x-mongrel2-upload-start", "BAD")
upload = headers.get("x-mongrel2-upload-done", None)
if expected == upload:
self.request_callback(self._request)
elif headers.get("x-mongrel2-upload-start", None):
# this is just a notification that a file upload has started. Do
# nothing for now!
pass
else:
self.request_callback(self._request) | python | def _begin_request(self):
"""
Actually start executing this request.
"""
headers = self.m2req.headers
self._request = HTTPRequest(connection=self,
method=headers.get("METHOD"),
uri=self.m2req.path,
version=headers.get("VERSION"),
headers=headers,
remote_ip=headers.get("x-forwarded-for"))
if len(self.m2req.body) > 0:
self._request.body = self.m2req.body
if self.m2req.is_disconnect():
self.finish()
elif headers.get("x-mongrel2-upload-done", None):
# there has been a file upload.
expected = headers.get("x-mongrel2-upload-start", "BAD")
upload = headers.get("x-mongrel2-upload-done", None)
if expected == upload:
self.request_callback(self._request)
elif headers.get("x-mongrel2-upload-start", None):
# this is just a notification that a file upload has started. Do
# nothing for now!
pass
else:
self.request_callback(self._request) | [
"def",
"_begin_request",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"m2req",
".",
"headers",
"self",
".",
"_request",
"=",
"HTTPRequest",
"(",
"connection",
"=",
"self",
",",
"method",
"=",
"headers",
".",
"get",
"(",
"\"METHOD\"",
")",
",",
"... | Actually start executing this request. | [
"Actually",
"start",
"executing",
"this",
"request",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L113-L146 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | MongrelConnection.finish | def finish(self):
"""
Finish this connection.
"""
assert self._request, "Request closed"
self._request_finished = True
if self.m2req.should_close() or self.no_keep_alive:
self._send("")
self._request = None | python | def finish(self):
"""
Finish this connection.
"""
assert self._request, "Request closed"
self._request_finished = True
if self.m2req.should_close() or self.no_keep_alive:
self._send("")
self._request = None | [
"def",
"finish",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_request",
",",
"\"Request closed\"",
"self",
".",
"_request_finished",
"=",
"True",
"if",
"self",
".",
"m2req",
".",
"should_close",
"(",
")",
"or",
"self",
".",
"no_keep_alive",
":",
"self",... | Finish this connection. | [
"Finish",
"this",
"connection",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L154-L162 |
truemped/tornadotools | tornadotools/mongrel2/handler.py | MongrelConnection._send | def _send(self, msg):
"""
Raw send to the given connection ID at the given uuid, mostly used
internally.
"""
uuid = self.m2req.sender
conn_id = self.m2req.conn_id
header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id))
zmq_message = header + ' ' + msg
self.stream.send(zmq_message) | python | def _send(self, msg):
"""
Raw send to the given connection ID at the given uuid, mostly used
internally.
"""
uuid = self.m2req.sender
conn_id = self.m2req.conn_id
header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id))
zmq_message = header + ' ' + msg
self.stream.send(zmq_message) | [
"def",
"_send",
"(",
"self",
",",
"msg",
")",
":",
"uuid",
"=",
"self",
".",
"m2req",
".",
"sender",
"conn_id",
"=",
"self",
".",
"m2req",
".",
"conn_id",
"header",
"=",
"\"%s %d:%s,\"",
"%",
"(",
"uuid",
",",
"len",
"(",
"str",
"(",
"conn_id",
")"... | Raw send to the given connection ID at the given uuid, mostly used
internally. | [
"Raw",
"send",
"to",
"the",
"given",
"connection",
"ID",
"at",
"the",
"given",
"uuid",
"mostly",
"used",
"internally",
"."
] | train | https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L164-L174 |
72squared/redpipe | redpipe/structs.py | _json_default_encoder | def _json_default_encoder(func):
"""
Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Struct object so I can tell
that's what it is.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized.
"""
@wraps(func)
def inner(self, o):
try:
return o._redpipe_struct_as_dict # noqa
except AttributeError:
pass
return func(self, o)
return inner | python | def _json_default_encoder(func):
"""
Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Struct object so I can tell
that's what it is.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized.
"""
@wraps(func)
def inner(self, o):
try:
return o._redpipe_struct_as_dict # noqa
except AttributeError:
pass
return func(self, o)
return inner | [
"def",
"_json_default_encoder",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"self",
",",
"o",
")",
":",
"try",
":",
"return",
"o",
".",
"_redpipe_struct_as_dict",
"# noqa",
"except",
"AttributeError",
":",
"pass",
"return",
... | Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Struct object so I can tell
that's what it is.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized. | [
"Monkey",
"-",
"Patch",
"the",
"core",
"json",
"encoder",
"library",
".",
"This",
"isn",
"t",
"as",
"bad",
"as",
"it",
"sounds",
".",
"We",
"override",
"the",
"default",
"method",
"so",
"that",
"if",
"an",
"object",
"falls",
"through",
"and",
"can",
"t... | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/structs.py#L881-L911 |
vladcalin/gemstone | gemstone/util.py | as_completed | def as_completed(*async_result_wrappers):
"""
Yields results as they become available from asynchronous method calls.
Example usage
::
async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)]
for async_call in gemstone.as_completed(*async_calls):
print("just finished with result ", async_call.result())
:param async_result_wrappers: :py:class:`gemstone.client.structs.AsyncMethodCall` instances.
:return: a generator that yields items as soon they results become available.
.. versionadded:: 0.5.0
"""
for item in async_result_wrappers:
if not isinstance(item, AsyncMethodCall):
raise TypeError("Got non-AsyncMethodCall object: {}".format(item))
wrappers_copy = list(async_result_wrappers)
while len(wrappers_copy):
completed = list(filter(lambda x: x.finished(), wrappers_copy))
if not len(completed):
continue
for item in completed:
wrappers_copy.remove(item)
yield item | python | def as_completed(*async_result_wrappers):
"""
Yields results as they become available from asynchronous method calls.
Example usage
::
async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)]
for async_call in gemstone.as_completed(*async_calls):
print("just finished with result ", async_call.result())
:param async_result_wrappers: :py:class:`gemstone.client.structs.AsyncMethodCall` instances.
:return: a generator that yields items as soon they results become available.
.. versionadded:: 0.5.0
"""
for item in async_result_wrappers:
if not isinstance(item, AsyncMethodCall):
raise TypeError("Got non-AsyncMethodCall object: {}".format(item))
wrappers_copy = list(async_result_wrappers)
while len(wrappers_copy):
completed = list(filter(lambda x: x.finished(), wrappers_copy))
if not len(completed):
continue
for item in completed:
wrappers_copy.remove(item)
yield item | [
"def",
"as_completed",
"(",
"*",
"async_result_wrappers",
")",
":",
"for",
"item",
"in",
"async_result_wrappers",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"AsyncMethodCall",
")",
":",
"raise",
"TypeError",
"(",
"\"Got non-AsyncMethodCall object: {}\"",
".",... | Yields results as they become available from asynchronous method calls.
Example usage
::
async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)]
for async_call in gemstone.as_completed(*async_calls):
print("just finished with result ", async_call.result())
:param async_result_wrappers: :py:class:`gemstone.client.structs.AsyncMethodCall` instances.
:return: a generator that yields items as soon they results become available.
.. versionadded:: 0.5.0 | [
"Yields",
"results",
"as",
"they",
"become",
"available",
"from",
"asynchronous",
"method",
"calls",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/util.py#L14-L45 |
vladcalin/gemstone | gemstone/util.py | first_completed | def first_completed(*async_result_wrappers):
"""
Just like :py:func:`as_completed`, but returns only the first item and discards the
rest.
:param async_result_wrappers:
:return:
.. versionadded:: 0.5.0
"""
for item in async_result_wrappers:
if not isinstance(item, AsyncMethodCall):
raise TypeError("Got non-AsyncMethodCall object: {}".format(item))
wrappers_copy = list(async_result_wrappers)
while True:
completed = list(filter(lambda x: x.finished(), wrappers_copy))
if not len(completed):
continue
return completed[0].result() | python | def first_completed(*async_result_wrappers):
"""
Just like :py:func:`as_completed`, but returns only the first item and discards the
rest.
:param async_result_wrappers:
:return:
.. versionadded:: 0.5.0
"""
for item in async_result_wrappers:
if not isinstance(item, AsyncMethodCall):
raise TypeError("Got non-AsyncMethodCall object: {}".format(item))
wrappers_copy = list(async_result_wrappers)
while True:
completed = list(filter(lambda x: x.finished(), wrappers_copy))
if not len(completed):
continue
return completed[0].result() | [
"def",
"first_completed",
"(",
"*",
"async_result_wrappers",
")",
":",
"for",
"item",
"in",
"async_result_wrappers",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"AsyncMethodCall",
")",
":",
"raise",
"TypeError",
"(",
"\"Got non-AsyncMethodCall object: {}\"",
"... | Just like :py:func:`as_completed`, but returns only the first item and discards the
rest.
:param async_result_wrappers:
:return:
.. versionadded:: 0.5.0 | [
"Just",
"like",
":",
"py",
":",
"func",
":",
"as_completed",
"but",
"returns",
"only",
"the",
"first",
"item",
"and",
"discards",
"the",
"rest",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/util.py#L48-L67 |
vladcalin/gemstone | gemstone/util.py | dynamic_load | def dynamic_load(module_or_member):
"""
Dynamically loads a class or member of a class.
If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``.
If ``module_or_member`` is something like ``"a"`` will perform ``import a``
:param module_or_member: the name of a module or member of a module to import.
:return: the returned entity, be it a module or member of a module.
"""
parts = module_or_member.split(".")
if len(parts) > 1:
name_to_import = parts[-1]
module_to_import = ".".join(parts[:-1])
else:
name_to_import = None
module_to_import = module_or_member
module = importlib.import_module(module_to_import)
if name_to_import:
to_return = getattr(module, name_to_import)
if not to_return:
raise AttributeError("{} has no attribute {}".format(module, name_to_import))
return to_return
else:
return module | python | def dynamic_load(module_or_member):
"""
Dynamically loads a class or member of a class.
If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``.
If ``module_or_member`` is something like ``"a"`` will perform ``import a``
:param module_or_member: the name of a module or member of a module to import.
:return: the returned entity, be it a module or member of a module.
"""
parts = module_or_member.split(".")
if len(parts) > 1:
name_to_import = parts[-1]
module_to_import = ".".join(parts[:-1])
else:
name_to_import = None
module_to_import = module_or_member
module = importlib.import_module(module_to_import)
if name_to_import:
to_return = getattr(module, name_to_import)
if not to_return:
raise AttributeError("{} has no attribute {}".format(module, name_to_import))
return to_return
else:
return module | [
"def",
"dynamic_load",
"(",
"module_or_member",
")",
":",
"parts",
"=",
"module_or_member",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"name_to_import",
"=",
"parts",
"[",
"-",
"1",
"]",
"module_to_import",
"=",
"\".\... | Dynamically loads a class or member of a class.
If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``.
If ``module_or_member`` is something like ``"a"`` will perform ``import a``
:param module_or_member: the name of a module or member of a module to import.
:return: the returned entity, be it a module or member of a module. | [
"Dynamically",
"loads",
"a",
"class",
"or",
"member",
"of",
"a",
"class",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/util.py#L74-L100 |
72squared/redpipe | redpipe/fields.py | BooleanField.encode | def encode(cls, value):
"""
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
"""
if value not in [True, False]:
raise InvalidValue('not a boolean')
return b'1' if value else b'' | python | def encode(cls, value):
"""
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
"""
if value not in [True, False]:
raise InvalidValue('not a boolean')
return b'1' if value else b'' | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"InvalidValue",
"(",
"'not a boolean'",
")",
"return",
"b'1'",
"if",
"value",
"else",
"b''"
] | convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes | [
"convert",
"a",
"boolean",
"value",
"into",
"something",
"we",
"can",
"persist",
"to",
"redis",
".",
"An",
"empty",
"string",
"is",
"the",
"representation",
"for",
"False",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L38-L49 |
72squared/redpipe | redpipe/fields.py | FloatField.encode | def encode(cls, value):
"""
encode a floating point number to bytes in redis
:param value: float
:return: bytes
"""
try:
if float(value) + 0 == value:
return repr(value)
except (TypeError, ValueError):
pass
raise InvalidValue('not a float') | python | def encode(cls, value):
"""
encode a floating point number to bytes in redis
:param value: float
:return: bytes
"""
try:
if float(value) + 0 == value:
return repr(value)
except (TypeError, ValueError):
pass
raise InvalidValue('not a float') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"if",
"float",
"(",
"value",
")",
"+",
"0",
"==",
"value",
":",
"return",
"repr",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"raise",
"Invalid... | encode a floating point number to bytes in redis
:param value: float
:return: bytes | [
"encode",
"a",
"floating",
"point",
"number",
"to",
"bytes",
"in",
"redis"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L79-L92 |
72squared/redpipe | redpipe/fields.py | IntegerField.encode | def encode(cls, value):
"""
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
"""
try:
coerced = int(value)
if coerced + 0 == value:
return repr(coerced)
except (TypeError, ValueError):
pass
raise InvalidValue('not an int') | python | def encode(cls, value):
"""
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
"""
try:
coerced = int(value)
if coerced + 0 == value:
return repr(coerced)
except (TypeError, ValueError):
pass
raise InvalidValue('not an int') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"int",
"(",
"value",
")",
"if",
"coerced",
"+",
"0",
"==",
"value",
":",
"return",
"repr",
"(",
"coerced",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":"... | take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str | [
"take",
"an",
"integer",
"and",
"turn",
"it",
"into",
"a",
"string",
"representation",
"to",
"write",
"into",
"redis",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L111-L127 |
72squared/redpipe | redpipe/fields.py | TextField.encode | def encode(cls, value):
"""
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
"""
coerced = unicode(value)
if coerced == value:
return coerced.encode(cls._encoding)
raise InvalidValue('not text') | python | def encode(cls, value):
"""
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
"""
coerced = unicode(value)
if coerced == value:
return coerced.encode(cls._encoding)
raise InvalidValue('not text') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"coerced",
"=",
"unicode",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
":",
"return",
"coerced",
".",
"encode",
"(",
"cls",
".",
"_encoding",
")",
"raise",
"InvalidValue",
"(",
"'not text'",
"... | take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes | [
"take",
"a",
"valid",
"unicode",
"string",
"and",
"turn",
"it",
"into",
"utf",
"-",
"8",
"bytes"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L139-L150 |
72squared/redpipe | redpipe/fields.py | AsciiField.encode | def encode(cls, value):
"""
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
"""
coerced = unicode(value)
if coerced == value and cls.PATTERN.match(coerced):
return coerced.encode(cls._encoding)
raise InvalidValue('not ascii') | python | def encode(cls, value):
"""
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
"""
coerced = unicode(value)
if coerced == value and cls.PATTERN.match(coerced):
return coerced.encode(cls._encoding)
raise InvalidValue('not ascii') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"coerced",
"=",
"unicode",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
"and",
"cls",
".",
"PATTERN",
".",
"match",
"(",
"coerced",
")",
":",
"return",
"coerced",
".",
"encode",
"(",
"cls",
... | take a list of strings and turn it into utf-8 byte-string
:param value:
:return: | [
"take",
"a",
"list",
"of",
"strings",
"and",
"turn",
"it",
"into",
"utf",
"-",
"8",
"byte",
"-",
"string"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L170-L181 |
72squared/redpipe | redpipe/fields.py | BinaryField.encode | def encode(cls, value):
"""
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
"""
try:
coerced = bytes(value)
if coerced == value:
return coerced
except (TypeError, UnicodeError):
pass
raise InvalidValue('not binary') | python | def encode(cls, value):
"""
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
"""
try:
coerced = bytes(value)
if coerced == value:
return coerced
except (TypeError, UnicodeError):
pass
raise InvalidValue('not binary') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"bytes",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
":",
"return",
"coerced",
"except",
"(",
"TypeError",
",",
"UnicodeError",
")",
":",
"pass",
"raise",
"InvalidV... | write binary data into redis without encoding it.
:param value: bytes
:return: bytes | [
"write",
"binary",
"data",
"into",
"redis",
"without",
"encoding",
"it",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L190-L204 |
72squared/redpipe | redpipe/fields.py | ListField.encode | def encode(cls, value):
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except TypeError:
pass
raise InvalidValue('not a list') | python | def encode(cls, value):
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except TypeError:
pass
raise InvalidValue('not a list') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"list",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
":",
"return",
"json",
".",
"dumps",
"(",
"coerced",
")",
".",
"encode",
"(",
"cls",
".",
"_encoding",
")",
... | take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes | [
"take",
"a",
"list",
"and",
"turn",
"it",
"into",
"a",
"utf",
"-",
"8",
"encoded",
"byte",
"-",
"string",
"for",
"redis",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L225-L239 |
72squared/redpipe | redpipe/fields.py | ListField.decode | def decode(cls, value):
"""
take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list
"""
try:
return None if value is None else \
list(json.loads(value.decode(cls._encoding)))
except (TypeError, AttributeError):
return list(value) | python | def decode(cls, value):
"""
take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list
"""
try:
return None if value is None else \
list(json.loads(value.decode(cls._encoding)))
except (TypeError, AttributeError):
return list(value) | [
"def",
"decode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"return",
"None",
"if",
"value",
"is",
"None",
"else",
"list",
"(",
"json",
".",
"loads",
"(",
"value",
".",
"decode",
"(",
"cls",
".",
"_encoding",
")",
")",
")",
"except",
"(",
"T... | take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list | [
"take",
"a",
"utf",
"-",
"8",
"encoded",
"byte",
"-",
"string",
"from",
"redis",
"and",
"turn",
"it",
"back",
"into",
"a",
"list"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L242-L254 |
72squared/redpipe | redpipe/fields.py | DictField.encode | def encode(cls, value):
"""
encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes
"""
try:
coerced = dict(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except (TypeError, ValueError):
pass
raise InvalidValue('not a dict') | python | def encode(cls, value):
"""
encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes
"""
try:
coerced = dict(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except (TypeError, ValueError):
pass
raise InvalidValue('not a dict') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"dict",
"(",
"value",
")",
"if",
"coerced",
"==",
"value",
":",
"return",
"json",
".",
"dumps",
"(",
"coerced",
")",
".",
"encode",
"(",
"cls",
".",
"_encoding",
")",
... | encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes | [
"encode",
"the",
"dict",
"as",
"a",
"json",
"string",
"to",
"be",
"written",
"into",
"redis",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L261-L274 |
72squared/redpipe | redpipe/fields.py | StringListField.decode | def decode(cls, value):
"""
decode the data from redis.
:param value: bytes
:return: list
"""
try:
data = [v for v in value.decode(cls._encoding).split(',') if
v != '']
return data if data else None
except AttributeError:
return value | python | def decode(cls, value):
"""
decode the data from redis.
:param value: bytes
:return: list
"""
try:
data = [v for v in value.decode(cls._encoding).split(',') if
v != '']
return data if data else None
except AttributeError:
return value | [
"def",
"decode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"data",
"=",
"[",
"v",
"for",
"v",
"in",
"value",
".",
"decode",
"(",
"cls",
".",
"_encoding",
")",
".",
"split",
"(",
"','",
")",
"if",
"v",
"!=",
"''",
"]",
"return",
"data",
... | decode the data from redis.
:param value: bytes
:return: list | [
"decode",
"the",
"data",
"from",
"redis",
".",
":",
"param",
"value",
":",
"bytes",
":",
"return",
":",
"list"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L298-L309 |
72squared/redpipe | redpipe/fields.py | StringListField.encode | def encode(cls, value):
"""
the list it so it can be stored in redis.
:param value: list
:return: bytes
"""
try:
coerced = [str(v) for v in value]
if coerced == value:
return ",".join(coerced).encode(cls._encoding) if len(
value) > 0 else None
except TypeError:
pass
raise InvalidValue('not a list of strings') | python | def encode(cls, value):
"""
the list it so it can be stored in redis.
:param value: list
:return: bytes
"""
try:
coerced = [str(v) for v in value]
if coerced == value:
return ",".join(coerced).encode(cls._encoding) if len(
value) > 0 else None
except TypeError:
pass
raise InvalidValue('not a list of strings') | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
"if",
"coerced",
"==",
"value",
":",
"return",
"\",\"",
".",
"join",
"(",
"coerced",
")",
".",
"encode",
... | the list it so it can be stored in redis.
:param value: list
:return: bytes | [
"the",
"list",
"it",
"so",
"it",
"can",
"be",
"stored",
"in",
"redis",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L312-L327 |
inveniosoftware/invenio-openaire | invenio_openaire/ext.py | InvenioOpenAIRE.init_app | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.cli.add_command(openaire)
before_record_index.connect(indexer_receiver, sender=app)
app.extensions['invenio-openaire'] = self | python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.cli.add_command(openaire)
before_record_index.connect(indexer_receiver, sender=app)
app.extensions['invenio-openaire'] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"app",
".",
"cli",
".",
"add_command",
"(",
"openaire",
")",
"before_record_index",
".",
"connect",
"(",
"indexer_receiver",
",",
"sender",
"=",
"app",
")"... | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/ext.py#L44-L49 |
svetlyak40wt/python-processor | src/processor/utils/twitter.py | swap_twitter_subject | def swap_twitter_subject(subject, body):
"""If subject starts from 'Tweet from...'
then we need to get first meaning line from the body."""
if subject.startswith('Tweet from'):
lines = body.split('\n')
for idx, line in enumerate(lines):
if re.match(r'.*, ?\d{2}:\d{2}]]', line) is not None:
try:
subject = lines[idx + 1]
except IndexError:
pass
break
return subject, body | python | def swap_twitter_subject(subject, body):
"""If subject starts from 'Tweet from...'
then we need to get first meaning line from the body."""
if subject.startswith('Tweet from'):
lines = body.split('\n')
for idx, line in enumerate(lines):
if re.match(r'.*, ?\d{2}:\d{2}]]', line) is not None:
try:
subject = lines[idx + 1]
except IndexError:
pass
break
return subject, body | [
"def",
"swap_twitter_subject",
"(",
"subject",
",",
"body",
")",
":",
"if",
"subject",
".",
"startswith",
"(",
"'Tweet from'",
")",
":",
"lines",
"=",
"body",
".",
"split",
"(",
"'\\n'",
")",
"for",
"idx",
",",
"line",
"in",
"enumerate",
"(",
"lines",
... | If subject starts from 'Tweet from...'
then we need to get first meaning line from the body. | [
"If",
"subject",
"starts",
"from",
"Tweet",
"from",
"...",
"then",
"we",
"need",
"to",
"get",
"first",
"meaning",
"line",
"from",
"the",
"body",
"."
] | train | https://github.com/svetlyak40wt/python-processor/blob/9126a021d603030899897803ab9973250e5b16f6/src/processor/utils/twitter.py#L13-L26 |
richardliaw/track | track/__init__.py | trial | def trial(log_dir=None,
upload_dir=None,
sync_period=None,
trial_prefix="",
param_map=None,
init_logging=True):
"""
Generates a trial within a with context.
"""
global _trial # pylint: disable=global-statement
if _trial:
# TODO: would be nice to stack crawl at creation time to report
# where that initial trial was created, and that creation line
# info is helpful to keep around anyway.
raise ValueError("A trial already exists in the current context")
local_trial = Trial(
log_dir=log_dir,
upload_dir=upload_dir,
sync_period=sync_period,
trial_prefix=trial_prefix,
param_map=param_map,
init_logging=True)
try:
_trial = local_trial
_trial.start()
yield local_trial
finally:
_trial = None
local_trial.close() | python | def trial(log_dir=None,
upload_dir=None,
sync_period=None,
trial_prefix="",
param_map=None,
init_logging=True):
"""
Generates a trial within a with context.
"""
global _trial # pylint: disable=global-statement
if _trial:
# TODO: would be nice to stack crawl at creation time to report
# where that initial trial was created, and that creation line
# info is helpful to keep around anyway.
raise ValueError("A trial already exists in the current context")
local_trial = Trial(
log_dir=log_dir,
upload_dir=upload_dir,
sync_period=sync_period,
trial_prefix=trial_prefix,
param_map=param_map,
init_logging=True)
try:
_trial = local_trial
_trial.start()
yield local_trial
finally:
_trial = None
local_trial.close() | [
"def",
"trial",
"(",
"log_dir",
"=",
"None",
",",
"upload_dir",
"=",
"None",
",",
"sync_period",
"=",
"None",
",",
"trial_prefix",
"=",
"\"\"",
",",
"param_map",
"=",
"None",
",",
"init_logging",
"=",
"True",
")",
":",
"global",
"_trial",
"# pylint: disabl... | Generates a trial within a with context. | [
"Generates",
"a",
"trial",
"within",
"a",
"with",
"context",
"."
] | train | https://github.com/richardliaw/track/blob/7ac42ea34e5c1d7bb92fd813e938835a06a63fc7/track/__init__.py#L28-L56 |
p3trus/slave | slave/misc.py | index | def index(index, length):
"""Generates an index.
:param index: The index, can be positive or negative.
:param length: The length of the sequence to index.
:raises: IndexError
Negative indices are typically used to index a sequence in reverse order.
But to use them, the indexed object must convert them to the correct,
positive index. This function can be used to do this.
"""
if index < 0:
index += length
if 0 <= index < length:
return index
raise IndexError() | python | def index(index, length):
"""Generates an index.
:param index: The index, can be positive or negative.
:param length: The length of the sequence to index.
:raises: IndexError
Negative indices are typically used to index a sequence in reverse order.
But to use them, the indexed object must convert them to the correct,
positive index. This function can be used to do this.
"""
if index < 0:
index += length
if 0 <= index < length:
return index
raise IndexError() | [
"def",
"index",
"(",
"index",
",",
"length",
")",
":",
"if",
"index",
"<",
"0",
":",
"index",
"+=",
"length",
"if",
"0",
"<=",
"index",
"<",
"length",
":",
"return",
"index",
"raise",
"IndexError",
"(",
")"
] | Generates an index.
:param index: The index, can be positive or negative.
:param length: The length of the sequence to index.
:raises: IndexError
Negative indices are typically used to index a sequence in reverse order.
But to use them, the indexed object must convert them to the correct,
positive index. This function can be used to do this. | [
"Generates",
"an",
"index",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/misc.py#L78-L95 |
p3trus/slave | slave/misc.py | range_to_numeric | def range_to_numeric(ranges):
"""Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
"""
values, units = zip(*(r.split() for r in ranges))
# Detect common unit.
unit = os.path.commonprefix([u[::-1] for u in units])
# Strip unit to get just the SI prefix.
prefixes = (u[:-len(unit)] for u in units)
# Convert string value and scale with prefix.
values = [float(v) * SI_PREFIX[p] for v, p in zip(values, prefixes)]
return values | python | def range_to_numeric(ranges):
"""Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
"""
values, units = zip(*(r.split() for r in ranges))
# Detect common unit.
unit = os.path.commonprefix([u[::-1] for u in units])
# Strip unit to get just the SI prefix.
prefixes = (u[:-len(unit)] for u in units)
# Convert string value and scale with prefix.
values = [float(v) * SI_PREFIX[p] for v, p in zip(values, prefixes)]
return values | [
"def",
"range_to_numeric",
"(",
"ranges",
")",
":",
"values",
",",
"units",
"=",
"zip",
"(",
"*",
"(",
"r",
".",
"split",
"(",
")",
"for",
"r",
"in",
"ranges",
")",
")",
"# Detect common unit.",
"unit",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(... | Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0] | [
"Converts",
"a",
"sequence",
"of",
"string",
"ranges",
"to",
"a",
"sequence",
"of",
"floats",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/misc.py#L98-L116 |
p3trus/slave | slave/misc.py | wrap_exception | def wrap_exception(exc, new_exc):
"""Catches exceptions `exc` and raises `new_exc(exc)` instead.
E.g.::
>>> class MyValueError(Exception):
... '''Custom ValueError.'''
... @wrap_exception(exc=ValueError, new_exc=MyValueError)
... def test():
... raise ValueError()
"""
def make_wrapper(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
try:
return fn(*args, **kw)
except exc as e:
future.utils.raise_with_traceback(new_exc(e))
return wrapper
return make_wrapper | python | def wrap_exception(exc, new_exc):
"""Catches exceptions `exc` and raises `new_exc(exc)` instead.
E.g.::
>>> class MyValueError(Exception):
... '''Custom ValueError.'''
... @wrap_exception(exc=ValueError, new_exc=MyValueError)
... def test():
... raise ValueError()
"""
def make_wrapper(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
try:
return fn(*args, **kw)
except exc as e:
future.utils.raise_with_traceback(new_exc(e))
return wrapper
return make_wrapper | [
"def",
"wrap_exception",
"(",
"exc",
",",
"new_exc",
")",
":",
"def",
"make_wrapper",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"return",
"f... | Catches exceptions `exc` and raises `new_exc(exc)` instead.
E.g.::
>>> class MyValueError(Exception):
... '''Custom ValueError.'''
... @wrap_exception(exc=ValueError, new_exc=MyValueError)
... def test():
... raise ValueError() | [
"Catches",
"exceptions",
"exc",
"and",
"raises",
"new_exc",
"(",
"exc",
")",
"instead",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/misc.py#L277-L297 |
p3trus/slave | slave/misc.py | AutoRange.range | def range(self, value):
"""Estimates an appropriate sensitivity range."""
self._buffer.append(abs(value))
mean = sum(self._buffer) / len(self._buffer)
estimate = next(
(r for r in self.ranges if mean < self.scale * r),
self.ranges[-1]
)
if self._mapping:
return self._mapping[estimate]
else:
return estimate | python | def range(self, value):
"""Estimates an appropriate sensitivity range."""
self._buffer.append(abs(value))
mean = sum(self._buffer) / len(self._buffer)
estimate = next(
(r for r in self.ranges if mean < self.scale * r),
self.ranges[-1]
)
if self._mapping:
return self._mapping[estimate]
else:
return estimate | [
"def",
"range",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_buffer",
".",
"append",
"(",
"abs",
"(",
"value",
")",
")",
"mean",
"=",
"sum",
"(",
"self",
".",
"_buffer",
")",
"/",
"len",
"(",
"self",
".",
"_buffer",
")",
"estimate",
"=",
... | Estimates an appropriate sensitivity range. | [
"Estimates",
"an",
"appropriate",
"sensitivity",
"range",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/misc.py#L146-L157 |
pudo/jsongraph | jsongraph/context.py | Context.add | def add(self, schema, data):
""" Stage ``data`` as a set of statements, based on the given
``schema`` definition. """
binding = self.get_binding(schema, data)
uri, triples = triplify(binding)
for triple in triples:
self.graph.add(triple)
return uri | python | def add(self, schema, data):
""" Stage ``data`` as a set of statements, based on the given
``schema`` definition. """
binding = self.get_binding(schema, data)
uri, triples = triplify(binding)
for triple in triples:
self.graph.add(triple)
return uri | [
"def",
"add",
"(",
"self",
",",
"schema",
",",
"data",
")",
":",
"binding",
"=",
"self",
".",
"get_binding",
"(",
"schema",
",",
"data",
")",
"uri",
",",
"triples",
"=",
"triplify",
"(",
"binding",
")",
"for",
"triple",
"in",
"triples",
":",
"self",
... | Stage ``data`` as a set of statements, based on the given
``schema`` definition. | [
"Stage",
"data",
"as",
"a",
"set",
"of",
"statements",
"based",
"on",
"the",
"given",
"schema",
"definition",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/context.py#L29-L36 |
pudo/jsongraph | jsongraph/context.py | Context.save | def save(self):
""" Transfer the statements in this context over to the main store. """
if self.parent.buffered:
query = """
INSERT DATA { GRAPH %s { %s } }
"""
query = query % (self.identifier.n3(),
self.graph.serialize(format='nt'))
self.parent.graph.update(query)
self.flush()
else:
self.meta.generate() | python | def save(self):
""" Transfer the statements in this context over to the main store. """
if self.parent.buffered:
query = """
INSERT DATA { GRAPH %s { %s } }
"""
query = query % (self.identifier.n3(),
self.graph.serialize(format='nt'))
self.parent.graph.update(query)
self.flush()
else:
self.meta.generate() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"buffered",
":",
"query",
"=",
"\"\"\"\n INSERT DATA { GRAPH %s { %s } }\n \"\"\"",
"query",
"=",
"query",
"%",
"(",
"self",
".",
"identifier",
".",
"n3",
"(",
")",... | Transfer the statements in this context over to the main store. | [
"Transfer",
"the",
"statements",
"in",
"this",
"context",
"over",
"to",
"the",
"main",
"store",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/context.py#L38-L49 |
pudo/jsongraph | jsongraph/context.py | Context.delete | def delete(self):
""" Delete all statements matching the current context identifier
from the main store. """
if self.parent.buffered:
query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3()
self.parent.graph.update(query)
self.flush()
else:
self.graph.remove((None, None, None)) | python | def delete(self):
""" Delete all statements matching the current context identifier
from the main store. """
if self.parent.buffered:
query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3()
self.parent.graph.update(query)
self.flush()
else:
self.graph.remove((None, None, None)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"buffered",
":",
"query",
"=",
"'CLEAR SILENT GRAPH %s ;'",
"%",
"self",
".",
"identifier",
".",
"n3",
"(",
")",
"self",
".",
"parent",
".",
"graph",
".",
"update",
"(",
"query",... | Delete all statements matching the current context identifier
from the main store. | [
"Delete",
"all",
"statements",
"matching",
"the",
"current",
"context",
"identifier",
"from",
"the",
"main",
"store",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/context.py#L51-L59 |
p3trus/slave | slave/transport.py | Transport.read_bytes | def read_bytes(self, num_bytes):
"""Reads at most `num_bytes`."""
buffer_size = len(self._buffer)
if buffer_size > num_bytes:
# The buffer is larger than the requested amount of bytes.
data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:]
elif 0 < buffer_size <= num_bytes:
# This might return less bytes than requested.
data, self._buffer = self._buffer, bytearray()
else:
# Buffer is empty. Try to read `num_bytes` and call `read_bytes()`
# again. This ensures that at most `num_bytes` are returned.
self._buffer += self.__read__(num_bytes)
return self.read_bytes(num_bytes)
return data | python | def read_bytes(self, num_bytes):
"""Reads at most `num_bytes`."""
buffer_size = len(self._buffer)
if buffer_size > num_bytes:
# The buffer is larger than the requested amount of bytes.
data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:]
elif 0 < buffer_size <= num_bytes:
# This might return less bytes than requested.
data, self._buffer = self._buffer, bytearray()
else:
# Buffer is empty. Try to read `num_bytes` and call `read_bytes()`
# again. This ensures that at most `num_bytes` are returned.
self._buffer += self.__read__(num_bytes)
return self.read_bytes(num_bytes)
return data | [
"def",
"read_bytes",
"(",
"self",
",",
"num_bytes",
")",
":",
"buffer_size",
"=",
"len",
"(",
"self",
".",
"_buffer",
")",
"if",
"buffer_size",
">",
"num_bytes",
":",
"# The buffer is larger than the requested amount of bytes.",
"data",
",",
"self",
".",
"_buffer"... | Reads at most `num_bytes`. | [
"Reads",
"at",
"most",
"num_bytes",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/transport.py#L62-L76 |
p3trus/slave | slave/transport.py | Transport.read_until | def read_until(self, delimiter):
"""Reads until the delimiter is found."""
if delimiter in self._buffer:
data, delimiter, self._buffer = self._buffer.partition(delimiter)
return data
else:
self._buffer += self.__read__(self._max_bytes)
return self.read_until(delimiter) | python | def read_until(self, delimiter):
"""Reads until the delimiter is found."""
if delimiter in self._buffer:
data, delimiter, self._buffer = self._buffer.partition(delimiter)
return data
else:
self._buffer += self.__read__(self._max_bytes)
return self.read_until(delimiter) | [
"def",
"read_until",
"(",
"self",
",",
"delimiter",
")",
":",
"if",
"delimiter",
"in",
"self",
".",
"_buffer",
":",
"data",
",",
"delimiter",
",",
"self",
".",
"_buffer",
"=",
"self",
".",
"_buffer",
".",
"partition",
"(",
"delimiter",
")",
"return",
"... | Reads until the delimiter is found. | [
"Reads",
"until",
"the",
"delimiter",
"is",
"found",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/transport.py#L94-L101 |
p3trus/slave | slave/transport.py | LinuxGpib.close | def close(self):
"""Closes the gpib transport."""
if self._device is not None:
ibsta = self._lib.ibonl(self._device, 0)
self._check_status(ibsta)
self._device = None | python | def close(self):
"""Closes the gpib transport."""
if self._device is not None:
ibsta = self._lib.ibonl(self._device, 0)
self._check_status(ibsta)
self._device = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_device",
"is",
"not",
"None",
":",
"ibsta",
"=",
"self",
".",
"_lib",
".",
"ibonl",
"(",
"self",
".",
"_device",
",",
"0",
")",
"self",
".",
"_check_status",
"(",
"ibsta",
")",
"self",
"... | Closes the gpib transport. | [
"Closes",
"the",
"gpib",
"transport",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/transport.py#L473-L478 |
p3trus/slave | slave/transport.py | LinuxGpib.trigger | def trigger(self):
"""Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device.
"""
ibsta = self._lib.ibtrg(self._device)
self._check_status(ibsta) | python | def trigger(self):
"""Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device.
"""
ibsta = self._lib.ibtrg(self._device)
self._check_status(ibsta) | [
"def",
"trigger",
"(",
"self",
")",
":",
"ibsta",
"=",
"self",
".",
"_lib",
".",
"ibtrg",
"(",
"self",
".",
"_device",
")",
"self",
".",
"_check_status",
"(",
"ibsta",
")"
] | Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device. | [
"Triggers",
"the",
"device",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/transport.py#L495-L502 |
p3trus/slave | slave/transport.py | LinuxGpib._check_status | def _check_status(self, ibsta):
"""Checks ibsta value."""
if ibsta & 0x4000:
raise LinuxGpib.Timeout()
elif ibsta & 0x8000:
raise LinuxGpib.Error(self.error_status) | python | def _check_status(self, ibsta):
"""Checks ibsta value."""
if ibsta & 0x4000:
raise LinuxGpib.Timeout()
elif ibsta & 0x8000:
raise LinuxGpib.Error(self.error_status) | [
"def",
"_check_status",
"(",
"self",
",",
"ibsta",
")",
":",
"if",
"ibsta",
"&",
"0x4000",
":",
"raise",
"LinuxGpib",
".",
"Timeout",
"(",
")",
"elif",
"ibsta",
"&",
"0x8000",
":",
"raise",
"LinuxGpib",
".",
"Error",
"(",
"self",
".",
"error_status",
"... | Checks ibsta value. | [
"Checks",
"ibsta",
"value",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/transport.py#L514-L519 |
miku/gluish | examples/newspapers.py | DownloadPage.run | def run(self):
""" Just run wget quietly. """
output = shellout('wget -q "{url}" -O {output}', url=self.url)
luigi.LocalTarget(output).move(self.output().path) | python | def run(self):
""" Just run wget quietly. """
output = shellout('wget -q "{url}" -O {output}', url=self.url)
luigi.LocalTarget(output).move(self.output().path) | [
"def",
"run",
"(",
"self",
")",
":",
"output",
"=",
"shellout",
"(",
"'wget -q \"{url}\" -O {output}'",
",",
"url",
"=",
"self",
".",
"url",
")",
"luigi",
".",
"LocalTarget",
"(",
"output",
")",
".",
"move",
"(",
"self",
".",
"output",
"(",
")",
".",
... | Just run wget quietly. | [
"Just",
"run",
"wget",
"quietly",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L67-L70 |
miku/gluish | examples/newspapers.py | DownloadPage.output | def output(self):
""" Use the digest version, since URL can be ugly. """
return luigi.LocalTarget(path=self.path(digest=True, ext='html')) | python | def output(self):
""" Use the digest version, since URL can be ugly. """
return luigi.LocalTarget(path=self.path(digest=True, ext='html')) | [
"def",
"output",
"(",
"self",
")",
":",
"return",
"luigi",
".",
"LocalTarget",
"(",
"path",
"=",
"self",
".",
"path",
"(",
"digest",
"=",
"True",
",",
"ext",
"=",
"'html'",
")",
")"
] | Use the digest version, since URL can be ugly. | [
"Use",
"the",
"digest",
"version",
"since",
"URL",
"can",
"be",
"ugly",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L72-L74 |
miku/gluish | examples/newspapers.py | JsonPage.run | def run(self):
""" Construct the document id from the date and the url. """
document = {}
document['_id'] = hashlib.sha1('%s:%s' % (
self.date, self.url)).hexdigest()
with self.input().open() as handle:
document['content'] = handle.read().decode('utf-8', 'ignore')
document['url'] = self.url
document['date'] = unicode(self.date)
with self.output().open('w') as output:
output.write(json.dumps(document)) | python | def run(self):
""" Construct the document id from the date and the url. """
document = {}
document['_id'] = hashlib.sha1('%s:%s' % (
self.date, self.url)).hexdigest()
with self.input().open() as handle:
document['content'] = handle.read().decode('utf-8', 'ignore')
document['url'] = self.url
document['date'] = unicode(self.date)
with self.output().open('w') as output:
output.write(json.dumps(document)) | [
"def",
"run",
"(",
"self",
")",
":",
"document",
"=",
"{",
"}",
"document",
"[",
"'_id'",
"]",
"=",
"hashlib",
".",
"sha1",
"(",
"'%s:%s'",
"%",
"(",
"self",
".",
"date",
",",
"self",
".",
"url",
")",
")",
".",
"hexdigest",
"(",
")",
"with",
"s... | Construct the document id from the date and the url. | [
"Construct",
"the",
"document",
"id",
"from",
"the",
"date",
"and",
"the",
"url",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L86-L96 |
miku/gluish | examples/newspapers.py | IndexPage.run | def run(self):
""" Index the document. Since ids are predictable,
we won't index anything twice. """
with self.input().open() as handle:
body = json.loads(handle.read())
es = elasticsearch.Elasticsearch()
id = body.get('_id')
es.index(index='frontpage', doc_type='html', id=id, body=body) | python | def run(self):
""" Index the document. Since ids are predictable,
we won't index anything twice. """
with self.input().open() as handle:
body = json.loads(handle.read())
es = elasticsearch.Elasticsearch()
id = body.get('_id')
es.index(index='frontpage', doc_type='html', id=id, body=body) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"self",
".",
"input",
"(",
")",
".",
"open",
"(",
")",
"as",
"handle",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"handle",
".",
"read",
"(",
")",
")",
"es",
"=",
"elasticsearch",
".",
"Elasticsearch... | Index the document. Since ids are predictable,
we won't index anything twice. | [
"Index",
"the",
"document",
".",
"Since",
"ids",
"are",
"predictable",
"we",
"won",
"t",
"index",
"anything",
"twice",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L115-L122 |
miku/gluish | examples/newspapers.py | IndexPage.complete | def complete(self):
""" Check, if out hashed date:url id is already in the index. """
id = hashlib.sha1('%s:%s' % (self.date, self.url)).hexdigest()
es = elasticsearch.Elasticsearch()
try:
es.get(index='frontpage', doc_type='html', id=id)
except elasticsearch.NotFoundError:
return False
return True | python | def complete(self):
""" Check, if out hashed date:url id is already in the index. """
id = hashlib.sha1('%s:%s' % (self.date, self.url)).hexdigest()
es = elasticsearch.Elasticsearch()
try:
es.get(index='frontpage', doc_type='html', id=id)
except elasticsearch.NotFoundError:
return False
return True | [
"def",
"complete",
"(",
"self",
")",
":",
"id",
"=",
"hashlib",
".",
"sha1",
"(",
"'%s:%s'",
"%",
"(",
"self",
".",
"date",
",",
"self",
".",
"url",
")",
")",
".",
"hexdigest",
"(",
")",
"es",
"=",
"elasticsearch",
".",
"Elasticsearch",
"(",
")",
... | Check, if out hashed date:url id is already in the index. | [
"Check",
"if",
"out",
"hashed",
"date",
":",
"url",
"id",
"is",
"already",
"in",
"the",
"index",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L124-L132 |
miku/gluish | examples/newspapers.py | DailyIndex.requires | def requires(self):
""" Index all pages. """
for url in NEWSPAPERS:
yield IndexPage(url=url, date=self.date) | python | def requires(self):
""" Index all pages. """
for url in NEWSPAPERS:
yield IndexPage(url=url, date=self.date) | [
"def",
"requires",
"(",
"self",
")",
":",
"for",
"url",
"in",
"NEWSPAPERS",
":",
"yield",
"IndexPage",
"(",
"url",
"=",
"url",
",",
"date",
"=",
"self",
".",
"date",
")"
] | Index all pages. | [
"Index",
"all",
"pages",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/examples/newspapers.py#L156-L159 |
pudo/jsongraph | jsongraph/query.py | Query.get_name | def get_name(self, data):
""" For non-specific queries, this will return the actual name in the
result. """
if self.node.specific_attribute:
return self.node.name
name = data.get(self.predicate_var)
if str(RDF.type) in [self.node.name, name]:
return '$schema'
if name.startswith(PRED):
name = name[len(PRED):]
return name | python | def get_name(self, data):
""" For non-specific queries, this will return the actual name in the
result. """
if self.node.specific_attribute:
return self.node.name
name = data.get(self.predicate_var)
if str(RDF.type) in [self.node.name, name]:
return '$schema'
if name.startswith(PRED):
name = name[len(PRED):]
return name | [
"def",
"get_name",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"node",
".",
"specific_attribute",
":",
"return",
"self",
".",
"node",
".",
"name",
"name",
"=",
"data",
".",
"get",
"(",
"self",
".",
"predicate_var",
")",
"if",
"str",
"(",
... | For non-specific queries, this will return the actual name in the
result. | [
"For",
"non",
"-",
"specific",
"queries",
"this",
"will",
"return",
"the",
"actual",
"name",
"in",
"the",
"result",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L56-L66 |
pudo/jsongraph | jsongraph/query.py | Query.project | def project(self, q, parent=False):
""" Figure out which attributes should be returned for the current
level of the query. """
if self.parent:
print (self.parent.var, self.predicate, self.var)
q = q.project(self.var, append=True)
if parent and self.parent:
q = q.project(self.parent.var, append=True)
if not self.node.specific_attribute:
q = q.project(self.predicate, append=True)
for child in self.children:
if child.node.leaf:
q = child.project(q)
return q | python | def project(self, q, parent=False):
""" Figure out which attributes should be returned for the current
level of the query. """
if self.parent:
print (self.parent.var, self.predicate, self.var)
q = q.project(self.var, append=True)
if parent and self.parent:
q = q.project(self.parent.var, append=True)
if not self.node.specific_attribute:
q = q.project(self.predicate, append=True)
for child in self.children:
if child.node.leaf:
q = child.project(q)
return q | [
"def",
"project",
"(",
"self",
",",
"q",
",",
"parent",
"=",
"False",
")",
":",
"if",
"self",
".",
"parent",
":",
"print",
"(",
"self",
".",
"parent",
".",
"var",
",",
"self",
".",
"predicate",
",",
"self",
".",
"var",
")",
"q",
"=",
"q",
".",
... | Figure out which attributes should be returned for the current
level of the query. | [
"Figure",
"out",
"which",
"attributes",
"should",
"be",
"returned",
"for",
"the",
"current",
"level",
"of",
"the",
"query",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L68-L81 |
pudo/jsongraph | jsongraph/query.py | Query.filter | def filter(self, q, parents=None):
""" Apply any filters to the query. """
if self.node.leaf and self.node.filtered:
# TODO: subject filters?
q = q.where((self.parent.var,
self.predicate,
self.var))
# TODO: inverted nodes
q = self.filter_value(q, self.var)
elif self.parent is not None:
q = q.where((self.parent.var, self.predicate, self.var))
if parents is not None:
parents = [URIRef(p) for p in parents]
q = q.filter(self.parent.var.in_(*parents))
# TODO: forbidden nodes.
for child in self.children:
q = child.filter(q)
return q | python | def filter(self, q, parents=None):
""" Apply any filters to the query. """
if self.node.leaf and self.node.filtered:
# TODO: subject filters?
q = q.where((self.parent.var,
self.predicate,
self.var))
# TODO: inverted nodes
q = self.filter_value(q, self.var)
elif self.parent is not None:
q = q.where((self.parent.var, self.predicate, self.var))
if parents is not None:
parents = [URIRef(p) for p in parents]
q = q.filter(self.parent.var.in_(*parents))
# TODO: forbidden nodes.
for child in self.children:
q = child.filter(q)
return q | [
"def",
"filter",
"(",
"self",
",",
"q",
",",
"parents",
"=",
"None",
")",
":",
"if",
"self",
".",
"node",
".",
"leaf",
"and",
"self",
".",
"node",
".",
"filtered",
":",
"# TODO: subject filters?",
"q",
"=",
"q",
".",
"where",
"(",
"(",
"self",
".",... | Apply any filters to the query. | [
"Apply",
"any",
"filters",
"to",
"the",
"query",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L104-L123 |
pudo/jsongraph | jsongraph/query.py | Query.query | def query(self, parents=None):
""" Compose the query and generate SPARQL. """
# TODO: benchmark single-query strategy
q = Select([])
q = self.project(q, parent=True)
q = self.filter(q, parents=parents)
if self.parent is None:
subq = Select([self.var])
subq = self.filter(subq, parents=parents)
subq = subq.offset(self.node.offset)
subq = subq.limit(self.node.limit)
subq = subq.distinct()
# TODO: sorting.
subq = subq.order_by(desc(self.var))
q = q.where(subq)
# if hasattr(self.context, 'identifier'):
# q._where = graph(self.context.identifier, q._where)
log.debug("Compiled query: %r", q.compile())
return q | python | def query(self, parents=None):
""" Compose the query and generate SPARQL. """
# TODO: benchmark single-query strategy
q = Select([])
q = self.project(q, parent=True)
q = self.filter(q, parents=parents)
if self.parent is None:
subq = Select([self.var])
subq = self.filter(subq, parents=parents)
subq = subq.offset(self.node.offset)
subq = subq.limit(self.node.limit)
subq = subq.distinct()
# TODO: sorting.
subq = subq.order_by(desc(self.var))
q = q.where(subq)
# if hasattr(self.context, 'identifier'):
# q._where = graph(self.context.identifier, q._where)
log.debug("Compiled query: %r", q.compile())
return q | [
"def",
"query",
"(",
"self",
",",
"parents",
"=",
"None",
")",
":",
"# TODO: benchmark single-query strategy",
"q",
"=",
"Select",
"(",
"[",
"]",
")",
"q",
"=",
"self",
".",
"project",
"(",
"q",
",",
"parent",
"=",
"True",
")",
"q",
"=",
"self",
".",... | Compose the query and generate SPARQL. | [
"Compose",
"the",
"query",
"and",
"generate",
"SPARQL",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L132-L152 |
pudo/jsongraph | jsongraph/query.py | Query.base_object | def base_object(self, data):
""" Make sure to return all the existing filter fields
for query results. """
obj = {'id': data.get(self.id)}
if self.parent is not None:
obj['$parent'] = data.get(self.parent.id)
return obj | python | def base_object(self, data):
""" Make sure to return all the existing filter fields
for query results. """
obj = {'id': data.get(self.id)}
if self.parent is not None:
obj['$parent'] = data.get(self.parent.id)
return obj | [
"def",
"base_object",
"(",
"self",
",",
"data",
")",
":",
"obj",
"=",
"{",
"'id'",
":",
"data",
".",
"get",
"(",
"self",
".",
"id",
")",
"}",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"obj",
"[",
"'$parent'",
"]",
"=",
"data",
".",... | Make sure to return all the existing filter fields
for query results. | [
"Make",
"sure",
"to",
"return",
"all",
"the",
"existing",
"filter",
"fields",
"for",
"query",
"results",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L154-L160 |
pudo/jsongraph | jsongraph/query.py | Query.execute | def execute(self, parents=None):
""" Run the data query and construct entities from it's results. """
results = OrderedDict()
for row in self.query(parents=parents).execute(self.context.graph):
data = {k: v.toPython() for (k, v) in row.asdict().items()}
id = data.get(self.id)
if id not in results:
results[id] = self.base_object(data)
for child in self.children:
if child.id in data:
name = child.get_name(data)
value = data.get(child.id)
if child.node.many and \
child.node.op not in [OP_IN, OP_NIN]:
if name not in results[id]:
results[id][name] = [value]
else:
results[id][name].append(value)
else:
results[id][name] = value
return results | python | def execute(self, parents=None):
""" Run the data query and construct entities from it's results. """
results = OrderedDict()
for row in self.query(parents=parents).execute(self.context.graph):
data = {k: v.toPython() for (k, v) in row.asdict().items()}
id = data.get(self.id)
if id not in results:
results[id] = self.base_object(data)
for child in self.children:
if child.id in data:
name = child.get_name(data)
value = data.get(child.id)
if child.node.many and \
child.node.op not in [OP_IN, OP_NIN]:
if name not in results[id]:
results[id][name] = [value]
else:
results[id][name].append(value)
else:
results[id][name] = value
return results | [
"def",
"execute",
"(",
"self",
",",
"parents",
"=",
"None",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"for",
"row",
"in",
"self",
".",
"query",
"(",
"parents",
"=",
"parents",
")",
".",
"execute",
"(",
"self",
".",
"context",
".",
"graph",
... | Run the data query and construct entities from it's results. | [
"Run",
"the",
"data",
"query",
"and",
"construct",
"entities",
"from",
"it",
"s",
"results",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L162-L183 |
pudo/jsongraph | jsongraph/query.py | Query.collect | def collect(self, parents=None):
""" Given re-constructed entities, conduct queries for child
entities and merge them into the current level's object graph. """
results = self.execute(parents=parents)
ids = results.keys()
for child in self.nested():
name = child.node.name
for child_data in child.collect(parents=ids).values():
parent_id = child_data.pop('$parent', None)
if child.node.many:
if name not in results[parent_id]:
results[parent_id][name] = []
results[parent_id][name].append(child_data)
else:
results[parent_id][name] = child_data
return results | python | def collect(self, parents=None):
""" Given re-constructed entities, conduct queries for child
entities and merge them into the current level's object graph. """
results = self.execute(parents=parents)
ids = results.keys()
for child in self.nested():
name = child.node.name
for child_data in child.collect(parents=ids).values():
parent_id = child_data.pop('$parent', None)
if child.node.many:
if name not in results[parent_id]:
results[parent_id][name] = []
results[parent_id][name].append(child_data)
else:
results[parent_id][name] = child_data
return results | [
"def",
"collect",
"(",
"self",
",",
"parents",
"=",
"None",
")",
":",
"results",
"=",
"self",
".",
"execute",
"(",
"parents",
"=",
"parents",
")",
"ids",
"=",
"results",
".",
"keys",
"(",
")",
"for",
"child",
"in",
"self",
".",
"nested",
"(",
")",
... | Given re-constructed entities, conduct queries for child
entities and merge them into the current level's object graph. | [
"Given",
"re",
"-",
"constructed",
"entities",
"conduct",
"queries",
"for",
"child",
"entities",
"and",
"merge",
"them",
"into",
"the",
"current",
"level",
"s",
"object",
"graph",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L185-L200 |
openvax/datacache | datacache/download.py | _download_and_decompress_if_necessary | def _download_and_decompress_if_necessary(
full_path,
download_url,
timeout=None,
use_wget_if_available=False):
"""
Downloads remote file at `download_url` to local file at `full_path`
"""
logger.info("Downloading %s to %s", download_url, full_path)
filename = os.path.split(full_path)[1]
base_name, ext = os.path.splitext(filename)
tmp_path = _download_to_temp_file(
download_url=download_url,
timeout=timeout,
base_name=base_name,
ext=ext,
use_wget_if_available=use_wget_if_available)
if download_url.endswith("zip") and not filename.endswith("zip"):
logger.info("Decompressing zip into %s...", filename)
with zipfile.ZipFile(tmp_path) as z:
names = z.namelist()
assert len(names) > 0, "Empty zip archive"
if filename in names:
chosen_filename = filename
else:
# If zip archive contains multiple files, choose the biggest.
biggest_size = 0
chosen_filename = names[0]
for info in z.infolist():
if info.file_size > biggest_size:
chosen_filename = info.filename
biggest_size = info.file_size
extract_path = z.extract(chosen_filename)
move(extract_path, full_path)
os.remove(tmp_path)
elif download_url.endswith("gz") and not filename.endswith("gz"):
logger.info("Decompressing gzip into %s...", filename)
with gzip.GzipFile(tmp_path) as src:
contents = src.read()
os.remove(tmp_path)
with open(full_path, 'wb') as dst:
dst.write(contents)
elif download_url.endswith(("html", "htm")) and full_path.endswith(".csv"):
logger.info("Extracting HTML table into CSV %s...", filename)
df = pd.read_html(tmp_path, header=0)[0]
df.to_csv(full_path, sep=',', index=False, encoding='utf-8')
else:
move(tmp_path, full_path) | python | def _download_and_decompress_if_necessary(
full_path,
download_url,
timeout=None,
use_wget_if_available=False):
"""
Downloads remote file at `download_url` to local file at `full_path`
"""
logger.info("Downloading %s to %s", download_url, full_path)
filename = os.path.split(full_path)[1]
base_name, ext = os.path.splitext(filename)
tmp_path = _download_to_temp_file(
download_url=download_url,
timeout=timeout,
base_name=base_name,
ext=ext,
use_wget_if_available=use_wget_if_available)
if download_url.endswith("zip") and not filename.endswith("zip"):
logger.info("Decompressing zip into %s...", filename)
with zipfile.ZipFile(tmp_path) as z:
names = z.namelist()
assert len(names) > 0, "Empty zip archive"
if filename in names:
chosen_filename = filename
else:
# If zip archive contains multiple files, choose the biggest.
biggest_size = 0
chosen_filename = names[0]
for info in z.infolist():
if info.file_size > biggest_size:
chosen_filename = info.filename
biggest_size = info.file_size
extract_path = z.extract(chosen_filename)
move(extract_path, full_path)
os.remove(tmp_path)
elif download_url.endswith("gz") and not filename.endswith("gz"):
logger.info("Decompressing gzip into %s...", filename)
with gzip.GzipFile(tmp_path) as src:
contents = src.read()
os.remove(tmp_path)
with open(full_path, 'wb') as dst:
dst.write(contents)
elif download_url.endswith(("html", "htm")) and full_path.endswith(".csv"):
logger.info("Extracting HTML table into CSV %s...", filename)
df = pd.read_html(tmp_path, header=0)[0]
df.to_csv(full_path, sep=',', index=False, encoding='utf-8')
else:
move(tmp_path, full_path) | [
"def",
"_download_and_decompress_if_necessary",
"(",
"full_path",
",",
"download_url",
",",
"timeout",
"=",
"None",
",",
"use_wget_if_available",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"Downloading %s to %s\"",
",",
"download_url",
",",
"full_path",
"... | Downloads remote file at `download_url` to local file at `full_path` | [
"Downloads",
"remote",
"file",
"at",
"download_url",
"to",
"local",
"file",
"at",
"full_path"
] | train | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L94-L142 |
openvax/datacache | datacache/download.py | file_exists | def file_exists(
download_url,
filename=None,
decompress=False,
subdir=None):
"""
Return True if a local file corresponding to these arguments
exists.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
return os.path.exists(full_path) | python | def file_exists(
download_url,
filename=None,
decompress=False,
subdir=None):
"""
Return True if a local file corresponding to these arguments
exists.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
return os.path.exists(full_path) | [
"def",
"file_exists",
"(",
"download_url",
",",
"filename",
"=",
"None",
",",
"decompress",
"=",
"False",
",",
"subdir",
"=",
"None",
")",
":",
"filename",
"=",
"build_local_filename",
"(",
"download_url",
",",
"filename",
",",
"decompress",
")",
"full_path",
... | Return True if a local file corresponding to these arguments
exists. | [
"Return",
"True",
"if",
"a",
"local",
"file",
"corresponding",
"to",
"these",
"arguments",
"exists",
"."
] | train | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L145-L156 |
openvax/datacache | datacache/download.py | fetch_file | def fetch_file(
download_url,
filename=None,
decompress=False,
subdir=None,
force=False,
timeout=None,
use_wget_if_available=False):
"""
Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename : str, optional
Local filename, used as cache key. If omitted, then determine the local
filename from the URL.
decompress : bool, optional
By default any file whose remote extension is one of (".zip", ".gzip")
and whose local filename lacks this suffix is decompressed. If a local
filename wasn't provided but you still want to decompress the stored
data then set this option to True.
subdir : str, optional
Group downloads in a single subdirectory.
force : bool, optional
By default, a remote file is not downloaded if it's already present.
However, with this argument set to True, it will be overwritten.
timeout : float, optional
Timeout for download in seconds, default is None which uses
global timeout.
use_wget_if_available: bool, optional
If the `wget` command is available, use that for download instead
of Python libraries (default True)
Returns the full path of the local file.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
if not os.path.exists(full_path) or force:
logger.info("Fetching %s from URL %s", filename, download_url)
_download_and_decompress_if_necessary(
full_path=full_path,
download_url=download_url,
timeout=timeout,
use_wget_if_available=use_wget_if_available)
else:
logger.info("Cached file %s from URL %s", filename, download_url)
return full_path | python | def fetch_file(
download_url,
filename=None,
decompress=False,
subdir=None,
force=False,
timeout=None,
use_wget_if_available=False):
"""
Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename : str, optional
Local filename, used as cache key. If omitted, then determine the local
filename from the URL.
decompress : bool, optional
By default any file whose remote extension is one of (".zip", ".gzip")
and whose local filename lacks this suffix is decompressed. If a local
filename wasn't provided but you still want to decompress the stored
data then set this option to True.
subdir : str, optional
Group downloads in a single subdirectory.
force : bool, optional
By default, a remote file is not downloaded if it's already present.
However, with this argument set to True, it will be overwritten.
timeout : float, optional
Timeout for download in seconds, default is None which uses
global timeout.
use_wget_if_available: bool, optional
If the `wget` command is available, use that for download instead
of Python libraries (default True)
Returns the full path of the local file.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
if not os.path.exists(full_path) or force:
logger.info("Fetching %s from URL %s", filename, download_url)
_download_and_decompress_if_necessary(
full_path=full_path,
download_url=download_url,
timeout=timeout,
use_wget_if_available=use_wget_if_available)
else:
logger.info("Cached file %s from URL %s", filename, download_url)
return full_path | [
"def",
"fetch_file",
"(",
"download_url",
",",
"filename",
"=",
"None",
",",
"decompress",
"=",
"False",
",",
"subdir",
"=",
"None",
",",
"force",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"use_wget_if_available",
"=",
"False",
")",
":",
"filename",
... | Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename : str, optional
Local filename, used as cache key. If omitted, then determine the local
filename from the URL.
decompress : bool, optional
By default any file whose remote extension is one of (".zip", ".gzip")
and whose local filename lacks this suffix is decompressed. If a local
filename wasn't provided but you still want to decompress the stored
data then set this option to True.
subdir : str, optional
Group downloads in a single subdirectory.
force : bool, optional
By default, a remote file is not downloaded if it's already present.
However, with this argument set to True, it will be overwritten.
timeout : float, optional
Timeout for download in seconds, default is None which uses
global timeout.
use_wget_if_available: bool, optional
If the `wget` command is available, use that for download instead
of Python libraries (default True)
Returns the full path of the local file. | [
"Download",
"a",
"remote",
"file",
"and",
"store",
"it",
"locally",
"in",
"a",
"cache",
"directory",
".",
"Don",
"t",
"download",
"it",
"again",
"if",
"it",
"s",
"already",
"present",
"(",
"unless",
"force",
"is",
"True",
".",
")"
] | train | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L159-L214 |
openvax/datacache | datacache/download.py | fetch_and_transform | def fetch_and_transform(
transformed_filename,
transformer,
loader,
source_filename,
source_url,
subdir=None):
"""
Fetch a remote file from `source_url`, save it locally as `source_filename` and then use
the `loader` and `transformer` function arguments to turn this saved data into an in-memory
object.
"""
transformed_path = build_path(transformed_filename, subdir)
if not os.path.exists(transformed_path):
source_path = fetch_file(source_url, source_filename, subdir)
logger.info("Generating data file %s from %s", transformed_path, source_path)
result = transformer(source_path, transformed_path)
else:
logger.info("Cached data file: %s", transformed_path)
result = loader(transformed_path)
assert os.path.exists(transformed_path)
return result | python | def fetch_and_transform(
transformed_filename,
transformer,
loader,
source_filename,
source_url,
subdir=None):
"""
Fetch a remote file from `source_url`, save it locally as `source_filename` and then use
the `loader` and `transformer` function arguments to turn this saved data into an in-memory
object.
"""
transformed_path = build_path(transformed_filename, subdir)
if not os.path.exists(transformed_path):
source_path = fetch_file(source_url, source_filename, subdir)
logger.info("Generating data file %s from %s", transformed_path, source_path)
result = transformer(source_path, transformed_path)
else:
logger.info("Cached data file: %s", transformed_path)
result = loader(transformed_path)
assert os.path.exists(transformed_path)
return result | [
"def",
"fetch_and_transform",
"(",
"transformed_filename",
",",
"transformer",
",",
"loader",
",",
"source_filename",
",",
"source_url",
",",
"subdir",
"=",
"None",
")",
":",
"transformed_path",
"=",
"build_path",
"(",
"transformed_filename",
",",
"subdir",
")",
"... | Fetch a remote file from `source_url`, save it locally as `source_filename` and then use
the `loader` and `transformer` function arguments to turn this saved data into an in-memory
object. | [
"Fetch",
"a",
"remote",
"file",
"from",
"source_url",
"save",
"it",
"locally",
"as",
"source_filename",
"and",
"then",
"use",
"the",
"loader",
"and",
"transformer",
"function",
"arguments",
"to",
"turn",
"this",
"saved",
"data",
"into",
"an",
"in",
"-",
"mem... | train | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L217-L238 |
openvax/datacache | datacache/download.py | fetch_csv_dataframe | def fetch_csv_dataframe(
download_url,
filename=None,
subdir=None,
**pandas_kwargs):
"""
Download a remote file from `download_url` and save it locally as `filename`.
Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'.
"""
path = fetch_file(
download_url=download_url,
filename=filename,
decompress=True,
subdir=subdir)
return pd.read_csv(path, **pandas_kwargs) | python | def fetch_csv_dataframe(
download_url,
filename=None,
subdir=None,
**pandas_kwargs):
"""
Download a remote file from `download_url` and save it locally as `filename`.
Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'.
"""
path = fetch_file(
download_url=download_url,
filename=filename,
decompress=True,
subdir=subdir)
return pd.read_csv(path, **pandas_kwargs) | [
"def",
"fetch_csv_dataframe",
"(",
"download_url",
",",
"filename",
"=",
"None",
",",
"subdir",
"=",
"None",
",",
"*",
"*",
"pandas_kwargs",
")",
":",
"path",
"=",
"fetch_file",
"(",
"download_url",
"=",
"download_url",
",",
"filename",
"=",
"filename",
",",... | Download a remote file from `download_url` and save it locally as `filename`.
Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'. | [
"Download",
"a",
"remote",
"file",
"from",
"download_url",
"and",
"save",
"it",
"locally",
"as",
"filename",
".",
"Load",
"that",
"local",
"file",
"as",
"a",
"CSV",
"into",
"Pandas",
"using",
"extra",
"keyword",
"arguments",
"such",
"as",
"sep",
"=",
"\\",... | train | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L241-L255 |
twisted/mantissa | xmantissa/publicweb.py | getLoader | def getLoader(*a, **kw):
"""
Deprecated. Don't use this.
"""
warn("xmantissa.publicweb.getLoader is deprecated, use "
"PrivateApplication.getDocFactory or SiteTemplateResolver."
"getDocFactory.", category=DeprecationWarning, stacklevel=2)
from xmantissa.webtheme import getLoader
return getLoader(*a, **kw) | python | def getLoader(*a, **kw):
"""
Deprecated. Don't use this.
"""
warn("xmantissa.publicweb.getLoader is deprecated, use "
"PrivateApplication.getDocFactory or SiteTemplateResolver."
"getDocFactory.", category=DeprecationWarning, stacklevel=2)
from xmantissa.webtheme import getLoader
return getLoader(*a, **kw) | [
"def",
"getLoader",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"warn",
"(",
"\"xmantissa.publicweb.getLoader is deprecated, use \"",
"\"PrivateApplication.getDocFactory or SiteTemplateResolver.\"",
"\"getDocFactory.\"",
",",
"category",
"=",
"DeprecationWarning",
",",
"s... | Deprecated. Don't use this. | [
"Deprecated",
".",
"Don",
"t",
"use",
"this",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L35-L43 |
twisted/mantissa | xmantissa/publicweb.py | renderShortUsername | def renderShortUsername(ctx, username):
"""
Render a potentially shortened version of the user's login identifier,
depending on how the user is viewing it. For example, if bob@example.com
is viewing http://example.com/private/, then render 'bob'. If bob instead
signed up with only his email address (bob@hotmail.com), and is viewing a
page at example.com, then render the full address, 'bob@hotmail.com'.
@param ctx: a L{WovenContext} which has remembered IRequest.
@param username: a string of the form localpart@domain.
@return: a L{Tag}, the given context's tag, with the appropriate username
appended to it.
"""
if username is None:
return ''
req = inevow.IRequest(ctx)
localpart, domain = username.split('@')
host = req.getHeader('Host').split(':')[0]
if host == domain or host.endswith("." + domain):
username = localpart
return ctx.tag[username] | python | def renderShortUsername(ctx, username):
"""
Render a potentially shortened version of the user's login identifier,
depending on how the user is viewing it. For example, if bob@example.com
is viewing http://example.com/private/, then render 'bob'. If bob instead
signed up with only his email address (bob@hotmail.com), and is viewing a
page at example.com, then render the full address, 'bob@hotmail.com'.
@param ctx: a L{WovenContext} which has remembered IRequest.
@param username: a string of the form localpart@domain.
@return: a L{Tag}, the given context's tag, with the appropriate username
appended to it.
"""
if username is None:
return ''
req = inevow.IRequest(ctx)
localpart, domain = username.split('@')
host = req.getHeader('Host').split(':')[0]
if host == domain or host.endswith("." + domain):
username = localpart
return ctx.tag[username] | [
"def",
"renderShortUsername",
"(",
"ctx",
",",
"username",
")",
":",
"if",
"username",
"is",
"None",
":",
"return",
"''",
"req",
"=",
"inevow",
".",
"IRequest",
"(",
"ctx",
")",
"localpart",
",",
"domain",
"=",
"username",
".",
"split",
"(",
"'@'",
")"... | Render a potentially shortened version of the user's login identifier,
depending on how the user is viewing it. For example, if bob@example.com
is viewing http://example.com/private/, then render 'bob'. If bob instead
signed up with only his email address (bob@hotmail.com), and is viewing a
page at example.com, then render the full address, 'bob@hotmail.com'.
@param ctx: a L{WovenContext} which has remembered IRequest.
@param username: a string of the form localpart@domain.
@return: a L{Tag}, the given context's tag, with the appropriate username
appended to it. | [
"Render",
"a",
"potentially",
"shortened",
"version",
"of",
"the",
"user",
"s",
"login",
"identifier",
"depending",
"on",
"how",
"the",
"user",
"is",
"viewing",
"it",
".",
"For",
"example",
"if",
"bob@example",
".",
"com",
"is",
"viewing",
"http",
":",
"//... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L47-L69 |
twisted/mantissa | xmantissa/publicweb.py | _installV2Powerups | def _installV2Powerups(anonymousSite):
"""
Install the given L{AnonymousSite} for the powerup interfaces it was given
in version 2.
"""
anonymousSite.store.powerUp(anonymousSite, IWebViewer)
anonymousSite.store.powerUp(anonymousSite, IMantissaSite) | python | def _installV2Powerups(anonymousSite):
"""
Install the given L{AnonymousSite} for the powerup interfaces it was given
in version 2.
"""
anonymousSite.store.powerUp(anonymousSite, IWebViewer)
anonymousSite.store.powerUp(anonymousSite, IMantissaSite) | [
"def",
"_installV2Powerups",
"(",
"anonymousSite",
")",
":",
"anonymousSite",
".",
"store",
".",
"powerUp",
"(",
"anonymousSite",
",",
"IWebViewer",
")",
"anonymousSite",
".",
"store",
".",
"powerUp",
"(",
"anonymousSite",
",",
"IMantissaSite",
")"
] | Install the given L{AnonymousSite} for the powerup interfaces it was given
in version 2. | [
"Install",
"the",
"given",
"L",
"{",
"AnonymousSite",
"}",
"for",
"the",
"powerup",
"interfaces",
"it",
"was",
"given",
"in",
"version",
"2",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L1061-L1067 |
twisted/mantissa | xmantissa/publicweb.py | PublicWeb.createResource | def createResource(self):
"""
When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex}
for my application.
"""
pp = ixmantissa.IPublicPage(self.application, None)
if pp is not None:
warn(
"Use the sharing system to provide public pages, not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
return pp.getResource()
return SharingIndex(self.application.open()) | python | def createResource(self):
"""
When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex}
for my application.
"""
pp = ixmantissa.IPublicPage(self.application, None)
if pp is not None:
warn(
"Use the sharing system to provide public pages, not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
return pp.getResource()
return SharingIndex(self.application.open()) | [
"def",
"createResource",
"(",
"self",
")",
":",
"pp",
"=",
"ixmantissa",
".",
"IPublicPage",
"(",
"self",
".",
"application",
",",
"None",
")",
"if",
"pp",
"is",
"not",
"None",
":",
"warn",
"(",
"\"Use the sharing system to provide public pages, not IPublicPage\""... | When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex}
for my application. | [
"When",
"invoked",
"by",
"L",
"{",
"PrefixURLMixin",
"}",
"return",
"a",
"L",
"{",
"websharing",
".",
"SharingIndex",
"}",
"for",
"my",
"application",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L121-L133 |
twisted/mantissa | xmantissa/publicweb.py | _AnonymousWebViewer._wrapNavFrag | def _wrapNavFrag(self, frag, useAthena):
"""
Wrap the given L{INavigableFragment} in the appropriate type of
L{_PublicPageMixin}.
"""
if useAthena:
return PublicAthenaLivePage(self._siteStore, frag)
else:
return PublicPage(None, self._siteStore, frag, None, None) | python | def _wrapNavFrag(self, frag, useAthena):
"""
Wrap the given L{INavigableFragment} in the appropriate type of
L{_PublicPageMixin}.
"""
if useAthena:
return PublicAthenaLivePage(self._siteStore, frag)
else:
return PublicPage(None, self._siteStore, frag, None, None) | [
"def",
"_wrapNavFrag",
"(",
"self",
",",
"frag",
",",
"useAthena",
")",
":",
"if",
"useAthena",
":",
"return",
"PublicAthenaLivePage",
"(",
"self",
".",
"_siteStore",
",",
"frag",
")",
"else",
":",
"return",
"PublicPage",
"(",
"None",
",",
"self",
".",
"... | Wrap the given L{INavigableFragment} in the appropriate type of
L{_PublicPageMixin}. | [
"Wrap",
"the",
"given",
"L",
"{",
"INavigableFragment",
"}",
"in",
"the",
"appropriate",
"type",
"of",
"L",
"{",
"_PublicPageMixin",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L197-L205 |
twisted/mantissa | xmantissa/publicweb.py | _CustomizingResource.locateChild | def locateChild(self, ctx, segments):
"""
Return a Deferred which will fire with the customized version of the
resource being located.
"""
D = defer.maybeDeferred(
self.currentResource.locateChild, ctx, segments)
def finishLocating((nextRes, nextPath)):
custom = ixmantissa.ICustomizable(nextRes, None)
if custom is not None:
return (custom.customizeFor(self.forWho), nextPath)
self.currentResource = nextRes
if nextRes is None:
return (nextRes, nextPath)
return (_CustomizingResource(nextRes, self.forWho), nextPath)
return D.addCallback(finishLocating) | python | def locateChild(self, ctx, segments):
"""
Return a Deferred which will fire with the customized version of the
resource being located.
"""
D = defer.maybeDeferred(
self.currentResource.locateChild, ctx, segments)
def finishLocating((nextRes, nextPath)):
custom = ixmantissa.ICustomizable(nextRes, None)
if custom is not None:
return (custom.customizeFor(self.forWho), nextPath)
self.currentResource = nextRes
if nextRes is None:
return (nextRes, nextPath)
return (_CustomizingResource(nextRes, self.forWho), nextPath)
return D.addCallback(finishLocating) | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"D",
"=",
"defer",
".",
"maybeDeferred",
"(",
"self",
".",
"currentResource",
".",
"locateChild",
",",
"ctx",
",",
"segments",
")",
"def",
"finishLocating",
"(",
"(",
"nextRes",
",... | Return a Deferred which will fire with the customized version of the
resource being located. | [
"Return",
"a",
"Deferred",
"which",
"will",
"fire",
"with",
"the",
"customized",
"version",
"of",
"the",
"resource",
"being",
"located",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L241-L258 |
twisted/mantissa | xmantissa/publicweb.py | CustomizedPublicPage.produceResource | def produceResource(self, request, segments, webViewer):
"""
Produce a resource that traverses site-wide content, passing down the
given webViewer. This delegates to the site store's
L{IMantissaSite} adapter, to avoid a conflict with the
L{ISiteRootPlugin} interface.
This method will typically be given an L{_AuthenticatedWebViewer}, which
can build an appropriate resource for an authenticated shell page,
whereas the site store's L{IWebViewer} adapter would show an anonymous
page.
The result of this method will be a L{_CustomizingResource}, to provide
support for resources which may provide L{ICustomizable}. Note that
Mantissa itself no longer implements L{ICustomizable} anywhere, though.
All application code should phase out inspecting the string passed to
ICustomizable in favor of getting more structured information from the
L{IWebViewer}. However, it has not been deprecated yet because
the interface which allows application code to easily access the
L{IWebViewer} from view code has not yet been developed; it is
forthcoming.
See ticket #2707 for progress on this.
"""
mantissaSite = self.publicSiteRoot
if mantissaSite is not None:
for resource, domain in userbase.getAccountNames(self.store):
username = '%s@%s' % (resource, domain)
break
else:
username = None
bottomResource, newSegments = mantissaSite.siteProduceResource(
request, segments, webViewer)
return (_CustomizingResource(bottomResource, username), newSegments)
return None | python | def produceResource(self, request, segments, webViewer):
"""
Produce a resource that traverses site-wide content, passing down the
given webViewer. This delegates to the site store's
L{IMantissaSite} adapter, to avoid a conflict with the
L{ISiteRootPlugin} interface.
This method will typically be given an L{_AuthenticatedWebViewer}, which
can build an appropriate resource for an authenticated shell page,
whereas the site store's L{IWebViewer} adapter would show an anonymous
page.
The result of this method will be a L{_CustomizingResource}, to provide
support for resources which may provide L{ICustomizable}. Note that
Mantissa itself no longer implements L{ICustomizable} anywhere, though.
All application code should phase out inspecting the string passed to
ICustomizable in favor of getting more structured information from the
L{IWebViewer}. However, it has not been deprecated yet because
the interface which allows application code to easily access the
L{IWebViewer} from view code has not yet been developed; it is
forthcoming.
See ticket #2707 for progress on this.
"""
mantissaSite = self.publicSiteRoot
if mantissaSite is not None:
for resource, domain in userbase.getAccountNames(self.store):
username = '%s@%s' % (resource, domain)
break
else:
username = None
bottomResource, newSegments = mantissaSite.siteProduceResource(
request, segments, webViewer)
return (_CustomizingResource(bottomResource, username), newSegments)
return None | [
"def",
"produceResource",
"(",
"self",
",",
"request",
",",
"segments",
",",
"webViewer",
")",
":",
"mantissaSite",
"=",
"self",
".",
"publicSiteRoot",
"if",
"mantissaSite",
"is",
"not",
"None",
":",
"for",
"resource",
",",
"domain",
"in",
"userbase",
".",
... | Produce a resource that traverses site-wide content, passing down the
given webViewer. This delegates to the site store's
L{IMantissaSite} adapter, to avoid a conflict with the
L{ISiteRootPlugin} interface.
This method will typically be given an L{_AuthenticatedWebViewer}, which
can build an appropriate resource for an authenticated shell page,
whereas the site store's L{IWebViewer} adapter would show an anonymous
page.
The result of this method will be a L{_CustomizingResource}, to provide
support for resources which may provide L{ICustomizable}. Note that
Mantissa itself no longer implements L{ICustomizable} anywhere, though.
All application code should phase out inspecting the string passed to
ICustomizable in favor of getting more structured information from the
L{IWebViewer}. However, it has not been deprecated yet because
the interface which allows application code to easily access the
L{IWebViewer} from view code has not yet been developed; it is
forthcoming.
See ticket #2707 for progress on this. | [
"Produce",
"a",
"resource",
"that",
"traverses",
"site",
"-",
"wide",
"content",
"passing",
"down",
"the",
"given",
"webViewer",
".",
"This",
"delegates",
"to",
"the",
"site",
"store",
"s",
"L",
"{",
"IMantissaSite",
"}",
"adapter",
"to",
"avoid",
"a",
"co... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L294-L328 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin._getViewerPrivateApplication | def _getViewerPrivateApplication(self):
"""
Get the L{PrivateApplication} object for the logged-in user who is
viewing this resource, as indicated by its C{username} attribute.
This is highly problematic because it precludes the possibility of
separating the stores of the viewer and the viewee into separate
processes, and it is only here until we can get rid of it. The reason
it remains is that some application code still imports things which
subclass L{PublicAthenaLivePage} and L{PublicPage} and uses them with
usernames specified. See ticket #2702 for progress on this goal.
However, Mantissa itself will no longer set this class's username
attribute to anything other than None, because authenticated users'
pages will be generated using
L{xmantissa.webapp._AuthenticatedWebViewer}. This method is used only
to render content in the shell template, and those classes have a direct
reference to the requisite object.
@rtype: L{PrivateApplication}
"""
ls = self.store.findUnique(userbase.LoginSystem)
substore = ls.accountByAddress(*self.username.split('@')).avatars.open()
from xmantissa.webapp import PrivateApplication
return substore.findUnique(PrivateApplication) | python | def _getViewerPrivateApplication(self):
"""
Get the L{PrivateApplication} object for the logged-in user who is
viewing this resource, as indicated by its C{username} attribute.
This is highly problematic because it precludes the possibility of
separating the stores of the viewer and the viewee into separate
processes, and it is only here until we can get rid of it. The reason
it remains is that some application code still imports things which
subclass L{PublicAthenaLivePage} and L{PublicPage} and uses them with
usernames specified. See ticket #2702 for progress on this goal.
However, Mantissa itself will no longer set this class's username
attribute to anything other than None, because authenticated users'
pages will be generated using
L{xmantissa.webapp._AuthenticatedWebViewer}. This method is used only
to render content in the shell template, and those classes have a direct
reference to the requisite object.
@rtype: L{PrivateApplication}
"""
ls = self.store.findUnique(userbase.LoginSystem)
substore = ls.accountByAddress(*self.username.split('@')).avatars.open()
from xmantissa.webapp import PrivateApplication
return substore.findUnique(PrivateApplication) | [
"def",
"_getViewerPrivateApplication",
"(",
"self",
")",
":",
"ls",
"=",
"self",
".",
"store",
".",
"findUnique",
"(",
"userbase",
".",
"LoginSystem",
")",
"substore",
"=",
"ls",
".",
"accountByAddress",
"(",
"*",
"self",
".",
"username",
".",
"split",
"("... | Get the L{PrivateApplication} object for the logged-in user who is
viewing this resource, as indicated by its C{username} attribute.
This is highly problematic because it precludes the possibility of
separating the stores of the viewer and the viewee into separate
processes, and it is only here until we can get rid of it. The reason
it remains is that some application code still imports things which
subclass L{PublicAthenaLivePage} and L{PublicPage} and uses them with
usernames specified. See ticket #2702 for progress on this goal.
However, Mantissa itself will no longer set this class's username
attribute to anything other than None, because authenticated users'
pages will be generated using
L{xmantissa.webapp._AuthenticatedWebViewer}. This method is used only
to render content in the shell template, and those classes have a direct
reference to the requisite object.
@rtype: L{PrivateApplication} | [
"Get",
"the",
"L",
"{",
"PrivateApplication",
"}",
"object",
"for",
"the",
"logged",
"-",
"in",
"user",
"who",
"is",
"viewing",
"this",
"resource",
"as",
"indicated",
"by",
"its",
"C",
"{",
"username",
"}",
"attribute",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L354-L378 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_authenticateLinks | def render_authenticateLinks(self, ctx, data):
"""
For unauthenticated users, add login and signup links to the given tag.
For authenticated users, remove the given tag from the output.
When necessary, the I{signup-link} pattern will be loaded from the tag.
Each copy of it will have I{prompt} and I{url} slots filled. The list
of copies will be added as children of the tag.
"""
if self.username is not None:
return ''
# there is a circular import here which should probably be avoidable,
# since we don't actually need signup links on the signup page. on the
# other hand, maybe we want to eventually put those there for
# consistency. for now, this import is easiest, and although it's a
# "friend" API, which I dislike, it doesn't seem to cause any real
# problems... -glyph
from xmantissa.signup import _getPublicSignupInfo
IQ = inevow.IQ(ctx.tag)
signupPattern = IQ.patternGenerator('signup-link')
signups = []
for (prompt, url) in _getPublicSignupInfo(self.store):
signups.append(signupPattern.fillSlots(
'prompt', prompt).fillSlots(
'url', url))
return ctx.tag[signups] | python | def render_authenticateLinks(self, ctx, data):
"""
For unauthenticated users, add login and signup links to the given tag.
For authenticated users, remove the given tag from the output.
When necessary, the I{signup-link} pattern will be loaded from the tag.
Each copy of it will have I{prompt} and I{url} slots filled. The list
of copies will be added as children of the tag.
"""
if self.username is not None:
return ''
# there is a circular import here which should probably be avoidable,
# since we don't actually need signup links on the signup page. on the
# other hand, maybe we want to eventually put those there for
# consistency. for now, this import is easiest, and although it's a
# "friend" API, which I dislike, it doesn't seem to cause any real
# problems... -glyph
from xmantissa.signup import _getPublicSignupInfo
IQ = inevow.IQ(ctx.tag)
signupPattern = IQ.patternGenerator('signup-link')
signups = []
for (prompt, url) in _getPublicSignupInfo(self.store):
signups.append(signupPattern.fillSlots(
'prompt', prompt).fillSlots(
'url', url))
return ctx.tag[signups] | [
"def",
"render_authenticateLinks",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"username",
"is",
"not",
"None",
":",
"return",
"''",
"# there is a circular import here which should probably be avoidable,",
"# since we don't actually need signup links ... | For unauthenticated users, add login and signup links to the given tag.
For authenticated users, remove the given tag from the output.
When necessary, the I{signup-link} pattern will be loaded from the tag.
Each copy of it will have I{prompt} and I{url} slots filled. The list
of copies will be added as children of the tag. | [
"For",
"unauthenticated",
"users",
"add",
"login",
"and",
"signup",
"links",
"to",
"the",
"given",
"tag",
".",
"For",
"authenticated",
"users",
"remove",
"the",
"given",
"tag",
"from",
"the",
"output",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L381-L409 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_startmenu | def render_startmenu(self, ctx, data):
"""
For authenticated users, add the start-menu style navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.startMenu}
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
pageComponents = translator.getPageComponents()
return startMenu(translator, pageComponents.navigation, ctx.tag) | python | def render_startmenu(self, ctx, data):
"""
For authenticated users, add the start-menu style navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.startMenu}
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
pageComponents = translator.getPageComponents()
return startMenu(translator, pageComponents.navigation, ctx.tag) | [
"def",
"render_startmenu",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
":",
"return",
"''",
"translator",
"=",
"self",
".",
"_getViewerPrivateApplication",
"(",
")",
"pageComponents",
"=",
"translator",
".",
... | For authenticated users, add the start-menu style navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.startMenu} | [
"For",
"authenticated",
"users",
"add",
"the",
"start",
"-",
"menu",
"style",
"navigation",
"to",
"the",
"given",
"tag",
".",
"For",
"unauthenticated",
"users",
"remove",
"the",
"given",
"tag",
"from",
"the",
"output",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L412-L424 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_settingsLink | def render_settingsLink(self, ctx, data):
"""
For authenticated users, add the URL of the settings page to the given
tag. For unauthenticated users, remove the given tag from the output.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
return settingsLink(
translator,
translator.getPageComponents().settings,
ctx.tag) | python | def render_settingsLink(self, ctx, data):
"""
For authenticated users, add the URL of the settings page to the given
tag. For unauthenticated users, remove the given tag from the output.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
return settingsLink(
translator,
translator.getPageComponents().settings,
ctx.tag) | [
"def",
"render_settingsLink",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
":",
"return",
"''",
"translator",
"=",
"self",
".",
"_getViewerPrivateApplication",
"(",
")",
"return",
"settingsLink",
"(",
"translat... | For authenticated users, add the URL of the settings page to the given
tag. For unauthenticated users, remove the given tag from the output. | [
"For",
"authenticated",
"users",
"add",
"the",
"URL",
"of",
"the",
"settings",
"page",
"to",
"the",
"given",
"tag",
".",
"For",
"unauthenticated",
"users",
"remove",
"the",
"given",
"tag",
"from",
"the",
"output",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L427-L438 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_applicationNavigation | def render_applicationNavigation(self, ctx, data):
"""
For authenticated users, add primary application navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.applicationNavigation}
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
return applicationNavigation(
ctx,
translator,
translator.getPageComponents().navigation) | python | def render_applicationNavigation(self, ctx, data):
"""
For authenticated users, add primary application navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.applicationNavigation}
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
return applicationNavigation(
ctx,
translator,
translator.getPageComponents().navigation) | [
"def",
"render_applicationNavigation",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
":",
"return",
"''",
"translator",
"=",
"self",
".",
"_getViewerPrivateApplication",
"(",
")",
"return",
"applicationNavigation",
... | For authenticated users, add primary application navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.applicationNavigation} | [
"For",
"authenticated",
"users",
"add",
"primary",
"application",
"navigation",
"to",
"the",
"given",
"tag",
".",
"For",
"unauthenticated",
"users",
"remove",
"the",
"given",
"tag",
"from",
"the",
"output",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L441-L455 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_search | def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
searchAggregator = translator.getPageComponents().searchAggregator
if searchAggregator is None or not searchAggregator.providers():
return ''
return ctx.tag.fillSlots(
'form-action', translator.linkTo(searchAggregator.storeID)) | python | def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
searchAggregator = translator.getPageComponents().searchAggregator
if searchAggregator is None or not searchAggregator.providers():
return ''
return ctx.tag.fillSlots(
'form-action', translator.linkTo(searchAggregator.storeID)) | [
"def",
"render_search",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
":",
"return",
"''",
"translator",
"=",
"self",
".",
"_getViewerPrivateApplication",
"(",
")",
"searchAggregator",
"=",
"translator",
".",
... | Render some UI for performing searches, if we know about a search
aggregator. | [
"Render",
"some",
"UI",
"for",
"performing",
"searches",
"if",
"we",
"know",
"about",
"a",
"search",
"aggregator",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L458-L470 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_rootURL | def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
"""
return ctx.tag[
ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))] | python | def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
"""
return ctx.tag[
ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))] | [
"def",
"render_rootURL",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"return",
"ctx",
".",
"tag",
"[",
"ixmantissa",
".",
"ISiteURLGenerator",
"(",
"self",
".",
"store",
")",
".",
"rootURL",
"(",
"IRequest",
"(",
"ctx",
")",
")",
"]"
] | Add the WebSite's root URL as a child of the given tag. | [
"Add",
"the",
"WebSite",
"s",
"root",
"URL",
"as",
"a",
"child",
"of",
"the",
"given",
"tag",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L491-L496 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_header | def render_header(self, ctx, data):
"""
Render any required static content in the header, from the C{staticContent}
attribute of this page.
"""
if self.staticContent is None:
return ctx.tag
header = self.staticContent.getHeader()
if header is not None:
return ctx.tag[header]
else:
return ctx.tag | python | def render_header(self, ctx, data):
"""
Render any required static content in the header, from the C{staticContent}
attribute of this page.
"""
if self.staticContent is None:
return ctx.tag
header = self.staticContent.getHeader()
if header is not None:
return ctx.tag[header]
else:
return ctx.tag | [
"def",
"render_header",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"staticContent",
"is",
"None",
":",
"return",
"ctx",
".",
"tag",
"header",
"=",
"self",
".",
"staticContent",
".",
"getHeader",
"(",
")",
"if",
"header",
"is",
... | Render any required static content in the header, from the C{staticContent}
attribute of this page. | [
"Render",
"any",
"required",
"static",
"content",
"in",
"the",
"header",
"from",
"the",
"C",
"{",
"staticContent",
"}",
"attribute",
"of",
"this",
"page",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L499-L511 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_footer | def render_footer(self, ctx, data):
"""
Render any required static content in the footer, from the C{staticContent}
attribute of this page.
"""
if self.staticContent is None:
return ctx.tag
header = self.staticContent.getFooter()
if header is not None:
return ctx.tag[header]
else:
return ctx.tag | python | def render_footer(self, ctx, data):
"""
Render any required static content in the footer, from the C{staticContent}
attribute of this page.
"""
if self.staticContent is None:
return ctx.tag
header = self.staticContent.getFooter()
if header is not None:
return ctx.tag[header]
else:
return ctx.tag | [
"def",
"render_footer",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"if",
"self",
".",
"staticContent",
"is",
"None",
":",
"return",
"ctx",
".",
"tag",
"header",
"=",
"self",
".",
"staticContent",
".",
"getFooter",
"(",
")",
"if",
"header",
"is",
... | Render any required static content in the footer, from the C{staticContent}
attribute of this page. | [
"Render",
"any",
"required",
"static",
"content",
"in",
"the",
"footer",
"from",
"the",
"C",
"{",
"staticContent",
"}",
"attribute",
"of",
"this",
"page",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L514-L526 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_urchin | def render_urchin(self, ctx, data):
"""
Render the code for recording Google Analytics statistics, if so
configured.
"""
key = website.APIKey.getKeyForAPI(self.store, website.APIKey.URCHIN)
if key is None:
return ''
return ctx.tag.fillSlots('urchin-key', key.apiKey) | python | def render_urchin(self, ctx, data):
"""
Render the code for recording Google Analytics statistics, if so
configured.
"""
key = website.APIKey.getKeyForAPI(self.store, website.APIKey.URCHIN)
if key is None:
return ''
return ctx.tag.fillSlots('urchin-key', key.apiKey) | [
"def",
"render_urchin",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"key",
"=",
"website",
".",
"APIKey",
".",
"getKeyForAPI",
"(",
"self",
".",
"store",
",",
"website",
".",
"APIKey",
".",
"URCHIN",
")",
"if",
"key",
"is",
"None",
":",
"return",... | Render the code for recording Google Analytics statistics, if so
configured. | [
"Render",
"the",
"code",
"for",
"recording",
"Google",
"Analytics",
"statistics",
"if",
"so",
"configured",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L529-L537 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.getHeadContent | def getHeadContent(self, req):
"""
Retrieve a list of header content from all installed themes on the site
store.
"""
site = ixmantissa.ISiteURLGenerator(self.store)
for t in getInstalledThemes(self.store):
yield t.head(req, site) | python | def getHeadContent(self, req):
"""
Retrieve a list of header content from all installed themes on the site
store.
"""
site = ixmantissa.ISiteURLGenerator(self.store)
for t in getInstalledThemes(self.store):
yield t.head(req, site) | [
"def",
"getHeadContent",
"(",
"self",
",",
"req",
")",
":",
"site",
"=",
"ixmantissa",
".",
"ISiteURLGenerator",
"(",
"self",
".",
"store",
")",
"for",
"t",
"in",
"getInstalledThemes",
"(",
"self",
".",
"store",
")",
":",
"yield",
"t",
".",
"head",
"("... | Retrieve a list of header content from all installed themes on the site
store. | [
"Retrieve",
"a",
"list",
"of",
"header",
"content",
"from",
"all",
"installed",
"themes",
"on",
"the",
"site",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L548-L555 |
twisted/mantissa | xmantissa/publicweb.py | _PublicPageMixin.render_head | def render_head(self, ctx, data):
"""
This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method.
"""
req = inevow.IRequest(ctx)
more = getattr(self.fragment, 'head', None)
if more is not None:
fragmentHead = more()
else:
fragmentHead = None
return ctx.tag[filter(None, list(self.getHeadContent(req)) +
[fragmentHead])] | python | def render_head(self, ctx, data):
"""
This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method.
"""
req = inevow.IRequest(ctx)
more = getattr(self.fragment, 'head', None)
if more is not None:
fragmentHead = more()
else:
fragmentHead = None
return ctx.tag[filter(None, list(self.getHeadContent(req)) +
[fragmentHead])] | [
"def",
"render_head",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"req",
"=",
"inevow",
".",
"IRequest",
"(",
"ctx",
")",
"more",
"=",
"getattr",
"(",
"self",
".",
"fragment",
",",
"'head'",
",",
"None",
")",
"if",
"more",
"is",
"not",
"None",
... | This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method. | [
"This",
"renderer",
"calculates",
"content",
"for",
"the",
"<head",
">",
"tag",
"by",
"concatenating",
"the",
"values",
"from",
"L",
"{",
"getHeadContent",
"}",
"and",
"the",
"overridden",
"L",
"{",
"head",
"}",
"method",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L558-L570 |
twisted/mantissa | xmantissa/publicweb.py | _OfferingsFragment.data_offerings | def data_offerings(self, ctx, data):
"""
Generate a list of installed offerings.
@return: a generator of dictionaries mapping 'name' to the name of an
offering installed on the store.
"""
for io in self.original.store.query(offering.InstalledOffering):
pp = ixmantissa.IPublicPage(io.application, None)
if pp is not None and getattr(pp, 'index', True):
warn("Use the sharing system to provide public pages,"
" not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
yield {'name': io.offeringName}
else:
s = io.application.open()
try:
pp = getEveryoneRole(s).getShare(getDefaultShareID(s))
yield {'name': io.offeringName}
except NoSuchShare:
continue | python | def data_offerings(self, ctx, data):
"""
Generate a list of installed offerings.
@return: a generator of dictionaries mapping 'name' to the name of an
offering installed on the store.
"""
for io in self.original.store.query(offering.InstalledOffering):
pp = ixmantissa.IPublicPage(io.application, None)
if pp is not None and getattr(pp, 'index', True):
warn("Use the sharing system to provide public pages,"
" not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
yield {'name': io.offeringName}
else:
s = io.application.open()
try:
pp = getEveryoneRole(s).getShare(getDefaultShareID(s))
yield {'name': io.offeringName}
except NoSuchShare:
continue | [
"def",
"data_offerings",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"for",
"io",
"in",
"self",
".",
"original",
".",
"store",
".",
"query",
"(",
"offering",
".",
"InstalledOffering",
")",
":",
"pp",
"=",
"ixmantissa",
".",
"IPublicPage",
"(",
"io"... | Generate a list of installed offerings.
@return: a generator of dictionaries mapping 'name' to the name of an
offering installed on the store. | [
"Generate",
"a",
"list",
"of",
"installed",
"offerings",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L643-L664 |
twisted/mantissa | xmantissa/publicweb.py | _PublicFrontPage.locateChild | def locateChild(self, ctx, segments):
"""
Look up children in the normal manner, but then customize them for the
authenticated user if they support the L{ICustomizable} interface. If
the user is attempting to access a private URL, redirect them.
"""
result = self._getAppStoreResource(ctx, segments[0])
if result is not None:
child, segments = result, segments[1:]
return child, segments
if segments[0] == '':
result = self.child_(ctx)
if result is not None:
child, segments = result, segments[1:]
return child, segments
# If the user is trying to access /private/*, then his session has
# expired or he is otherwise not logged in. Redirect him to /login,
# preserving the URL segments, rather than giving him an obscure 404.
if segments[0] == 'private':
u = URL.fromContext(ctx).click('/').child('login')
for seg in segments:
u = u.child(seg)
return u, ()
return rend.NotFound | python | def locateChild(self, ctx, segments):
"""
Look up children in the normal manner, but then customize them for the
authenticated user if they support the L{ICustomizable} interface. If
the user is attempting to access a private URL, redirect them.
"""
result = self._getAppStoreResource(ctx, segments[0])
if result is not None:
child, segments = result, segments[1:]
return child, segments
if segments[0] == '':
result = self.child_(ctx)
if result is not None:
child, segments = result, segments[1:]
return child, segments
# If the user is trying to access /private/*, then his session has
# expired or he is otherwise not logged in. Redirect him to /login,
# preserving the URL segments, rather than giving him an obscure 404.
if segments[0] == 'private':
u = URL.fromContext(ctx).click('/').child('login')
for seg in segments:
u = u.child(seg)
return u, ()
return rend.NotFound | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"result",
"=",
"self",
".",
"_getAppStoreResource",
"(",
"ctx",
",",
"segments",
"[",
"0",
"]",
")",
"if",
"result",
"is",
"not",
"None",
":",
"child",
",",
"segments",
"=",
"r... | Look up children in the normal manner, but then customize them for the
authenticated user if they support the L{ICustomizable} interface. If
the user is attempting to access a private URL, redirect them. | [
"Look",
"up",
"children",
"in",
"the",
"normal",
"manner",
"but",
"then",
"customize",
"them",
"for",
"the",
"authenticated",
"user",
"if",
"they",
"support",
"the",
"L",
"{",
"ICustomizable",
"}",
"interface",
".",
"If",
"the",
"user",
"is",
"attempting",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L690-L716 |
twisted/mantissa | xmantissa/publicweb.py | _PublicFrontPage._getAppStoreResource | def _getAppStoreResource(self, ctx, name):
"""
Customize child lookup such that all installed offerings on the site
store that this page is viewing are given an opportunity to display
their own page.
"""
offer = self.frontPageItem.store.findFirst(
offering.InstalledOffering,
offering.InstalledOffering.offeringName == unicode(name, 'ascii'))
if offer is not None:
pp = ixmantissa.IPublicPage(offer.application, None)
if pp is not None:
warn("Use the sharing system to provide public pages,"
" not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
return pp.getResource()
return SharingIndex(offer.application.open(),
self.webViewer)
return None | python | def _getAppStoreResource(self, ctx, name):
"""
Customize child lookup such that all installed offerings on the site
store that this page is viewing are given an opportunity to display
their own page.
"""
offer = self.frontPageItem.store.findFirst(
offering.InstalledOffering,
offering.InstalledOffering.offeringName == unicode(name, 'ascii'))
if offer is not None:
pp = ixmantissa.IPublicPage(offer.application, None)
if pp is not None:
warn("Use the sharing system to provide public pages,"
" not IPublicPage",
category=DeprecationWarning,
stacklevel=2)
return pp.getResource()
return SharingIndex(offer.application.open(),
self.webViewer)
return None | [
"def",
"_getAppStoreResource",
"(",
"self",
",",
"ctx",
",",
"name",
")",
":",
"offer",
"=",
"self",
".",
"frontPageItem",
".",
"store",
".",
"findFirst",
"(",
"offering",
".",
"InstalledOffering",
",",
"offering",
".",
"InstalledOffering",
".",
"offeringName"... | Customize child lookup such that all installed offerings on the site
store that this page is viewing are given an opportunity to display
their own page. | [
"Customize",
"child",
"lookup",
"such",
"that",
"all",
"installed",
"offerings",
"on",
"the",
"site",
"store",
"that",
"this",
"page",
"is",
"viewing",
"are",
"given",
"an",
"opportunity",
"to",
"display",
"their",
"own",
"page",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L719-L738 |
twisted/mantissa | xmantissa/publicweb.py | _PublicFrontPage.child_ | def child_(self, ctx):
"""
If the root resource is requested, return the primary
application's front page, if a primary application has been
chosen. Otherwise return 'self', since this page can render a
simple index.
"""
if self.frontPageItem.defaultApplication is None:
return self.webViewer.wrapModel(
_OfferingsFragment(self.frontPageItem))
else:
return SharingIndex(self.frontPageItem.defaultApplication.open(),
self.webViewer).locateChild(ctx, [''])[0] | python | def child_(self, ctx):
"""
If the root resource is requested, return the primary
application's front page, if a primary application has been
chosen. Otherwise return 'self', since this page can render a
simple index.
"""
if self.frontPageItem.defaultApplication is None:
return self.webViewer.wrapModel(
_OfferingsFragment(self.frontPageItem))
else:
return SharingIndex(self.frontPageItem.defaultApplication.open(),
self.webViewer).locateChild(ctx, [''])[0] | [
"def",
"child_",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"self",
".",
"frontPageItem",
".",
"defaultApplication",
"is",
"None",
":",
"return",
"self",
".",
"webViewer",
".",
"wrapModel",
"(",
"_OfferingsFragment",
"(",
"self",
".",
"frontPageItem",
")",
"... | If the root resource is requested, return the primary
application's front page, if a primary application has been
chosen. Otherwise return 'self', since this page can render a
simple index. | [
"If",
"the",
"root",
"resource",
"is",
"requested",
"return",
"the",
"primary",
"application",
"s",
"front",
"page",
"if",
"a",
"primary",
"application",
"has",
"been",
"chosen",
".",
"Otherwise",
"return",
"self",
"since",
"this",
"page",
"can",
"render",
"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L741-L753 |
twisted/mantissa | xmantissa/publicweb.py | LoginPage.beforeRender | def beforeRender(self, ctx):
"""
Before rendering this page, identify the correct URL for the login to post
to, and the error message to display (if any), and fill the 'login
action' and 'error' slots in the template accordingly.
"""
generator = ixmantissa.ISiteURLGenerator(self.store)
url = generator.rootURL(IRequest(ctx))
url = url.child('__login__')
for seg in self.segments:
url = url.child(seg)
for queryKey, queryValues in self.arguments.iteritems():
for queryValue in queryValues:
url = url.add(queryKey, queryValue)
req = inevow.IRequest(ctx)
err = req.args.get('login-failure', ('',))[0]
if 0 < len(err):
error = inevow.IQ(
self.fragment).onePattern(
'error').fillSlots('error', err)
else:
error = ''
ctx.fillSlots("login-action", url)
ctx.fillSlots("error", error) | python | def beforeRender(self, ctx):
"""
Before rendering this page, identify the correct URL for the login to post
to, and the error message to display (if any), and fill the 'login
action' and 'error' slots in the template accordingly.
"""
generator = ixmantissa.ISiteURLGenerator(self.store)
url = generator.rootURL(IRequest(ctx))
url = url.child('__login__')
for seg in self.segments:
url = url.child(seg)
for queryKey, queryValues in self.arguments.iteritems():
for queryValue in queryValues:
url = url.add(queryKey, queryValue)
req = inevow.IRequest(ctx)
err = req.args.get('login-failure', ('',))[0]
if 0 < len(err):
error = inevow.IQ(
self.fragment).onePattern(
'error').fillSlots('error', err)
else:
error = ''
ctx.fillSlots("login-action", url)
ctx.fillSlots("error", error) | [
"def",
"beforeRender",
"(",
"self",
",",
"ctx",
")",
":",
"generator",
"=",
"ixmantissa",
".",
"ISiteURLGenerator",
"(",
"self",
".",
"store",
")",
"url",
"=",
"generator",
".",
"rootURL",
"(",
"IRequest",
"(",
"ctx",
")",
")",
"url",
"=",
"url",
".",
... | Before rendering this page, identify the correct URL for the login to post
to, and the error message to display (if any), and fill the 'login
action' and 'error' slots in the template accordingly. | [
"Before",
"rendering",
"this",
"page",
"identify",
"the",
"correct",
"URL",
"for",
"the",
"login",
"to",
"post",
"to",
"and",
"the",
"error",
"message",
"to",
"display",
"(",
"if",
"any",
")",
"and",
"fill",
"the",
"login",
"action",
"and",
"error",
"slo... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L801-L827 |
twisted/mantissa | xmantissa/publicweb.py | LoginPage.locateChild | def locateChild(self, ctx, segments):
"""
Return a clone of this page that remembers its segments, so that URLs like
/login/private/stuff will redirect the user to /private/stuff after
login has completed.
"""
arguments = IRequest(ctx).args
return self.__class__(
self.store, segments, arguments), () | python | def locateChild(self, ctx, segments):
"""
Return a clone of this page that remembers its segments, so that URLs like
/login/private/stuff will redirect the user to /private/stuff after
login has completed.
"""
arguments = IRequest(ctx).args
return self.__class__(
self.store, segments, arguments), () | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"arguments",
"=",
"IRequest",
"(",
"ctx",
")",
".",
"args",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"store",
",",
"segments",
",",
"arguments",
")",
",",
"(",
")"... | Return a clone of this page that remembers its segments, so that URLs like
/login/private/stuff will redirect the user to /private/stuff after
login has completed. | [
"Return",
"a",
"clone",
"of",
"this",
"page",
"that",
"remembers",
"its",
"segments",
"so",
"that",
"URLs",
"like",
"/",
"login",
"/",
"private",
"/",
"stuff",
"will",
"redirect",
"the",
"user",
"to",
"/",
"private",
"/",
"stuff",
"after",
"login",
"has"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L830-L838 |
twisted/mantissa | xmantissa/publicweb.py | LoginPage.fromRequest | def fromRequest(cls, store, request):
"""
Return a L{LoginPage} which will present the user with a login prompt.
@type store: L{Store}
@param store: A I{site} store.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request which encountered a need for
authentication. This will be effectively re-issued after login
succeeds.
@return: A L{LoginPage} and the remaining segments to be processed.
"""
location = URL.fromRequest(request)
segments = location.pathList(unquote=True, copy=False)
segments.append(request.postpath[0])
return cls(store, segments, request.args) | python | def fromRequest(cls, store, request):
"""
Return a L{LoginPage} which will present the user with a login prompt.
@type store: L{Store}
@param store: A I{site} store.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request which encountered a need for
authentication. This will be effectively re-issued after login
succeeds.
@return: A L{LoginPage} and the remaining segments to be processed.
"""
location = URL.fromRequest(request)
segments = location.pathList(unquote=True, copy=False)
segments.append(request.postpath[0])
return cls(store, segments, request.args) | [
"def",
"fromRequest",
"(",
"cls",
",",
"store",
",",
"request",
")",
":",
"location",
"=",
"URL",
".",
"fromRequest",
"(",
"request",
")",
"segments",
"=",
"location",
".",
"pathList",
"(",
"unquote",
"=",
"True",
",",
"copy",
"=",
"False",
")",
"segme... | Return a L{LoginPage} which will present the user with a login prompt.
@type store: L{Store}
@param store: A I{site} store.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request which encountered a need for
authentication. This will be effectively re-issued after login
succeeds.
@return: A L{LoginPage} and the remaining segments to be processed. | [
"Return",
"a",
"L",
"{",
"LoginPage",
"}",
"which",
"will",
"present",
"the",
"user",
"with",
"a",
"login",
"prompt",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L841-L858 |
twisted/mantissa | xmantissa/publicweb.py | PublicAthenaLivePage.render_head | def render_head(self, ctx, data):
"""
Put liveglue content into the header of this page to activate it, but
otherwise delegate to my parent's renderer for <head>.
"""
ctx.tag[tags.invisible(render=tags.directive('liveglue'))]
return _PublicPageMixin.render_head(self, ctx, data) | python | def render_head(self, ctx, data):
"""
Put liveglue content into the header of this page to activate it, but
otherwise delegate to my parent's renderer for <head>.
"""
ctx.tag[tags.invisible(render=tags.directive('liveglue'))]
return _PublicPageMixin.render_head(self, ctx, data) | [
"def",
"render_head",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"ctx",
".",
"tag",
"[",
"tags",
".",
"invisible",
"(",
"render",
"=",
"tags",
".",
"directive",
"(",
"'liveglue'",
")",
")",
"]",
"return",
"_PublicPageMixin",
".",
"render_head",
"(... | Put liveglue content into the header of this page to activate it, but
otherwise delegate to my parent's renderer for <head>. | [
"Put",
"liveglue",
"content",
"into",
"the",
"header",
"of",
"this",
"page",
"to",
"activate",
"it",
"but",
"otherwise",
"delegate",
"to",
"my",
"parent",
"s",
"renderer",
"for",
"<head",
">",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L968-L974 |
twisted/mantissa | xmantissa/publicweb.py | AnonymousSite.rootChild_resetPassword | def rootChild_resetPassword(self, req, webViewer):
"""
Return a page which will allow the user to re-set their password.
"""
from xmantissa.signup import PasswordResetResource
return PasswordResetResource(self.store) | python | def rootChild_resetPassword(self, req, webViewer):
"""
Return a page which will allow the user to re-set their password.
"""
from xmantissa.signup import PasswordResetResource
return PasswordResetResource(self.store) | [
"def",
"rootChild_resetPassword",
"(",
"self",
",",
"req",
",",
"webViewer",
")",
":",
"from",
"xmantissa",
".",
"signup",
"import",
"PasswordResetResource",
"return",
"PasswordResetResource",
"(",
"self",
".",
"store",
")"
] | Return a page which will allow the user to re-set their password. | [
"Return",
"a",
"page",
"which",
"will",
"allow",
"the",
"user",
"to",
"re",
"-",
"set",
"their",
"password",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L1009-L1014 |
twisted/mantissa | xmantissa/publicweb.py | AnonymousSite.indirect | def indirect(self, interface):
"""
Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}.
"""
if interface == IWebViewer:
return _AnonymousWebViewer(self.store)
return super(AnonymousSite, self).indirect(interface) | python | def indirect(self, interface):
"""
Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}.
"""
if interface == IWebViewer:
return _AnonymousWebViewer(self.store)
return super(AnonymousSite, self).indirect(interface) | [
"def",
"indirect",
"(",
"self",
",",
"interface",
")",
":",
"if",
"interface",
"==",
"IWebViewer",
":",
"return",
"_AnonymousWebViewer",
"(",
"self",
".",
"store",
")",
"return",
"super",
"(",
"AnonymousSite",
",",
"self",
")",
".",
"indirect",
"(",
"inter... | Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. | [
"Indirect",
"the",
"implementation",
"of",
"L",
"{",
"IWebViewer",
"}",
"to",
"L",
"{",
"_AnonymousWebViewer",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/publicweb.py#L1044-L1050 |
vladcalin/gemstone | gemstone/config/configurator.py | BaseConfigurator.get_configurable_by_name | def get_configurable_by_name(self, name):
"""
Returns the registered configurable with the specified name or ``None`` if no
such configurator exists.
"""
l = [c for c in self.configurables if c.name == name]
if l:
return l[0] | python | def get_configurable_by_name(self, name):
"""
Returns the registered configurable with the specified name or ``None`` if no
such configurator exists.
"""
l = [c for c in self.configurables if c.name == name]
if l:
return l[0] | [
"def",
"get_configurable_by_name",
"(",
"self",
",",
"name",
")",
":",
"l",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"configurables",
"if",
"c",
".",
"name",
"==",
"name",
"]",
"if",
"l",
":",
"return",
"l",
"[",
"0",
"]"
] | Returns the registered configurable with the specified name or ``None`` if no
such configurator exists. | [
"Returns",
"the",
"registered",
"configurable",
"with",
"the",
"specified",
"name",
"or",
"None",
"if",
"no",
"such",
"configurator",
"exists",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/config/configurator.py#L39-L46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.