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
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
Skype4Py/Skype4Py | Skype4Py/user.py | User.SaveAvatarToFile | def SaveAvatarToFile(self, Filename, AvatarId=1):
"""Saves user avatar to a file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id.
"""
s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename))
self._Owner._DoCommand('GET %s' % s, s) | python | def SaveAvatarToFile(self, Filename, AvatarId=1):
"""Saves user avatar to a file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id.
"""
s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename))
self._Owner._DoCommand('GET %s' % s, s) | [
"def",
"SaveAvatarToFile",
"(",
"self",
",",
"Filename",
",",
"AvatarId",
"=",
"1",
")",
":",
"s",
"=",
"'USER %s AVATAR %s %s'",
"%",
"(",
"self",
".",
"Handle",
",",
"AvatarId",
",",
"path2unicode",
"(",
"Filename",
")",
")",
"self",
".",
"_Owner",
".",
"_DoCommand",
"(",
"'GET %s'",
"%",
"s",
",",
"s",
")"
] | Saves user avatar to a file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id. | [
"Saves",
"user",
"avatar",
"to",
"a",
"file",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/user.py#L21-L31 |
Skype4Py/Skype4Py | Skype4Py/user.py | User.SetBuddyStatusPendingAuthorization | def SetBuddyStatusPendingAuthorization(self, Text=u''):
"""Sets the BuddyStaus property to `enums.budPendingAuthorization`
additionally specifying the authorization text.
:Parameters:
Text : unicode
The authorization text.
:see: `BuddyStatus`
"""
self._Property('BUDDYSTATUS', '%d %s' % (budPendingAuthorization, tounicode(Text)), Cache=False) | python | def SetBuddyStatusPendingAuthorization(self, Text=u''):
"""Sets the BuddyStaus property to `enums.budPendingAuthorization`
additionally specifying the authorization text.
:Parameters:
Text : unicode
The authorization text.
:see: `BuddyStatus`
"""
self._Property('BUDDYSTATUS', '%d %s' % (budPendingAuthorization, tounicode(Text)), Cache=False) | [
"def",
"SetBuddyStatusPendingAuthorization",
"(",
"self",
",",
"Text",
"=",
"u''",
")",
":",
"self",
".",
"_Property",
"(",
"'BUDDYSTATUS'",
",",
"'%d %s'",
"%",
"(",
"budPendingAuthorization",
",",
"tounicode",
"(",
"Text",
")",
")",
",",
"Cache",
"=",
"False",
")"
] | Sets the BuddyStaus property to `enums.budPendingAuthorization`
additionally specifying the authorization text.
:Parameters:
Text : unicode
The authorization text.
:see: `BuddyStatus` | [
"Sets",
"the",
"BuddyStaus",
"property",
"to",
"enums",
".",
"budPendingAuthorization",
"additionally",
"specifying",
"the",
"authorization",
"text",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/user.py#L33-L43 |
Skype4Py/Skype4Py | examples/SkypeTunnel.py | StreamWrite | def StreamWrite(stream, *obj):
"""Writes Python object to Skype application stream."""
stream.Write(base64.encodestring(pickle.dumps(obj))) | python | def StreamWrite(stream, *obj):
"""Writes Python object to Skype application stream."""
stream.Write(base64.encodestring(pickle.dumps(obj))) | [
"def",
"StreamWrite",
"(",
"stream",
",",
"*",
"obj",
")",
":",
"stream",
".",
"Write",
"(",
"base64",
".",
"encodestring",
"(",
"pickle",
".",
"dumps",
"(",
"obj",
")",
")",
")"
] | Writes Python object to Skype application stream. | [
"Writes",
"Python",
"object",
"to",
"Skype",
"application",
"stream",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/examples/SkypeTunnel.py#L121-L123 |
Skype4Py/Skype4Py | examples/SkypeTunnel.py | TCPTunnel.close | def close(self):
"""Closes the tunnel."""
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
except socket.error:
pass | python | def close(self):
"""Closes the tunnel."""
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
except socket.error:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"self",
".",
"sock",
".",
"close",
"(",
")",
"except",
"socket",
".",
"error",
":",
"pass"
] | Closes the tunnel. | [
"Closes",
"the",
"tunnel",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/examples/SkypeTunnel.py#L206-L213 |
Skype4Py/Skype4Py | examples/SkypeTunnel.py | SkypeEvents.ApplicationReceiving | def ApplicationReceiving(self, app, streams):
"""Called when the list of streams with data ready to be read changes."""
# we should only proceed if we are in TCP mode
if stype != socket.SOCK_STREAM:
return
# handle all streams
for stream in streams:
# read object from the stream
obj = StreamRead(stream)
if obj:
if obj[0] == cmdData:
# data were received, reroute it to the tunnel based on the tunnel ID
try:
TCPTunnel.threads[obj[1]].send(obj[2])
except KeyError:
pass
elif obj[0] == cmdConnect:
# a connection request received, connect the socket
n = obj[1]
sock = socket.socket(type=stype)
try:
sock.connect(addr)
# start the tunnel thread
TCPTunnel(sock, stream, n).start()
except socket.error, e:
# connection failed, send an error report back through the stream
print 'error (%s): %s' % (n, e)
StreamWrite(stream, cmdError, n, tuple(e))
StreamWrite(stream, cmdDisconnect, n)
elif obj[0] == cmdDisconnect:
# an disconnection request received, close the tunnel
try:
TCPTunnel.threads[obj[1]].close()
except KeyError:
pass
elif obj[0] == cmdError:
# connection failed on the other side, display the error
print 'error (%s): %s' % obj[1:2] | python | def ApplicationReceiving(self, app, streams):
"""Called when the list of streams with data ready to be read changes."""
# we should only proceed if we are in TCP mode
if stype != socket.SOCK_STREAM:
return
# handle all streams
for stream in streams:
# read object from the stream
obj = StreamRead(stream)
if obj:
if obj[0] == cmdData:
# data were received, reroute it to the tunnel based on the tunnel ID
try:
TCPTunnel.threads[obj[1]].send(obj[2])
except KeyError:
pass
elif obj[0] == cmdConnect:
# a connection request received, connect the socket
n = obj[1]
sock = socket.socket(type=stype)
try:
sock.connect(addr)
# start the tunnel thread
TCPTunnel(sock, stream, n).start()
except socket.error, e:
# connection failed, send an error report back through the stream
print 'error (%s): %s' % (n, e)
StreamWrite(stream, cmdError, n, tuple(e))
StreamWrite(stream, cmdDisconnect, n)
elif obj[0] == cmdDisconnect:
# an disconnection request received, close the tunnel
try:
TCPTunnel.threads[obj[1]].close()
except KeyError:
pass
elif obj[0] == cmdError:
# connection failed on the other side, display the error
print 'error (%s): %s' % obj[1:2] | [
"def",
"ApplicationReceiving",
"(",
"self",
",",
"app",
",",
"streams",
")",
":",
"# we should only proceed if we are in TCP mode",
"if",
"stype",
"!=",
"socket",
".",
"SOCK_STREAM",
":",
"return",
"# handle all streams",
"for",
"stream",
"in",
"streams",
":",
"# read object from the stream",
"obj",
"=",
"StreamRead",
"(",
"stream",
")",
"if",
"obj",
":",
"if",
"obj",
"[",
"0",
"]",
"==",
"cmdData",
":",
"# data were received, reroute it to the tunnel based on the tunnel ID",
"try",
":",
"TCPTunnel",
".",
"threads",
"[",
"obj",
"[",
"1",
"]",
"]",
".",
"send",
"(",
"obj",
"[",
"2",
"]",
")",
"except",
"KeyError",
":",
"pass",
"elif",
"obj",
"[",
"0",
"]",
"==",
"cmdConnect",
":",
"# a connection request received, connect the socket",
"n",
"=",
"obj",
"[",
"1",
"]",
"sock",
"=",
"socket",
".",
"socket",
"(",
"type",
"=",
"stype",
")",
"try",
":",
"sock",
".",
"connect",
"(",
"addr",
")",
"# start the tunnel thread",
"TCPTunnel",
"(",
"sock",
",",
"stream",
",",
"n",
")",
".",
"start",
"(",
")",
"except",
"socket",
".",
"error",
",",
"e",
":",
"# connection failed, send an error report back through the stream",
"print",
"'error (%s): %s'",
"%",
"(",
"n",
",",
"e",
")",
"StreamWrite",
"(",
"stream",
",",
"cmdError",
",",
"n",
",",
"tuple",
"(",
"e",
")",
")",
"StreamWrite",
"(",
"stream",
",",
"cmdDisconnect",
",",
"n",
")",
"elif",
"obj",
"[",
"0",
"]",
"==",
"cmdDisconnect",
":",
"# an disconnection request received, close the tunnel",
"try",
":",
"TCPTunnel",
".",
"threads",
"[",
"obj",
"[",
"1",
"]",
"]",
".",
"close",
"(",
")",
"except",
"KeyError",
":",
"pass",
"elif",
"obj",
"[",
"0",
"]",
"==",
"cmdError",
":",
"# connection failed on the other side, display the error",
"print",
"'error (%s): %s'",
"%",
"obj",
"[",
"1",
":",
"2",
"]"
] | Called when the list of streams with data ready to be read changes. | [
"Called",
"when",
"the",
"list",
"of",
"streams",
"with",
"data",
"ready",
"to",
"be",
"read",
"changes",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/examples/SkypeTunnel.py#L218-L257 |
Skype4Py/Skype4Py | examples/SkypeTunnel.py | SkypeEvents.ApplicationDatagram | def ApplicationDatagram(self, app, stream, text):
"""Called when a datagram is received over a stream."""
# we should only proceed if we are in UDP mode
if stype != socket.SOCK_DGRAM:
return
# decode the data
data = base64.decodestring(text)
# open an UDP socket
sock = socket.socket(type=stype)
# send the data
try:
sock.sendto(data, addr)
except socket.error, e:
print 'error: %s' % e | python | def ApplicationDatagram(self, app, stream, text):
"""Called when a datagram is received over a stream."""
# we should only proceed if we are in UDP mode
if stype != socket.SOCK_DGRAM:
return
# decode the data
data = base64.decodestring(text)
# open an UDP socket
sock = socket.socket(type=stype)
# send the data
try:
sock.sendto(data, addr)
except socket.error, e:
print 'error: %s' % e | [
"def",
"ApplicationDatagram",
"(",
"self",
",",
"app",
",",
"stream",
",",
"text",
")",
":",
"# we should only proceed if we are in UDP mode",
"if",
"stype",
"!=",
"socket",
".",
"SOCK_DGRAM",
":",
"return",
"# decode the data",
"data",
"=",
"base64",
".",
"decodestring",
"(",
"text",
")",
"# open an UDP socket",
"sock",
"=",
"socket",
".",
"socket",
"(",
"type",
"=",
"stype",
")",
"# send the data",
"try",
":",
"sock",
".",
"sendto",
"(",
"data",
",",
"addr",
")",
"except",
"socket",
".",
"error",
",",
"e",
":",
"print",
"'error: %s'",
"%",
"e"
] | Called when a datagram is received over a stream. | [
"Called",
"when",
"a",
"datagram",
"is",
"received",
"over",
"a",
"stream",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/examples/SkypeTunnel.py#L259-L276 |
Skype4Py/Skype4Py | Skype4Py/utils.py | chop | def chop(s, n=1, d=None):
"""Chops initial words from a string and returns a list of them and the rest of the string.
The returned list is guaranteed to be n+1 long. If too little words are found in the string,
a ValueError exception is raised.
:Parameters:
s : str or unicode
String to chop from.
n : int
Number of words to chop.
d : str or unicode
Optional delimiter. Any white-char by default.
:return: A list of n first words from the string followed by the rest of the string (``[w1, w2,
..., wn, rest_of_string]``).
:rtype: list of: str or unicode
"""
spl = s.split(d, n)
if len(spl) == n:
spl.append(s[:0])
if len(spl) != n + 1:
raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s))
return spl | python | def chop(s, n=1, d=None):
"""Chops initial words from a string and returns a list of them and the rest of the string.
The returned list is guaranteed to be n+1 long. If too little words are found in the string,
a ValueError exception is raised.
:Parameters:
s : str or unicode
String to chop from.
n : int
Number of words to chop.
d : str or unicode
Optional delimiter. Any white-char by default.
:return: A list of n first words from the string followed by the rest of the string (``[w1, w2,
..., wn, rest_of_string]``).
:rtype: list of: str or unicode
"""
spl = s.split(d, n)
if len(spl) == n:
spl.append(s[:0])
if len(spl) != n + 1:
raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s))
return spl | [
"def",
"chop",
"(",
"s",
",",
"n",
"=",
"1",
",",
"d",
"=",
"None",
")",
":",
"spl",
"=",
"s",
".",
"split",
"(",
"d",
",",
"n",
")",
"if",
"len",
"(",
"spl",
")",
"==",
"n",
":",
"spl",
".",
"append",
"(",
"s",
"[",
":",
"0",
"]",
")",
"if",
"len",
"(",
"spl",
")",
"!=",
"n",
"+",
"1",
":",
"raise",
"ValueError",
"(",
"'chop: Could not chop %d words from \\'%s\\''",
"%",
"(",
"n",
",",
"s",
")",
")",
"return",
"spl"
] | Chops initial words from a string and returns a list of them and the rest of the string.
The returned list is guaranteed to be n+1 long. If too little words are found in the string,
a ValueError exception is raised.
:Parameters:
s : str or unicode
String to chop from.
n : int
Number of words to chop.
d : str or unicode
Optional delimiter. Any white-char by default.
:return: A list of n first words from the string followed by the rest of the string (``[w1, w2,
..., wn, rest_of_string]``).
:rtype: list of: str or unicode | [
"Chops",
"initial",
"words",
"from",
"a",
"string",
"and",
"returns",
"a",
"list",
"of",
"them",
"and",
"the",
"rest",
"of",
"the",
"string",
".",
"The",
"returned",
"list",
"is",
"guaranteed",
"to",
"be",
"n",
"+",
"1",
"long",
".",
"If",
"too",
"little",
"words",
"are",
"found",
"in",
"the",
"string",
"a",
"ValueError",
"exception",
"is",
"raised",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L59-L82 |
Skype4Py/Skype4Py | Skype4Py/utils.py | args2dict | def args2dict(s):
"""Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings
into a dictionary.
:Parameters:
s : str or unicode
Input string.
:return: ``{'ARG': 'value'}`` dictionary.
:rtype: dict
"""
d = {}
while s:
t, s = chop(s, 1, '=')
if s.startswith('"'):
# XXX: This function is used to parse strings from Skype. The question is,
# how does Skype escape the double-quotes. The code below implements the
# VisualBasic technique ("" -> ").
i = 0
while True:
i = s.find('"', i+1)
try:
if s[i+1] != '"':
break
else:
i += 1
except IndexError:
break
if i > 0:
d[t] = s[1:i].replace('""', '"')
if s[i+1:i+3] == ', ':
i += 2
s = s[i+1:]
else:
d[t] = s
break
else:
i = s.find(', ')
if i >= 0:
d[t] = s[:i]
s = s[i+2:]
else:
d[t] = s
break
return d | python | def args2dict(s):
"""Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings
into a dictionary.
:Parameters:
s : str or unicode
Input string.
:return: ``{'ARG': 'value'}`` dictionary.
:rtype: dict
"""
d = {}
while s:
t, s = chop(s, 1, '=')
if s.startswith('"'):
# XXX: This function is used to parse strings from Skype. The question is,
# how does Skype escape the double-quotes. The code below implements the
# VisualBasic technique ("" -> ").
i = 0
while True:
i = s.find('"', i+1)
try:
if s[i+1] != '"':
break
else:
i += 1
except IndexError:
break
if i > 0:
d[t] = s[1:i].replace('""', '"')
if s[i+1:i+3] == ', ':
i += 2
s = s[i+1:]
else:
d[t] = s
break
else:
i = s.find(', ')
if i >= 0:
d[t] = s[:i]
s = s[i+2:]
else:
d[t] = s
break
return d | [
"def",
"args2dict",
"(",
"s",
")",
":",
"d",
"=",
"{",
"}",
"while",
"s",
":",
"t",
",",
"s",
"=",
"chop",
"(",
"s",
",",
"1",
",",
"'='",
")",
"if",
"s",
".",
"startswith",
"(",
"'\"'",
")",
":",
"# XXX: This function is used to parse strings from Skype. The question is,",
"# how does Skype escape the double-quotes. The code below implements the",
"# VisualBasic technique (\"\" -> \").",
"i",
"=",
"0",
"while",
"True",
":",
"i",
"=",
"s",
".",
"find",
"(",
"'\"'",
",",
"i",
"+",
"1",
")",
"try",
":",
"if",
"s",
"[",
"i",
"+",
"1",
"]",
"!=",
"'\"'",
":",
"break",
"else",
":",
"i",
"+=",
"1",
"except",
"IndexError",
":",
"break",
"if",
"i",
">",
"0",
":",
"d",
"[",
"t",
"]",
"=",
"s",
"[",
"1",
":",
"i",
"]",
".",
"replace",
"(",
"'\"\"'",
",",
"'\"'",
")",
"if",
"s",
"[",
"i",
"+",
"1",
":",
"i",
"+",
"3",
"]",
"==",
"', '",
":",
"i",
"+=",
"2",
"s",
"=",
"s",
"[",
"i",
"+",
"1",
":",
"]",
"else",
":",
"d",
"[",
"t",
"]",
"=",
"s",
"break",
"else",
":",
"i",
"=",
"s",
".",
"find",
"(",
"', '",
")",
"if",
"i",
">=",
"0",
":",
"d",
"[",
"t",
"]",
"=",
"s",
"[",
":",
"i",
"]",
"s",
"=",
"s",
"[",
"i",
"+",
"2",
":",
"]",
"else",
":",
"d",
"[",
"t",
"]",
"=",
"s",
"break",
"return",
"d"
] | Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings
into a dictionary.
:Parameters:
s : str or unicode
Input string.
:return: ``{'ARG': 'value'}`` dictionary.
:rtype: dict | [
"Converts",
"a",
"string",
"or",
"comma",
"-",
"separated",
"ARG",
"=",
"a",
"value",
"or",
"ARG",
"=",
"value2",
"strings",
"into",
"a",
"dictionary",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L85-L130 |
Skype4Py/Skype4Py | Skype4Py/utils.py | EventHandlingBase._CallEventHandler | def _CallEventHandler(self, Event, *Args, **KwArgs):
"""Calls all event handlers defined for given Event, additional parameters
will be passed unchanged to event handlers, all event handlers are fired on
separate threads.
:Parameters:
Event : str
Name of the event.
Args
Positional arguments for the event handlers.
KwArgs
Keyword arguments for the event handlers.
"""
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
args = map(repr, Args) + ['%s=%s' % (key, repr(value)) for key, value in KwArgs.items()]
self.__Logger.debug('calling %s: %s', Event, ', '.join(args))
# Get a list of handlers for this event.
try:
handlers = [self._DefaultEventHandlers[Event]]
except KeyError:
handlers = []
try:
handlers.append(getattr(self._EventHandlerObject, Event))
except AttributeError:
pass
handlers.extend(self._EventHandlers[Event])
# Proceed only if there are handlers.
if handlers:
# Get the last thread for this event.
after = self._EventThreads.get(Event, None)
# Create a new thread, pass the last one to it so it can wait until it is finished.
thread = EventSchedulerThread(Event, after, handlers, Args, KwArgs)
# Store a weak reference to the new thread for this event.
self._EventThreads[Event] = thread
# Start the thread.
thread.start() | python | def _CallEventHandler(self, Event, *Args, **KwArgs):
"""Calls all event handlers defined for given Event, additional parameters
will be passed unchanged to event handlers, all event handlers are fired on
separate threads.
:Parameters:
Event : str
Name of the event.
Args
Positional arguments for the event handlers.
KwArgs
Keyword arguments for the event handlers.
"""
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
args = map(repr, Args) + ['%s=%s' % (key, repr(value)) for key, value in KwArgs.items()]
self.__Logger.debug('calling %s: %s', Event, ', '.join(args))
# Get a list of handlers for this event.
try:
handlers = [self._DefaultEventHandlers[Event]]
except KeyError:
handlers = []
try:
handlers.append(getattr(self._EventHandlerObject, Event))
except AttributeError:
pass
handlers.extend(self._EventHandlers[Event])
# Proceed only if there are handlers.
if handlers:
# Get the last thread for this event.
after = self._EventThreads.get(Event, None)
# Create a new thread, pass the last one to it so it can wait until it is finished.
thread = EventSchedulerThread(Event, after, handlers, Args, KwArgs)
# Store a weak reference to the new thread for this event.
self._EventThreads[Event] = thread
# Start the thread.
thread.start() | [
"def",
"_CallEventHandler",
"(",
"self",
",",
"Event",
",",
"*",
"Args",
",",
"*",
"*",
"KwArgs",
")",
":",
"if",
"Event",
"not",
"in",
"self",
".",
"_EventHandlers",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid %s event name'",
"%",
"(",
"Event",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"args",
"=",
"map",
"(",
"repr",
",",
"Args",
")",
"+",
"[",
"'%s=%s'",
"%",
"(",
"key",
",",
"repr",
"(",
"value",
")",
")",
"for",
"key",
",",
"value",
"in",
"KwArgs",
".",
"items",
"(",
")",
"]",
"self",
".",
"__Logger",
".",
"debug",
"(",
"'calling %s: %s'",
",",
"Event",
",",
"', '",
".",
"join",
"(",
"args",
")",
")",
"# Get a list of handlers for this event.",
"try",
":",
"handlers",
"=",
"[",
"self",
".",
"_DefaultEventHandlers",
"[",
"Event",
"]",
"]",
"except",
"KeyError",
":",
"handlers",
"=",
"[",
"]",
"try",
":",
"handlers",
".",
"append",
"(",
"getattr",
"(",
"self",
".",
"_EventHandlerObject",
",",
"Event",
")",
")",
"except",
"AttributeError",
":",
"pass",
"handlers",
".",
"extend",
"(",
"self",
".",
"_EventHandlers",
"[",
"Event",
"]",
")",
"# Proceed only if there are handlers.",
"if",
"handlers",
":",
"# Get the last thread for this event.",
"after",
"=",
"self",
".",
"_EventThreads",
".",
"get",
"(",
"Event",
",",
"None",
")",
"# Create a new thread, pass the last one to it so it can wait until it is finished.",
"thread",
"=",
"EventSchedulerThread",
"(",
"Event",
",",
"after",
",",
"handlers",
",",
"Args",
",",
"KwArgs",
")",
"# Store a weak reference to the new thread for this event.",
"self",
".",
"_EventThreads",
"[",
"Event",
"]",
"=",
"thread",
"# Start the thread.",
"thread",
".",
"start",
"(",
")"
] | Calls all event handlers defined for given Event, additional parameters
will be passed unchanged to event handlers, all event handlers are fired on
separate threads.
:Parameters:
Event : str
Name of the event.
Args
Positional arguments for the event handlers.
KwArgs
Keyword arguments for the event handlers. | [
"Calls",
"all",
"event",
"handlers",
"defined",
"for",
"given",
"Event",
"additional",
"parameters",
"will",
"be",
"passed",
"unchanged",
"to",
"event",
"handlers",
"all",
"event",
"handlers",
"are",
"fired",
"on",
"separate",
"threads",
".",
":",
"Parameters",
":",
"Event",
":",
"str",
"Name",
"of",
"the",
"event",
".",
"Args",
"Positional",
"arguments",
"for",
"the",
"event",
"handlers",
".",
"KwArgs",
"Keyword",
"arguments",
"for",
"the",
"event",
"handlers",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L375-L411 |
Skype4Py/Skype4Py | Skype4Py/utils.py | EventHandlingBase.RegisterEventHandler | def RegisterEventHandler(self, Event, Target):
"""Registers any callable as an event handler.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to register as the event handler.
:return: True is callable was successfully registered, False if it was already registered.
:rtype: bool
:see: `UnregisterEventHandler`
"""
if not callable(Target):
raise TypeError('%s is not callable' % repr(Target))
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
if Target in self._EventHandlers[Event]:
return False
self._EventHandlers[Event].append(Target)
self.__Logger.info('registered %s: %s', Event, repr(Target))
return True | python | def RegisterEventHandler(self, Event, Target):
"""Registers any callable as an event handler.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to register as the event handler.
:return: True is callable was successfully registered, False if it was already registered.
:rtype: bool
:see: `UnregisterEventHandler`
"""
if not callable(Target):
raise TypeError('%s is not callable' % repr(Target))
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
if Target in self._EventHandlers[Event]:
return False
self._EventHandlers[Event].append(Target)
self.__Logger.info('registered %s: %s', Event, repr(Target))
return True | [
"def",
"RegisterEventHandler",
"(",
"self",
",",
"Event",
",",
"Target",
")",
":",
"if",
"not",
"callable",
"(",
"Target",
")",
":",
"raise",
"TypeError",
"(",
"'%s is not callable'",
"%",
"repr",
"(",
"Target",
")",
")",
"if",
"Event",
"not",
"in",
"self",
".",
"_EventHandlers",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid %s event name'",
"%",
"(",
"Event",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"Target",
"in",
"self",
".",
"_EventHandlers",
"[",
"Event",
"]",
":",
"return",
"False",
"self",
".",
"_EventHandlers",
"[",
"Event",
"]",
".",
"append",
"(",
"Target",
")",
"self",
".",
"__Logger",
".",
"info",
"(",
"'registered %s: %s'",
",",
"Event",
",",
"repr",
"(",
"Target",
")",
")",
"return",
"True"
] | Registers any callable as an event handler.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to register as the event handler.
:return: True is callable was successfully registered, False if it was already registered.
:rtype: bool
:see: `UnregisterEventHandler` | [
"Registers",
"any",
"callable",
"as",
"an",
"event",
"handler",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L413-L435 |
Skype4Py/Skype4Py | Skype4Py/utils.py | EventHandlingBase.UnregisterEventHandler | def UnregisterEventHandler(self, Event, Target):
"""Unregisters an event handler previously registered with `RegisterEventHandler`.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to unregister.
:return: True if callable was successfully unregistered, False if it wasn't registered
first.
:rtype: bool
:see: `RegisterEventHandler`
"""
if not callable(Target):
raise TypeError('%s is not callable' % repr(Target))
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
if Target in self._EventHandlers[Event]:
self._EventHandlers[Event].remove(Target)
self.__Logger.info('unregistered %s: %s', Event, repr(Target))
return True
return False | python | def UnregisterEventHandler(self, Event, Target):
"""Unregisters an event handler previously registered with `RegisterEventHandler`.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to unregister.
:return: True if callable was successfully unregistered, False if it wasn't registered
first.
:rtype: bool
:see: `RegisterEventHandler`
"""
if not callable(Target):
raise TypeError('%s is not callable' % repr(Target))
if Event not in self._EventHandlers:
raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
if Target in self._EventHandlers[Event]:
self._EventHandlers[Event].remove(Target)
self.__Logger.info('unregistered %s: %s', Event, repr(Target))
return True
return False | [
"def",
"UnregisterEventHandler",
"(",
"self",
",",
"Event",
",",
"Target",
")",
":",
"if",
"not",
"callable",
"(",
"Target",
")",
":",
"raise",
"TypeError",
"(",
"'%s is not callable'",
"%",
"repr",
"(",
"Target",
")",
")",
"if",
"Event",
"not",
"in",
"self",
".",
"_EventHandlers",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid %s event name'",
"%",
"(",
"Event",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"Target",
"in",
"self",
".",
"_EventHandlers",
"[",
"Event",
"]",
":",
"self",
".",
"_EventHandlers",
"[",
"Event",
"]",
".",
"remove",
"(",
"Target",
")",
"self",
".",
"__Logger",
".",
"info",
"(",
"'unregistered %s: %s'",
",",
"Event",
",",
"repr",
"(",
"Target",
")",
")",
"return",
"True",
"return",
"False"
] | Unregisters an event handler previously registered with `RegisterEventHandler`.
:Parameters:
Event : str
Name of the event. For event names, see the respective ``...Events`` class.
Target : callable
Callable to unregister.
:return: True if callable was successfully unregistered, False if it wasn't registered
first.
:rtype: bool
:see: `RegisterEventHandler` | [
"Unregisters",
"an",
"event",
"handler",
"previously",
"registered",
"with",
"RegisterEventHandler",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L437-L460 |
Skype4Py/Skype4Py | Skype4Py/utils.py | EventHandlingBase._SetEventHandlerObject | def _SetEventHandlerObject(self, Object):
"""Registers an object as events handler, object should contain methods with names
corresponding to event names, only one object may be registered at a time.
:Parameters:
Object
Object to register. May be None in which case the currently registered object
will be unregistered.
"""
self._EventHandlerObject = Object
self.__Logger.info('set object: %s', repr(Object)) | python | def _SetEventHandlerObject(self, Object):
"""Registers an object as events handler, object should contain methods with names
corresponding to event names, only one object may be registered at a time.
:Parameters:
Object
Object to register. May be None in which case the currently registered object
will be unregistered.
"""
self._EventHandlerObject = Object
self.__Logger.info('set object: %s', repr(Object)) | [
"def",
"_SetEventHandlerObject",
"(",
"self",
",",
"Object",
")",
":",
"self",
".",
"_EventHandlerObject",
"=",
"Object",
"self",
".",
"__Logger",
".",
"info",
"(",
"'set object: %s'",
",",
"repr",
"(",
"Object",
")",
")"
] | Registers an object as events handler, object should contain methods with names
corresponding to event names, only one object may be registered at a time.
:Parameters:
Object
Object to register. May be None in which case the currently registered object
will be unregistered. | [
"Registers",
"an",
"object",
"as",
"events",
"handler",
"object",
"should",
"contain",
"methods",
"with",
"names",
"corresponding",
"to",
"event",
"names",
"only",
"one",
"object",
"may",
"be",
"registered",
"at",
"a",
"time",
".",
":",
"Parameters",
":",
"Object",
"Object",
"to",
"register",
".",
"May",
"be",
"None",
"in",
"which",
"case",
"the",
"currently",
"registered",
"object",
"will",
"be",
"unregistered",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L480-L490 |
Skype4Py/Skype4Py | Skype4Py/utils.py | EventHandlingBase._AddEvents | def _AddEvents(cls, Class):
"""Adds events based on the attributes of the given ``...Events`` class.
:Parameters:
Class : class
An `...Events` class whose methods define events that may occur in the
instances of the current class.
"""
def make_event(event):
return property(lambda self: self._GetDefaultEventHandler(event),
lambda self, Value: self._SetDefaultEventHandler(event, Value))
for event in dir(Class):
if not event.startswith('_'):
setattr(cls, 'On%s' % event, make_event(event))
cls._EventNames.append(event) | python | def _AddEvents(cls, Class):
"""Adds events based on the attributes of the given ``...Events`` class.
:Parameters:
Class : class
An `...Events` class whose methods define events that may occur in the
instances of the current class.
"""
def make_event(event):
return property(lambda self: self._GetDefaultEventHandler(event),
lambda self, Value: self._SetDefaultEventHandler(event, Value))
for event in dir(Class):
if not event.startswith('_'):
setattr(cls, 'On%s' % event, make_event(event))
cls._EventNames.append(event) | [
"def",
"_AddEvents",
"(",
"cls",
",",
"Class",
")",
":",
"def",
"make_event",
"(",
"event",
")",
":",
"return",
"property",
"(",
"lambda",
"self",
":",
"self",
".",
"_GetDefaultEventHandler",
"(",
"event",
")",
",",
"lambda",
"self",
",",
"Value",
":",
"self",
".",
"_SetDefaultEventHandler",
"(",
"event",
",",
"Value",
")",
")",
"for",
"event",
"in",
"dir",
"(",
"Class",
")",
":",
"if",
"not",
"event",
".",
"startswith",
"(",
"'_'",
")",
":",
"setattr",
"(",
"cls",
",",
"'On%s'",
"%",
"event",
",",
"make_event",
"(",
"event",
")",
")",
"cls",
".",
"_EventNames",
".",
"append",
"(",
"event",
")"
] | Adds events based on the attributes of the given ``...Events`` class.
:Parameters:
Class : class
An `...Events` class whose methods define events that may occur in the
instances of the current class. | [
"Adds",
"events",
"based",
"on",
"the",
"attributes",
"of",
"the",
"given",
"...",
"Events",
"class",
".",
":",
"Parameters",
":",
"Class",
":",
"class",
"An",
"...",
"Events",
"class",
"whose",
"methods",
"define",
"events",
"that",
"may",
"occur",
"in",
"the",
"instances",
"of",
"the",
"current",
"class",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L493-L507 |
Skype4Py/Skype4Py | Skype4Py/chat.py | Chat._Alter | def _Alter(self, AlterName, Args=None):
'''
--- Prajna bug fix ---
Original code:
return self._Owner._Alter('CHAT', self.Name, AlterName, Args,
'ALTER CHAT %s %s' % (self.Name, AlterName))
Whereas most of the ALTER commands echo the command in the reply,
the ALTER CHAT commands strip the <chat_id> from the reply,
so we need to do the same for the expected reply
'''
return self._Owner._Alter('CHAT', self.Name, AlterName, Args,
'ALTER CHAT %s' % (AlterName)) | python | def _Alter(self, AlterName, Args=None):
'''
--- Prajna bug fix ---
Original code:
return self._Owner._Alter('CHAT', self.Name, AlterName, Args,
'ALTER CHAT %s %s' % (self.Name, AlterName))
Whereas most of the ALTER commands echo the command in the reply,
the ALTER CHAT commands strip the <chat_id> from the reply,
so we need to do the same for the expected reply
'''
return self._Owner._Alter('CHAT', self.Name, AlterName, Args,
'ALTER CHAT %s' % (AlterName)) | [
"def",
"_Alter",
"(",
"self",
",",
"AlterName",
",",
"Args",
"=",
"None",
")",
":",
"return",
"self",
".",
"_Owner",
".",
"_Alter",
"(",
"'CHAT'",
",",
"self",
".",
"Name",
",",
"AlterName",
",",
"Args",
",",
"'ALTER CHAT %s'",
"%",
"(",
"AlterName",
")",
")"
] | --- Prajna bug fix ---
Original code:
return self._Owner._Alter('CHAT', self.Name, AlterName, Args,
'ALTER CHAT %s %s' % (self.Name, AlterName))
Whereas most of the ALTER commands echo the command in the reply,
the ALTER CHAT commands strip the <chat_id> from the reply,
so we need to do the same for the expected reply | [
"---",
"Prajna",
"bug",
"fix",
"---",
"Original",
"code",
":",
"return",
"self",
".",
"_Owner",
".",
"_Alter",
"(",
"CHAT",
"self",
".",
"Name",
"AlterName",
"Args",
"ALTER",
"CHAT",
"%s",
"%s",
"%",
"(",
"self",
".",
"Name",
"AlterName",
"))",
"Whereas",
"most",
"of",
"the",
"ALTER",
"commands",
"echo",
"the",
"command",
"in",
"the",
"reply",
"the",
"ALTER",
"CHAT",
"commands",
"strip",
"the",
"<chat_id",
">",
"from",
"the",
"reply",
"so",
"we",
"need",
"to",
"do",
"the",
"same",
"for",
"the",
"expected",
"reply"
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/chat.py#L19-L30 |
Skype4Py/Skype4Py | Skype4Py/chat.py | Chat.AddMembers | def AddMembers(self, *Members):
"""Adds new members to the chat.
:Parameters:
Members : `User`
One or more users to add.
"""
self._Alter('ADDMEMBERS', ', '.join([x.Handle for x in Members])) | python | def AddMembers(self, *Members):
"""Adds new members to the chat.
:Parameters:
Members : `User`
One or more users to add.
"""
self._Alter('ADDMEMBERS', ', '.join([x.Handle for x in Members])) | [
"def",
"AddMembers",
"(",
"self",
",",
"*",
"Members",
")",
":",
"self",
".",
"_Alter",
"(",
"'ADDMEMBERS'",
",",
"', '",
".",
"join",
"(",
"[",
"x",
".",
"Handle",
"for",
"x",
"in",
"Members",
"]",
")",
")"
] | Adds new members to the chat.
:Parameters:
Members : `User`
One or more users to add. | [
"Adds",
"new",
"members",
"to",
"the",
"chat",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/chat.py#L40-L47 |
Skype4Py/Skype4Py | Skype4Py/chat.py | Chat.SendMessage | def SendMessage(self, MessageText):
"""Sends a chat message.
:Parameters:
MessageText : unicode
Message text
:return: Message object
:rtype: `ChatMessage`
"""
return ChatMessage(self._Owner, chop(self._Owner._DoCommand('CHATMESSAGE %s %s' % (self.Name,
tounicode(MessageText))), 2)[1]) | python | def SendMessage(self, MessageText):
"""Sends a chat message.
:Parameters:
MessageText : unicode
Message text
:return: Message object
:rtype: `ChatMessage`
"""
return ChatMessage(self._Owner, chop(self._Owner._DoCommand('CHATMESSAGE %s %s' % (self.Name,
tounicode(MessageText))), 2)[1]) | [
"def",
"SendMessage",
"(",
"self",
",",
"MessageText",
")",
":",
"return",
"ChatMessage",
"(",
"self",
".",
"_Owner",
",",
"chop",
"(",
"self",
".",
"_Owner",
".",
"_DoCommand",
"(",
"'CHATMESSAGE %s %s'",
"%",
"(",
"self",
".",
"Name",
",",
"tounicode",
"(",
"MessageText",
")",
")",
")",
",",
"2",
")",
"[",
"1",
"]",
")"
] | Sends a chat message.
:Parameters:
MessageText : unicode
Message text
:return: Message object
:rtype: `ChatMessage` | [
"Sends",
"a",
"chat",
"message",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/chat.py#L106-L117 |
Skype4Py/Skype4Py | Skype4Py/chat.py | Chat.SetPassword | def SetPassword(self, Password, Hint=''):
"""Sets the chat password.
:Parameters:
Password : unicode
Password
Hint : unicode
Password hint
"""
if ' ' in Password:
raise ValueError('Password mut be one word')
self._Alter('SETPASSWORD', '%s %s' % (tounicode(Password), tounicode(Hint))) | python | def SetPassword(self, Password, Hint=''):
"""Sets the chat password.
:Parameters:
Password : unicode
Password
Hint : unicode
Password hint
"""
if ' ' in Password:
raise ValueError('Password mut be one word')
self._Alter('SETPASSWORD', '%s %s' % (tounicode(Password), tounicode(Hint))) | [
"def",
"SetPassword",
"(",
"self",
",",
"Password",
",",
"Hint",
"=",
"''",
")",
":",
"if",
"' '",
"in",
"Password",
":",
"raise",
"ValueError",
"(",
"'Password mut be one word'",
")",
"self",
".",
"_Alter",
"(",
"'SETPASSWORD'",
",",
"'%s %s'",
"%",
"(",
"tounicode",
"(",
"Password",
")",
",",
"tounicode",
"(",
"Hint",
")",
")",
")"
] | Sets the chat password.
:Parameters:
Password : unicode
Password
Hint : unicode
Password hint | [
"Sets",
"the",
"chat",
"password",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/chat.py#L119-L130 |
Skype4Py/Skype4Py | Skype4Py/chat.py | ChatMember.CanSetRoleTo | def CanSetRoleTo(self, Role):
"""Checks if the new role can be applied to the member.
:Parameters:
Role : `enums`.chatMemberRole*
New chat member role.
:return: True if the new role can be applied, False otherwise.
:rtype: bool
"""
t = self._Owner._Alter('CHATMEMBER', self.Id, 'CANSETROLETO', Role,
'ALTER CHATMEMBER CANSETROLETO')
return (chop(t, 1)[-1] == 'TRUE') | python | def CanSetRoleTo(self, Role):
"""Checks if the new role can be applied to the member.
:Parameters:
Role : `enums`.chatMemberRole*
New chat member role.
:return: True if the new role can be applied, False otherwise.
:rtype: bool
"""
t = self._Owner._Alter('CHATMEMBER', self.Id, 'CANSETROLETO', Role,
'ALTER CHATMEMBER CANSETROLETO')
return (chop(t, 1)[-1] == 'TRUE') | [
"def",
"CanSetRoleTo",
"(",
"self",
",",
"Role",
")",
":",
"t",
"=",
"self",
".",
"_Owner",
".",
"_Alter",
"(",
"'CHATMEMBER'",
",",
"self",
".",
"Id",
",",
"'CANSETROLETO'",
",",
"Role",
",",
"'ALTER CHATMEMBER CANSETROLETO'",
")",
"return",
"(",
"chop",
"(",
"t",
",",
"1",
")",
"[",
"-",
"1",
"]",
"==",
"'TRUE'",
")"
] | Checks if the new role can be applied to the member.
:Parameters:
Role : `enums`.chatMemberRole*
New chat member role.
:return: True if the new role can be applied, False otherwise.
:rtype: bool | [
"Checks",
"if",
"the",
"new",
"role",
"can",
"be",
"applied",
"to",
"the",
"member",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/chat.py#L630-L642 |
Skype4Py/Skype4Py | Skype4Py/callchannel.py | CallChannelManager.Connect | def Connect(self, Skype):
"""Connects this call channel manager instance to Skype. This is the first thing you should
do after creating this object.
:Parameters:
Skype : `Skype`
The Skype object.
:see: `Disconnect`
"""
self._Skype = Skype
self._Skype.RegisterEventHandler('CallStatus', self._CallStatus)
del self._Channels[:] | python | def Connect(self, Skype):
"""Connects this call channel manager instance to Skype. This is the first thing you should
do after creating this object.
:Parameters:
Skype : `Skype`
The Skype object.
:see: `Disconnect`
"""
self._Skype = Skype
self._Skype.RegisterEventHandler('CallStatus', self._CallStatus)
del self._Channels[:] | [
"def",
"Connect",
"(",
"self",
",",
"Skype",
")",
":",
"self",
".",
"_Skype",
"=",
"Skype",
"self",
".",
"_Skype",
".",
"RegisterEventHandler",
"(",
"'CallStatus'",
",",
"self",
".",
"_CallStatus",
")",
"del",
"self",
".",
"_Channels",
"[",
":",
"]"
] | Connects this call channel manager instance to Skype. This is the first thing you should
do after creating this object.
:Parameters:
Skype : `Skype`
The Skype object.
:see: `Disconnect` | [
"Connects",
"this",
"call",
"channel",
"manager",
"instance",
"to",
"Skype",
".",
"This",
"is",
"the",
"first",
"thing",
"you",
"should",
"do",
"after",
"creating",
"this",
"object",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/callchannel.py#L116-L128 |
Skype4Py/Skype4Py | Skype4Py/callchannel.py | CallChannelManager.CreateApplication | def CreateApplication(self, ApplicationName=None):
"""Creates an APP2APP application context. The application is automatically created using
`application.Application.Create` method.
:Parameters:
ApplicationName : unicode
Application name. Initial name, when the manager is created, is ``u'CallChannelManager'``.
"""
if ApplicationName is not None:
self.Name = tounicode(ApplicationName)
self._App = self._Skype.Application(self.Name)
self._Skype.RegisterEventHandler('ApplicationStreams', self._ApplicationStreams)
self._Skype.RegisterEventHandler('ApplicationReceiving', self._ApplicationReceiving)
self._Skype.RegisterEventHandler('ApplicationDatagram', self._ApplicationDatagram)
self._App.Create()
self._CallEventHandler('Created', self) | python | def CreateApplication(self, ApplicationName=None):
"""Creates an APP2APP application context. The application is automatically created using
`application.Application.Create` method.
:Parameters:
ApplicationName : unicode
Application name. Initial name, when the manager is created, is ``u'CallChannelManager'``.
"""
if ApplicationName is not None:
self.Name = tounicode(ApplicationName)
self._App = self._Skype.Application(self.Name)
self._Skype.RegisterEventHandler('ApplicationStreams', self._ApplicationStreams)
self._Skype.RegisterEventHandler('ApplicationReceiving', self._ApplicationReceiving)
self._Skype.RegisterEventHandler('ApplicationDatagram', self._ApplicationDatagram)
self._App.Create()
self._CallEventHandler('Created', self) | [
"def",
"CreateApplication",
"(",
"self",
",",
"ApplicationName",
"=",
"None",
")",
":",
"if",
"ApplicationName",
"is",
"not",
"None",
":",
"self",
".",
"Name",
"=",
"tounicode",
"(",
"ApplicationName",
")",
"self",
".",
"_App",
"=",
"self",
".",
"_Skype",
".",
"Application",
"(",
"self",
".",
"Name",
")",
"self",
".",
"_Skype",
".",
"RegisterEventHandler",
"(",
"'ApplicationStreams'",
",",
"self",
".",
"_ApplicationStreams",
")",
"self",
".",
"_Skype",
".",
"RegisterEventHandler",
"(",
"'ApplicationReceiving'",
",",
"self",
".",
"_ApplicationReceiving",
")",
"self",
".",
"_Skype",
".",
"RegisterEventHandler",
"(",
"'ApplicationDatagram'",
",",
"self",
".",
"_ApplicationDatagram",
")",
"self",
".",
"_App",
".",
"Create",
"(",
")",
"self",
".",
"_CallEventHandler",
"(",
"'Created'",
",",
"self",
")"
] | Creates an APP2APP application context. The application is automatically created using
`application.Application.Create` method.
:Parameters:
ApplicationName : unicode
Application name. Initial name, when the manager is created, is ``u'CallChannelManager'``. | [
"Creates",
"an",
"APP2APP",
"application",
"context",
".",
"The",
"application",
"is",
"automatically",
"created",
"using",
"application",
".",
"Application",
".",
"Create",
"method",
".",
":",
"Parameters",
":",
"ApplicationName",
":",
"unicode",
"Application",
"name",
".",
"Initial",
"name",
"when",
"the",
"manager",
"is",
"created",
"is",
"u",
"CallChannelManager",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/callchannel.py#L130-L145 |
Skype4Py/Skype4Py | Skype4Py/callchannel.py | CallChannel.SendTextMessage | def SendTextMessage(self, Text):
"""Sends a text message over channel.
:Parameters:
Text : unicode
Text to send.
"""
if self.Type == cctReliable:
self.Stream.Write(Text)
elif self.Type == cctDatagram:
self.Stream.SendDatagram(Text)
else:
raise SkypeError(0, 'Cannot send using %s channel type' & repr(self.Type)) | python | def SendTextMessage(self, Text):
"""Sends a text message over channel.
:Parameters:
Text : unicode
Text to send.
"""
if self.Type == cctReliable:
self.Stream.Write(Text)
elif self.Type == cctDatagram:
self.Stream.SendDatagram(Text)
else:
raise SkypeError(0, 'Cannot send using %s channel type' & repr(self.Type)) | [
"def",
"SendTextMessage",
"(",
"self",
",",
"Text",
")",
":",
"if",
"self",
".",
"Type",
"==",
"cctReliable",
":",
"self",
".",
"Stream",
".",
"Write",
"(",
"Text",
")",
"elif",
"self",
".",
"Type",
"==",
"cctDatagram",
":",
"self",
".",
"Stream",
".",
"SendDatagram",
"(",
"Text",
")",
"else",
":",
"raise",
"SkypeError",
"(",
"0",
",",
"'Cannot send using %s channel type'",
"&",
"repr",
"(",
"self",
".",
"Type",
")",
")"
] | Sends a text message over channel.
:Parameters:
Text : unicode
Text to send. | [
"Sends",
"a",
"text",
"message",
"over",
"channel",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/callchannel.py#L245-L257 |
Skype4Py/Skype4Py | Skype4Py/conversion.py | Conversion.TextToAttachmentStatus | def TextToAttachmentStatus(self, Text):
"""Returns attachment status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'SUCCESS', 'PENDING_AUTHORIZATION', 'REFUSED', 'NOT_AVAILABLE',
'AVAILABLE'.
:return: Attachment status.
:rtype: `enums`.apiAttach*
"""
conv = {'UNKNOWN': enums.apiAttachUnknown,
'SUCCESS': enums.apiAttachSuccess,
'PENDING_AUTHORIZATION': enums.apiAttachPendingAuthorization,
'REFUSED': enums.apiAttachRefused,
'NOT_AVAILABLE': enums.apiAttachNotAvailable,
'AVAILABLE': enums.apiAttachAvailable}
try:
return self._TextTo('api', conv[Text.upper()])
except KeyError:
raise ValueError('Bad text') | python | def TextToAttachmentStatus(self, Text):
"""Returns attachment status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'SUCCESS', 'PENDING_AUTHORIZATION', 'REFUSED', 'NOT_AVAILABLE',
'AVAILABLE'.
:return: Attachment status.
:rtype: `enums`.apiAttach*
"""
conv = {'UNKNOWN': enums.apiAttachUnknown,
'SUCCESS': enums.apiAttachSuccess,
'PENDING_AUTHORIZATION': enums.apiAttachPendingAuthorization,
'REFUSED': enums.apiAttachRefused,
'NOT_AVAILABLE': enums.apiAttachNotAvailable,
'AVAILABLE': enums.apiAttachAvailable}
try:
return self._TextTo('api', conv[Text.upper()])
except KeyError:
raise ValueError('Bad text') | [
"def",
"TextToAttachmentStatus",
"(",
"self",
",",
"Text",
")",
":",
"conv",
"=",
"{",
"'UNKNOWN'",
":",
"enums",
".",
"apiAttachUnknown",
",",
"'SUCCESS'",
":",
"enums",
".",
"apiAttachSuccess",
",",
"'PENDING_AUTHORIZATION'",
":",
"enums",
".",
"apiAttachPendingAuthorization",
",",
"'REFUSED'",
":",
"enums",
".",
"apiAttachRefused",
",",
"'NOT_AVAILABLE'",
":",
"enums",
".",
"apiAttachNotAvailable",
",",
"'AVAILABLE'",
":",
"enums",
".",
"apiAttachAvailable",
"}",
"try",
":",
"return",
"self",
".",
"_TextTo",
"(",
"'api'",
",",
"conv",
"[",
"Text",
".",
"upper",
"(",
")",
"]",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Bad text'",
")"
] | Returns attachment status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'SUCCESS', 'PENDING_AUTHORIZATION', 'REFUSED', 'NOT_AVAILABLE',
'AVAILABLE'.
:return: Attachment status.
:rtype: `enums`.apiAttach* | [
"Returns",
"attachment",
"status",
"code",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/conversion.py#L256-L276 |
Skype4Py/Skype4Py | Skype4Py/conversion.py | Conversion.TextToBuddyStatus | def TextToBuddyStatus(self, Text):
"""Returns buddy status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'NEVER_BEEN_FRIEND', 'DELETED_FRIEND', 'PENDING_AUTHORIZATION',
'FRIEND'.
:return: Buddy status.
:rtype: `enums`.bud*
"""
conv = {'UNKNOWN': enums.budUnknown,
'NEVER_BEEN_FRIEND': enums.budNeverBeenFriend,
'DELETED_FRIEND': enums.budDeletedFriend,
'PENDING_AUTHORIZATION': enums.budPendingAuthorization,
'FRIEND': enums.budFriend}
try:
return self._TextTo('bud', conv[Text.upper()])
except KeyError:
raise ValueError('Bad text') | python | def TextToBuddyStatus(self, Text):
"""Returns buddy status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'NEVER_BEEN_FRIEND', 'DELETED_FRIEND', 'PENDING_AUTHORIZATION',
'FRIEND'.
:return: Buddy status.
:rtype: `enums`.bud*
"""
conv = {'UNKNOWN': enums.budUnknown,
'NEVER_BEEN_FRIEND': enums.budNeverBeenFriend,
'DELETED_FRIEND': enums.budDeletedFriend,
'PENDING_AUTHORIZATION': enums.budPendingAuthorization,
'FRIEND': enums.budFriend}
try:
return self._TextTo('bud', conv[Text.upper()])
except KeyError:
raise ValueError('Bad text') | [
"def",
"TextToBuddyStatus",
"(",
"self",
",",
"Text",
")",
":",
"conv",
"=",
"{",
"'UNKNOWN'",
":",
"enums",
".",
"budUnknown",
",",
"'NEVER_BEEN_FRIEND'",
":",
"enums",
".",
"budNeverBeenFriend",
",",
"'DELETED_FRIEND'",
":",
"enums",
".",
"budDeletedFriend",
",",
"'PENDING_AUTHORIZATION'",
":",
"enums",
".",
"budPendingAuthorization",
",",
"'FRIEND'",
":",
"enums",
".",
"budFriend",
"}",
"try",
":",
"return",
"self",
".",
"_TextTo",
"(",
"'bud'",
",",
"conv",
"[",
"Text",
".",
"upper",
"(",
")",
"]",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Bad text'",
")"
] | Returns buddy status code.
:Parameters:
Text : unicode
Text, one of 'UNKNOWN', 'NEVER_BEEN_FRIEND', 'DELETED_FRIEND', 'PENDING_AUTHORIZATION',
'FRIEND'.
:return: Buddy status.
:rtype: `enums`.bud* | [
"Returns",
"buddy",
"status",
"code",
"."
] | train | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/conversion.py#L278-L297 |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.add_composite_field | def add_composite_field(self, name, field):
"""
Add a dynamic composite field to the already existing ones and
initialize it appropriatly.
"""
self.composite_fields[name] = field
self._init_composite_field(name, field) | python | def add_composite_field(self, name, field):
"""
Add a dynamic composite field to the already existing ones and
initialize it appropriatly.
"""
self.composite_fields[name] = field
self._init_composite_field(name, field) | [
"def",
"add_composite_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"self",
".",
"composite_fields",
"[",
"name",
"]",
"=",
"field",
"self",
".",
"_init_composite_field",
"(",
"name",
",",
"field",
")"
] | Add a dynamic composite field to the already existing ones and
initialize it appropriatly. | [
"Add",
"a",
"dynamic",
"composite",
"field",
"to",
"the",
"already",
"existing",
"ones",
"and",
"initialize",
"it",
"appropriatly",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L189-L195 |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.get_composite_field_value | def get_composite_field_value(self, name):
"""
Return the form/formset instance for the given field name.
"""
field = self.composite_fields[name]
if hasattr(field, 'get_form'):
return self.forms[name]
if hasattr(field, 'get_formset'):
return self.formsets[name] | python | def get_composite_field_value(self, name):
"""
Return the form/formset instance for the given field name.
"""
field = self.composite_fields[name]
if hasattr(field, 'get_form'):
return self.forms[name]
if hasattr(field, 'get_formset'):
return self.formsets[name] | [
"def",
"get_composite_field_value",
"(",
"self",
",",
"name",
")",
":",
"field",
"=",
"self",
".",
"composite_fields",
"[",
"name",
"]",
"if",
"hasattr",
"(",
"field",
",",
"'get_form'",
")",
":",
"return",
"self",
".",
"forms",
"[",
"name",
"]",
"if",
"hasattr",
"(",
"field",
",",
"'get_formset'",
")",
":",
"return",
"self",
".",
"formsets",
"[",
"name",
"]"
] | Return the form/formset instance for the given field name. | [
"Return",
"the",
"form",
"/",
"formset",
"instance",
"for",
"the",
"given",
"field",
"name",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L197-L205 |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin._init_composite_fields | def _init_composite_fields(self):
"""
Setup the forms and formsets.
"""
# The base_composite_fields class attribute is the *class-wide*
# definition of fields. Because a particular *instance* of the class
# might want to alter self.composite_fields, we create
# self.composite_fields here by copying base_composite_fields.
# Instances should always modify self.composite_fields; they should not
# modify base_composite_fields.
self.composite_fields = copy.deepcopy(self.base_composite_fields)
self.forms = OrderedDict()
self.formsets = OrderedDict()
for name, field in self.composite_fields.items():
self._init_composite_field(name, field) | python | def _init_composite_fields(self):
"""
Setup the forms and formsets.
"""
# The base_composite_fields class attribute is the *class-wide*
# definition of fields. Because a particular *instance* of the class
# might want to alter self.composite_fields, we create
# self.composite_fields here by copying base_composite_fields.
# Instances should always modify self.composite_fields; they should not
# modify base_composite_fields.
self.composite_fields = copy.deepcopy(self.base_composite_fields)
self.forms = OrderedDict()
self.formsets = OrderedDict()
for name, field in self.composite_fields.items():
self._init_composite_field(name, field) | [
"def",
"_init_composite_fields",
"(",
"self",
")",
":",
"# The base_composite_fields class attribute is the *class-wide*",
"# definition of fields. Because a particular *instance* of the class",
"# might want to alter self.composite_fields, we create",
"# self.composite_fields here by copying base_composite_fields.",
"# Instances should always modify self.composite_fields; they should not",
"# modify base_composite_fields.",
"self",
".",
"composite_fields",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"base_composite_fields",
")",
"self",
".",
"forms",
"=",
"OrderedDict",
"(",
")",
"self",
".",
"formsets",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
",",
"field",
"in",
"self",
".",
"composite_fields",
".",
"items",
"(",
")",
":",
"self",
".",
"_init_composite_field",
"(",
"name",
",",
"field",
")"
] | Setup the forms and formsets. | [
"Setup",
"the",
"forms",
"and",
"formsets",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L215-L229 |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.full_clean | def full_clean(self):
"""
Clean the form, including all formsets and add formset errors to the
errors dict. Errors of nested forms and formsets are only included if
they actually contain errors.
"""
super(SuperFormMixin, self).full_clean()
for field_name, composite in self.forms.items():
composite.full_clean()
if not composite.is_valid() and composite._errors:
self._errors[field_name] = ErrorDict(composite._errors)
for field_name, composite in self.formsets.items():
composite.full_clean()
if not composite.is_valid() and composite._errors:
self._errors[field_name] = ErrorList(composite._errors) | python | def full_clean(self):
"""
Clean the form, including all formsets and add formset errors to the
errors dict. Errors of nested forms and formsets are only included if
they actually contain errors.
"""
super(SuperFormMixin, self).full_clean()
for field_name, composite in self.forms.items():
composite.full_clean()
if not composite.is_valid() and composite._errors:
self._errors[field_name] = ErrorDict(composite._errors)
for field_name, composite in self.formsets.items():
composite.full_clean()
if not composite.is_valid() and composite._errors:
self._errors[field_name] = ErrorList(composite._errors) | [
"def",
"full_clean",
"(",
"self",
")",
":",
"super",
"(",
"SuperFormMixin",
",",
"self",
")",
".",
"full_clean",
"(",
")",
"for",
"field_name",
",",
"composite",
"in",
"self",
".",
"forms",
".",
"items",
"(",
")",
":",
"composite",
".",
"full_clean",
"(",
")",
"if",
"not",
"composite",
".",
"is_valid",
"(",
")",
"and",
"composite",
".",
"_errors",
":",
"self",
".",
"_errors",
"[",
"field_name",
"]",
"=",
"ErrorDict",
"(",
"composite",
".",
"_errors",
")",
"for",
"field_name",
",",
"composite",
"in",
"self",
".",
"formsets",
".",
"items",
"(",
")",
":",
"composite",
".",
"full_clean",
"(",
")",
"if",
"not",
"composite",
".",
"is_valid",
"(",
")",
"and",
"composite",
".",
"_errors",
":",
"self",
".",
"_errors",
"[",
"field_name",
"]",
"=",
"ErrorList",
"(",
"composite",
".",
"_errors",
")"
] | Clean the form, including all formsets and add formset errors to the
errors dict. Errors of nested forms and formsets are only included if
they actually contain errors. | [
"Clean",
"the",
"form",
"including",
"all",
"formsets",
"and",
"add",
"formset",
"errors",
"to",
"the",
"errors",
"dict",
".",
"Errors",
"of",
"nested",
"forms",
"and",
"formsets",
"are",
"only",
"included",
"if",
"they",
"actually",
"contain",
"errors",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L231-L245 |
gregmuellegger/django-superform | django_superform/forms.py | SuperFormMixin.media | def media(self):
"""
Incooperate composite field's media.
"""
media_list = []
media_list.append(super(SuperFormMixin, self).media)
for composite_name in self.composite_fields.keys():
form = self.get_composite_field_value(composite_name)
media_list.append(form.media)
return reduce(lambda a, b: a + b, media_list) | python | def media(self):
"""
Incooperate composite field's media.
"""
media_list = []
media_list.append(super(SuperFormMixin, self).media)
for composite_name in self.composite_fields.keys():
form = self.get_composite_field_value(composite_name)
media_list.append(form.media)
return reduce(lambda a, b: a + b, media_list) | [
"def",
"media",
"(",
"self",
")",
":",
"media_list",
"=",
"[",
"]",
"media_list",
".",
"append",
"(",
"super",
"(",
"SuperFormMixin",
",",
"self",
")",
".",
"media",
")",
"for",
"composite_name",
"in",
"self",
".",
"composite_fields",
".",
"keys",
"(",
")",
":",
"form",
"=",
"self",
".",
"get_composite_field_value",
"(",
"composite_name",
")",
"media_list",
".",
"append",
"(",
"form",
".",
"media",
")",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
"b",
",",
"media_list",
")"
] | Incooperate composite field's media. | [
"Incooperate",
"composite",
"field",
"s",
"media",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L248-L257 |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save | def save(self, commit=True):
"""
When saving a super model form, the nested forms and formsets will be
saved as well.
The implementation of ``.save()`` looks like this:
.. code:: python
saved_obj = self.save_form()
self.save_forms()
self.save_formsets()
return saved_obj
That makes it easy to override it in order to change the order in which
things are saved.
The ``.save()`` method will return only a single model instance even if
nested forms are saved as well. That keeps the API similiar to what
Django's model forms are offering.
If ``commit=False`` django's modelform implementation will attach a
``save_m2m`` method to the form instance, so that you can call it
manually later. When you call ``save_m2m``, the ``save_forms`` and
``save_formsets`` methods will be executed as well so again all nested
forms are taken care of transparantly.
"""
saved_obj = self.save_form(commit=commit)
self.save_forms(commit=commit)
self.save_formsets(commit=commit)
return saved_obj | python | def save(self, commit=True):
"""
When saving a super model form, the nested forms and formsets will be
saved as well.
The implementation of ``.save()`` looks like this:
.. code:: python
saved_obj = self.save_form()
self.save_forms()
self.save_formsets()
return saved_obj
That makes it easy to override it in order to change the order in which
things are saved.
The ``.save()`` method will return only a single model instance even if
nested forms are saved as well. That keeps the API similiar to what
Django's model forms are offering.
If ``commit=False`` django's modelform implementation will attach a
``save_m2m`` method to the form instance, so that you can call it
manually later. When you call ``save_m2m``, the ``save_forms`` and
``save_formsets`` methods will be executed as well so again all nested
forms are taken care of transparantly.
"""
saved_obj = self.save_form(commit=commit)
self.save_forms(commit=commit)
self.save_formsets(commit=commit)
return saved_obj | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"saved_obj",
"=",
"self",
".",
"save_form",
"(",
"commit",
"=",
"commit",
")",
"self",
".",
"save_forms",
"(",
"commit",
"=",
"commit",
")",
"self",
".",
"save_formsets",
"(",
"commit",
"=",
"commit",
")",
"return",
"saved_obj"
] | When saving a super model form, the nested forms and formsets will be
saved as well.
The implementation of ``.save()`` looks like this:
.. code:: python
saved_obj = self.save_form()
self.save_forms()
self.save_formsets()
return saved_obj
That makes it easy to override it in order to change the order in which
things are saved.
The ``.save()`` method will return only a single model instance even if
nested forms are saved as well. That keeps the API similiar to what
Django's model forms are offering.
If ``commit=False`` django's modelform implementation will attach a
``save_m2m`` method to the form instance, so that you can call it
manually later. When you call ``save_m2m``, the ``save_forms`` and
``save_formsets`` methods will be executed as well so again all nested
forms are taken care of transparantly. | [
"When",
"saving",
"a",
"super",
"model",
"form",
"the",
"nested",
"forms",
"and",
"formsets",
"will",
"be",
"saved",
"as",
"well",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L277-L307 |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save_form | def save_form(self, commit=True):
"""
This calls Django's ``ModelForm.save()``. It only takes care of
saving this actual form, and leaves the nested forms and formsets
alone.
We separate this out of the
:meth:`~django_superform.forms.SuperModelForm.save` method to make
extensibility easier.
"""
return super(SuperModelFormMixin, self).save(commit=commit) | python | def save_form(self, commit=True):
"""
This calls Django's ``ModelForm.save()``. It only takes care of
saving this actual form, and leaves the nested forms and formsets
alone.
We separate this out of the
:meth:`~django_superform.forms.SuperModelForm.save` method to make
extensibility easier.
"""
return super(SuperModelFormMixin, self).save(commit=commit) | [
"def",
"save_form",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"return",
"super",
"(",
"SuperModelFormMixin",
",",
"self",
")",
".",
"save",
"(",
"commit",
"=",
"commit",
")"
] | This calls Django's ``ModelForm.save()``. It only takes care of
saving this actual form, and leaves the nested forms and formsets
alone.
We separate this out of the
:meth:`~django_superform.forms.SuperModelForm.save` method to make
extensibility easier. | [
"This",
"calls",
"Django",
"s",
"ModelForm",
".",
"save",
"()",
".",
"It",
"only",
"takes",
"care",
"of",
"saving",
"this",
"actual",
"form",
"and",
"leaves",
"the",
"nested",
"forms",
"and",
"formsets",
"alone",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L337-L347 |
gregmuellegger/django-superform | django_superform/forms.py | SuperModelFormMixin.save_formsets | def save_formsets(self, commit=True):
"""
Save all formsets. If ``commit=False``, it will modify the form's
``save_m2m()`` so that it also calls the formsets' ``save_m2m()``
methods.
"""
saved_composites = []
for name, composite in self.formsets.items():
field = self.composite_fields[name]
if hasattr(field, 'save'):
field.save(self, name, composite, commit=commit)
saved_composites.append(composite)
self._extend_save_m2m('save_formsets_m2m', saved_composites) | python | def save_formsets(self, commit=True):
"""
Save all formsets. If ``commit=False``, it will modify the form's
``save_m2m()`` so that it also calls the formsets' ``save_m2m()``
methods.
"""
saved_composites = []
for name, composite in self.formsets.items():
field = self.composite_fields[name]
if hasattr(field, 'save'):
field.save(self, name, composite, commit=commit)
saved_composites.append(composite)
self._extend_save_m2m('save_formsets_m2m', saved_composites) | [
"def",
"save_formsets",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"saved_composites",
"=",
"[",
"]",
"for",
"name",
",",
"composite",
"in",
"self",
".",
"formsets",
".",
"items",
"(",
")",
":",
"field",
"=",
"self",
".",
"composite_fields",
"[",
"name",
"]",
"if",
"hasattr",
"(",
"field",
",",
"'save'",
")",
":",
"field",
".",
"save",
"(",
"self",
",",
"name",
",",
"composite",
",",
"commit",
"=",
"commit",
")",
"saved_composites",
".",
"append",
"(",
"composite",
")",
"self",
".",
"_extend_save_m2m",
"(",
"'save_formsets_m2m'",
",",
"saved_composites",
")"
] | Save all formsets. If ``commit=False``, it will modify the form's
``save_m2m()`` so that it also calls the formsets' ``save_m2m()``
methods. | [
"Save",
"all",
"formsets",
".",
"If",
"commit",
"=",
"False",
"it",
"will",
"modify",
"the",
"form",
"s",
"save_m2m",
"()",
"so",
"that",
"it",
"also",
"calls",
"the",
"formsets",
"save_m2m",
"()",
"methods",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/forms.py#L359-L372 |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_prefix | def get_prefix(self, form, name):
"""
Return the prefix that is used for the formset.
"""
return '{form_prefix}{prefix_name}-{field_name}'.format(
form_prefix=form.prefix + '-' if form.prefix else '',
prefix_name=self.prefix_name,
field_name=name) | python | def get_prefix(self, form, name):
"""
Return the prefix that is used for the formset.
"""
return '{form_prefix}{prefix_name}-{field_name}'.format(
form_prefix=form.prefix + '-' if form.prefix else '',
prefix_name=self.prefix_name,
field_name=name) | [
"def",
"get_prefix",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"return",
"'{form_prefix}{prefix_name}-{field_name}'",
".",
"format",
"(",
"form_prefix",
"=",
"form",
".",
"prefix",
"+",
"'-'",
"if",
"form",
".",
"prefix",
"else",
"''",
",",
"prefix_name",
"=",
"self",
".",
"prefix_name",
",",
"field_name",
"=",
"name",
")"
] | Return the prefix that is used for the formset. | [
"Return",
"the",
"prefix",
"that",
"is",
"used",
"for",
"the",
"formset",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L67-L74 |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_initial | def get_initial(self, form, name):
"""
Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given.
"""
if hasattr(form, 'initial'):
return form.initial.get(name, None)
return None | python | def get_initial(self, form, name):
"""
Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given.
"""
if hasattr(form, 'initial'):
return form.initial.get(name, None)
return None | [
"def",
"get_initial",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"if",
"hasattr",
"(",
"form",
",",
"'initial'",
")",
":",
"return",
"form",
".",
"initial",
".",
"get",
"(",
"name",
",",
"None",
")",
"return",
"None"
] | Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given. | [
"Get",
"the",
"initial",
"data",
"that",
"got",
"passed",
"into",
"the",
"superform",
"for",
"this",
"composite",
"field",
".",
"It",
"should",
"return",
"None",
"if",
"no",
"initial",
"values",
"where",
"given",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L76-L85 |
gregmuellegger/django-superform | django_superform/fields.py | CompositeField.get_kwargs | def get_kwargs(self, form, name):
"""
Return the keyword arguments that are used to instantiate the formset.
"""
kwargs = {
'prefix': self.get_prefix(form, name),
'initial': self.get_initial(form, name),
}
kwargs.update(self.default_kwargs)
return kwargs | python | def get_kwargs(self, form, name):
"""
Return the keyword arguments that are used to instantiate the formset.
"""
kwargs = {
'prefix': self.get_prefix(form, name),
'initial': self.get_initial(form, name),
}
kwargs.update(self.default_kwargs)
return kwargs | [
"def",
"get_kwargs",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"kwargs",
"=",
"{",
"'prefix'",
":",
"self",
".",
"get_prefix",
"(",
"form",
",",
"name",
")",
",",
"'initial'",
":",
"self",
".",
"get_initial",
"(",
"form",
",",
"name",
")",
",",
"}",
"kwargs",
".",
"update",
"(",
"self",
".",
"default_kwargs",
")",
"return",
"kwargs"
] | Return the keyword arguments that are used to instantiate the formset. | [
"Return",
"the",
"keyword",
"arguments",
"that",
"are",
"used",
"to",
"instantiate",
"the",
"formset",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L87-L96 |
gregmuellegger/django-superform | django_superform/fields.py | FormField.get_form | def get_form(self, form, name):
"""
Get an instance of the form.
"""
kwargs = self.get_kwargs(form, name)
form_class = self.get_form_class(form, name)
composite_form = form_class(
data=form.data if form.is_bound else None,
files=form.files if form.is_bound else None,
**kwargs)
return composite_form | python | def get_form(self, form, name):
"""
Get an instance of the form.
"""
kwargs = self.get_kwargs(form, name)
form_class = self.get_form_class(form, name)
composite_form = form_class(
data=form.data if form.is_bound else None,
files=form.files if form.is_bound else None,
**kwargs)
return composite_form | [
"def",
"get_form",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"kwargs",
"=",
"self",
".",
"get_kwargs",
"(",
"form",
",",
"name",
")",
"form_class",
"=",
"self",
".",
"get_form_class",
"(",
"form",
",",
"name",
")",
"composite_form",
"=",
"form_class",
"(",
"data",
"=",
"form",
".",
"data",
"if",
"form",
".",
"is_bound",
"else",
"None",
",",
"files",
"=",
"form",
".",
"files",
"if",
"form",
".",
"is_bound",
"else",
"None",
",",
"*",
"*",
"kwargs",
")",
"return",
"composite_form"
] | Get an instance of the form. | [
"Get",
"an",
"instance",
"of",
"the",
"form",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L170-L180 |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.get_kwargs | def get_kwargs(self, form, name):
"""
Return the keyword arguments that are used to instantiate the formset.
The ``instance`` kwarg will be set to the value returned by
:meth:`~django_superform.fields.ModelFormField.get_instance`. The
``empty_permitted`` kwarg will be set to the inverse of the
``required`` argument passed into the constructor of this field.
"""
kwargs = super(ModelFormField, self).get_kwargs(form, name)
instance = self.get_instance(form, name)
kwargs.setdefault('instance', instance)
kwargs.setdefault('empty_permitted', not self.required)
return kwargs | python | def get_kwargs(self, form, name):
"""
Return the keyword arguments that are used to instantiate the formset.
The ``instance`` kwarg will be set to the value returned by
:meth:`~django_superform.fields.ModelFormField.get_instance`. The
``empty_permitted`` kwarg will be set to the inverse of the
``required`` argument passed into the constructor of this field.
"""
kwargs = super(ModelFormField, self).get_kwargs(form, name)
instance = self.get_instance(form, name)
kwargs.setdefault('instance', instance)
kwargs.setdefault('empty_permitted', not self.required)
return kwargs | [
"def",
"get_kwargs",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"kwargs",
"=",
"super",
"(",
"ModelFormField",
",",
"self",
")",
".",
"get_kwargs",
"(",
"form",
",",
"name",
")",
"instance",
"=",
"self",
".",
"get_instance",
"(",
"form",
",",
"name",
")",
"kwargs",
".",
"setdefault",
"(",
"'instance'",
",",
"instance",
")",
"kwargs",
".",
"setdefault",
"(",
"'empty_permitted'",
",",
"not",
"self",
".",
"required",
")",
"return",
"kwargs"
] | Return the keyword arguments that are used to instantiate the formset.
The ``instance`` kwarg will be set to the value returned by
:meth:`~django_superform.fields.ModelFormField.get_instance`. The
``empty_permitted`` kwarg will be set to the inverse of the
``required`` argument passed into the constructor of this field. | [
"Return",
"the",
"keyword",
"arguments",
"that",
"are",
"used",
"to",
"instantiate",
"the",
"formset",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L238-L251 |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.shall_save | def shall_save(self, form, name, composite_form):
"""
Return ``True`` if the given ``composite_form`` (the nested form of
this field) shall be saved. Return ``False`` if the form shall not be
saved together with the super-form.
By default it will return ``False`` if the form was not changed and the
``empty_permitted`` argument for the form was set to ``True``. That way
you can allow empty forms.
"""
if composite_form.empty_permitted and not composite_form.has_changed():
return False
return True | python | def shall_save(self, form, name, composite_form):
"""
Return ``True`` if the given ``composite_form`` (the nested form of
this field) shall be saved. Return ``False`` if the form shall not be
saved together with the super-form.
By default it will return ``False`` if the form was not changed and the
``empty_permitted`` argument for the form was set to ``True``. That way
you can allow empty forms.
"""
if composite_form.empty_permitted and not composite_form.has_changed():
return False
return True | [
"def",
"shall_save",
"(",
"self",
",",
"form",
",",
"name",
",",
"composite_form",
")",
":",
"if",
"composite_form",
".",
"empty_permitted",
"and",
"not",
"composite_form",
".",
"has_changed",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Return ``True`` if the given ``composite_form`` (the nested form of
this field) shall be saved. Return ``False`` if the form shall not be
saved together with the super-form.
By default it will return ``False`` if the form was not changed and the
``empty_permitted`` argument for the form was set to ``True``. That way
you can allow empty forms. | [
"Return",
"True",
"if",
"the",
"given",
"composite_form",
"(",
"the",
"nested",
"form",
"of",
"this",
"field",
")",
"shall",
"be",
"saved",
".",
"Return",
"False",
"if",
"the",
"form",
"shall",
"not",
"be",
"saved",
"together",
"with",
"the",
"super",
"-",
"form",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L253-L265 |
gregmuellegger/django-superform | django_superform/fields.py | ModelFormField.save | def save(self, form, name, composite_form, commit):
"""
This method is called by
:meth:`django_superform.forms.SuperModelForm.save` in order to save the
modelform that this field takes care of and calls on the nested form's
``save()`` method. But only if
:meth:`~django_superform.fields.ModelFormField.shall_save` returns
``True``.
"""
if self.shall_save(form, name, composite_form):
return composite_form.save(commit=commit)
return None | python | def save(self, form, name, composite_form, commit):
"""
This method is called by
:meth:`django_superform.forms.SuperModelForm.save` in order to save the
modelform that this field takes care of and calls on the nested form's
``save()`` method. But only if
:meth:`~django_superform.fields.ModelFormField.shall_save` returns
``True``.
"""
if self.shall_save(form, name, composite_form):
return composite_form.save(commit=commit)
return None | [
"def",
"save",
"(",
"self",
",",
"form",
",",
"name",
",",
"composite_form",
",",
"commit",
")",
":",
"if",
"self",
".",
"shall_save",
"(",
"form",
",",
"name",
",",
"composite_form",
")",
":",
"return",
"composite_form",
".",
"save",
"(",
"commit",
"=",
"commit",
")",
"return",
"None"
] | This method is called by
:meth:`django_superform.forms.SuperModelForm.save` in order to save the
modelform that this field takes care of and calls on the nested form's
``save()`` method. But only if
:meth:`~django_superform.fields.ModelFormField.shall_save` returns
``True``. | [
"This",
"method",
"is",
"called",
"by",
":",
"meth",
":",
"django_superform",
".",
"forms",
".",
"SuperModelForm",
".",
"save",
"in",
"order",
"to",
"save",
"the",
"modelform",
"that",
"this",
"field",
"takes",
"care",
"of",
"and",
"calls",
"on",
"the",
"nested",
"form",
"s",
"save",
"()",
"method",
".",
"But",
"only",
"if",
":",
"meth",
":",
"~django_superform",
".",
"fields",
".",
"ModelFormField",
".",
"shall_save",
"returns",
"True",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L267-L278 |
gregmuellegger/django-superform | django_superform/fields.py | ForeignKeyFormField.allow_blank | def allow_blank(self, form, name):
"""
Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey.
"""
if self.blank is not None:
return self.blank
model = form._meta.model
field = model._meta.get_field(self.get_field_name(form, name))
return field.blank | python | def allow_blank(self, form, name):
"""
Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey.
"""
if self.blank is not None:
return self.blank
model = form._meta.model
field = model._meta.get_field(self.get_field_name(form, name))
return field.blank | [
"def",
"allow_blank",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"if",
"self",
".",
"blank",
"is",
"not",
"None",
":",
"return",
"self",
".",
"blank",
"model",
"=",
"form",
".",
"_meta",
".",
"model",
"field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"self",
".",
"get_field_name",
"(",
"form",
",",
"name",
")",
")",
"return",
"field",
".",
"blank"
] | Allow blank determines if the form might be completely empty. If it's
empty it will result in a None as the saved value for the ForeignKey. | [
"Allow",
"blank",
"determines",
"if",
"the",
"form",
"might",
"be",
"completely",
"empty",
".",
"If",
"it",
"s",
"empty",
"it",
"will",
"result",
"in",
"a",
"None",
"as",
"the",
"saved",
"value",
"for",
"the",
"ForeignKey",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L301-L310 |
gregmuellegger/django-superform | django_superform/fields.py | FormSetField.get_formset | def get_formset(self, form, name):
"""
Get an instance of the formset.
"""
kwargs = self.get_kwargs(form, name)
formset_class = self.get_formset_class(form, name)
formset = formset_class(
form.data if form.is_bound else None,
form.files if form.is_bound else None,
**kwargs)
return formset | python | def get_formset(self, form, name):
"""
Get an instance of the formset.
"""
kwargs = self.get_kwargs(form, name)
formset_class = self.get_formset_class(form, name)
formset = formset_class(
form.data if form.is_bound else None,
form.files if form.is_bound else None,
**kwargs)
return formset | [
"def",
"get_formset",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"kwargs",
"=",
"self",
".",
"get_kwargs",
"(",
"form",
",",
"name",
")",
"formset_class",
"=",
"self",
".",
"get_formset_class",
"(",
"form",
",",
"name",
")",
"formset",
"=",
"formset_class",
"(",
"form",
".",
"data",
"if",
"form",
".",
"is_bound",
"else",
"None",
",",
"form",
".",
"files",
"if",
"form",
".",
"is_bound",
"else",
"None",
",",
"*",
"*",
"kwargs",
")",
"return",
"formset"
] | Get an instance of the formset. | [
"Get",
"an",
"instance",
"of",
"the",
"formset",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L367-L377 |
gregmuellegger/django-superform | django_superform/fields.py | InlineFormSetField.get_formset_class | def get_formset_class(self, form, name):
"""
Either return the formset class that was provided as argument to the
__init__ method, or build one based on the ``parent_model`` and
``model`` attributes.
"""
if self.formset_class is not None:
return self.formset_class
formset_class = inlineformset_factory(
self.get_parent_model(form, name),
self.get_model(form, name),
**self.formset_factory_kwargs)
return formset_class | python | def get_formset_class(self, form, name):
"""
Either return the formset class that was provided as argument to the
__init__ method, or build one based on the ``parent_model`` and
``model`` attributes.
"""
if self.formset_class is not None:
return self.formset_class
formset_class = inlineformset_factory(
self.get_parent_model(form, name),
self.get_model(form, name),
**self.formset_factory_kwargs)
return formset_class | [
"def",
"get_formset_class",
"(",
"self",
",",
"form",
",",
"name",
")",
":",
"if",
"self",
".",
"formset_class",
"is",
"not",
"None",
":",
"return",
"self",
".",
"formset_class",
"formset_class",
"=",
"inlineformset_factory",
"(",
"self",
".",
"get_parent_model",
"(",
"form",
",",
"name",
")",
",",
"self",
".",
"get_model",
"(",
"form",
",",
"name",
")",
",",
"*",
"*",
"self",
".",
"formset_factory_kwargs",
")",
"return",
"formset_class"
] | Either return the formset class that was provided as argument to the
__init__ method, or build one based on the ``parent_model`` and
``model`` attributes. | [
"Either",
"return",
"the",
"formset",
"class",
"that",
"was",
"provided",
"as",
"argument",
"to",
"the",
"__init__",
"method",
"or",
"build",
"one",
"based",
"on",
"the",
"parent_model",
"and",
"model",
"attributes",
"."
] | train | https://github.com/gregmuellegger/django-superform/blob/5f389911ad38932b6dad184cc7fa81f27db752f9/django_superform/fields.py#L479-L491 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | MongoAlchemy.init_app | def init_app(self, app, config_prefix='MONGOALCHEMY'):
"""This callback can be used to initialize an application for the use with this
MongoDB setup. Never use a database in the context of an application not
initialized that way or connections will leak."""
self.config_prefix = config_prefix
def key(suffix):
return '%s_%s' % (config_prefix, suffix)
if key('DATABASE') not in app.config:
raise ImproperlyConfiguredError("You should provide a database name "
"(the %s setting)." % key('DATABASE'))
uri = _get_mongo_uri(app, key)
rs = app.config.get(key('REPLICA_SET'))
timezone = None
if key('TIMEZONE') in app.config:
timezone = pytz.timezone(app.config.get(key('TIMEZONE')))
self.session = session.Session.connect(app.config.get(key('DATABASE')),
safe=app.config.get(key('SAFE_SESSION'),
False),
timezone = timezone,
host=uri, replicaSet=rs)
self.Document._session = self.session | python | def init_app(self, app, config_prefix='MONGOALCHEMY'):
"""This callback can be used to initialize an application for the use with this
MongoDB setup. Never use a database in the context of an application not
initialized that way or connections will leak."""
self.config_prefix = config_prefix
def key(suffix):
return '%s_%s' % (config_prefix, suffix)
if key('DATABASE') not in app.config:
raise ImproperlyConfiguredError("You should provide a database name "
"(the %s setting)." % key('DATABASE'))
uri = _get_mongo_uri(app, key)
rs = app.config.get(key('REPLICA_SET'))
timezone = None
if key('TIMEZONE') in app.config:
timezone = pytz.timezone(app.config.get(key('TIMEZONE')))
self.session = session.Session.connect(app.config.get(key('DATABASE')),
safe=app.config.get(key('SAFE_SESSION'),
False),
timezone = timezone,
host=uri, replicaSet=rs)
self.Document._session = self.session | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"config_prefix",
"=",
"'MONGOALCHEMY'",
")",
":",
"self",
".",
"config_prefix",
"=",
"config_prefix",
"def",
"key",
"(",
"suffix",
")",
":",
"return",
"'%s_%s'",
"%",
"(",
"config_prefix",
",",
"suffix",
")",
"if",
"key",
"(",
"'DATABASE'",
")",
"not",
"in",
"app",
".",
"config",
":",
"raise",
"ImproperlyConfiguredError",
"(",
"\"You should provide a database name \"",
"\"(the %s setting).\"",
"%",
"key",
"(",
"'DATABASE'",
")",
")",
"uri",
"=",
"_get_mongo_uri",
"(",
"app",
",",
"key",
")",
"rs",
"=",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'REPLICA_SET'",
")",
")",
"timezone",
"=",
"None",
"if",
"key",
"(",
"'TIMEZONE'",
")",
"in",
"app",
".",
"config",
":",
"timezone",
"=",
"pytz",
".",
"timezone",
"(",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'TIMEZONE'",
")",
")",
")",
"self",
".",
"session",
"=",
"session",
".",
"Session",
".",
"connect",
"(",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'DATABASE'",
")",
")",
",",
"safe",
"=",
"app",
".",
"config",
".",
"get",
"(",
"key",
"(",
"'SAFE_SESSION'",
")",
",",
"False",
")",
",",
"timezone",
"=",
"timezone",
",",
"host",
"=",
"uri",
",",
"replicaSet",
"=",
"rs",
")",
"self",
".",
"Document",
".",
"_session",
"=",
"self",
".",
"session"
] | This callback can be used to initialize an application for the use with this
MongoDB setup. Never use a database in the context of an application not
initialized that way or connections will leak. | [
"This",
"callback",
"can",
"be",
"used",
"to",
"initialize",
"an",
"application",
"for",
"the",
"use",
"with",
"this",
"MongoDB",
"setup",
".",
"Never",
"use",
"a",
"database",
"in",
"the",
"context",
"of",
"an",
"application",
"not",
"initialized",
"that",
"way",
"or",
"connections",
"will",
"leak",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L106-L129 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | Pagination.prev | def prev(self, error_out=False):
"""Return a :class:`Pagination` object for the previous page."""
return self.query.paginate(self.page - 1, self.per_page, error_out) | python | def prev(self, error_out=False):
"""Return a :class:`Pagination` object for the previous page."""
return self.query.paginate(self.page - 1, self.per_page, error_out) | [
"def",
"prev",
"(",
"self",
",",
"error_out",
"=",
"False",
")",
":",
"return",
"self",
".",
"query",
".",
"paginate",
"(",
"self",
".",
"page",
"-",
"1",
",",
"self",
".",
"per_page",
",",
"error_out",
")"
] | Return a :class:`Pagination` object for the previous page. | [
"Return",
"a",
":",
"class",
":",
"Pagination",
"object",
"for",
"the",
"previous",
"page",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L175-L177 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | BaseQuery.get | def get(self, mongo_id):
"""Returns a :class:`Document` instance from its ``mongo_id`` or ``None``
if not found"""
try:
return self.filter(self.type.mongo_id == mongo_id).first()
except exceptions.BadValueException:
return None | python | def get(self, mongo_id):
"""Returns a :class:`Document` instance from its ``mongo_id`` or ``None``
if not found"""
try:
return self.filter(self.type.mongo_id == mongo_id).first()
except exceptions.BadValueException:
return None | [
"def",
"get",
"(",
"self",
",",
"mongo_id",
")",
":",
"try",
":",
"return",
"self",
".",
"filter",
"(",
"self",
".",
"type",
".",
"mongo_id",
"==",
"mongo_id",
")",
".",
"first",
"(",
")",
"except",
"exceptions",
".",
"BadValueException",
":",
"return",
"None"
] | Returns a :class:`Document` instance from its ``mongo_id`` or ``None``
if not found | [
"Returns",
"a",
":",
"class",
":",
"Document",
"instance",
"from",
"its",
"mongo_id",
"or",
"None",
"if",
"not",
"found"
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L222-L228 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | BaseQuery.get_or_404 | def get_or_404(self, mongo_id):
"""Like :meth:`get` method but aborts with 404 if not found instead of
returning `None`"""
document = self.get(mongo_id)
if document is None:
abort(404)
return document | python | def get_or_404(self, mongo_id):
"""Like :meth:`get` method but aborts with 404 if not found instead of
returning `None`"""
document = self.get(mongo_id)
if document is None:
abort(404)
return document | [
"def",
"get_or_404",
"(",
"self",
",",
"mongo_id",
")",
":",
"document",
"=",
"self",
".",
"get",
"(",
"mongo_id",
")",
"if",
"document",
"is",
"None",
":",
"abort",
"(",
"404",
")",
"return",
"document"
] | Like :meth:`get` method but aborts with 404 if not found instead of
returning `None` | [
"Like",
":",
"meth",
":",
"get",
"method",
"but",
"aborts",
"with",
"404",
"if",
"not",
"found",
"instead",
"of",
"returning",
"None"
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L230-L236 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | BaseQuery.paginate | def paginate(self, page, per_page=20, error_out=True):
"""Returns ``per_page`` items from page ``page`` By default, it will
abort with 404 if no items were found and the page was larger than 1.
This behaviour can be disabled by setting ``error_out`` to ``False``.
Returns a :class:`Pagination` object."""
if page < 1 and error_out:
abort(404)
items = self.skip((page - 1) * per_page).limit(per_page).all()
if len(items) < 1 and page != 1 and error_out:
abort(404)
return Pagination(self, page, per_page, self.count(), items) | python | def paginate(self, page, per_page=20, error_out=True):
"""Returns ``per_page`` items from page ``page`` By default, it will
abort with 404 if no items were found and the page was larger than 1.
This behaviour can be disabled by setting ``error_out`` to ``False``.
Returns a :class:`Pagination` object."""
if page < 1 and error_out:
abort(404)
items = self.skip((page - 1) * per_page).limit(per_page).all()
if len(items) < 1 and page != 1 and error_out:
abort(404)
return Pagination(self, page, per_page, self.count(), items) | [
"def",
"paginate",
"(",
"self",
",",
"page",
",",
"per_page",
"=",
"20",
",",
"error_out",
"=",
"True",
")",
":",
"if",
"page",
"<",
"1",
"and",
"error_out",
":",
"abort",
"(",
"404",
")",
"items",
"=",
"self",
".",
"skip",
"(",
"(",
"page",
"-",
"1",
")",
"*",
"per_page",
")",
".",
"limit",
"(",
"per_page",
")",
".",
"all",
"(",
")",
"if",
"len",
"(",
"items",
")",
"<",
"1",
"and",
"page",
"!=",
"1",
"and",
"error_out",
":",
"abort",
"(",
"404",
")",
"return",
"Pagination",
"(",
"self",
",",
"page",
",",
"per_page",
",",
"self",
".",
"count",
"(",
")",
",",
"items",
")"
] | Returns ``per_page`` items from page ``page`` By default, it will
abort with 404 if no items were found and the page was larger than 1.
This behaviour can be disabled by setting ``error_out`` to ``False``.
Returns a :class:`Pagination` object. | [
"Returns",
"per_page",
"items",
"from",
"page",
"page",
"By",
"default",
"it",
"will",
"abort",
"with",
"404",
"if",
"no",
"items",
"were",
"found",
"and",
"the",
"page",
"was",
"larger",
"than",
"1",
".",
"This",
"behaviour",
"can",
"be",
"disabled",
"by",
"setting",
"error_out",
"to",
"False",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L246-L260 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | Document.save | def save(self, safe=None):
"""Saves the document itself in the database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete.
"""
self._session.insert(self, safe=safe)
self._session.flush() | python | def save(self, safe=None):
"""Saves the document itself in the database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete.
"""
self._session.insert(self, safe=safe)
self._session.flush() | [
"def",
"save",
"(",
"self",
",",
"safe",
"=",
"None",
")",
":",
"self",
".",
"_session",
".",
"insert",
"(",
"self",
",",
"safe",
"=",
"safe",
")",
"self",
".",
"_session",
".",
"flush",
"(",
")"
] | Saves the document itself in the database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete. | [
"Saves",
"the",
"document",
"itself",
"in",
"the",
"database",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L274-L281 |
cobrateam/flask-mongoalchemy | flask_mongoalchemy/__init__.py | Document.remove | def remove(self, safe=None):
"""Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete.
"""
self._session.remove(self, safe=None)
self._session.flush() | python | def remove(self, safe=None):
"""Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete.
"""
self._session.remove(self, safe=None)
self._session.flush() | [
"def",
"remove",
"(",
"self",
",",
"safe",
"=",
"None",
")",
":",
"self",
".",
"_session",
".",
"remove",
"(",
"self",
",",
"safe",
"=",
"None",
")",
"self",
".",
"_session",
".",
"flush",
"(",
")"
] | Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete. | [
"Removes",
"the",
"document",
"itself",
"from",
"database",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/flask_mongoalchemy/__init__.py#L283-L290 |
cobrateam/flask-mongoalchemy | examples/library/library.py | list_authors | def list_authors():
"""List all authors.
e.g.: GET /authors"""
authors = Author.query.all()
content = '<p>Authors:</p>'
for author in authors:
content += '<p>%s</p>' % author.name
return content | python | def list_authors():
"""List all authors.
e.g.: GET /authors"""
authors = Author.query.all()
content = '<p>Authors:</p>'
for author in authors:
content += '<p>%s</p>' % author.name
return content | [
"def",
"list_authors",
"(",
")",
":",
"authors",
"=",
"Author",
".",
"query",
".",
"all",
"(",
")",
"content",
"=",
"'<p>Authors:</p>'",
"for",
"author",
"in",
"authors",
":",
"content",
"+=",
"'<p>%s</p>'",
"%",
"author",
".",
"name",
"return",
"content"
] | List all authors.
e.g.: GET /authors | [
"List",
"all",
"authors",
"."
] | train | https://github.com/cobrateam/flask-mongoalchemy/blob/66ab6f857cae69e35d37035880c1dfaf1dc9bd15/examples/library/library.py#L37-L45 |
jessevdk/cldoc | cldoc/clang/cindex.py | Diagnostic.disable_option | def disable_option(self):
"""The command-line option that disables this diagnostic."""
disable = _CXString()
conf.lib.clang_getDiagnosticOption(self, byref(disable))
return _CXString.from_result(disable) | python | def disable_option(self):
"""The command-line option that disables this diagnostic."""
disable = _CXString()
conf.lib.clang_getDiagnosticOption(self, byref(disable))
return _CXString.from_result(disable) | [
"def",
"disable_option",
"(",
"self",
")",
":",
"disable",
"=",
"_CXString",
"(",
")",
"conf",
".",
"lib",
".",
"clang_getDiagnosticOption",
"(",
"self",
",",
"byref",
"(",
"disable",
")",
")",
"return",
"_CXString",
".",
"from_result",
"(",
"disable",
")"
] | The command-line option that disables this diagnostic. | [
"The",
"command",
"-",
"line",
"option",
"that",
"disables",
"this",
"diagnostic",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L480-L484 |
jessevdk/cldoc | cldoc/clang/cindex.py | Diagnostic.format | def format(self, options=None):
"""
Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used.
"""
if options is None:
options = conf.lib.clang_defaultDiagnosticDisplayOptions()
if options & ~Diagnostic._FormatOptionsMask:
raise ValueError('Invalid format options')
return conf.lib.clang_formatDiagnostic(self, options) | python | def format(self, options=None):
"""
Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used.
"""
if options is None:
options = conf.lib.clang_defaultDiagnosticDisplayOptions()
if options & ~Diagnostic._FormatOptionsMask:
raise ValueError('Invalid format options')
return conf.lib.clang_formatDiagnostic(self, options) | [
"def",
"format",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultDiagnosticDisplayOptions",
"(",
")",
"if",
"options",
"&",
"~",
"Diagnostic",
".",
"_FormatOptionsMask",
":",
"raise",
"ValueError",
"(",
"'Invalid format options'",
")",
"return",
"conf",
".",
"lib",
".",
"clang_formatDiagnostic",
"(",
"self",
",",
"options",
")"
] | Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used. | [
"Format",
"this",
"diagnostic",
"for",
"display",
".",
"The",
"options",
"argument",
"takes",
"Diagnostic",
".",
"Display",
"*",
"flags",
"which",
"can",
"be",
"combined",
"using",
"bitwise",
"OR",
".",
"If",
"the",
"options",
"argument",
"is",
"not",
"provided",
"the",
"default",
"display",
"options",
"will",
"be",
"used",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L486-L497 |
jessevdk/cldoc | cldoc/clang/cindex.py | BaseEnumeration.name | def name(self):
"""Get the enumeration name of this cursor kind."""
if self._name_map is None:
self._name_map = {}
for key, value in self.__class__.__dict__.items():
if isinstance(value, self.__class__):
self._name_map[value] = key
return self._name_map[self] | python | def name(self):
"""Get the enumeration name of this cursor kind."""
if self._name_map is None:
self._name_map = {}
for key, value in self.__class__.__dict__.items():
if isinstance(value, self.__class__):
self._name_map[value] = key
return self._name_map[self] | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name_map",
"is",
"None",
":",
"self",
".",
"_name_map",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__class__",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"self",
".",
"__class__",
")",
":",
"self",
".",
"_name_map",
"[",
"value",
"]",
"=",
"key",
"return",
"self",
".",
"_name_map",
"[",
"self",
"]"
] | Get the enumeration name of this cursor kind. | [
"Get",
"the",
"enumeration",
"name",
"of",
"this",
"cursor",
"kind",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L643-L650 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.spelling | def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling | python | def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling | [
"def",
"spelling",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_spelling'",
")",
":",
"self",
".",
"_spelling",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSpelling",
"(",
"self",
")",
"return",
"self",
".",
"_spelling"
] | Return the spelling of the entity pointed at by the cursor. | [
"Return",
"the",
"spelling",
"of",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1528-L1533 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.displayname | def displayname(self):
"""
Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization.
"""
if not hasattr(self, '_displayname'):
self._displayname = conf.lib.clang_getCursorDisplayName(self)
return self._displayname | python | def displayname(self):
"""
Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization.
"""
if not hasattr(self, '_displayname'):
self._displayname = conf.lib.clang_getCursorDisplayName(self)
return self._displayname | [
"def",
"displayname",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_displayname'",
")",
":",
"self",
".",
"_displayname",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorDisplayName",
"(",
"self",
")",
"return",
"self",
".",
"_displayname"
] | Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization. | [
"Return",
"the",
"display",
"name",
"for",
"the",
"entity",
"referenced",
"by",
"this",
"cursor",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1536-L1547 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.mangled_name | def mangled_name(self):
"""Return the mangled name for the entity referenced by this cursor."""
if not hasattr(self, '_mangled_name'):
self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
return self._mangled_name | python | def mangled_name(self):
"""Return the mangled name for the entity referenced by this cursor."""
if not hasattr(self, '_mangled_name'):
self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
return self._mangled_name | [
"def",
"mangled_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_mangled_name'",
")",
":",
"self",
".",
"_mangled_name",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getMangling",
"(",
"self",
")",
"return",
"self",
".",
"_mangled_name"
] | Return the mangled name for the entity referenced by this cursor. | [
"Return",
"the",
"mangled",
"name",
"for",
"the",
"entity",
"referenced",
"by",
"this",
"cursor",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1550-L1555 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.linkage | def linkage(self):
"""Return the linkage of this cursor."""
if not hasattr(self, '_linkage'):
self._linkage = conf.lib.clang_getCursorLinkage(self)
return LinkageKind.from_id(self._linkage) | python | def linkage(self):
"""Return the linkage of this cursor."""
if not hasattr(self, '_linkage'):
self._linkage = conf.lib.clang_getCursorLinkage(self)
return LinkageKind.from_id(self._linkage) | [
"def",
"linkage",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_linkage'",
")",
":",
"self",
".",
"_linkage",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorLinkage",
"(",
"self",
")",
"return",
"LinkageKind",
".",
"from_id",
"(",
"self",
".",
"_linkage",
")"
] | Return the linkage of this cursor. | [
"Return",
"the",
"linkage",
"of",
"this",
"cursor",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1569-L1574 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.availability | def availability(self):
"""
Retrieves the availability of the entity pointed at by the cursor.
"""
if not hasattr(self, '_availability'):
self._availability = conf.lib.clang_getCursorAvailability(self)
return AvailabilityKind.from_id(self._availability) | python | def availability(self):
"""
Retrieves the availability of the entity pointed at by the cursor.
"""
if not hasattr(self, '_availability'):
self._availability = conf.lib.clang_getCursorAvailability(self)
return AvailabilityKind.from_id(self._availability) | [
"def",
"availability",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_availability'",
")",
":",
"self",
".",
"_availability",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorAvailability",
"(",
"self",
")",
"return",
"AvailabilityKind",
".",
"from_id",
"(",
"self",
".",
"_availability",
")"
] | Retrieves the availability of the entity pointed at by the cursor. | [
"Retrieves",
"the",
"availability",
"of",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1599-L1606 |
jessevdk/cldoc | cldoc/clang/cindex.py | Cursor.objc_type_encoding | def objc_type_encoding(self):
"""Return the Objective-C type encoding as a str."""
if not hasattr(self, '_objc_type_encoding'):
self._objc_type_encoding = \
conf.lib.clang_getDeclObjCTypeEncoding(self)
return self._objc_type_encoding | python | def objc_type_encoding(self):
"""Return the Objective-C type encoding as a str."""
if not hasattr(self, '_objc_type_encoding'):
self._objc_type_encoding = \
conf.lib.clang_getDeclObjCTypeEncoding(self)
return self._objc_type_encoding | [
"def",
"objc_type_encoding",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_objc_type_encoding'",
")",
":",
"self",
".",
"_objc_type_encoding",
"=",
"conf",
".",
"lib",
".",
"clang_getDeclObjCTypeEncoding",
"(",
"self",
")",
"return",
"self",
".",
"_objc_type_encoding"
] | Return the Objective-C type encoding as a str. | [
"Return",
"the",
"Objective",
"-",
"C",
"type",
"encoding",
"as",
"a",
"str",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1704-L1710 |
jessevdk/cldoc | cldoc/clang/cindex.py | TranslationUnit.from_source | def from_source(cls, filename, args=None, unsaved_files=None, options=0,
index=None):
"""Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments that would be passed to clang are specified as
a list via args. These can be used to specify include paths, warnings,
etc. e.g. ["-Wall", "-I/path/to/include"].
In-memory file content can be provided via unsaved_files. This is an
iterable of 2-tuples. The first element is the str filename. The
second element defines the content. Content can be provided as str
source code or as file objects (anything with a read() method). If
a file object is being used, content will be read until EOF and the
read cursor will not be reset to its original position.
options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
control parsing behavior.
index is an Index instance to utilize. If not provided, a new Index
will be created for this TranslationUnit.
To parse source from the filesystem, the filename of the file to parse
is specified by the filename argument. Or, filename could be None and
the args list would contain the filename(s) to parse.
To parse source from an in-memory buffer, set filename to the virtual
filename you wish to associate with this source (e.g. "test.c"). The
contents of that file are then provided in unsaved_files.
If an error occurs, a TranslationUnitLoadError is raised.
Please note that a TranslationUnit with parser errors may be returned.
It is the caller's responsibility to check tu.diagnostics for errors.
Also note that Clang infers the source language from the extension of
the input filename. If you pass in source code containing a C++ class
declaration with the filename "test.c" parsing will fail.
"""
if args is None:
args = []
if unsaved_files is None:
unsaved_files = []
if index is None:
index = Index.create()
args_array = None
if len(args) > 0:
args_array = (c_char_p * len(args))(*[b(x) for x in args])
unsaved_array = None
if len(unsaved_files) > 0:
unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
for i, (name, contents) in enumerate(unsaved_files):
if hasattr(contents, "read"):
contents = contents.read()
unsaved_array[i].name = b(name)
unsaved_array[i].contents = b(contents)
unsaved_array[i].length = len(contents)
ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
len(args), unsaved_array,
len(unsaved_files), options)
if not ptr:
raise TranslationUnitLoadError("Error parsing translation unit.")
return cls(ptr, index=index) | python | def from_source(cls, filename, args=None, unsaved_files=None, options=0,
index=None):
"""Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments that would be passed to clang are specified as
a list via args. These can be used to specify include paths, warnings,
etc. e.g. ["-Wall", "-I/path/to/include"].
In-memory file content can be provided via unsaved_files. This is an
iterable of 2-tuples. The first element is the str filename. The
second element defines the content. Content can be provided as str
source code or as file objects (anything with a read() method). If
a file object is being used, content will be read until EOF and the
read cursor will not be reset to its original position.
options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
control parsing behavior.
index is an Index instance to utilize. If not provided, a new Index
will be created for this TranslationUnit.
To parse source from the filesystem, the filename of the file to parse
is specified by the filename argument. Or, filename could be None and
the args list would contain the filename(s) to parse.
To parse source from an in-memory buffer, set filename to the virtual
filename you wish to associate with this source (e.g. "test.c"). The
contents of that file are then provided in unsaved_files.
If an error occurs, a TranslationUnitLoadError is raised.
Please note that a TranslationUnit with parser errors may be returned.
It is the caller's responsibility to check tu.diagnostics for errors.
Also note that Clang infers the source language from the extension of
the input filename. If you pass in source code containing a C++ class
declaration with the filename "test.c" parsing will fail.
"""
if args is None:
args = []
if unsaved_files is None:
unsaved_files = []
if index is None:
index = Index.create()
args_array = None
if len(args) > 0:
args_array = (c_char_p * len(args))(*[b(x) for x in args])
unsaved_array = None
if len(unsaved_files) > 0:
unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
for i, (name, contents) in enumerate(unsaved_files):
if hasattr(contents, "read"):
contents = contents.read()
unsaved_array[i].name = b(name)
unsaved_array[i].contents = b(contents)
unsaved_array[i].length = len(contents)
ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
len(args), unsaved_array,
len(unsaved_files), options)
if not ptr:
raise TranslationUnitLoadError("Error parsing translation unit.")
return cls(ptr, index=index) | [
"def",
"from_source",
"(",
"cls",
",",
"filename",
",",
"args",
"=",
"None",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
",",
"index",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"[",
"]",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"Index",
".",
"create",
"(",
")",
"args_array",
"=",
"None",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"args_array",
"=",
"(",
"c_char_p",
"*",
"len",
"(",
"args",
")",
")",
"(",
"*",
"[",
"b",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
")",
"unsaved_array",
"=",
"None",
"if",
"len",
"(",
"unsaved_files",
")",
">",
"0",
":",
"unsaved_array",
"=",
"(",
"_CXUnsavedFile",
"*",
"len",
"(",
"unsaved_files",
")",
")",
"(",
")",
"for",
"i",
",",
"(",
"name",
",",
"contents",
")",
"in",
"enumerate",
"(",
"unsaved_files",
")",
":",
"if",
"hasattr",
"(",
"contents",
",",
"\"read\"",
")",
":",
"contents",
"=",
"contents",
".",
"read",
"(",
")",
"unsaved_array",
"[",
"i",
"]",
".",
"name",
"=",
"b",
"(",
"name",
")",
"unsaved_array",
"[",
"i",
"]",
".",
"contents",
"=",
"b",
"(",
"contents",
")",
"unsaved_array",
"[",
"i",
"]",
".",
"length",
"=",
"len",
"(",
"contents",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_parseTranslationUnit",
"(",
"index",
",",
"filename",
",",
"args_array",
",",
"len",
"(",
"args",
")",
",",
"unsaved_array",
",",
"len",
"(",
"unsaved_files",
")",
",",
"options",
")",
"if",
"not",
"ptr",
":",
"raise",
"TranslationUnitLoadError",
"(",
"\"Error parsing translation unit.\"",
")",
"return",
"cls",
"(",
"ptr",
",",
"index",
"=",
"index",
")"
] | Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments that would be passed to clang are specified as
a list via args. These can be used to specify include paths, warnings,
etc. e.g. ["-Wall", "-I/path/to/include"].
In-memory file content can be provided via unsaved_files. This is an
iterable of 2-tuples. The first element is the str filename. The
second element defines the content. Content can be provided as str
source code or as file objects (anything with a read() method). If
a file object is being used, content will be read until EOF and the
read cursor will not be reset to its original position.
options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
control parsing behavior.
index is an Index instance to utilize. If not provided, a new Index
will be created for this TranslationUnit.
To parse source from the filesystem, the filename of the file to parse
is specified by the filename argument. Or, filename could be None and
the args list would contain the filename(s) to parse.
To parse source from an in-memory buffer, set filename to the virtual
filename you wish to associate with this source (e.g. "test.c"). The
contents of that file are then provided in unsaved_files.
If an error occurs, a TranslationUnitLoadError is raised.
Please note that a TranslationUnit with parser errors may be returned.
It is the caller's responsibility to check tu.diagnostics for errors.
Also note that Clang infers the source language from the extension of
the input filename. If you pass in source code containing a C++ class
declaration with the filename "test.c" parsing will fail. | [
"Create",
"a",
"TranslationUnit",
"by",
"parsing",
"source",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L2737-L2809 |
jessevdk/cldoc | cldoc/clang/cindex.py | Token.cursor | def cursor(self):
"""The Cursor this Token corresponds to."""
cursor = Cursor()
cursor._tu = self._tu
conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
return cursor | python | def cursor(self):
"""The Cursor this Token corresponds to."""
cursor = Cursor()
cursor._tu = self._tu
conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
return cursor | [
"def",
"cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"Cursor",
"(",
")",
"cursor",
".",
"_tu",
"=",
"self",
".",
"_tu",
"conf",
".",
"lib",
".",
"clang_annotateTokens",
"(",
"self",
".",
"_tu",
",",
"byref",
"(",
"self",
")",
",",
"1",
",",
"byref",
"(",
"cursor",
")",
")",
"return",
"cursor"
] | The Cursor this Token corresponds to. | [
"The",
"Cursor",
"this",
"Token",
"corresponds",
"to",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L3286-L3293 |
jessevdk/cldoc | cldoc/tree.py | Tree.process | def process(self):
"""
process processes all the files with clang and extracts all relevant
nodes from the generated AST
"""
self.index = cindex.Index.create()
self.headers = {}
for f in self.files:
if f in self.processed:
continue
print('Processing {0}'.format(os.path.basename(f)))
tu = self.index.parse(f, self.flags)
if len(tu.diagnostics) != 0:
fatal = False
for d in tu.diagnostics:
sys.stderr.write(d.format())
sys.stderr.write("\n")
if d.severity == cindex.Diagnostic.Fatal or \
d.severity == cindex.Diagnostic.Error:
fatal = True
if fatal:
sys.stderr.write("\nCould not generate documentation due to parser errors\n")
sys.exit(1)
if not tu:
sys.stderr.write("Could not parse file %s...\n" % (f,))
sys.exit(1)
# Extract comments from files and included files that we are
# supposed to inspect
extractfiles = [f]
for inc in tu.get_includes():
filename = str(inc.include)
self.headers[filename] = True
if filename in self.processed or (not filename in self.files) or filename in extractfiles:
continue
extractfiles.append(filename)
for e in extractfiles:
db = comment.CommentsDatabase(e, tu)
self.add_categories(db.category_names)
self.commentsdbs[e] = db
self.visit(tu.cursor.get_children())
for f in self.processing:
self.processed[f] = True
self.processing = {}
# Construct hierarchy of nodes.
for node in self.all_nodes:
q = node.qid
if node.parent is None:
par = self.find_parent(node)
# Lookup categories for things in the root
if (par is None or par == self.root) and (not node.cursor is None):
location = node.cursor.extent.start
db = self.commentsdbs[location.file.name]
if db:
par = self.category_to_node[db.lookup_category(location)]
if par is None:
par = self.root
par.append(node)
# Resolve comment
cm = self.find_node_comment(node)
if cm:
node.merge_comment(cm)
# Keep track of classes to resolve bases and subclasses
classes = {}
# Map final qid to node
for node in self.all_nodes:
q = node.qid
self.qid_to_node[q] = node
if isinstance(node, nodes.Class):
classes[q] = node
# Resolve bases and subclasses
for qid in classes:
classes[qid].resolve_bases(classes) | python | def process(self):
"""
process processes all the files with clang and extracts all relevant
nodes from the generated AST
"""
self.index = cindex.Index.create()
self.headers = {}
for f in self.files:
if f in self.processed:
continue
print('Processing {0}'.format(os.path.basename(f)))
tu = self.index.parse(f, self.flags)
if len(tu.diagnostics) != 0:
fatal = False
for d in tu.diagnostics:
sys.stderr.write(d.format())
sys.stderr.write("\n")
if d.severity == cindex.Diagnostic.Fatal or \
d.severity == cindex.Diagnostic.Error:
fatal = True
if fatal:
sys.stderr.write("\nCould not generate documentation due to parser errors\n")
sys.exit(1)
if not tu:
sys.stderr.write("Could not parse file %s...\n" % (f,))
sys.exit(1)
# Extract comments from files and included files that we are
# supposed to inspect
extractfiles = [f]
for inc in tu.get_includes():
filename = str(inc.include)
self.headers[filename] = True
if filename in self.processed or (not filename in self.files) or filename in extractfiles:
continue
extractfiles.append(filename)
for e in extractfiles:
db = comment.CommentsDatabase(e, tu)
self.add_categories(db.category_names)
self.commentsdbs[e] = db
self.visit(tu.cursor.get_children())
for f in self.processing:
self.processed[f] = True
self.processing = {}
# Construct hierarchy of nodes.
for node in self.all_nodes:
q = node.qid
if node.parent is None:
par = self.find_parent(node)
# Lookup categories for things in the root
if (par is None or par == self.root) and (not node.cursor is None):
location = node.cursor.extent.start
db = self.commentsdbs[location.file.name]
if db:
par = self.category_to_node[db.lookup_category(location)]
if par is None:
par = self.root
par.append(node)
# Resolve comment
cm = self.find_node_comment(node)
if cm:
node.merge_comment(cm)
# Keep track of classes to resolve bases and subclasses
classes = {}
# Map final qid to node
for node in self.all_nodes:
q = node.qid
self.qid_to_node[q] = node
if isinstance(node, nodes.Class):
classes[q] = node
# Resolve bases and subclasses
for qid in classes:
classes[qid].resolve_bases(classes) | [
"def",
"process",
"(",
"self",
")",
":",
"self",
".",
"index",
"=",
"cindex",
".",
"Index",
".",
"create",
"(",
")",
"self",
".",
"headers",
"=",
"{",
"}",
"for",
"f",
"in",
"self",
".",
"files",
":",
"if",
"f",
"in",
"self",
".",
"processed",
":",
"continue",
"print",
"(",
"'Processing {0}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
")",
"tu",
"=",
"self",
".",
"index",
".",
"parse",
"(",
"f",
",",
"self",
".",
"flags",
")",
"if",
"len",
"(",
"tu",
".",
"diagnostics",
")",
"!=",
"0",
":",
"fatal",
"=",
"False",
"for",
"d",
"in",
"tu",
".",
"diagnostics",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"d",
".",
"format",
"(",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n\"",
")",
"if",
"d",
".",
"severity",
"==",
"cindex",
".",
"Diagnostic",
".",
"Fatal",
"or",
"d",
".",
"severity",
"==",
"cindex",
".",
"Diagnostic",
".",
"Error",
":",
"fatal",
"=",
"True",
"if",
"fatal",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nCould not generate documentation due to parser errors\\n\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"tu",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Could not parse file %s...\\n\"",
"%",
"(",
"f",
",",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Extract comments from files and included files that we are",
"# supposed to inspect",
"extractfiles",
"=",
"[",
"f",
"]",
"for",
"inc",
"in",
"tu",
".",
"get_includes",
"(",
")",
":",
"filename",
"=",
"str",
"(",
"inc",
".",
"include",
")",
"self",
".",
"headers",
"[",
"filename",
"]",
"=",
"True",
"if",
"filename",
"in",
"self",
".",
"processed",
"or",
"(",
"not",
"filename",
"in",
"self",
".",
"files",
")",
"or",
"filename",
"in",
"extractfiles",
":",
"continue",
"extractfiles",
".",
"append",
"(",
"filename",
")",
"for",
"e",
"in",
"extractfiles",
":",
"db",
"=",
"comment",
".",
"CommentsDatabase",
"(",
"e",
",",
"tu",
")",
"self",
".",
"add_categories",
"(",
"db",
".",
"category_names",
")",
"self",
".",
"commentsdbs",
"[",
"e",
"]",
"=",
"db",
"self",
".",
"visit",
"(",
"tu",
".",
"cursor",
".",
"get_children",
"(",
")",
")",
"for",
"f",
"in",
"self",
".",
"processing",
":",
"self",
".",
"processed",
"[",
"f",
"]",
"=",
"True",
"self",
".",
"processing",
"=",
"{",
"}",
"# Construct hierarchy of nodes.",
"for",
"node",
"in",
"self",
".",
"all_nodes",
":",
"q",
"=",
"node",
".",
"qid",
"if",
"node",
".",
"parent",
"is",
"None",
":",
"par",
"=",
"self",
".",
"find_parent",
"(",
"node",
")",
"# Lookup categories for things in the root",
"if",
"(",
"par",
"is",
"None",
"or",
"par",
"==",
"self",
".",
"root",
")",
"and",
"(",
"not",
"node",
".",
"cursor",
"is",
"None",
")",
":",
"location",
"=",
"node",
".",
"cursor",
".",
"extent",
".",
"start",
"db",
"=",
"self",
".",
"commentsdbs",
"[",
"location",
".",
"file",
".",
"name",
"]",
"if",
"db",
":",
"par",
"=",
"self",
".",
"category_to_node",
"[",
"db",
".",
"lookup_category",
"(",
"location",
")",
"]",
"if",
"par",
"is",
"None",
":",
"par",
"=",
"self",
".",
"root",
"par",
".",
"append",
"(",
"node",
")",
"# Resolve comment",
"cm",
"=",
"self",
".",
"find_node_comment",
"(",
"node",
")",
"if",
"cm",
":",
"node",
".",
"merge_comment",
"(",
"cm",
")",
"# Keep track of classes to resolve bases and subclasses",
"classes",
"=",
"{",
"}",
"# Map final qid to node",
"for",
"node",
"in",
"self",
".",
"all_nodes",
":",
"q",
"=",
"node",
".",
"qid",
"self",
".",
"qid_to_node",
"[",
"q",
"]",
"=",
"node",
"if",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Class",
")",
":",
"classes",
"[",
"q",
"]",
"=",
"node",
"# Resolve bases and subclasses",
"for",
"qid",
"in",
"classes",
":",
"classes",
"[",
"qid",
"]",
".",
"resolve_bases",
"(",
"classes",
")"
] | process processes all the files with clang and extracts all relevant
nodes from the generated AST | [
"process",
"processes",
"all",
"the",
"files",
"with",
"clang",
"and",
"extracts",
"all",
"relevant",
"nodes",
"from",
"the",
"generated",
"AST"
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/tree.py#L194-L295 |
jessevdk/cldoc | cldoc/tree.py | Tree.visit | def visit(self, citer, parent=None):
"""
visit iterates over the provided cursor iterator and creates nodes
from the AST cursors.
"""
if not citer:
return
while True:
try:
item = next(citer)
except StopIteration:
return
# Check the source of item
if not item.location.file:
self.visit(item.get_children())
continue
# Ignore files we already processed
if str(item.location.file) in self.processed:
continue
# Ignore files other than the ones we are scanning for
if not str(item.location.file) in self.files:
continue
# Ignore unexposed things
if item.kind == cindex.CursorKind.UNEXPOSED_DECL:
self.visit(item.get_children(), parent)
continue
self.processing[str(item.location.file)] = True
if item.kind in self.kindmap:
cls = self.kindmap[item.kind]
if not cls:
# Skip
continue
# see if we already have a node for this thing
node = self.usr_to_node[item.get_usr()]
if not node or self.is_unique_anon_struct(node, parent):
# Only register new nodes if they are exposed.
if self.cursor_is_exposed(item):
node = cls(item, None)
self.register_node(node, parent)
elif isinstance(parent, nodes.Typedef) and isinstance(node, nodes.Struct):
# Typedefs are handled a bit specially because what happens
# is that clang first exposes an unnamed struct/enum, and
# then exposes the typedef, with as a child again the
# cursor to the already defined struct/enum. This is a
# bit reversed as to how we normally process things.
self.register_anon_typedef(node, parent)
else:
self.cursor_to_node[item] = node
node.add_ref(item)
if node and node.process_children:
self.visit(item.get_children(), node)
else:
par = self.cursor_to_node[item.semantic_parent]
if not par:
par = parent
if par:
ret = par.visit(item, citer)
if not ret is None:
for node in ret:
self.register_node(node, par)
ignoretop = [cindex.CursorKind.TYPE_REF, cindex.CursorKind.PARM_DECL]
if (not par or ret is None) and not item.kind in ignoretop:
log.warning("Unhandled cursor: %s", item.kind) | python | def visit(self, citer, parent=None):
"""
visit iterates over the provided cursor iterator and creates nodes
from the AST cursors.
"""
if not citer:
return
while True:
try:
item = next(citer)
except StopIteration:
return
# Check the source of item
if not item.location.file:
self.visit(item.get_children())
continue
# Ignore files we already processed
if str(item.location.file) in self.processed:
continue
# Ignore files other than the ones we are scanning for
if not str(item.location.file) in self.files:
continue
# Ignore unexposed things
if item.kind == cindex.CursorKind.UNEXPOSED_DECL:
self.visit(item.get_children(), parent)
continue
self.processing[str(item.location.file)] = True
if item.kind in self.kindmap:
cls = self.kindmap[item.kind]
if not cls:
# Skip
continue
# see if we already have a node for this thing
node = self.usr_to_node[item.get_usr()]
if not node or self.is_unique_anon_struct(node, parent):
# Only register new nodes if they are exposed.
if self.cursor_is_exposed(item):
node = cls(item, None)
self.register_node(node, parent)
elif isinstance(parent, nodes.Typedef) and isinstance(node, nodes.Struct):
# Typedefs are handled a bit specially because what happens
# is that clang first exposes an unnamed struct/enum, and
# then exposes the typedef, with as a child again the
# cursor to the already defined struct/enum. This is a
# bit reversed as to how we normally process things.
self.register_anon_typedef(node, parent)
else:
self.cursor_to_node[item] = node
node.add_ref(item)
if node and node.process_children:
self.visit(item.get_children(), node)
else:
par = self.cursor_to_node[item.semantic_parent]
if not par:
par = parent
if par:
ret = par.visit(item, citer)
if not ret is None:
for node in ret:
self.register_node(node, par)
ignoretop = [cindex.CursorKind.TYPE_REF, cindex.CursorKind.PARM_DECL]
if (not par or ret is None) and not item.kind in ignoretop:
log.warning("Unhandled cursor: %s", item.kind) | [
"def",
"visit",
"(",
"self",
",",
"citer",
",",
"parent",
"=",
"None",
")",
":",
"if",
"not",
"citer",
":",
"return",
"while",
"True",
":",
"try",
":",
"item",
"=",
"next",
"(",
"citer",
")",
"except",
"StopIteration",
":",
"return",
"# Check the source of item",
"if",
"not",
"item",
".",
"location",
".",
"file",
":",
"self",
".",
"visit",
"(",
"item",
".",
"get_children",
"(",
")",
")",
"continue",
"# Ignore files we already processed",
"if",
"str",
"(",
"item",
".",
"location",
".",
"file",
")",
"in",
"self",
".",
"processed",
":",
"continue",
"# Ignore files other than the ones we are scanning for",
"if",
"not",
"str",
"(",
"item",
".",
"location",
".",
"file",
")",
"in",
"self",
".",
"files",
":",
"continue",
"# Ignore unexposed things",
"if",
"item",
".",
"kind",
"==",
"cindex",
".",
"CursorKind",
".",
"UNEXPOSED_DECL",
":",
"self",
".",
"visit",
"(",
"item",
".",
"get_children",
"(",
")",
",",
"parent",
")",
"continue",
"self",
".",
"processing",
"[",
"str",
"(",
"item",
".",
"location",
".",
"file",
")",
"]",
"=",
"True",
"if",
"item",
".",
"kind",
"in",
"self",
".",
"kindmap",
":",
"cls",
"=",
"self",
".",
"kindmap",
"[",
"item",
".",
"kind",
"]",
"if",
"not",
"cls",
":",
"# Skip",
"continue",
"# see if we already have a node for this thing",
"node",
"=",
"self",
".",
"usr_to_node",
"[",
"item",
".",
"get_usr",
"(",
")",
"]",
"if",
"not",
"node",
"or",
"self",
".",
"is_unique_anon_struct",
"(",
"node",
",",
"parent",
")",
":",
"# Only register new nodes if they are exposed.",
"if",
"self",
".",
"cursor_is_exposed",
"(",
"item",
")",
":",
"node",
"=",
"cls",
"(",
"item",
",",
"None",
")",
"self",
".",
"register_node",
"(",
"node",
",",
"parent",
")",
"elif",
"isinstance",
"(",
"parent",
",",
"nodes",
".",
"Typedef",
")",
"and",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Struct",
")",
":",
"# Typedefs are handled a bit specially because what happens",
"# is that clang first exposes an unnamed struct/enum, and",
"# then exposes the typedef, with as a child again the",
"# cursor to the already defined struct/enum. This is a",
"# bit reversed as to how we normally process things.",
"self",
".",
"register_anon_typedef",
"(",
"node",
",",
"parent",
")",
"else",
":",
"self",
".",
"cursor_to_node",
"[",
"item",
"]",
"=",
"node",
"node",
".",
"add_ref",
"(",
"item",
")",
"if",
"node",
"and",
"node",
".",
"process_children",
":",
"self",
".",
"visit",
"(",
"item",
".",
"get_children",
"(",
")",
",",
"node",
")",
"else",
":",
"par",
"=",
"self",
".",
"cursor_to_node",
"[",
"item",
".",
"semantic_parent",
"]",
"if",
"not",
"par",
":",
"par",
"=",
"parent",
"if",
"par",
":",
"ret",
"=",
"par",
".",
"visit",
"(",
"item",
",",
"citer",
")",
"if",
"not",
"ret",
"is",
"None",
":",
"for",
"node",
"in",
"ret",
":",
"self",
".",
"register_node",
"(",
"node",
",",
"par",
")",
"ignoretop",
"=",
"[",
"cindex",
".",
"CursorKind",
".",
"TYPE_REF",
",",
"cindex",
".",
"CursorKind",
".",
"PARM_DECL",
"]",
"if",
"(",
"not",
"par",
"or",
"ret",
"is",
"None",
")",
"and",
"not",
"item",
".",
"kind",
"in",
"ignoretop",
":",
"log",
".",
"warning",
"(",
"\"Unhandled cursor: %s\"",
",",
"item",
".",
"kind",
")"
] | visit iterates over the provided cursor iterator and creates nodes
from the AST cursors. | [
"visit",
"iterates",
"over",
"the",
"provided",
"cursor",
"iterator",
"and",
"creates",
"nodes",
"from",
"the",
"AST",
"cursors",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/tree.py#L492-L571 |
jessevdk/cldoc | cldoc/comment.py | CommentsDatabase.extract | def extract(self, filename, tu):
"""
extract extracts comments from a translation unit for a given file by
iterating over all the tokens in the TU, locating the COMMENT tokens and
finding out to which cursors the comments semantically belong.
"""
it = tu.get_tokens(extent=tu.get_extent(filename, (0, int(os.stat(filename).st_size))))
while True:
try:
self.extract_loop(it)
except StopIteration:
break | python | def extract(self, filename, tu):
"""
extract extracts comments from a translation unit for a given file by
iterating over all the tokens in the TU, locating the COMMENT tokens and
finding out to which cursors the comments semantically belong.
"""
it = tu.get_tokens(extent=tu.get_extent(filename, (0, int(os.stat(filename).st_size))))
while True:
try:
self.extract_loop(it)
except StopIteration:
break | [
"def",
"extract",
"(",
"self",
",",
"filename",
",",
"tu",
")",
":",
"it",
"=",
"tu",
".",
"get_tokens",
"(",
"extent",
"=",
"tu",
".",
"get_extent",
"(",
"filename",
",",
"(",
"0",
",",
"int",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size",
")",
")",
")",
")",
"while",
"True",
":",
"try",
":",
"self",
".",
"extract_loop",
"(",
"it",
")",
"except",
"StopIteration",
":",
"break"
] | extract extracts comments from a translation unit for a given file by
iterating over all the tokens in the TU, locating the COMMENT tokens and
finding out to which cursors the comments semantically belong. | [
"extract",
"extracts",
"comments",
"from",
"a",
"translation",
"unit",
"for",
"a",
"given",
"file",
"by",
"iterating",
"over",
"all",
"the",
"tokens",
"in",
"the",
"TU",
"locating",
"the",
"COMMENT",
"tokens",
"and",
"finding",
"out",
"to",
"which",
"cursors",
"the",
"comments",
"semantically",
"belong",
"."
] | train | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/comment.py#L378-L390 |
ergoithz/browsepy | browsepy/manager.py | defaultsnamedtuple | def defaultsnamedtuple(name, fields, defaults=None):
'''
Generate namedtuple with default values.
:param name: name
:param fields: iterable with field names
:param defaults: iterable or mapping with field defaults
:returns: defaultdict with given fields and given defaults
:rtype: collections.defaultdict
'''
nt = collections.namedtuple(name, fields)
nt.__new__.__defaults__ = (None,) * len(nt._fields)
if isinstance(defaults, collections.Mapping):
nt.__new__.__defaults__ = tuple(nt(**defaults))
elif defaults:
nt.__new__.__defaults__ = tuple(nt(*defaults))
return nt | python | def defaultsnamedtuple(name, fields, defaults=None):
'''
Generate namedtuple with default values.
:param name: name
:param fields: iterable with field names
:param defaults: iterable or mapping with field defaults
:returns: defaultdict with given fields and given defaults
:rtype: collections.defaultdict
'''
nt = collections.namedtuple(name, fields)
nt.__new__.__defaults__ = (None,) * len(nt._fields)
if isinstance(defaults, collections.Mapping):
nt.__new__.__defaults__ = tuple(nt(**defaults))
elif defaults:
nt.__new__.__defaults__ = tuple(nt(*defaults))
return nt | [
"def",
"defaultsnamedtuple",
"(",
"name",
",",
"fields",
",",
"defaults",
"=",
"None",
")",
":",
"nt",
"=",
"collections",
".",
"namedtuple",
"(",
"name",
",",
"fields",
")",
"nt",
".",
"__new__",
".",
"__defaults__",
"=",
"(",
"None",
",",
")",
"*",
"len",
"(",
"nt",
".",
"_fields",
")",
"if",
"isinstance",
"(",
"defaults",
",",
"collections",
".",
"Mapping",
")",
":",
"nt",
".",
"__new__",
".",
"__defaults__",
"=",
"tuple",
"(",
"nt",
"(",
"*",
"*",
"defaults",
")",
")",
"elif",
"defaults",
":",
"nt",
".",
"__new__",
".",
"__defaults__",
"=",
"tuple",
"(",
"nt",
"(",
"*",
"defaults",
")",
")",
"return",
"nt"
] | Generate namedtuple with default values.
:param name: name
:param fields: iterable with field names
:param defaults: iterable or mapping with field defaults
:returns: defaultdict with given fields and given defaults
:rtype: collections.defaultdict | [
"Generate",
"namedtuple",
"with",
"default",
"values",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L18-L34 |
ergoithz/browsepy | browsepy/manager.py | PluginManagerBase.init_app | def init_app(self, app):
'''
Initialize this Flask extension for given app.
'''
self.app = app
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['plugin_manager'] = self
self.reload() | python | def init_app(self, app):
'''
Initialize this Flask extension for given app.
'''
self.app = app
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['plugin_manager'] = self
self.reload() | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"app",
"=",
"app",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'plugin_manager'",
"]",
"=",
"self",
"self",
".",
"reload",
"(",
")"
] | Initialize this Flask extension for given app. | [
"Initialize",
"this",
"Flask",
"extension",
"for",
"given",
"app",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L71-L79 |
ergoithz/browsepy | browsepy/manager.py | PluginManagerBase.reload | def reload(self):
'''
Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded.
'''
self.clear()
for plugin in self.app.config.get('plugin_modules', ()):
self.load_plugin(plugin) | python | def reload(self):
'''
Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded.
'''
self.clear()
for plugin in self.app.config.get('plugin_modules', ()):
self.load_plugin(plugin) | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"for",
"plugin",
"in",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'plugin_modules'",
",",
"(",
")",
")",
":",
"self",
".",
"load_plugin",
"(",
"plugin",
")"
] | Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded. | [
"Clear",
"plugin",
"manager",
"state",
"and",
"reload",
"plugins",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L81-L91 |
ergoithz/browsepy | browsepy/manager.py | PluginManagerBase.import_plugin | def import_plugin(self, plugin):
'''
Import plugin by given name, looking at :attr:`namespaces`.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace
'''
names = [
'%s%s%s' % (namespace, '' if namespace[-1] == '_' else '.', plugin)
if namespace else
plugin
for namespace in self.namespaces
]
for name in names:
if name in sys.modules:
return sys.modules[name]
for name in names:
try:
__import__(name)
return sys.modules[name]
except (ImportError, KeyError):
pass
raise PluginNotFoundError(
'No plugin module %r found, tried %r' % (plugin, names),
plugin, names) | python | def import_plugin(self, plugin):
'''
Import plugin by given name, looking at :attr:`namespaces`.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace
'''
names = [
'%s%s%s' % (namespace, '' if namespace[-1] == '_' else '.', plugin)
if namespace else
plugin
for namespace in self.namespaces
]
for name in names:
if name in sys.modules:
return sys.modules[name]
for name in names:
try:
__import__(name)
return sys.modules[name]
except (ImportError, KeyError):
pass
raise PluginNotFoundError(
'No plugin module %r found, tried %r' % (plugin, names),
plugin, names) | [
"def",
"import_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"names",
"=",
"[",
"'%s%s%s'",
"%",
"(",
"namespace",
",",
"''",
"if",
"namespace",
"[",
"-",
"1",
"]",
"==",
"'_'",
"else",
"'.'",
",",
"plugin",
")",
"if",
"namespace",
"else",
"plugin",
"for",
"namespace",
"in",
"self",
".",
"namespaces",
"]",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"name",
"]",
"for",
"name",
"in",
"names",
":",
"try",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]",
"except",
"(",
"ImportError",
",",
"KeyError",
")",
":",
"pass",
"raise",
"PluginNotFoundError",
"(",
"'No plugin module %r found, tried %r'",
"%",
"(",
"plugin",
",",
"names",
")",
",",
"plugin",
",",
"names",
")"
] | Import plugin by given name, looking at :attr:`namespaces`.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace | [
"Import",
"plugin",
"by",
"given",
"name",
"looking",
"at",
":",
"attr",
":",
"namespaces",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L99-L127 |
ergoithz/browsepy | browsepy/manager.py | RegistrablePluginManager.load_plugin | def load_plugin(self, plugin):
'''
Import plugin (see :meth:`import_plugin`) and load related data.
If available, plugin's module-level :func:`register_plugin` function
will be called with current plugin manager instance as first argument.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace
'''
module = super(RegistrablePluginManager, self).load_plugin(plugin)
if hasattr(module, 'register_plugin'):
module.register_plugin(self)
return module | python | def load_plugin(self, plugin):
'''
Import plugin (see :meth:`import_plugin`) and load related data.
If available, plugin's module-level :func:`register_plugin` function
will be called with current plugin manager instance as first argument.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace
'''
module = super(RegistrablePluginManager, self).load_plugin(plugin)
if hasattr(module, 'register_plugin'):
module.register_plugin(self)
return module | [
"def",
"load_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"module",
"=",
"super",
"(",
"RegistrablePluginManager",
",",
"self",
")",
".",
"load_plugin",
"(",
"plugin",
")",
"if",
"hasattr",
"(",
"module",
",",
"'register_plugin'",
")",
":",
"module",
".",
"register_plugin",
"(",
"self",
")",
"return",
"module"
] | Import plugin (see :meth:`import_plugin`) and load related data.
If available, plugin's module-level :func:`register_plugin` function
will be called with current plugin manager instance as first argument.
:param plugin: plugin module name
:type plugin: str
:raises PluginNotFoundError: if not found on any namespace | [
"Import",
"plugin",
"(",
"see",
":",
"meth",
":",
"import_plugin",
")",
"and",
"load",
"related",
"data",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L145-L159 |
ergoithz/browsepy | browsepy/manager.py | BlueprintPluginManager.register_blueprint | def register_blueprint(self, blueprint):
'''
Register given blueprint on curren app.
This method is provided for using inside plugin's module-level
:func:`register_plugin` functions.
:param blueprint: blueprint object with plugin endpoints
:type blueprint: flask.Blueprint
'''
if blueprint not in self._blueprint_known:
self.app.register_blueprint(blueprint)
self._blueprint_known.add(blueprint) | python | def register_blueprint(self, blueprint):
'''
Register given blueprint on curren app.
This method is provided for using inside plugin's module-level
:func:`register_plugin` functions.
:param blueprint: blueprint object with plugin endpoints
:type blueprint: flask.Blueprint
'''
if blueprint not in self._blueprint_known:
self.app.register_blueprint(blueprint)
self._blueprint_known.add(blueprint) | [
"def",
"register_blueprint",
"(",
"self",
",",
"blueprint",
")",
":",
"if",
"blueprint",
"not",
"in",
"self",
".",
"_blueprint_known",
":",
"self",
".",
"app",
".",
"register_blueprint",
"(",
"blueprint",
")",
"self",
".",
"_blueprint_known",
".",
"add",
"(",
"blueprint",
")"
] | Register given blueprint on curren app.
This method is provided for using inside plugin's module-level
:func:`register_plugin` functions.
:param blueprint: blueprint object with plugin endpoints
:type blueprint: flask.Blueprint | [
"Register",
"given",
"blueprint",
"on",
"curren",
"app",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L173-L185 |
ergoithz/browsepy | browsepy/manager.py | WidgetPluginManager._resolve_widget | def _resolve_widget(cls, file, widget):
'''
Resolve widget callable properties into static ones.
:param file: file will be used to resolve callable properties.
:type file: browsepy.file.Node
:param widget: widget instance optionally with callable properties
:type widget: object
:returns: a new widget instance of the same type as widget parameter
:rtype: object
'''
return widget.__class__(*[
value(file) if callable(value) else value
for value in widget
]) | python | def _resolve_widget(cls, file, widget):
'''
Resolve widget callable properties into static ones.
:param file: file will be used to resolve callable properties.
:type file: browsepy.file.Node
:param widget: widget instance optionally with callable properties
:type widget: object
:returns: a new widget instance of the same type as widget parameter
:rtype: object
'''
return widget.__class__(*[
value(file) if callable(value) else value
for value in widget
]) | [
"def",
"_resolve_widget",
"(",
"cls",
",",
"file",
",",
"widget",
")",
":",
"return",
"widget",
".",
"__class__",
"(",
"*",
"[",
"value",
"(",
"file",
")",
"if",
"callable",
"(",
"value",
")",
"else",
"value",
"for",
"value",
"in",
"widget",
"]",
")"
] | Resolve widget callable properties into static ones.
:param file: file will be used to resolve callable properties.
:type file: browsepy.file.Node
:param widget: widget instance optionally with callable properties
:type widget: object
:returns: a new widget instance of the same type as widget parameter
:rtype: object | [
"Resolve",
"widget",
"callable",
"properties",
"into",
"static",
"ones",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L256-L270 |
ergoithz/browsepy | browsepy/manager.py | WidgetPluginManager.iter_widgets | def iter_widgets(self, file=None, place=None):
'''
Iterate registered widgets, optionally matching given criteria.
:param file: optional file object will be passed to widgets' filter
functions.
:type file: browsepy.file.Node or None
:param place: optional template place hint.
:type place: str
:yields: widget instances
:ytype: object
'''
for filter, dynamic, cwidget in self._widgets:
try:
if file and filter and not filter(file):
continue
except BaseException as e:
# Exception is handled as this method execution is deffered,
# making hard to debug for plugin developers.
warnings.warn(
'Plugin action filtering failed with error: %s' % e,
RuntimeWarning
)
continue
if place and place != cwidget.place:
continue
if file and dynamic:
cwidget = self._resolve_widget(file, cwidget)
yield cwidget | python | def iter_widgets(self, file=None, place=None):
'''
Iterate registered widgets, optionally matching given criteria.
:param file: optional file object will be passed to widgets' filter
functions.
:type file: browsepy.file.Node or None
:param place: optional template place hint.
:type place: str
:yields: widget instances
:ytype: object
'''
for filter, dynamic, cwidget in self._widgets:
try:
if file and filter and not filter(file):
continue
except BaseException as e:
# Exception is handled as this method execution is deffered,
# making hard to debug for plugin developers.
warnings.warn(
'Plugin action filtering failed with error: %s' % e,
RuntimeWarning
)
continue
if place and place != cwidget.place:
continue
if file and dynamic:
cwidget = self._resolve_widget(file, cwidget)
yield cwidget | [
"def",
"iter_widgets",
"(",
"self",
",",
"file",
"=",
"None",
",",
"place",
"=",
"None",
")",
":",
"for",
"filter",
",",
"dynamic",
",",
"cwidget",
"in",
"self",
".",
"_widgets",
":",
"try",
":",
"if",
"file",
"and",
"filter",
"and",
"not",
"filter",
"(",
"file",
")",
":",
"continue",
"except",
"BaseException",
"as",
"e",
":",
"# Exception is handled as this method execution is deffered,",
"# making hard to debug for plugin developers.",
"warnings",
".",
"warn",
"(",
"'Plugin action filtering failed with error: %s'",
"%",
"e",
",",
"RuntimeWarning",
")",
"continue",
"if",
"place",
"and",
"place",
"!=",
"cwidget",
".",
"place",
":",
"continue",
"if",
"file",
"and",
"dynamic",
":",
"cwidget",
"=",
"self",
".",
"_resolve_widget",
"(",
"file",
",",
"cwidget",
")",
"yield",
"cwidget"
] | Iterate registered widgets, optionally matching given criteria.
:param file: optional file object will be passed to widgets' filter
functions.
:type file: browsepy.file.Node or None
:param place: optional template place hint.
:type place: str
:yields: widget instances
:ytype: object | [
"Iterate",
"registered",
"widgets",
"optionally",
"matching",
"given",
"criteria",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L272-L300 |
ergoithz/browsepy | browsepy/manager.py | WidgetPluginManager.create_widget | def create_widget(self, place, type, file=None, **kwargs):
'''
Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwargs` parameters will be passed to widget constructor.
:param place: place hint where widget should be shown.
:type place: str
:param type: widget type name as taken from :attr:`widget_types` dict
keys.
:type type: str
:param file: optional file object for widget attribute resolving
:type type: browsepy.files.Node or None
:returns: widget instance
:rtype: object
'''
widget_class = self.widget_types.get(type, self.widget_types['base'])
kwargs.update(place=place, type=type)
try:
element = widget_class(**kwargs)
except TypeError as e:
message = e.args[0] if e.args else ''
if (
'unexpected keyword argument' in message or
'required positional argument' in message
):
raise WidgetParameterException(
'type %s; %s; available: %r'
% (type, message, widget_class._fields)
)
raise e
if file and any(map(callable, element)):
return self._resolve_widget(file, element)
return element | python | def create_widget(self, place, type, file=None, **kwargs):
'''
Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwargs` parameters will be passed to widget constructor.
:param place: place hint where widget should be shown.
:type place: str
:param type: widget type name as taken from :attr:`widget_types` dict
keys.
:type type: str
:param file: optional file object for widget attribute resolving
:type type: browsepy.files.Node or None
:returns: widget instance
:rtype: object
'''
widget_class = self.widget_types.get(type, self.widget_types['base'])
kwargs.update(place=place, type=type)
try:
element = widget_class(**kwargs)
except TypeError as e:
message = e.args[0] if e.args else ''
if (
'unexpected keyword argument' in message or
'required positional argument' in message
):
raise WidgetParameterException(
'type %s; %s; available: %r'
% (type, message, widget_class._fields)
)
raise e
if file and any(map(callable, element)):
return self._resolve_widget(file, element)
return element | [
"def",
"create_widget",
"(",
"self",
",",
"place",
",",
"type",
",",
"file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"widget_class",
"=",
"self",
".",
"widget_types",
".",
"get",
"(",
"type",
",",
"self",
".",
"widget_types",
"[",
"'base'",
"]",
")",
"kwargs",
".",
"update",
"(",
"place",
"=",
"place",
",",
"type",
"=",
"type",
")",
"try",
":",
"element",
"=",
"widget_class",
"(",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
"as",
"e",
":",
"message",
"=",
"e",
".",
"args",
"[",
"0",
"]",
"if",
"e",
".",
"args",
"else",
"''",
"if",
"(",
"'unexpected keyword argument'",
"in",
"message",
"or",
"'required positional argument'",
"in",
"message",
")",
":",
"raise",
"WidgetParameterException",
"(",
"'type %s; %s; available: %r'",
"%",
"(",
"type",
",",
"message",
",",
"widget_class",
".",
"_fields",
")",
")",
"raise",
"e",
"if",
"file",
"and",
"any",
"(",
"map",
"(",
"callable",
",",
"element",
")",
")",
":",
"return",
"self",
".",
"_resolve_widget",
"(",
"file",
",",
"element",
")",
"return",
"element"
] | Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwargs` parameters will be passed to widget constructor.
:param place: place hint where widget should be shown.
:type place: str
:param type: widget type name as taken from :attr:`widget_types` dict
keys.
:type type: str
:param file: optional file object for widget attribute resolving
:type type: browsepy.files.Node or None
:returns: widget instance
:rtype: object | [
"Create",
"a",
"widget",
"object",
"based",
"on",
"given",
"arguments",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L302-L339 |
ergoithz/browsepy | browsepy/manager.py | WidgetPluginManager.register_widget | def register_widget(self, place=None, type=None, widget=None, filter=None,
**kwargs):
'''
Create (see :meth:`create_widget`) or use provided widget and register
it.
This method provides this dual behavior in order to simplify widget
creation-registration on an functional single step without sacrifycing
the reusability of a object-oriented approach.
:param place: where widget should be placed. This param conflicts
with `widget` argument.
:type place: str or None
:param type: widget type name as taken from :attr:`widget_types` dict
keys. This param conflicts with `widget` argument.
:type type: str or None
:param widget: optional widget object will be used as is. This param
conflicts with both place and type arguments.
:type widget: object or None
:raises TypeError: if both widget and place or type are provided at
the same time (they're mutually exclusive).
:returns: created or given widget object
:rtype: object
'''
if bool(widget) == bool(place or type):
raise InvalidArgumentError(
'register_widget takes either place and type or widget'
)
widget = widget or self.create_widget(place, type, **kwargs)
dynamic = any(map(callable, widget))
self._widgets.append((filter, dynamic, widget))
return widget | python | def register_widget(self, place=None, type=None, widget=None, filter=None,
**kwargs):
'''
Create (see :meth:`create_widget`) or use provided widget and register
it.
This method provides this dual behavior in order to simplify widget
creation-registration on an functional single step without sacrifycing
the reusability of a object-oriented approach.
:param place: where widget should be placed. This param conflicts
with `widget` argument.
:type place: str or None
:param type: widget type name as taken from :attr:`widget_types` dict
keys. This param conflicts with `widget` argument.
:type type: str or None
:param widget: optional widget object will be used as is. This param
conflicts with both place and type arguments.
:type widget: object or None
:raises TypeError: if both widget and place or type are provided at
the same time (they're mutually exclusive).
:returns: created or given widget object
:rtype: object
'''
if bool(widget) == bool(place or type):
raise InvalidArgumentError(
'register_widget takes either place and type or widget'
)
widget = widget or self.create_widget(place, type, **kwargs)
dynamic = any(map(callable, widget))
self._widgets.append((filter, dynamic, widget))
return widget | [
"def",
"register_widget",
"(",
"self",
",",
"place",
"=",
"None",
",",
"type",
"=",
"None",
",",
"widget",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"bool",
"(",
"widget",
")",
"==",
"bool",
"(",
"place",
"or",
"type",
")",
":",
"raise",
"InvalidArgumentError",
"(",
"'register_widget takes either place and type or widget'",
")",
"widget",
"=",
"widget",
"or",
"self",
".",
"create_widget",
"(",
"place",
",",
"type",
",",
"*",
"*",
"kwargs",
")",
"dynamic",
"=",
"any",
"(",
"map",
"(",
"callable",
",",
"widget",
")",
")",
"self",
".",
"_widgets",
".",
"append",
"(",
"(",
"filter",
",",
"dynamic",
",",
"widget",
")",
")",
"return",
"widget"
] | Create (see :meth:`create_widget`) or use provided widget and register
it.
This method provides this dual behavior in order to simplify widget
creation-registration on an functional single step without sacrifycing
the reusability of a object-oriented approach.
:param place: where widget should be placed. This param conflicts
with `widget` argument.
:type place: str or None
:param type: widget type name as taken from :attr:`widget_types` dict
keys. This param conflicts with `widget` argument.
:type type: str or None
:param widget: optional widget object will be used as is. This param
conflicts with both place and type arguments.
:type widget: object or None
:raises TypeError: if both widget and place or type are provided at
the same time (they're mutually exclusive).
:returns: created or given widget object
:rtype: object | [
"Create",
"(",
"see",
":",
"meth",
":",
"create_widget",
")",
"or",
"use",
"provided",
"widget",
"and",
"register",
"it",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L341-L372 |
ergoithz/browsepy | browsepy/manager.py | MimetypePluginManager.clear | def clear(self):
'''
Clear plugin manager state.
Registered mimetype functions will be disposed after calling this
method.
'''
self._mimetype_functions = list(self._default_mimetype_functions)
super(MimetypePluginManager, self).clear() | python | def clear(self):
'''
Clear plugin manager state.
Registered mimetype functions will be disposed after calling this
method.
'''
self._mimetype_functions = list(self._default_mimetype_functions)
super(MimetypePluginManager, self).clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_mimetype_functions",
"=",
"list",
"(",
"self",
".",
"_default_mimetype_functions",
")",
"super",
"(",
"MimetypePluginManager",
",",
"self",
")",
".",
"clear",
"(",
")"
] | Clear plugin manager state.
Registered mimetype functions will be disposed after calling this
method. | [
"Clear",
"plugin",
"manager",
"state",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L385-L393 |
ergoithz/browsepy | browsepy/manager.py | MimetypePluginManager.get_mimetype | def get_mimetype(self, path):
'''
Get mimetype of given path calling all registered mime functions (and
default ones).
:param path: filesystem path of file
:type path: str
:returns: mimetype
:rtype: str
'''
for fnc in self._mimetype_functions:
mime = fnc(path)
if mime:
return mime
return mimetype.by_default(path) | python | def get_mimetype(self, path):
'''
Get mimetype of given path calling all registered mime functions (and
default ones).
:param path: filesystem path of file
:type path: str
:returns: mimetype
:rtype: str
'''
for fnc in self._mimetype_functions:
mime = fnc(path)
if mime:
return mime
return mimetype.by_default(path) | [
"def",
"get_mimetype",
"(",
"self",
",",
"path",
")",
":",
"for",
"fnc",
"in",
"self",
".",
"_mimetype_functions",
":",
"mime",
"=",
"fnc",
"(",
"path",
")",
"if",
"mime",
":",
"return",
"mime",
"return",
"mimetype",
".",
"by_default",
"(",
"path",
")"
] | Get mimetype of given path calling all registered mime functions (and
default ones).
:param path: filesystem path of file
:type path: str
:returns: mimetype
:rtype: str | [
"Get",
"mimetype",
"of",
"given",
"path",
"calling",
"all",
"registered",
"mime",
"functions",
"(",
"and",
"default",
"ones",
")",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L395-L409 |
ergoithz/browsepy | browsepy/manager.py | ArgumentPluginManager.extract_plugin_arguments | def extract_plugin_arguments(self, plugin):
'''
Given a plugin name, extracts its registered_arguments as an
iterable of (args, kwargs) tuples.
:param plugin: plugin name
:type plugin: str
:returns: iterable if (args, kwargs) tuples.
:rtype: iterable
'''
module = self.import_plugin(plugin)
if hasattr(module, 'register_arguments'):
manager = ArgumentPluginManager()
module.register_arguments(manager)
return manager._argparse_argkwargs
return () | python | def extract_plugin_arguments(self, plugin):
'''
Given a plugin name, extracts its registered_arguments as an
iterable of (args, kwargs) tuples.
:param plugin: plugin name
:type plugin: str
:returns: iterable if (args, kwargs) tuples.
:rtype: iterable
'''
module = self.import_plugin(plugin)
if hasattr(module, 'register_arguments'):
manager = ArgumentPluginManager()
module.register_arguments(manager)
return manager._argparse_argkwargs
return () | [
"def",
"extract_plugin_arguments",
"(",
"self",
",",
"plugin",
")",
":",
"module",
"=",
"self",
".",
"import_plugin",
"(",
"plugin",
")",
"if",
"hasattr",
"(",
"module",
",",
"'register_arguments'",
")",
":",
"manager",
"=",
"ArgumentPluginManager",
"(",
")",
"module",
".",
"register_arguments",
"(",
"manager",
")",
"return",
"manager",
".",
"_argparse_argkwargs",
"return",
"(",
")"
] | Given a plugin name, extracts its registered_arguments as an
iterable of (args, kwargs) tuples.
:param plugin: plugin name
:type plugin: str
:returns: iterable if (args, kwargs) tuples.
:rtype: iterable | [
"Given",
"a",
"plugin",
"name",
"extracts",
"its",
"registered_arguments",
"as",
"an",
"iterable",
"of",
"(",
"args",
"kwargs",
")",
"tuples",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L438-L453 |
ergoithz/browsepy | browsepy/manager.py | ArgumentPluginManager.load_arguments | def load_arguments(self, argv, base=None):
'''
Process given argument list based on registered arguments and given
optional base :class:`argparse.ArgumentParser` instance.
This method saves processed arguments on itself, and this state won't
be lost after :meth:`clean` calls.
Processed argument state will be available via :meth:`get_argument`
method.
:param argv: command-line arguments (without command itself)
:type argv: iterable of str
:param base: optional base :class:`argparse.ArgumentParser` instance.
:type base: argparse.ArgumentParser or None
:returns: argparse.Namespace instance with processed arguments as
given by :meth:`argparse.ArgumentParser.parse_args`.
:rtype: argparse.Namespace
'''
plugin_parser = argparse.ArgumentParser(add_help=False)
plugin_parser.add_argument('--plugin', action='append', default=[])
parent = base or plugin_parser
parser = argparse.ArgumentParser(
parents=(parent,),
add_help=False,
**getattr(parent, 'defaults', {})
)
plugins = [
plugin
for plugins in plugin_parser.parse_known_args(argv)[0].plugin
for plugin in plugins.split(',')
]
for plugin in sorted(set(plugins), key=plugins.index):
arguments = self.extract_plugin_arguments(plugin)
if arguments:
group = parser.add_argument_group('%s arguments' % plugin)
for argargs, argkwargs in arguments:
group.add_argument(*argargs, **argkwargs)
self._argparse_arguments = parser.parse_args(argv)
return self._argparse_arguments | python | def load_arguments(self, argv, base=None):
'''
Process given argument list based on registered arguments and given
optional base :class:`argparse.ArgumentParser` instance.
This method saves processed arguments on itself, and this state won't
be lost after :meth:`clean` calls.
Processed argument state will be available via :meth:`get_argument`
method.
:param argv: command-line arguments (without command itself)
:type argv: iterable of str
:param base: optional base :class:`argparse.ArgumentParser` instance.
:type base: argparse.ArgumentParser or None
:returns: argparse.Namespace instance with processed arguments as
given by :meth:`argparse.ArgumentParser.parse_args`.
:rtype: argparse.Namespace
'''
plugin_parser = argparse.ArgumentParser(add_help=False)
plugin_parser.add_argument('--plugin', action='append', default=[])
parent = base or plugin_parser
parser = argparse.ArgumentParser(
parents=(parent,),
add_help=False,
**getattr(parent, 'defaults', {})
)
plugins = [
plugin
for plugins in plugin_parser.parse_known_args(argv)[0].plugin
for plugin in plugins.split(',')
]
for plugin in sorted(set(plugins), key=plugins.index):
arguments = self.extract_plugin_arguments(plugin)
if arguments:
group = parser.add_argument_group('%s arguments' % plugin)
for argargs, argkwargs in arguments:
group.add_argument(*argargs, **argkwargs)
self._argparse_arguments = parser.parse_args(argv)
return self._argparse_arguments | [
"def",
"load_arguments",
"(",
"self",
",",
"argv",
",",
"base",
"=",
"None",
")",
":",
"plugin_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"plugin_parser",
".",
"add_argument",
"(",
"'--plugin'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
")",
"parent",
"=",
"base",
"or",
"plugin_parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"parents",
"=",
"(",
"parent",
",",
")",
",",
"add_help",
"=",
"False",
",",
"*",
"*",
"getattr",
"(",
"parent",
",",
"'defaults'",
",",
"{",
"}",
")",
")",
"plugins",
"=",
"[",
"plugin",
"for",
"plugins",
"in",
"plugin_parser",
".",
"parse_known_args",
"(",
"argv",
")",
"[",
"0",
"]",
".",
"plugin",
"for",
"plugin",
"in",
"plugins",
".",
"split",
"(",
"','",
")",
"]",
"for",
"plugin",
"in",
"sorted",
"(",
"set",
"(",
"plugins",
")",
",",
"key",
"=",
"plugins",
".",
"index",
")",
":",
"arguments",
"=",
"self",
".",
"extract_plugin_arguments",
"(",
"plugin",
")",
"if",
"arguments",
":",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'%s arguments'",
"%",
"plugin",
")",
"for",
"argargs",
",",
"argkwargs",
"in",
"arguments",
":",
"group",
".",
"add_argument",
"(",
"*",
"argargs",
",",
"*",
"*",
"argkwargs",
")",
"self",
".",
"_argparse_arguments",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"return",
"self",
".",
"_argparse_arguments"
] | Process given argument list based on registered arguments and given
optional base :class:`argparse.ArgumentParser` instance.
This method saves processed arguments on itself, and this state won't
be lost after :meth:`clean` calls.
Processed argument state will be available via :meth:`get_argument`
method.
:param argv: command-line arguments (without command itself)
:type argv: iterable of str
:param base: optional base :class:`argparse.ArgumentParser` instance.
:type base: argparse.ArgumentParser or None
:returns: argparse.Namespace instance with processed arguments as
given by :meth:`argparse.ArgumentParser.parse_args`.
:rtype: argparse.Namespace | [
"Process",
"given",
"argument",
"list",
"based",
"on",
"registered",
"arguments",
"and",
"given",
"optional",
"base",
":",
"class",
":",
"argparse",
".",
"ArgumentParser",
"instance",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L455-L494 |
ergoithz/browsepy | browsepy/__init__.py | iter_cookie_browse_sorting | def iter_cookie_browse_sorting(cookies):
'''
Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings
'''
try:
data = cookies.get('browse-sorting', 'e30=').encode('ascii')
for path, prop in json.loads(base64.b64decode(data).decode('utf-8')):
yield path, prop
except (ValueError, TypeError, KeyError) as e:
logger.exception(e) | python | def iter_cookie_browse_sorting(cookies):
'''
Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings
'''
try:
data = cookies.get('browse-sorting', 'e30=').encode('ascii')
for path, prop in json.loads(base64.b64decode(data).decode('utf-8')):
yield path, prop
except (ValueError, TypeError, KeyError) as e:
logger.exception(e) | [
"def",
"iter_cookie_browse_sorting",
"(",
"cookies",
")",
":",
"try",
":",
"data",
"=",
"cookies",
".",
"get",
"(",
"'browse-sorting'",
",",
"'e30='",
")",
".",
"encode",
"(",
"'ascii'",
")",
"for",
"path",
",",
"prop",
"in",
"json",
".",
"loads",
"(",
"base64",
".",
"b64decode",
"(",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")",
":",
"yield",
"path",
",",
"prop",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")"
] | Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings | [
"Get",
"sorting",
"-",
"cookie",
"from",
"cookies",
"dictionary",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/__init__.py#L61-L73 |
ergoithz/browsepy | browsepy/__init__.py | get_cookie_browse_sorting | def get_cookie_browse_sorting(path, default):
'''
Get sorting-cookie data for path of current request.
:returns: sorting property
:rtype: string
'''
if request:
for cpath, cprop in iter_cookie_browse_sorting(request.cookies):
if path == cpath:
return cprop
return default | python | def get_cookie_browse_sorting(path, default):
'''
Get sorting-cookie data for path of current request.
:returns: sorting property
:rtype: string
'''
if request:
for cpath, cprop in iter_cookie_browse_sorting(request.cookies):
if path == cpath:
return cprop
return default | [
"def",
"get_cookie_browse_sorting",
"(",
"path",
",",
"default",
")",
":",
"if",
"request",
":",
"for",
"cpath",
",",
"cprop",
"in",
"iter_cookie_browse_sorting",
"(",
"request",
".",
"cookies",
")",
":",
"if",
"path",
"==",
"cpath",
":",
"return",
"cprop",
"return",
"default"
] | Get sorting-cookie data for path of current request.
:returns: sorting property
:rtype: string | [
"Get",
"sorting",
"-",
"cookie",
"data",
"for",
"path",
"of",
"current",
"request",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/__init__.py#L76-L87 |
ergoithz/browsepy | browsepy/__init__.py | browse_sortkey_reverse | def browse_sortkey_reverse(prop):
'''
Get sorting function for directory listing based on given attribute
name, with some caveats:
* Directories will be first.
* If *name* is given, link widget lowercase text will be used istead.
* If *size* is given, bytesize will be used.
:param prop: file attribute name
:returns: tuple with sorting gunction and reverse bool
:rtype: tuple of a dict and a bool
'''
if prop.startswith('-'):
prop = prop[1:]
reverse = True
else:
reverse = False
if prop == 'text':
return (
lambda x: (
x.is_directory == reverse,
x.link.text.lower() if x.link and x.link.text else x.name
),
reverse
)
if prop == 'size':
return (
lambda x: (
x.is_directory == reverse,
x.stats.st_size
),
reverse
)
return (
lambda x: (
x.is_directory == reverse,
getattr(x, prop, None)
),
reverse
) | python | def browse_sortkey_reverse(prop):
'''
Get sorting function for directory listing based on given attribute
name, with some caveats:
* Directories will be first.
* If *name* is given, link widget lowercase text will be used istead.
* If *size* is given, bytesize will be used.
:param prop: file attribute name
:returns: tuple with sorting gunction and reverse bool
:rtype: tuple of a dict and a bool
'''
if prop.startswith('-'):
prop = prop[1:]
reverse = True
else:
reverse = False
if prop == 'text':
return (
lambda x: (
x.is_directory == reverse,
x.link.text.lower() if x.link and x.link.text else x.name
),
reverse
)
if prop == 'size':
return (
lambda x: (
x.is_directory == reverse,
x.stats.st_size
),
reverse
)
return (
lambda x: (
x.is_directory == reverse,
getattr(x, prop, None)
),
reverse
) | [
"def",
"browse_sortkey_reverse",
"(",
"prop",
")",
":",
"if",
"prop",
".",
"startswith",
"(",
"'-'",
")",
":",
"prop",
"=",
"prop",
"[",
"1",
":",
"]",
"reverse",
"=",
"True",
"else",
":",
"reverse",
"=",
"False",
"if",
"prop",
"==",
"'text'",
":",
"return",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"is_directory",
"==",
"reverse",
",",
"x",
".",
"link",
".",
"text",
".",
"lower",
"(",
")",
"if",
"x",
".",
"link",
"and",
"x",
".",
"link",
".",
"text",
"else",
"x",
".",
"name",
")",
",",
"reverse",
")",
"if",
"prop",
"==",
"'size'",
":",
"return",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"is_directory",
"==",
"reverse",
",",
"x",
".",
"stats",
".",
"st_size",
")",
",",
"reverse",
")",
"return",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"is_directory",
"==",
"reverse",
",",
"getattr",
"(",
"x",
",",
"prop",
",",
"None",
")",
")",
",",
"reverse",
")"
] | Get sorting function for directory listing based on given attribute
name, with some caveats:
* Directories will be first.
* If *name* is given, link widget lowercase text will be used istead.
* If *size* is given, bytesize will be used.
:param prop: file attribute name
:returns: tuple with sorting gunction and reverse bool
:rtype: tuple of a dict and a bool | [
"Get",
"sorting",
"function",
"for",
"directory",
"listing",
"based",
"on",
"given",
"attribute",
"name",
"with",
"some",
"caveats",
":",
"*",
"Directories",
"will",
"be",
"first",
".",
"*",
"If",
"*",
"name",
"*",
"is",
"given",
"link",
"widget",
"lowercase",
"text",
"will",
"be",
"used",
"istead",
".",
"*",
"If",
"*",
"size",
"*",
"is",
"given",
"bytesize",
"will",
"be",
"used",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/__init__.py#L90-L130 |
ergoithz/browsepy | browsepy/__init__.py | stream_template | def stream_template(template_name, **context):
'''
Some templates can be huge, this function returns an streaming response,
sending the content in chunks and preventing from timeout.
:param template_name: template
:param **context: parameters for templates.
:yields: HTML strings
'''
app.update_template_context(context)
template = app.jinja_env.get_template(template_name)
stream = template.generate(context)
return Response(stream_with_context(stream)) | python | def stream_template(template_name, **context):
'''
Some templates can be huge, this function returns an streaming response,
sending the content in chunks and preventing from timeout.
:param template_name: template
:param **context: parameters for templates.
:yields: HTML strings
'''
app.update_template_context(context)
template = app.jinja_env.get_template(template_name)
stream = template.generate(context)
return Response(stream_with_context(stream)) | [
"def",
"stream_template",
"(",
"template_name",
",",
"*",
"*",
"context",
")",
":",
"app",
".",
"update_template_context",
"(",
"context",
")",
"template",
"=",
"app",
".",
"jinja_env",
".",
"get_template",
"(",
"template_name",
")",
"stream",
"=",
"template",
".",
"generate",
"(",
"context",
")",
"return",
"Response",
"(",
"stream_with_context",
"(",
"stream",
")",
")"
] | Some templates can be huge, this function returns an streaming response,
sending the content in chunks and preventing from timeout.
:param template_name: template
:param **context: parameters for templates.
:yields: HTML strings | [
"Some",
"templates",
"can",
"be",
"huge",
"this",
"function",
"returns",
"an",
"streaming",
"response",
"sending",
"the",
"content",
"in",
"chunks",
"and",
"preventing",
"from",
"timeout",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/__init__.py#L133-L145 |
ergoithz/browsepy | browsepy/appconfig.py | Config.gendict | def gendict(cls, *args, **kwargs):
'''
Pre-translated key dictionary constructor.
See :type:`dict` for more info.
:returns: dictionary with uppercase keys
:rtype: dict
'''
gk = cls.genkey
return dict((gk(k), v) for k, v in dict(*args, **kwargs).items()) | python | def gendict(cls, *args, **kwargs):
'''
Pre-translated key dictionary constructor.
See :type:`dict` for more info.
:returns: dictionary with uppercase keys
:rtype: dict
'''
gk = cls.genkey
return dict((gk(k), v) for k, v in dict(*args, **kwargs).items()) | [
"def",
"gendict",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"gk",
"=",
"cls",
".",
"genkey",
"return",
"dict",
"(",
"(",
"gk",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"items",
"(",
")",
")"
] | Pre-translated key dictionary constructor.
See :type:`dict` for more info.
:returns: dictionary with uppercase keys
:rtype: dict | [
"Pre",
"-",
"translated",
"key",
"dictionary",
"constructor",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/appconfig.py#L31-L41 |
ergoithz/browsepy | browsepy/transform/__init__.py | StateMachine.nearest | def nearest(self):
'''
Get the next state jump.
The next jump is calculated looking at :attr:`current` state
and its possible :attr:`jumps` to find the nearest and bigger
option in :attr:`pending` data.
If none is found, the returned next state label will be None.
:returns: tuple with index, substring and next state label
:rtype: tuple
'''
try:
options = self.jumps[self.current]
except KeyError:
raise KeyError(
'Current state %r not defined in %s.jumps.'
% (self.current, self.__class__)
)
offset = len(self.start)
index = len(self.pending)
if self.streaming:
index -= max(map(len, options))
key = (index, 1)
result = (index, '', None)
for amark, anext in options.items():
asize = len(amark)
aindex = self.pending.find(amark, offset, index + asize)
if aindex > -1:
index = aindex
akey = (aindex, -asize)
if akey < key:
key = akey
result = (aindex, amark, anext)
return result | python | def nearest(self):
'''
Get the next state jump.
The next jump is calculated looking at :attr:`current` state
and its possible :attr:`jumps` to find the nearest and bigger
option in :attr:`pending` data.
If none is found, the returned next state label will be None.
:returns: tuple with index, substring and next state label
:rtype: tuple
'''
try:
options = self.jumps[self.current]
except KeyError:
raise KeyError(
'Current state %r not defined in %s.jumps.'
% (self.current, self.__class__)
)
offset = len(self.start)
index = len(self.pending)
if self.streaming:
index -= max(map(len, options))
key = (index, 1)
result = (index, '', None)
for amark, anext in options.items():
asize = len(amark)
aindex = self.pending.find(amark, offset, index + asize)
if aindex > -1:
index = aindex
akey = (aindex, -asize)
if akey < key:
key = akey
result = (aindex, amark, anext)
return result | [
"def",
"nearest",
"(",
"self",
")",
":",
"try",
":",
"options",
"=",
"self",
".",
"jumps",
"[",
"self",
".",
"current",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Current state %r not defined in %s.jumps.'",
"%",
"(",
"self",
".",
"current",
",",
"self",
".",
"__class__",
")",
")",
"offset",
"=",
"len",
"(",
"self",
".",
"start",
")",
"index",
"=",
"len",
"(",
"self",
".",
"pending",
")",
"if",
"self",
".",
"streaming",
":",
"index",
"-=",
"max",
"(",
"map",
"(",
"len",
",",
"options",
")",
")",
"key",
"=",
"(",
"index",
",",
"1",
")",
"result",
"=",
"(",
"index",
",",
"''",
",",
"None",
")",
"for",
"amark",
",",
"anext",
"in",
"options",
".",
"items",
"(",
")",
":",
"asize",
"=",
"len",
"(",
"amark",
")",
"aindex",
"=",
"self",
".",
"pending",
".",
"find",
"(",
"amark",
",",
"offset",
",",
"index",
"+",
"asize",
")",
"if",
"aindex",
">",
"-",
"1",
":",
"index",
"=",
"aindex",
"akey",
"=",
"(",
"aindex",
",",
"-",
"asize",
")",
"if",
"akey",
"<",
"key",
":",
"key",
"=",
"akey",
"result",
"=",
"(",
"aindex",
",",
"amark",
",",
"anext",
")",
"return",
"result"
] | Get the next state jump.
The next jump is calculated looking at :attr:`current` state
and its possible :attr:`jumps` to find the nearest and bigger
option in :attr:`pending` data.
If none is found, the returned next state label will be None.
:returns: tuple with index, substring and next state label
:rtype: tuple | [
"Get",
"the",
"next",
"state",
"jump",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/transform/__init__.py#L20-L55 |
ergoithz/browsepy | browsepy/transform/__init__.py | StateMachine.transform | def transform(self, data, mark, next):
'''
Apply the appropriate transformation function on current state data,
which is supposed to end at this point.
It is expected transformation logic makes use of :attr:`start`,
:attr:`current` and :attr:`streaming` instance attributes to
bettee know the state is being left.
:param data: string to transform (includes start)
:type data: str
:param mark: string producing the new state jump
:type mark: str
:param next: state is about to star, None on finish
:type next: str or None
:returns: transformed data
:rtype: str
'''
method = getattr(self, 'transform_%s' % self.current, None)
return method(data, mark, next) if method else data | python | def transform(self, data, mark, next):
'''
Apply the appropriate transformation function on current state data,
which is supposed to end at this point.
It is expected transformation logic makes use of :attr:`start`,
:attr:`current` and :attr:`streaming` instance attributes to
bettee know the state is being left.
:param data: string to transform (includes start)
:type data: str
:param mark: string producing the new state jump
:type mark: str
:param next: state is about to star, None on finish
:type next: str or None
:returns: transformed data
:rtype: str
'''
method = getattr(self, 'transform_%s' % self.current, None)
return method(data, mark, next) if method else data | [
"def",
"transform",
"(",
"self",
",",
"data",
",",
"mark",
",",
"next",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'transform_%s'",
"%",
"self",
".",
"current",
",",
"None",
")",
"return",
"method",
"(",
"data",
",",
"mark",
",",
"next",
")",
"if",
"method",
"else",
"data"
] | Apply the appropriate transformation function on current state data,
which is supposed to end at this point.
It is expected transformation logic makes use of :attr:`start`,
:attr:`current` and :attr:`streaming` instance attributes to
bettee know the state is being left.
:param data: string to transform (includes start)
:type data: str
:param mark: string producing the new state jump
:type mark: str
:param next: state is about to star, None on finish
:type next: str or None
:returns: transformed data
:rtype: str | [
"Apply",
"the",
"appropriate",
"transformation",
"function",
"on",
"current",
"state",
"data",
"which",
"is",
"supposed",
"to",
"end",
"at",
"this",
"point",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/transform/__init__.py#L92-L112 |
ergoithz/browsepy | browsepy/transform/__init__.py | StateMachine.feed | def feed(self, data=''):
'''
Optionally add pending data, switch into streaming mode, and yield
result chunks.
:yields: result chunks
:ytype: str
'''
self.streaming = True
self.pending += data
for i in self:
yield i | python | def feed(self, data=''):
'''
Optionally add pending data, switch into streaming mode, and yield
result chunks.
:yields: result chunks
:ytype: str
'''
self.streaming = True
self.pending += data
for i in self:
yield i | [
"def",
"feed",
"(",
"self",
",",
"data",
"=",
"''",
")",
":",
"self",
".",
"streaming",
"=",
"True",
"self",
".",
"pending",
"+=",
"data",
"for",
"i",
"in",
"self",
":",
"yield",
"i"
] | Optionally add pending data, switch into streaming mode, and yield
result chunks.
:yields: result chunks
:ytype: str | [
"Optionally",
"add",
"pending",
"data",
"switch",
"into",
"streaming",
"mode",
"and",
"yield",
"result",
"chunks",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/transform/__init__.py#L114-L125 |
ergoithz/browsepy | browsepy/transform/__init__.py | StateMachine.finish | def finish(self, data=''):
'''
Optionally add pending data, turn off streaming mode, and yield
result chunks, which implies all pending data will be consumed.
:yields: result chunks
:ytype: str
'''
self.pending += data
self.streaming = False
for i in self:
yield i | python | def finish(self, data=''):
'''
Optionally add pending data, turn off streaming mode, and yield
result chunks, which implies all pending data will be consumed.
:yields: result chunks
:ytype: str
'''
self.pending += data
self.streaming = False
for i in self:
yield i | [
"def",
"finish",
"(",
"self",
",",
"data",
"=",
"''",
")",
":",
"self",
".",
"pending",
"+=",
"data",
"self",
".",
"streaming",
"=",
"False",
"for",
"i",
"in",
"self",
":",
"yield",
"i"
] | Optionally add pending data, turn off streaming mode, and yield
result chunks, which implies all pending data will be consumed.
:yields: result chunks
:ytype: str | [
"Optionally",
"add",
"pending",
"data",
"turn",
"off",
"streaming",
"mode",
"and",
"yield",
"result",
"chunks",
"which",
"implies",
"all",
"pending",
"data",
"will",
"be",
"consumed",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/transform/__init__.py#L127-L138 |
ergoithz/browsepy | browsepy/stream.py | TarFileStream.fill | def fill(self):
'''
Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
so there is little need to call it manually.
'''
if self.exclude:
exclude = self.exclude
ap = functools.partial(os.path.join, self.path)
self._tarfile.add(
self.path, "",
filter=lambda info: None if exclude(ap(info.name)) else info
)
else:
self._tarfile.add(self.path, "")
self._tarfile.close() # force stream flush
self._finished += 1
if not self._result.is_set():
self._result.set() | python | def fill(self):
'''
Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
so there is little need to call it manually.
'''
if self.exclude:
exclude = self.exclude
ap = functools.partial(os.path.join, self.path)
self._tarfile.add(
self.path, "",
filter=lambda info: None if exclude(ap(info.name)) else info
)
else:
self._tarfile.add(self.path, "")
self._tarfile.close() # force stream flush
self._finished += 1
if not self._result.is_set():
self._result.set() | [
"def",
"fill",
"(",
"self",
")",
":",
"if",
"self",
".",
"exclude",
":",
"exclude",
"=",
"self",
".",
"exclude",
"ap",
"=",
"functools",
".",
"partial",
"(",
"os",
".",
"path",
".",
"join",
",",
"self",
".",
"path",
")",
"self",
".",
"_tarfile",
".",
"add",
"(",
"self",
".",
"path",
",",
"\"\"",
",",
"filter",
"=",
"lambda",
"info",
":",
"None",
"if",
"exclude",
"(",
"ap",
"(",
"info",
".",
"name",
")",
")",
"else",
"info",
")",
"else",
":",
"self",
".",
"_tarfile",
".",
"add",
"(",
"self",
".",
"path",
",",
"\"\"",
")",
"self",
".",
"_tarfile",
".",
"close",
"(",
")",
"# force stream flush",
"self",
".",
"_finished",
"+=",
"1",
"if",
"not",
"self",
".",
"_result",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_result",
".",
"set",
"(",
")"
] | Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
so there is little need to call it manually. | [
"Writes",
"data",
"on",
"internal",
"tarfile",
"instance",
"which",
"writes",
"to",
"current",
"object",
"using",
":",
"meth",
":",
"write",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/stream.py#L54-L76 |
ergoithz/browsepy | browsepy/stream.py | TarFileStream.write | def write(self, data):
'''
Write method used by internal tarfile instance to output data.
This method blocks tarfile execution once internal buffer is full.
As this method is blocking, it is used inside the same thread of
:meth:`fill`.
:param data: bytes to write to internal buffer
:type data: bytes
:returns: number of bytes written
:rtype: int
'''
self._add.wait()
self._data += data
if len(self._data) > self._want:
self._add.clear()
self._result.set()
return len(data) | python | def write(self, data):
'''
Write method used by internal tarfile instance to output data.
This method blocks tarfile execution once internal buffer is full.
As this method is blocking, it is used inside the same thread of
:meth:`fill`.
:param data: bytes to write to internal buffer
:type data: bytes
:returns: number of bytes written
:rtype: int
'''
self._add.wait()
self._data += data
if len(self._data) > self._want:
self._add.clear()
self._result.set()
return len(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_add",
".",
"wait",
"(",
")",
"self",
".",
"_data",
"+=",
"data",
"if",
"len",
"(",
"self",
".",
"_data",
")",
">",
"self",
".",
"_want",
":",
"self",
".",
"_add",
".",
"clear",
"(",
")",
"self",
".",
"_result",
".",
"set",
"(",
")",
"return",
"len",
"(",
"data",
")"
] | Write method used by internal tarfile instance to output data.
This method blocks tarfile execution once internal buffer is full.
As this method is blocking, it is used inside the same thread of
:meth:`fill`.
:param data: bytes to write to internal buffer
:type data: bytes
:returns: number of bytes written
:rtype: int | [
"Write",
"method",
"used",
"by",
"internal",
"tarfile",
"instance",
"to",
"output",
"data",
".",
"This",
"method",
"blocks",
"tarfile",
"execution",
"once",
"internal",
"buffer",
"is",
"full",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/stream.py#L78-L96 |
ergoithz/browsepy | browsepy/stream.py | TarFileStream.read | def read(self, want=0):
'''
Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The combination of both write and this method running on different
threads makes tarfile being streamed on-the-fly, with data chunks being
processed and retrieved on demand.
:param want: number bytes to read, defaults to 0 (all available)
:type want: int
:returns: tarfile data as bytes
:rtype: bytes
'''
if self._finished:
if self._finished == 1:
self._finished += 1
return ""
return EOFError("EOF reached")
# Thread communication
self._want = want
self._add.set()
self._result.wait()
self._result.clear()
if want:
data = self._data[:want]
self._data = self._data[want:]
else:
data = self._data
self._data = bytes()
return data | python | def read(self, want=0):
'''
Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The combination of both write and this method running on different
threads makes tarfile being streamed on-the-fly, with data chunks being
processed and retrieved on demand.
:param want: number bytes to read, defaults to 0 (all available)
:type want: int
:returns: tarfile data as bytes
:rtype: bytes
'''
if self._finished:
if self._finished == 1:
self._finished += 1
return ""
return EOFError("EOF reached")
# Thread communication
self._want = want
self._add.set()
self._result.wait()
self._result.clear()
if want:
data = self._data[:want]
self._data = self._data[want:]
else:
data = self._data
self._data = bytes()
return data | [
"def",
"read",
"(",
"self",
",",
"want",
"=",
"0",
")",
":",
"if",
"self",
".",
"_finished",
":",
"if",
"self",
".",
"_finished",
"==",
"1",
":",
"self",
".",
"_finished",
"+=",
"1",
"return",
"\"\"",
"return",
"EOFError",
"(",
"\"EOF reached\"",
")",
"# Thread communication",
"self",
".",
"_want",
"=",
"want",
"self",
".",
"_add",
".",
"set",
"(",
")",
"self",
".",
"_result",
".",
"wait",
"(",
")",
"self",
".",
"_result",
".",
"clear",
"(",
")",
"if",
"want",
":",
"data",
"=",
"self",
".",
"_data",
"[",
":",
"want",
"]",
"self",
".",
"_data",
"=",
"self",
".",
"_data",
"[",
"want",
":",
"]",
"else",
":",
"data",
"=",
"self",
".",
"_data",
"self",
".",
"_data",
"=",
"bytes",
"(",
")",
"return",
"data"
] | Read method, gets data from internal buffer while releasing
:meth:`write` locks when needed.
The lock usage means it must ran on a different thread than
:meth:`fill`, ie. the main thread, otherwise will deadlock.
The combination of both write and this method running on different
threads makes tarfile being streamed on-the-fly, with data chunks being
processed and retrieved on demand.
:param want: number bytes to read, defaults to 0 (all available)
:type want: int
:returns: tarfile data as bytes
:rtype: bytes | [
"Read",
"method",
"gets",
"data",
"from",
"internal",
"buffer",
"while",
"releasing",
":",
"meth",
":",
"write",
"locks",
"when",
"needed",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/stream.py#L98-L133 |
ergoithz/browsepy | browsepy/compat.py | isexec | def isexec(path):
'''
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
'''
return os.path.isfile(path) and os.access(path, os.X_OK) | python | def isexec(path):
'''
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
'''
return os.path.isfile(path) and os.access(path, os.X_OK) | [
"def",
"isexec",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"X_OK",
")"
] | Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool | [
"Check",
"if",
"given",
"path",
"points",
"to",
"an",
"executable",
"file",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L30-L39 |
ergoithz/browsepy | browsepy/compat.py | fsdecode | def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Decode given path.
:param path: path will be decoded if using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: decoded path
:rtype: str
'''
if not isinstance(path, bytes):
return path
if not errors:
use_strict = PY_LEGACY or os_name == 'nt'
errors = 'strict' if use_strict else 'surrogateescape'
return path.decode(fs_encoding, errors=errors) | python | def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Decode given path.
:param path: path will be decoded if using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: decoded path
:rtype: str
'''
if not isinstance(path, bytes):
return path
if not errors:
use_strict = PY_LEGACY or os_name == 'nt'
errors = 'strict' if use_strict else 'surrogateescape'
return path.decode(fs_encoding, errors=errors) | [
"def",
"fsdecode",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"fs_encoding",
"=",
"FS_ENCODING",
",",
"errors",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"return",
"path",
"if",
"not",
"errors",
":",
"use_strict",
"=",
"PY_LEGACY",
"or",
"os_name",
"==",
"'nt'",
"errors",
"=",
"'strict'",
"if",
"use_strict",
"else",
"'surrogateescape'",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
",",
"errors",
"=",
"errors",
")"
] | Decode given path.
:param path: path will be decoded if using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: decoded path
:rtype: str | [
"Decode",
"given",
"path",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L42-L60 |
ergoithz/browsepy | browsepy/compat.py | fsencode | def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: encoded path
:rtype: bytes
'''
if isinstance(path, bytes):
return path
if not errors:
use_strict = PY_LEGACY or os_name == 'nt'
errors = 'strict' if use_strict else 'surrogateescape'
return path.encode(fs_encoding, errors=errors) | python | def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: encoded path
:rtype: bytes
'''
if isinstance(path, bytes):
return path
if not errors:
use_strict = PY_LEGACY or os_name == 'nt'
errors = 'strict' if use_strict else 'surrogateescape'
return path.encode(fs_encoding, errors=errors) | [
"def",
"fsencode",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"fs_encoding",
"=",
"FS_ENCODING",
",",
"errors",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"return",
"path",
"if",
"not",
"errors",
":",
"use_strict",
"=",
"PY_LEGACY",
"or",
"os_name",
"==",
"'nt'",
"errors",
"=",
"'strict'",
"if",
"use_strict",
"else",
"'surrogateescape'",
"return",
"path",
".",
"encode",
"(",
"fs_encoding",
",",
"errors",
"=",
"errors",
")"
] | Encode given path.
:param path: path will be encoded if not using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem encoding, defaults to autodetected
:type fs_encoding: str
:return: encoded path
:rtype: bytes | [
"Encode",
"given",
"path",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L63-L81 |
ergoithz/browsepy | browsepy/compat.py | getcwd | def getcwd(fs_encoding=FS_ENCODING, cwd_fnc=os.getcwd):
'''
Get current work directory's absolute path.
Like os.getcwd but garanteed to return an unicode-str object.
:param fs_encoding: filesystem encoding, defaults to autodetected
:type fs_encoding: str
:param cwd_fnc: callable used to get the path, defaults to os.getcwd
:type cwd_fnc: Callable
:return: path
:rtype: str
'''
path = fsdecode(cwd_fnc(), fs_encoding=fs_encoding)
return os.path.abspath(path) | python | def getcwd(fs_encoding=FS_ENCODING, cwd_fnc=os.getcwd):
'''
Get current work directory's absolute path.
Like os.getcwd but garanteed to return an unicode-str object.
:param fs_encoding: filesystem encoding, defaults to autodetected
:type fs_encoding: str
:param cwd_fnc: callable used to get the path, defaults to os.getcwd
:type cwd_fnc: Callable
:return: path
:rtype: str
'''
path = fsdecode(cwd_fnc(), fs_encoding=fs_encoding)
return os.path.abspath(path) | [
"def",
"getcwd",
"(",
"fs_encoding",
"=",
"FS_ENCODING",
",",
"cwd_fnc",
"=",
"os",
".",
"getcwd",
")",
":",
"path",
"=",
"fsdecode",
"(",
"cwd_fnc",
"(",
")",
",",
"fs_encoding",
"=",
"fs_encoding",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")"
] | Get current work directory's absolute path.
Like os.getcwd but garanteed to return an unicode-str object.
:param fs_encoding: filesystem encoding, defaults to autodetected
:type fs_encoding: str
:param cwd_fnc: callable used to get the path, defaults to os.getcwd
:type cwd_fnc: Callable
:return: path
:rtype: str | [
"Get",
"current",
"work",
"directory",
"s",
"absolute",
"path",
".",
"Like",
"os",
".",
"getcwd",
"but",
"garanteed",
"to",
"return",
"an",
"unicode",
"-",
"str",
"object",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L84-L97 |
ergoithz/browsepy | browsepy/compat.py | getdebug | def getdebug(environ=os.environ, true_values=TRUE_VALUES):
'''
Get if app is expected to be ran in debug mode looking at environment
variables.
:param environ: environment dict-like object
:type environ: collections.abc.Mapping
:returns: True if debug contains a true-like string, False otherwise
:rtype: bool
'''
return environ.get('DEBUG', '').lower() in true_values | python | def getdebug(environ=os.environ, true_values=TRUE_VALUES):
'''
Get if app is expected to be ran in debug mode looking at environment
variables.
:param environ: environment dict-like object
:type environ: collections.abc.Mapping
:returns: True if debug contains a true-like string, False otherwise
:rtype: bool
'''
return environ.get('DEBUG', '').lower() in true_values | [
"def",
"getdebug",
"(",
"environ",
"=",
"os",
".",
"environ",
",",
"true_values",
"=",
"TRUE_VALUES",
")",
":",
"return",
"environ",
".",
"get",
"(",
"'DEBUG'",
",",
"''",
")",
".",
"lower",
"(",
")",
"in",
"true_values"
] | Get if app is expected to be ran in debug mode looking at environment
variables.
:param environ: environment dict-like object
:type environ: collections.abc.Mapping
:returns: True if debug contains a true-like string, False otherwise
:rtype: bool | [
"Get",
"if",
"app",
"is",
"expected",
"to",
"be",
"ran",
"in",
"debug",
"mode",
"looking",
"at",
"environment",
"variables",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L100-L110 |
ergoithz/browsepy | browsepy/compat.py | deprecated | def deprecated(func_or_text, environ=os.environ):
'''
Decorator used to mark functions as deprecated. It will result in a
warning being emmitted hen the function is called.
Usage:
>>> @deprecated
... def fnc():
... pass
Usage (custom message):
>>> @deprecated('This is deprecated')
... def fnc():
... pass
:param func_or_text: message or callable to decorate
:type func_or_text: callable
:param environ: optional environment mapping
:type environ: collections.abc.Mapping
:returns: nested decorator or new decorated function (depending on params)
:rtype: callable
'''
def inner(func):
message = (
'Deprecated function {}.'.format(func.__name__)
if callable(func_or_text) else
func_or_text
)
@functools.wraps(func)
def new_func(*args, **kwargs):
with warnings.catch_warnings():
if getdebug(environ):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(message, category=DeprecationWarning,
stacklevel=3)
return func(*args, **kwargs)
return new_func
return inner(func_or_text) if callable(func_or_text) else inner | python | def deprecated(func_or_text, environ=os.environ):
'''
Decorator used to mark functions as deprecated. It will result in a
warning being emmitted hen the function is called.
Usage:
>>> @deprecated
... def fnc():
... pass
Usage (custom message):
>>> @deprecated('This is deprecated')
... def fnc():
... pass
:param func_or_text: message or callable to decorate
:type func_or_text: callable
:param environ: optional environment mapping
:type environ: collections.abc.Mapping
:returns: nested decorator or new decorated function (depending on params)
:rtype: callable
'''
def inner(func):
message = (
'Deprecated function {}.'.format(func.__name__)
if callable(func_or_text) else
func_or_text
)
@functools.wraps(func)
def new_func(*args, **kwargs):
with warnings.catch_warnings():
if getdebug(environ):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(message, category=DeprecationWarning,
stacklevel=3)
return func(*args, **kwargs)
return new_func
return inner(func_or_text) if callable(func_or_text) else inner | [
"def",
"deprecated",
"(",
"func_or_text",
",",
"environ",
"=",
"os",
".",
"environ",
")",
":",
"def",
"inner",
"(",
"func",
")",
":",
"message",
"=",
"(",
"'Deprecated function {}.'",
".",
"format",
"(",
"func",
".",
"__name__",
")",
"if",
"callable",
"(",
"func_or_text",
")",
"else",
"func_or_text",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"if",
"getdebug",
"(",
"environ",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'always'",
",",
"DeprecationWarning",
")",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_func",
"return",
"inner",
"(",
"func_or_text",
")",
"if",
"callable",
"(",
"func_or_text",
")",
"else",
"inner"
] | Decorator used to mark functions as deprecated. It will result in a
warning being emmitted hen the function is called.
Usage:
>>> @deprecated
... def fnc():
... pass
Usage (custom message):
>>> @deprecated('This is deprecated')
... def fnc():
... pass
:param func_or_text: message or callable to decorate
:type func_or_text: callable
:param environ: optional environment mapping
:type environ: collections.abc.Mapping
:returns: nested decorator or new decorated function (depending on params)
:rtype: callable | [
"Decorator",
"used",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"It",
"will",
"result",
"in",
"a",
"warning",
"being",
"emmitted",
"hen",
"the",
"function",
"is",
"called",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L113-L153 |
ergoithz/browsepy | browsepy/compat.py | usedoc | def usedoc(other):
'''
Decorator which copies __doc__ of given object into decorated one.
Usage:
>>> def fnc1():
... """docstring"""
... pass
>>> @usedoc(fnc1)
... def fnc2():
... pass
>>> fnc2.__doc__
'docstring'collections.abc.D
:param other: anything with a __doc__ attribute
:type other: any
:returns: decorator function
:rtype: callable
'''
def inner(fnc):
fnc.__doc__ = fnc.__doc__ or getattr(other, '__doc__')
return fnc
return inner | python | def usedoc(other):
'''
Decorator which copies __doc__ of given object into decorated one.
Usage:
>>> def fnc1():
... """docstring"""
... pass
>>> @usedoc(fnc1)
... def fnc2():
... pass
>>> fnc2.__doc__
'docstring'collections.abc.D
:param other: anything with a __doc__ attribute
:type other: any
:returns: decorator function
:rtype: callable
'''
def inner(fnc):
fnc.__doc__ = fnc.__doc__ or getattr(other, '__doc__')
return fnc
return inner | [
"def",
"usedoc",
"(",
"other",
")",
":",
"def",
"inner",
"(",
"fnc",
")",
":",
"fnc",
".",
"__doc__",
"=",
"fnc",
".",
"__doc__",
"or",
"getattr",
"(",
"other",
",",
"'__doc__'",
")",
"return",
"fnc",
"return",
"inner"
] | Decorator which copies __doc__ of given object into decorated one.
Usage:
>>> def fnc1():
... """docstring"""
... pass
>>> @usedoc(fnc1)
... def fnc2():
... pass
>>> fnc2.__doc__
'docstring'collections.abc.D
:param other: anything with a __doc__ attribute
:type other: any
:returns: decorator function
:rtype: callable | [
"Decorator",
"which",
"copies",
"__doc__",
"of",
"given",
"object",
"into",
"decorated",
"one",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L156-L179 |
ergoithz/browsepy | browsepy/compat.py | pathsplit | def pathsplit(value, sep=os.pathsep):
'''
Get enviroment PATH elements as list.
This function only cares about spliting across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:yields: every path
:ytype: str
'''
for part in value.split(sep):
if part[:1] == part[-1:] == '"' or part[:1] == part[-1:] == '\'':
part = part[1:-1]
yield part | python | def pathsplit(value, sep=os.pathsep):
'''
Get enviroment PATH elements as list.
This function only cares about spliting across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:yields: every path
:ytype: str
'''
for part in value.split(sep):
if part[:1] == part[-1:] == '"' or part[:1] == part[-1:] == '\'':
part = part[1:-1]
yield part | [
"def",
"pathsplit",
"(",
"value",
",",
"sep",
"=",
"os",
".",
"pathsep",
")",
":",
"for",
"part",
"in",
"value",
".",
"split",
"(",
"sep",
")",
":",
"if",
"part",
"[",
":",
"1",
"]",
"==",
"part",
"[",
"-",
"1",
":",
"]",
"==",
"'\"'",
"or",
"part",
"[",
":",
"1",
"]",
"==",
"part",
"[",
"-",
"1",
":",
"]",
"==",
"'\\''",
":",
"part",
"=",
"part",
"[",
"1",
":",
"-",
"1",
"]",
"yield",
"part"
] | Get enviroment PATH elements as list.
This function only cares about spliting across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:yields: every path
:ytype: str | [
"Get",
"enviroment",
"PATH",
"elements",
"as",
"list",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L182-L198 |
ergoithz/browsepy | browsepy/compat.py | pathparse | def pathparse(value, sep=os.pathsep, os_sep=os.sep):
'''
Get enviroment PATH directories as list.
This function cares about spliting, escapes and normalization of paths
across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:param os_sep: OS filesystem path separator, defaults to os.sep
:type os_sep: str
:yields: every path
:ytype: str
'''
escapes = []
normpath = ntpath.normpath if os_sep == '\\' else posixpath.normpath
if '\\' not in (os_sep, sep):
escapes.extend((
('\\\\', '<ESCAPE-ESCAPE>', '\\'),
('\\"', '<ESCAPE-DQUOTE>', '"'),
('\\\'', '<ESCAPE-SQUOTE>', '\''),
('\\%s' % sep, '<ESCAPE-PATHSEP>', sep),
))
for original, escape, unescape in escapes:
value = value.replace(original, escape)
for part in pathsplit(value, sep=sep):
if part[-1:] == os_sep and part != os_sep:
part = part[:-1]
for original, escape, unescape in escapes:
part = part.replace(escape, unescape)
yield normpath(fsdecode(part)) | python | def pathparse(value, sep=os.pathsep, os_sep=os.sep):
'''
Get enviroment PATH directories as list.
This function cares about spliting, escapes and normalization of paths
across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:param os_sep: OS filesystem path separator, defaults to os.sep
:type os_sep: str
:yields: every path
:ytype: str
'''
escapes = []
normpath = ntpath.normpath if os_sep == '\\' else posixpath.normpath
if '\\' not in (os_sep, sep):
escapes.extend((
('\\\\', '<ESCAPE-ESCAPE>', '\\'),
('\\"', '<ESCAPE-DQUOTE>', '"'),
('\\\'', '<ESCAPE-SQUOTE>', '\''),
('\\%s' % sep, '<ESCAPE-PATHSEP>', sep),
))
for original, escape, unescape in escapes:
value = value.replace(original, escape)
for part in pathsplit(value, sep=sep):
if part[-1:] == os_sep and part != os_sep:
part = part[:-1]
for original, escape, unescape in escapes:
part = part.replace(escape, unescape)
yield normpath(fsdecode(part)) | [
"def",
"pathparse",
"(",
"value",
",",
"sep",
"=",
"os",
".",
"pathsep",
",",
"os_sep",
"=",
"os",
".",
"sep",
")",
":",
"escapes",
"=",
"[",
"]",
"normpath",
"=",
"ntpath",
".",
"normpath",
"if",
"os_sep",
"==",
"'\\\\'",
"else",
"posixpath",
".",
"normpath",
"if",
"'\\\\'",
"not",
"in",
"(",
"os_sep",
",",
"sep",
")",
":",
"escapes",
".",
"extend",
"(",
"(",
"(",
"'\\\\\\\\'",
",",
"'<ESCAPE-ESCAPE>'",
",",
"'\\\\'",
")",
",",
"(",
"'\\\\\"'",
",",
"'<ESCAPE-DQUOTE>'",
",",
"'\"'",
")",
",",
"(",
"'\\\\\\''",
",",
"'<ESCAPE-SQUOTE>'",
",",
"'\\''",
")",
",",
"(",
"'\\\\%s'",
"%",
"sep",
",",
"'<ESCAPE-PATHSEP>'",
",",
"sep",
")",
",",
")",
")",
"for",
"original",
",",
"escape",
",",
"unescape",
"in",
"escapes",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"original",
",",
"escape",
")",
"for",
"part",
"in",
"pathsplit",
"(",
"value",
",",
"sep",
"=",
"sep",
")",
":",
"if",
"part",
"[",
"-",
"1",
":",
"]",
"==",
"os_sep",
"and",
"part",
"!=",
"os_sep",
":",
"part",
"=",
"part",
"[",
":",
"-",
"1",
"]",
"for",
"original",
",",
"escape",
",",
"unescape",
"in",
"escapes",
":",
"part",
"=",
"part",
".",
"replace",
"(",
"escape",
",",
"unescape",
")",
"yield",
"normpath",
"(",
"fsdecode",
"(",
"part",
")",
")"
] | Get enviroment PATH directories as list.
This function cares about spliting, escapes and normalization of paths
across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:param os_sep: OS filesystem path separator, defaults to os.sep
:type os_sep: str
:yields: every path
:ytype: str | [
"Get",
"enviroment",
"PATH",
"directories",
"as",
"list",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L201-L233 |
ergoithz/browsepy | browsepy/compat.py | pathconf | def pathconf(path,
os_name=os.name,
isdir_fnc=os.path.isdir,
pathconf_fnc=getattr(os, 'pathconf', None),
pathconf_names=getattr(os, 'pathconf_names', ())):
'''
Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict
'''
if pathconf_fnc and pathconf_names:
return {key: pathconf_fnc(path, key) for key in pathconf_names}
if os_name == 'nt':
maxpath = 246 if isdir_fnc(path) else 259 # 260 minus <END>
else:
maxpath = 255 # conservative sane default
return {
'PC_PATH_MAX': maxpath,
'PC_NAME_MAX': maxpath - len(path),
} | python | def pathconf(path,
os_name=os.name,
isdir_fnc=os.path.isdir,
pathconf_fnc=getattr(os, 'pathconf', None),
pathconf_names=getattr(os, 'pathconf_names', ())):
'''
Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict
'''
if pathconf_fnc and pathconf_names:
return {key: pathconf_fnc(path, key) for key in pathconf_names}
if os_name == 'nt':
maxpath = 246 if isdir_fnc(path) else 259 # 260 minus <END>
else:
maxpath = 255 # conservative sane default
return {
'PC_PATH_MAX': maxpath,
'PC_NAME_MAX': maxpath - len(path),
} | [
"def",
"pathconf",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"isdir_fnc",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"pathconf_fnc",
"=",
"getattr",
"(",
"os",
",",
"'pathconf'",
",",
"None",
")",
",",
"pathconf_names",
"=",
"getattr",
"(",
"os",
",",
"'pathconf_names'",
",",
"(",
")",
")",
")",
":",
"if",
"pathconf_fnc",
"and",
"pathconf_names",
":",
"return",
"{",
"key",
":",
"pathconf_fnc",
"(",
"path",
",",
"key",
")",
"for",
"key",
"in",
"pathconf_names",
"}",
"if",
"os_name",
"==",
"'nt'",
":",
"maxpath",
"=",
"246",
"if",
"isdir_fnc",
"(",
"path",
")",
"else",
"259",
"# 260 minus <END>",
"else",
":",
"maxpath",
"=",
"255",
"# conservative sane default",
"return",
"{",
"'PC_PATH_MAX'",
":",
"maxpath",
",",
"'PC_NAME_MAX'",
":",
"maxpath",
"-",
"len",
"(",
"path",
")",
",",
"}"
] | Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict | [
"Get",
"all",
"pathconf",
"variables",
"for",
"given",
"path",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L236-L259 |
ergoithz/browsepy | browsepy/compat.py | which | def which(name,
env_path=ENV_PATH,
env_path_ext=ENV_PATHEXT,
is_executable_fnc=isexec,
path_join_fnc=os.path.join,
os_name=os.name):
'''
Get command absolute path.
:param name: name of executable command
:type name: str
:param env_path: OS environment executable paths, defaults to autodetected
:type env_path: list of str
:param is_executable_fnc: callable will be used to detect if path is
executable, defaults to `isexec`
:type is_executable_fnc: Callable
:param path_join_fnc: callable will be used to join path components
:type path_join_fnc: Callable
:param os_name: os name, defaults to os.name
:type os_name: str
:return: absolute path
:rtype: str or None
'''
for path in env_path:
for suffix in env_path_ext:
exe_file = path_join_fnc(path, name) + suffix
if is_executable_fnc(exe_file):
return exe_file
return None | python | def which(name,
env_path=ENV_PATH,
env_path_ext=ENV_PATHEXT,
is_executable_fnc=isexec,
path_join_fnc=os.path.join,
os_name=os.name):
'''
Get command absolute path.
:param name: name of executable command
:type name: str
:param env_path: OS environment executable paths, defaults to autodetected
:type env_path: list of str
:param is_executable_fnc: callable will be used to detect if path is
executable, defaults to `isexec`
:type is_executable_fnc: Callable
:param path_join_fnc: callable will be used to join path components
:type path_join_fnc: Callable
:param os_name: os name, defaults to os.name
:type os_name: str
:return: absolute path
:rtype: str or None
'''
for path in env_path:
for suffix in env_path_ext:
exe_file = path_join_fnc(path, name) + suffix
if is_executable_fnc(exe_file):
return exe_file
return None | [
"def",
"which",
"(",
"name",
",",
"env_path",
"=",
"ENV_PATH",
",",
"env_path_ext",
"=",
"ENV_PATHEXT",
",",
"is_executable_fnc",
"=",
"isexec",
",",
"path_join_fnc",
"=",
"os",
".",
"path",
".",
"join",
",",
"os_name",
"=",
"os",
".",
"name",
")",
":",
"for",
"path",
"in",
"env_path",
":",
"for",
"suffix",
"in",
"env_path_ext",
":",
"exe_file",
"=",
"path_join_fnc",
"(",
"path",
",",
"name",
")",
"+",
"suffix",
"if",
"is_executable_fnc",
"(",
"exe_file",
")",
":",
"return",
"exe_file",
"return",
"None"
] | Get command absolute path.
:param name: name of executable command
:type name: str
:param env_path: OS environment executable paths, defaults to autodetected
:type env_path: list of str
:param is_executable_fnc: callable will be used to detect if path is
executable, defaults to `isexec`
:type is_executable_fnc: Callable
:param path_join_fnc: callable will be used to join path components
:type path_join_fnc: Callable
:param os_name: os name, defaults to os.name
:type os_name: str
:return: absolute path
:rtype: str or None | [
"Get",
"command",
"absolute",
"path",
"."
] | train | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L266-L294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.