repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jaraco/irc | irc/client.py | Reactor.add_global_handler | def add_global_handler(self, event, handler, priority=0):
"""Adds a global handler function for a specific event type.
Arguments:
event -- Event type (a string). Check the values of
numeric_events for possible event types.
handler -- Callback function taking 'connection' and 'event'
parameters.
priority -- A number (the lower number, the higher priority).
The handler function is called whenever the specified event is
triggered in any of the connections. See documentation for
the Event class.
The handler functions are called in priority order (lowest
number is highest priority). If a handler function returns
"NO MORE", no more handlers will be called.
"""
handler = PrioritizedHandler(priority, handler)
with self.mutex:
event_handlers = self.handlers.setdefault(event, [])
bisect.insort(event_handlers, handler) | python | def add_global_handler(self, event, handler, priority=0):
"""Adds a global handler function for a specific event type.
Arguments:
event -- Event type (a string). Check the values of
numeric_events for possible event types.
handler -- Callback function taking 'connection' and 'event'
parameters.
priority -- A number (the lower number, the higher priority).
The handler function is called whenever the specified event is
triggered in any of the connections. See documentation for
the Event class.
The handler functions are called in priority order (lowest
number is highest priority). If a handler function returns
"NO MORE", no more handlers will be called.
"""
handler = PrioritizedHandler(priority, handler)
with self.mutex:
event_handlers = self.handlers.setdefault(event, [])
bisect.insort(event_handlers, handler) | [
"def",
"add_global_handler",
"(",
"self",
",",
"event",
",",
"handler",
",",
"priority",
"=",
"0",
")",
":",
"handler",
"=",
"PrioritizedHandler",
"(",
"priority",
",",
"handler",
")",
"with",
"self",
".",
"mutex",
":",
"event_handlers",
"=",
"self",
".",
... | Adds a global handler function for a specific event type.
Arguments:
event -- Event type (a string). Check the values of
numeric_events for possible event types.
handler -- Callback function taking 'connection' and 'event'
parameters.
priority -- A number (the lower number, the higher priority).
The handler function is called whenever the specified event is
triggered in any of the connections. See documentation for
the Event class.
The handler functions are called in priority order (lowest
number is highest priority). If a handler function returns
"NO MORE", no more handlers will be called. | [
"Adds",
"a",
"global",
"handler",
"function",
"for",
"a",
"specific",
"event",
"type",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L850-L874 | train | 35,100 |
jaraco/irc | irc/client.py | Reactor.remove_global_handler | def remove_global_handler(self, event, handler):
"""Removes a global handler function.
Arguments:
event -- Event type (a string).
handler -- Callback function.
Returns 1 on success, otherwise 0.
"""
with self.mutex:
if event not in self.handlers:
return 0
for h in self.handlers[event]:
if handler == h.callback:
self.handlers[event].remove(h)
return 1 | python | def remove_global_handler(self, event, handler):
"""Removes a global handler function.
Arguments:
event -- Event type (a string).
handler -- Callback function.
Returns 1 on success, otherwise 0.
"""
with self.mutex:
if event not in self.handlers:
return 0
for h in self.handlers[event]:
if handler == h.callback:
self.handlers[event].remove(h)
return 1 | [
"def",
"remove_global_handler",
"(",
"self",
",",
"event",
",",
"handler",
")",
":",
"with",
"self",
".",
"mutex",
":",
"if",
"event",
"not",
"in",
"self",
".",
"handlers",
":",
"return",
"0",
"for",
"h",
"in",
"self",
".",
"handlers",
"[",
"event",
... | Removes a global handler function.
Arguments:
event -- Event type (a string).
handler -- Callback function.
Returns 1 on success, otherwise 0. | [
"Removes",
"a",
"global",
"handler",
"function",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L876-L892 | train | 35,101 |
jaraco/irc | irc/client.py | Reactor.dcc | def dcc(self, dcctype="chat"):
"""Creates and returns a DCCConnection object.
Arguments:
dcctype -- "chat" for DCC CHAT connections or "raw" for
DCC SEND (or other DCC types). If "chat",
incoming data will be split in newline-separated
chunks. If "raw", incoming data is not touched.
"""
with self.mutex:
conn = DCCConnection(self, dcctype)
self.connections.append(conn)
return conn | python | def dcc(self, dcctype="chat"):
"""Creates and returns a DCCConnection object.
Arguments:
dcctype -- "chat" for DCC CHAT connections or "raw" for
DCC SEND (or other DCC types). If "chat",
incoming data will be split in newline-separated
chunks. If "raw", incoming data is not touched.
"""
with self.mutex:
conn = DCCConnection(self, dcctype)
self.connections.append(conn)
return conn | [
"def",
"dcc",
"(",
"self",
",",
"dcctype",
"=",
"\"chat\"",
")",
":",
"with",
"self",
".",
"mutex",
":",
"conn",
"=",
"DCCConnection",
"(",
"self",
",",
"dcctype",
")",
"self",
".",
"connections",
".",
"append",
"(",
"conn",
")",
"return",
"conn"
] | Creates and returns a DCCConnection object.
Arguments:
dcctype -- "chat" for DCC CHAT connections or "raw" for
DCC SEND (or other DCC types). If "chat",
incoming data will be split in newline-separated
chunks. If "raw", incoming data is not touched. | [
"Creates",
"and",
"returns",
"a",
"DCCConnection",
"object",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L894-L907 | train | 35,102 |
jaraco/irc | irc/client.py | Reactor._handle_event | def _handle_event(self, connection, event):
"""
Handle an Event event incoming on ServerConnection connection.
"""
with self.mutex:
matching_handlers = sorted(
self.handlers.get("all_events", [])
+ self.handlers.get(event.type, [])
)
for handler in matching_handlers:
result = handler.callback(connection, event)
if result == "NO MORE":
return | python | def _handle_event(self, connection, event):
"""
Handle an Event event incoming on ServerConnection connection.
"""
with self.mutex:
matching_handlers = sorted(
self.handlers.get("all_events", [])
+ self.handlers.get(event.type, [])
)
for handler in matching_handlers:
result = handler.callback(connection, event)
if result == "NO MORE":
return | [
"def",
"_handle_event",
"(",
"self",
",",
"connection",
",",
"event",
")",
":",
"with",
"self",
".",
"mutex",
":",
"matching_handlers",
"=",
"sorted",
"(",
"self",
".",
"handlers",
".",
"get",
"(",
"\"all_events\"",
",",
"[",
"]",
")",
"+",
"self",
"."... | Handle an Event event incoming on ServerConnection connection. | [
"Handle",
"an",
"Event",
"event",
"incoming",
"on",
"ServerConnection",
"connection",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L909-L921 | train | 35,103 |
jaraco/irc | irc/client.py | DCCConnection.disconnect | def disconnect(self, message=""):
"""Hang up the connection and close the object.
Arguments:
message -- Quit message.
"""
try:
del self.connected
except AttributeError:
return
try:
self.socket.shutdown(socket.SHUT_WR)
self.socket.close()
except socket.error:
pass
del self.socket
self.reactor._handle_event(
self,
Event("dcc_disconnect", self.peeraddress, "", [message]))
self.reactor._remove_connection(self) | python | def disconnect(self, message=""):
"""Hang up the connection and close the object.
Arguments:
message -- Quit message.
"""
try:
del self.connected
except AttributeError:
return
try:
self.socket.shutdown(socket.SHUT_WR)
self.socket.close()
except socket.error:
pass
del self.socket
self.reactor._handle_event(
self,
Event("dcc_disconnect", self.peeraddress, "", [message]))
self.reactor._remove_connection(self) | [
"def",
"disconnect",
"(",
"self",
",",
"message",
"=",
"\"\"",
")",
":",
"try",
":",
"del",
"self",
".",
"connected",
"except",
"AttributeError",
":",
"return",
"try",
":",
"self",
".",
"socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_WR",
")",
"se... | Hang up the connection and close the object.
Arguments:
message -- Quit message. | [
"Hang",
"up",
"the",
"connection",
"and",
"close",
"the",
"object",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1004-L1025 | train | 35,104 |
jaraco/irc | irc/client.py | DCCConnection.privmsg | def privmsg(self, text):
"""
Send text to DCC peer.
The text will be padded with a newline if it's a DCC CHAT session.
"""
if self.dcctype == 'chat':
text += '\n'
return self.send_bytes(self.encode(text)) | python | def privmsg(self, text):
"""
Send text to DCC peer.
The text will be padded with a newline if it's a DCC CHAT session.
"""
if self.dcctype == 'chat':
text += '\n'
return self.send_bytes(self.encode(text)) | [
"def",
"privmsg",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"dcctype",
"==",
"'chat'",
":",
"text",
"+=",
"'\\n'",
"return",
"self",
".",
"send_bytes",
"(",
"self",
".",
"encode",
"(",
"text",
")",
")"
] | Send text to DCC peer.
The text will be padded with a newline if it's a DCC CHAT session. | [
"Send",
"text",
"to",
"DCC",
"peer",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1081-L1089 | train | 35,105 |
jaraco/irc | irc/client.py | DCCConnection.send_bytes | def send_bytes(self, bytes):
"""
Send data to DCC peer.
"""
try:
self.socket.send(bytes)
log.debug("TO PEER: %r\n", bytes)
except socket.error:
self.disconnect("Connection reset by peer.") | python | def send_bytes(self, bytes):
"""
Send data to DCC peer.
"""
try:
self.socket.send(bytes)
log.debug("TO PEER: %r\n", bytes)
except socket.error:
self.disconnect("Connection reset by peer.") | [
"def",
"send_bytes",
"(",
"self",
",",
"bytes",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"send",
"(",
"bytes",
")",
"log",
".",
"debug",
"(",
"\"TO PEER: %r\\n\"",
",",
"bytes",
")",
"except",
"socket",
".",
"error",
":",
"self",
".",
"disco... | Send data to DCC peer. | [
"Send",
"data",
"to",
"DCC",
"peer",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1091-L1099 | train | 35,106 |
jaraco/irc | irc/client.py | SimpleIRCClient.dcc | def dcc(self, *args, **kwargs):
"""Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer.
"""
dcc = self.reactor.dcc(*args, **kwargs)
self.dcc_connections.append(dcc)
return dcc | python | def dcc(self, *args, **kwargs):
"""Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer.
"""
dcc = self.reactor.dcc(*args, **kwargs)
self.dcc_connections.append(dcc)
return dcc | [
"def",
"dcc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dcc",
"=",
"self",
".",
"reactor",
".",
"dcc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"dcc_connections",
".",
"append",
"(",
"dcc",
")",
"ret... | Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer. | [
"Create",
"and",
"associate",
"a",
"new",
"DCCConnection",
"object",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1162-L1170 | train | 35,107 |
jaraco/irc | irc/client.py | SimpleIRCClient.dcc_connect | def dcc_connect(self, address, port, dcctype="chat"):
"""Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).connect()", DeprecationWarning)
return self.dcc(dcctype).connect(address, port) | python | def dcc_connect(self, address, port, dcctype="chat"):
"""Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).connect()", DeprecationWarning)
return self.dcc(dcctype).connect(address, port) | [
"def",
"dcc_connect",
"(",
"self",
",",
"address",
",",
"port",
",",
"dcctype",
"=",
"\"chat\"",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use self.dcc(type).connect()\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"dcc",
"(",
"dcctype",
")",
".... | Connect to a DCC peer.
Arguments:
address -- IP address of the peer.
port -- Port to connect to.
Returns a DCCConnection instance. | [
"Connect",
"to",
"a",
"DCC",
"peer",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1172-L1184 | train | 35,108 |
jaraco/irc | irc/client.py | SimpleIRCClient.dcc_listen | def dcc_listen(self, dcctype="chat"):
"""Listen for connections from a DCC peer.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).listen()", DeprecationWarning)
return self.dcc(dcctype).listen() | python | def dcc_listen(self, dcctype="chat"):
"""Listen for connections from a DCC peer.
Returns a DCCConnection instance.
"""
warnings.warn("Use self.dcc(type).listen()", DeprecationWarning)
return self.dcc(dcctype).listen() | [
"def",
"dcc_listen",
"(",
"self",
",",
"dcctype",
"=",
"\"chat\"",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use self.dcc(type).listen()\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"dcc",
"(",
"dcctype",
")",
".",
"listen",
"(",
")"
] | Listen for connections from a DCC peer.
Returns a DCCConnection instance. | [
"Listen",
"for",
"connections",
"from",
"a",
"DCC",
"peer",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1186-L1192 | train | 35,109 |
jaraco/irc | irc/ctcp.py | dequote | def dequote(message):
"""
Dequote a message according to CTCP specifications.
The function returns a list where each element can be either a
string (normal message) or a tuple of one or two strings (tagged
messages). If a tuple has only one element (ie is a singleton),
that element is the tag; otherwise the tuple has two elements: the
tag and the data.
Arguments:
message -- The message to be decoded.
"""
# Perform the substitution
message = low_level_regexp.sub(_low_level_replace, message)
if DELIMITER not in message:
return [message]
# Split it into parts.
chunks = message.split(DELIMITER)
return list(_gen_messages(chunks)) | python | def dequote(message):
"""
Dequote a message according to CTCP specifications.
The function returns a list where each element can be either a
string (normal message) or a tuple of one or two strings (tagged
messages). If a tuple has only one element (ie is a singleton),
that element is the tag; otherwise the tuple has two elements: the
tag and the data.
Arguments:
message -- The message to be decoded.
"""
# Perform the substitution
message = low_level_regexp.sub(_low_level_replace, message)
if DELIMITER not in message:
return [message]
# Split it into parts.
chunks = message.split(DELIMITER)
return list(_gen_messages(chunks)) | [
"def",
"dequote",
"(",
"message",
")",
":",
"# Perform the substitution",
"message",
"=",
"low_level_regexp",
".",
"sub",
"(",
"_low_level_replace",
",",
"message",
")",
"if",
"DELIMITER",
"not",
"in",
"message",
":",
"return",
"[",
"message",
"]",
"# Split it i... | Dequote a message according to CTCP specifications.
The function returns a list where each element can be either a
string (normal message) or a tuple of one or two strings (tagged
messages). If a tuple has only one element (ie is a singleton),
that element is the tag; otherwise the tuple has two elements: the
tag and the data.
Arguments:
message -- The message to be decoded. | [
"Dequote",
"a",
"message",
"according",
"to",
"CTCP",
"specifications",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/ctcp.py#L30-L54 | train | 35,110 |
sibson/vncdotool | vncdotool/api.py | connect | def connect(server, password=None,
factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
""" Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.connect('host') as client
>>> client.keyPress('c')
You may then call any regular VNCDoToolClient method on client from your
application code.
If you are using a GUI toolkit or other major async library please read
http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
for a better method of intergrating vncdotool.
"""
if not reactor.running:
global _THREAD
_THREAD = threading.Thread(target=reactor.run, name='Twisted',
kwargs={'installSignalHandlers': False})
_THREAD.daemon = True
_THREAD.start()
observer = PythonLoggingObserver()
observer.start()
factory = factory_class()
if password is not None:
factory.password = password
family, host, port = command.parse_server(server)
client = proxy(factory, timeout)
client.connect(host, port=port, family=family)
return client | python | def connect(server, password=None,
factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
""" Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.connect('host') as client
>>> client.keyPress('c')
You may then call any regular VNCDoToolClient method on client from your
application code.
If you are using a GUI toolkit or other major async library please read
http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
for a better method of intergrating vncdotool.
"""
if not reactor.running:
global _THREAD
_THREAD = threading.Thread(target=reactor.run, name='Twisted',
kwargs={'installSignalHandlers': False})
_THREAD.daemon = True
_THREAD.start()
observer = PythonLoggingObserver()
observer.start()
factory = factory_class()
if password is not None:
factory.password = password
family, host, port = command.parse_server(server)
client = proxy(factory, timeout)
client.connect(host, port=port, family=family)
return client | [
"def",
"connect",
"(",
"server",
",",
"password",
"=",
"None",
",",
"factory_class",
"=",
"VNCDoToolFactory",
",",
"proxy",
"=",
"ThreadedVNCClientProxy",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"reactor",
".",
"running",
":",
"global",
"_THREAD"... | Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.connect('host') as client
>>> client.keyPress('c')
You may then call any regular VNCDoToolClient method on client from your
application code.
If you are using a GUI toolkit or other major async library please read
http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
for a better method of intergrating vncdotool. | [
"Connect",
"to",
"a",
"VNCServer",
"and",
"return",
"a",
"Client",
"instance",
"that",
"is",
"usable",
"in",
"the",
"main",
"thread",
"of",
"non",
"-",
"Twisted",
"Python",
"Applications",
"EXPERIMENTAL",
"."
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/api.py#L121-L156 | train | 35,111 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.keyPress | def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self | python | def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self | [
"def",
"keyPress",
"(",
"self",
",",
"key",
")",
":",
"log",
".",
"debug",
"(",
"'keyPress %s'",
",",
"key",
")",
"self",
".",
"keyDown",
"(",
"key",
")",
"self",
".",
"keyUp",
"(",
"key",
")",
"return",
"self"
] | Send a key press to the server
key: string: either [a-z] or a from KEYMAP | [
"Send",
"a",
"key",
"press",
"to",
"the",
"server"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L165-L174 | train | 35,112 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mousePress | def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self | python | def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self | [
"def",
"mousePress",
"(",
"self",
",",
"button",
")",
":",
"log",
".",
"debug",
"(",
"'mousePress %s'",
",",
"button",
")",
"buttons",
"=",
"self",
".",
"buttons",
"|",
"(",
"1",
"<<",
"(",
"button",
"-",
"1",
")",
")",
"self",
".",
"mouseDown",
"(... | Send a mouse click at the last set position
button: int: [1-n] | [
"Send",
"a",
"mouse",
"click",
"at",
"the",
"last",
"set",
"position"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L192-L203 | train | 35,113 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mouseDown | def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self | python | def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self | [
"def",
"mouseDown",
"(",
"self",
",",
"button",
")",
":",
"log",
".",
"debug",
"(",
"'mouseDown %s'",
",",
"button",
")",
"self",
".",
"buttons",
"|=",
"1",
"<<",
"(",
"button",
"-",
"1",
")",
"self",
".",
"pointerEvent",
"(",
"self",
".",
"x",
","... | Send a mouse button down at the last set position
button: int: [1-n] | [
"Send",
"a",
"mouse",
"button",
"down",
"at",
"the",
"last",
"set",
"position"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L205-L215 | train | 35,114 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.captureRegion | def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h) | python | def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h) | [
"def",
"captureRegion",
"(",
"self",
",",
"filename",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
":",
"log",
".",
"debug",
"(",
"'captureRegion %s'",
",",
"filename",
")",
"return",
"self",
".",
"_capture",
"(",
"filename",
",",
"x",
",",
"y",
",... | Save a region of the current display to filename | [
"Save",
"a",
"region",
"of",
"the",
"current",
"display",
"to",
"filename"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L235-L239 | train | 35,115 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.expectScreen | def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms) | python | def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms) | [
"def",
"expectScreen",
"(",
"self",
",",
"filename",
",",
"maxrms",
"=",
"0",
")",
":",
"log",
".",
"debug",
"(",
"'expectScreen %s'",
",",
"filename",
")",
"return",
"self",
".",
"_expectFramebuffer",
"(",
"filename",
",",
"0",
",",
"0",
",",
"maxrms",
... | Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image | [
"Wait",
"until",
"the",
"display",
"matches",
"a",
"target",
"image"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L261-L269 | train | 35,116 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.expectRegion | def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms) | python | def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms) | [
"def",
"expectRegion",
"(",
"self",
",",
"filename",
",",
"x",
",",
"y",
",",
"maxrms",
"=",
"0",
")",
":",
"log",
".",
"debug",
"(",
"'expectRegion %s (%s, %s)'",
",",
"filename",
",",
"x",
",",
"y",
")",
"return",
"self",
".",
"_expectFramebuffer",
"... | Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height) | [
"Wait",
"until",
"a",
"portion",
"of",
"the",
"screen",
"matches",
"the",
"target",
"image"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L271-L278 | train | 35,117 |
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.setImageMode | def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat() | python | def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat() | [
"def",
"setImageMode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_version_server",
"==",
"3.889",
":",
"self",
".",
"setPixelFormat",
"(",
"bpp",
"=",
"16",
",",
"depth",
"=",
"16",
",",
"bigendian",
"=",
"0",
",",
"truecolor",
"=",
"1",
",",
"redma... | Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information | [
"Extracts",
"color",
"ordering",
"and",
"24",
"vs",
".",
"32",
"bpp",
"info",
"out",
"of",
"the",
"pixel",
"format",
"information"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L344-L363 | train | 35,118 |
sibson/vncdotool | vncdotool/rfb.py | RFBClient._handleDecodeHextileRAW | def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | python | def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | [
"def",
"_handleDecodeHextileRAW",
"(",
"self",
",",
"block",
",",
"bg",
",",
"color",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"tx",
",",
"ty",
",",
"tw",
",",
"th",
")",
":",
"self",
".",
"updateRectangle",
"(",
"tx",
",",
"ty",
","... | the tile is in raw encoding | [
"the",
"tile",
"is",
"in",
"raw",
"encoding"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L452-L455 | train | 35,119 |
sibson/vncdotool | vncdotool/rfb.py | RFBClient._handleDecodeHextileSubrectsColoured | def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | python | def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | [
"def",
"_handleDecodeHextileSubrectsColoured",
"(",
"self",
",",
"block",
",",
"bg",
",",
"color",
",",
"subrects",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"tx",
",",
"ty",
",",
"tw",
",",
"th",
")",
":",
"sz",
"=",
"self",
".",
"bypp... | subrects with their own color | [
"subrects",
"with",
"their",
"own",
"color"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L457-L473 | train | 35,120 |
sibson/vncdotool | vncdotool/rfb.py | RFBClient.fillRectangle | def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height) | python | def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height) | [
"def",
"fillRectangle",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
")",
":",
"#fallback variant, use update recatngle",
"#override with specialized function for better performance",
"self",
".",
"updateRectangle",
"(",
"x",
",",
"y",
... | fill the area with the color. the color is a string in
the pixel format set up earlier | [
"fill",
"the",
"area",
"with",
"the",
"color",
".",
"the",
"color",
"is",
"a",
"string",
"in",
"the",
"pixel",
"format",
"set",
"up",
"earlier"
] | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L634-L639 | train | 35,121 |
sibson/vncdotool | vncdotool/rfb.py | RFBDes.setKey | def setKey(self, key):
"""RFB protocol for authentication requires client to encrypt
challenge sent by server with password using DES method. However,
bits in each byte of the password are put in reverse order before
using it as encryption key."""
newkey = []
for ki in range(len(key)):
bsrc = ord(key[ki])
btgt = 0
for i in range(8):
if bsrc & (1 << i):
btgt = btgt | (1 << 7-i)
newkey.append(chr(btgt))
super(RFBDes, self).setKey(newkey) | python | def setKey(self, key):
"""RFB protocol for authentication requires client to encrypt
challenge sent by server with password using DES method. However,
bits in each byte of the password are put in reverse order before
using it as encryption key."""
newkey = []
for ki in range(len(key)):
bsrc = ord(key[ki])
btgt = 0
for i in range(8):
if bsrc & (1 << i):
btgt = btgt | (1 << 7-i)
newkey.append(chr(btgt))
super(RFBDes, self).setKey(newkey) | [
"def",
"setKey",
"(",
"self",
",",
"key",
")",
":",
"newkey",
"=",
"[",
"]",
"for",
"ki",
"in",
"range",
"(",
"len",
"(",
"key",
")",
")",
":",
"bsrc",
"=",
"ord",
"(",
"key",
"[",
"ki",
"]",
")",
"btgt",
"=",
"0",
"for",
"i",
"in",
"range"... | RFB protocol for authentication requires client to encrypt
challenge sent by server with password using DES method. However,
bits in each byte of the password are put in reverse order before
using it as encryption key. | [
"RFB",
"protocol",
"for",
"authentication",
"requires",
"client",
"to",
"encrypt",
"challenge",
"sent",
"by",
"server",
"with",
"password",
"using",
"DES",
"method",
".",
"However",
"bits",
"in",
"each",
"byte",
"of",
"the",
"password",
"are",
"put",
"in",
"... | e133a8916efaa0f5ed421e0aa737196624635b0c | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L667-L680 | train | 35,122 |
meraki-analytics/cassiopeia | cassiopeia/core/league.py | MiniSeries.not_played | def not_played(self) -> int:
"""The number of games in the player's promos that they haven't played yet."""
return len(self._data[MiniSeriesData].progress) - len(self.progress) | python | def not_played(self) -> int:
"""The number of games in the player's promos that they haven't played yet."""
return len(self._data[MiniSeriesData].progress) - len(self.progress) | [
"def",
"not_played",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"_data",
"[",
"MiniSeriesData",
"]",
".",
"progress",
")",
"-",
"len",
"(",
"self",
".",
"progress",
")"
] | The number of games in the player's promos that they haven't played yet. | [
"The",
"number",
"of",
"games",
"in",
"the",
"player",
"s",
"promos",
"that",
"they",
"haven",
"t",
"played",
"yet",
"."
] | de3db568586b34c0edf1f7736279485a4510822f | https://github.com/meraki-analytics/cassiopeia/blob/de3db568586b34c0edf1f7736279485a4510822f/cassiopeia/core/league.py#L134-L136 | train | 35,123 |
meraki-analytics/cassiopeia | cassiopeia/datastores/uniquekeys.py | _rgetattr | def _rgetattr(obj, key):
"""Recursive getattr for handling dots in keys."""
for k in key.split("."):
obj = getattr(obj, k)
return obj | python | def _rgetattr(obj, key):
"""Recursive getattr for handling dots in keys."""
for k in key.split("."):
obj = getattr(obj, k)
return obj | [
"def",
"_rgetattr",
"(",
"obj",
",",
"key",
")",
":",
"for",
"k",
"in",
"key",
".",
"split",
"(",
"\".\"",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"k",
")",
"return",
"obj"
] | Recursive getattr for handling dots in keys. | [
"Recursive",
"getattr",
"for",
"handling",
"dots",
"in",
"keys",
"."
] | de3db568586b34c0edf1f7736279485a4510822f | https://github.com/meraki-analytics/cassiopeia/blob/de3db568586b34c0edf1f7736279485a4510822f/cassiopeia/datastores/uniquekeys.py#L37-L41 | train | 35,124 |
wong2/pick | pick/__init__.py | Picker.draw | def draw(self):
"""draw the curses ui on the screen, handle scroll if needed"""
self.screen.clear()
x, y = 1, 1 # start point
max_y, max_x = self.screen.getmaxyx()
max_rows = max_y - y # the max rows we can draw
lines, current_line = self.get_lines()
# calculate how many lines we should scroll, relative to the top
scroll_top = getattr(self, 'scroll_top', 0)
if current_line <= scroll_top:
scroll_top = 0
elif current_line - scroll_top > max_rows:
scroll_top = current_line - max_rows
self.scroll_top = scroll_top
lines_to_draw = lines[scroll_top:scroll_top+max_rows]
for line in lines_to_draw:
if type(line) is tuple:
self.screen.addnstr(y, x, line[0], max_x-2, line[1])
else:
self.screen.addnstr(y, x, line, max_x-2)
y += 1
self.screen.refresh() | python | def draw(self):
"""draw the curses ui on the screen, handle scroll if needed"""
self.screen.clear()
x, y = 1, 1 # start point
max_y, max_x = self.screen.getmaxyx()
max_rows = max_y - y # the max rows we can draw
lines, current_line = self.get_lines()
# calculate how many lines we should scroll, relative to the top
scroll_top = getattr(self, 'scroll_top', 0)
if current_line <= scroll_top:
scroll_top = 0
elif current_line - scroll_top > max_rows:
scroll_top = current_line - max_rows
self.scroll_top = scroll_top
lines_to_draw = lines[scroll_top:scroll_top+max_rows]
for line in lines_to_draw:
if type(line) is tuple:
self.screen.addnstr(y, x, line[0], max_x-2, line[1])
else:
self.screen.addnstr(y, x, line, max_x-2)
y += 1
self.screen.refresh() | [
"def",
"draw",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"clear",
"(",
")",
"x",
",",
"y",
"=",
"1",
",",
"1",
"# start point",
"max_y",
",",
"max_x",
"=",
"self",
".",
"screen",
".",
"getmaxyx",
"(",
")",
"max_rows",
"=",
"max_y",
"-",
... | draw the curses ui on the screen, handle scroll if needed | [
"draw",
"the",
"curses",
"ui",
"on",
"the",
"screen",
"handle",
"scroll",
"if",
"needed"
] | bde1809387b17a0dd0b3250f03039e9123ecd9c7 | https://github.com/wong2/pick/blob/bde1809387b17a0dd0b3250f03039e9123ecd9c7/pick/__init__.py#L114-L141 | train | 35,125 |
chovanecm/sacredboard | sacredboard/app/webapi/files.py | get_file | def get_file(file_id: str, download):
"""
Get a specific file from GridFS.
Returns a binary stream response or HTTP 404 if not found.
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_files_dao()
file_fp, filename, upload_date = dao.get(file_id)
if download:
mime = mimetypes.guess_type(filename)[0]
if mime is None:
# unknown type
mime = "binary/octet-stream"
basename = os.path.basename(filename)
return send_file(file_fp, mimetype=mime, attachment_filename=basename, as_attachment=True)
else:
rawdata = file_fp.read()
try:
text = rawdata.decode('utf-8')
except UnicodeDecodeError:
# not decodable as utf-8
text = _get_binary_info(rawdata)
html = render_template("api/file_view.html", content=text)
file_fp.close()
return Response(html) | python | def get_file(file_id: str, download):
"""
Get a specific file from GridFS.
Returns a binary stream response or HTTP 404 if not found.
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_files_dao()
file_fp, filename, upload_date = dao.get(file_id)
if download:
mime = mimetypes.guess_type(filename)[0]
if mime is None:
# unknown type
mime = "binary/octet-stream"
basename = os.path.basename(filename)
return send_file(file_fp, mimetype=mime, attachment_filename=basename, as_attachment=True)
else:
rawdata = file_fp.read()
try:
text = rawdata.decode('utf-8')
except UnicodeDecodeError:
# not decodable as utf-8
text = _get_binary_info(rawdata)
html = render_template("api/file_view.html", content=text)
file_fp.close()
return Response(html) | [
"def",
"get_file",
"(",
"file_id",
":",
"str",
",",
"download",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"# type: DataStorage",
"dao",
"=",
"data",
".",
"get_files_dao",
"(",
")",
"file_fp",
",",
"filename",
",",
"upload_d... | Get a specific file from GridFS.
Returns a binary stream response or HTTP 404 if not found. | [
"Get",
"a",
"specific",
"file",
"from",
"GridFS",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/files.py#L36-L64 | train | 35,126 |
chovanecm/sacredboard | sacredboard/app/webapi/files.py | get_files_zip | def get_files_zip(run_id: int, filetype: _FileType):
"""Send all artifacts or sources of a run as ZIP."""
data = current_app.config["data"]
dao_runs = data.get_run_dao()
dao_files = data.get_files_dao()
run = dao_runs.get(run_id)
if filetype == _FileType.ARTIFACT:
target_files = run['artifacts']
elif filetype == _FileType.SOURCE:
target_files = run['experiment']['sources']
else:
raise Exception("Unknown file type: %s" % filetype)
memory_file = io.BytesIO()
with zipfile.ZipFile(memory_file, 'w') as zf:
for f in target_files:
# source and artifact files use a different data structure
file_id = f['file_id'] if 'file_id' in f else f[1]
file, filename, upload_date = dao_files.get(file_id)
data = zipfile.ZipInfo(filename, date_time=upload_date.timetuple())
data.compress_type = zipfile.ZIP_DEFLATED
zf.writestr(data, file.read())
memory_file.seek(0)
fn_suffix = _filetype_suffices[filetype]
return send_file(memory_file, attachment_filename='run{}_{}.zip'.format(run_id, fn_suffix), as_attachment=True) | python | def get_files_zip(run_id: int, filetype: _FileType):
"""Send all artifacts or sources of a run as ZIP."""
data = current_app.config["data"]
dao_runs = data.get_run_dao()
dao_files = data.get_files_dao()
run = dao_runs.get(run_id)
if filetype == _FileType.ARTIFACT:
target_files = run['artifacts']
elif filetype == _FileType.SOURCE:
target_files = run['experiment']['sources']
else:
raise Exception("Unknown file type: %s" % filetype)
memory_file = io.BytesIO()
with zipfile.ZipFile(memory_file, 'w') as zf:
for f in target_files:
# source and artifact files use a different data structure
file_id = f['file_id'] if 'file_id' in f else f[1]
file, filename, upload_date = dao_files.get(file_id)
data = zipfile.ZipInfo(filename, date_time=upload_date.timetuple())
data.compress_type = zipfile.ZIP_DEFLATED
zf.writestr(data, file.read())
memory_file.seek(0)
fn_suffix = _filetype_suffices[filetype]
return send_file(memory_file, attachment_filename='run{}_{}.zip'.format(run_id, fn_suffix), as_attachment=True) | [
"def",
"get_files_zip",
"(",
"run_id",
":",
"int",
",",
"filetype",
":",
"_FileType",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"dao_runs",
"=",
"data",
".",
"get_run_dao",
"(",
")",
"dao_files",
"=",
"data",
".",
"get_fi... | Send all artifacts or sources of a run as ZIP. | [
"Send",
"all",
"artifacts",
"or",
"sources",
"of",
"a",
"run",
"as",
"ZIP",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/files.py#L67-L93 | train | 35,127 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/filesdao.py | MongoFilesDAO.get | def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]:
"""
Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime
"""
if isinstance(file_id, str):
file_id = bson.ObjectId(file_id)
file = self._fs.get(file_id)
return file, file.filename, file.upload_date | python | def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]:
"""
Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime
"""
if isinstance(file_id, str):
file_id = bson.ObjectId(file_id)
file = self._fs.get(file_id)
return file, file.filename, file.upload_date | [
"def",
"get",
"(",
"self",
",",
"file_id",
":",
"Union",
"[",
"str",
",",
"bson",
".",
"ObjectId",
"]",
")",
"->",
"[",
"typing",
".",
"BinaryIO",
",",
"str",
",",
"datetime",
".",
"datetime",
"]",
":",
"if",
"isinstance",
"(",
"file_id",
",",
"str... | Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime | [
"Return",
"the",
"file",
"identified",
"by",
"a",
"file_id",
"string",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/filesdao.py#L27-L38 | train | 35,128 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/genericdao.py | GenericDAO.find_record | def find_record(self, collection_name, query):
"""
Return the first record mathing the given Mongo query.
:param collection_name: Name of the collection to search in.
:param query: MongoDB Query, e.g. {_id: 123}
:return: A single MongoDB record or None if not found.
:raise DataSourceError
"""
cursor = self._get_collection(collection_name).find(query)
for record in cursor:
# Return the first record found.
return record
# Return None if nothing found.
return None | python | def find_record(self, collection_name, query):
"""
Return the first record mathing the given Mongo query.
:param collection_name: Name of the collection to search in.
:param query: MongoDB Query, e.g. {_id: 123}
:return: A single MongoDB record or None if not found.
:raise DataSourceError
"""
cursor = self._get_collection(collection_name).find(query)
for record in cursor:
# Return the first record found.
return record
# Return None if nothing found.
return None | [
"def",
"find_record",
"(",
"self",
",",
"collection_name",
",",
"query",
")",
":",
"cursor",
"=",
"self",
".",
"_get_collection",
"(",
"collection_name",
")",
".",
"find",
"(",
"query",
")",
"for",
"record",
"in",
"cursor",
":",
"# Return the first record foun... | Return the first record mathing the given Mongo query.
:param collection_name: Name of the collection to search in.
:param query: MongoDB Query, e.g. {_id: 123}
:return: A single MongoDB record or None if not found.
:raise DataSourceError | [
"Return",
"the",
"first",
"record",
"mathing",
"the",
"given",
"Mongo",
"query",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L32-L47 | train | 35,129 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/genericdao.py | GenericDAO.find_records | def find_records(self, collection_name, query={}, sort_by=None,
sort_direction=None, start=0, limit=None):
"""
Return a cursor of records from the given MongoDB collection.
:param collection_name: Name of the MongoDB collection to query.
:param query: Standard MongoDB query. By default no restriction.
:param sort_by: Name of a single field to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:param start: Skip first n results.
:param limit: The maximum number of results to return.
:return: Cursor -- An iterable with results.
:raise DataSourceError
"""
cursor = self._get_collection(collection_name).find(query)
if sort_by is not None:
cursor = self._apply_sort(cursor, sort_by, sort_direction)
cursor = cursor.skip(start)
if limit is not None:
cursor = cursor.limit(limit)
return MongoDbCursor(cursor) | python | def find_records(self, collection_name, query={}, sort_by=None,
sort_direction=None, start=0, limit=None):
"""
Return a cursor of records from the given MongoDB collection.
:param collection_name: Name of the MongoDB collection to query.
:param query: Standard MongoDB query. By default no restriction.
:param sort_by: Name of a single field to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:param start: Skip first n results.
:param limit: The maximum number of results to return.
:return: Cursor -- An iterable with results.
:raise DataSourceError
"""
cursor = self._get_collection(collection_name).find(query)
if sort_by is not None:
cursor = self._apply_sort(cursor, sort_by, sort_direction)
cursor = cursor.skip(start)
if limit is not None:
cursor = cursor.limit(limit)
return MongoDbCursor(cursor) | [
"def",
"find_records",
"(",
"self",
",",
"collection_name",
",",
"query",
"=",
"{",
"}",
",",
"sort_by",
"=",
"None",
",",
"sort_direction",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"cursor",
"=",
"self",
".",
"_get_c... | Return a cursor of records from the given MongoDB collection.
:param collection_name: Name of the MongoDB collection to query.
:param query: Standard MongoDB query. By default no restriction.
:param sort_by: Name of a single field to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:param start: Skip first n results.
:param limit: The maximum number of results to return.
:return: Cursor -- An iterable with results.
:raise DataSourceError | [
"Return",
"a",
"cursor",
"of",
"records",
"from",
"the",
"given",
"MongoDB",
"collection",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L49-L70 | train | 35,130 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/genericdao.py | GenericDAO._get_database | def _get_database(self, database_name):
"""
Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError
"""
try:
return self._client[database_name]
except InvalidName as ex:
raise DataSourceError("Cannot connect to database %s!"
% self._database) from ex | python | def _get_database(self, database_name):
"""
Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError
"""
try:
return self._client[database_name]
except InvalidName as ex:
raise DataSourceError("Cannot connect to database %s!"
% self._database) from ex | [
"def",
"_get_database",
"(",
"self",
",",
"database_name",
")",
":",
"try",
":",
"return",
"self",
".",
"_client",
"[",
"database_name",
"]",
"except",
"InvalidName",
"as",
"ex",
":",
"raise",
"DataSourceError",
"(",
"\"Cannot connect to database %s!\"",
"%",
"s... | Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError | [
"Get",
"PyMongo",
"client",
"pointing",
"to",
"the",
"current",
"database",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L76-L87 | train | 35,131 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/genericdao.py | GenericDAO._get_collection | def _get_collection(self, collection_name):
"""
Get PyMongo client pointing to the current DB and the given collection.
:return: MongoDB client of the current database and given collection.
:raise DataSourceError
"""
try:
return self._database[collection_name]
except InvalidName as ex:
raise DataSourceError("Cannot access MongoDB collection %s!"
% collection_name) from ex
except Exception as ex:
raise DataSourceError("Unexpected error when accessing MongoDB"
"collection %s!"
% collection_name) from ex | python | def _get_collection(self, collection_name):
"""
Get PyMongo client pointing to the current DB and the given collection.
:return: MongoDB client of the current database and given collection.
:raise DataSourceError
"""
try:
return self._database[collection_name]
except InvalidName as ex:
raise DataSourceError("Cannot access MongoDB collection %s!"
% collection_name) from ex
except Exception as ex:
raise DataSourceError("Unexpected error when accessing MongoDB"
"collection %s!"
% collection_name) from ex | [
"def",
"_get_collection",
"(",
"self",
",",
"collection_name",
")",
":",
"try",
":",
"return",
"self",
".",
"_database",
"[",
"collection_name",
"]",
"except",
"InvalidName",
"as",
"ex",
":",
"raise",
"DataSourceError",
"(",
"\"Cannot access MongoDB collection %s!\"... | Get PyMongo client pointing to the current DB and the given collection.
:return: MongoDB client of the current database and given collection.
:raise DataSourceError | [
"Get",
"PyMongo",
"client",
"pointing",
"to",
"the",
"current",
"DB",
"and",
"the",
"given",
"collection",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L89-L104 | train | 35,132 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO.get | def get(self, run_id):
"""
Get a single run from the database.
:param run_id: The ID of the run.
:return: The whole object from the database.
:raise NotFoundError when not found
"""
id = self._parse_id(run_id)
run = self.generic_dao.find_record(self.collection_name,
{"_id": id})
if run is None:
raise NotFoundError("Run %s not found." % run_id)
return run | python | def get(self, run_id):
"""
Get a single run from the database.
:param run_id: The ID of the run.
:return: The whole object from the database.
:raise NotFoundError when not found
"""
id = self._parse_id(run_id)
run = self.generic_dao.find_record(self.collection_name,
{"_id": id})
if run is None:
raise NotFoundError("Run %s not found." % run_id)
return run | [
"def",
"get",
"(",
"self",
",",
"run_id",
")",
":",
"id",
"=",
"self",
".",
"_parse_id",
"(",
"run_id",
")",
"run",
"=",
"self",
".",
"generic_dao",
".",
"find_record",
"(",
"self",
".",
"collection_name",
",",
"{",
"\"_id\"",
":",
"id",
"}",
")",
... | Get a single run from the database.
:param run_id: The ID of the run.
:return: The whole object from the database.
:raise NotFoundError when not found | [
"Get",
"a",
"single",
"run",
"from",
"the",
"database",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L72-L86 | train | 35,133 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO._apply_sort | def _apply_sort(cursor, sort_by, sort_direction):
"""
Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:return:
"""
if sort_direction is not None and sort_direction.lower() == "desc":
sort = pymongo.DESCENDING
else:
sort = pymongo.ASCENDING
return cursor.sort(sort_by, sort) | python | def _apply_sort(cursor, sort_by, sort_direction):
"""
Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:return:
"""
if sort_direction is not None and sort_direction.lower() == "desc":
sort = pymongo.DESCENDING
else:
sort = pymongo.ASCENDING
return cursor.sort(sort_by, sort) | [
"def",
"_apply_sort",
"(",
"cursor",
",",
"sort_by",
",",
"sort_direction",
")",
":",
"if",
"sort_direction",
"is",
"not",
"None",
"and",
"sort_direction",
".",
"lower",
"(",
")",
"==",
"\"desc\"",
":",
"sort",
"=",
"pymongo",
".",
"DESCENDING",
"else",
":... | Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:return: | [
"Apply",
"sort",
"to",
"a",
"cursor",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L97-L111 | train | 35,134 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO._to_mongo_query | def _to_mongo_query(query):
"""
Convert the query received by the Sacred Web API to a MongoDB query.
Takes a query in format
{"type": "and", "filters": [
{"field": "host.hostname", "operator": "==", "value": "ntbacer"},
{"type": "or", "filters": [
{"field": "result", "operator": "==", "value": 2403.52},
{"field": "host.python_version", "operator": "==", "value":"3.5.2"}
]}]}
and returns an appropriate MongoDB Query.
:param query: A query in the Sacred Web API format.
:return: Mongo Query.
"""
mongo_query = []
for clause in query["filters"]:
if clause.get("type") is None:
mongo_clause = MongoRunDAO. \
_simple_clause_to_query(clause)
else:
# It's a subclause
mongo_clause = MongoRunDAO._to_mongo_query(clause)
mongo_query.append(mongo_clause)
if len(mongo_query) == 0:
return {}
if query["type"] == "and":
return {"$and": mongo_query}
elif query["type"] == "or":
return {"$or": mongo_query}
else:
raise ValueError("Unexpected query type %s" % query.get("type")) | python | def _to_mongo_query(query):
"""
Convert the query received by the Sacred Web API to a MongoDB query.
Takes a query in format
{"type": "and", "filters": [
{"field": "host.hostname", "operator": "==", "value": "ntbacer"},
{"type": "or", "filters": [
{"field": "result", "operator": "==", "value": 2403.52},
{"field": "host.python_version", "operator": "==", "value":"3.5.2"}
]}]}
and returns an appropriate MongoDB Query.
:param query: A query in the Sacred Web API format.
:return: Mongo Query.
"""
mongo_query = []
for clause in query["filters"]:
if clause.get("type") is None:
mongo_clause = MongoRunDAO. \
_simple_clause_to_query(clause)
else:
# It's a subclause
mongo_clause = MongoRunDAO._to_mongo_query(clause)
mongo_query.append(mongo_clause)
if len(mongo_query) == 0:
return {}
if query["type"] == "and":
return {"$and": mongo_query}
elif query["type"] == "or":
return {"$or": mongo_query}
else:
raise ValueError("Unexpected query type %s" % query.get("type")) | [
"def",
"_to_mongo_query",
"(",
"query",
")",
":",
"mongo_query",
"=",
"[",
"]",
"for",
"clause",
"in",
"query",
"[",
"\"filters\"",
"]",
":",
"if",
"clause",
".",
"get",
"(",
"\"type\"",
")",
"is",
"None",
":",
"mongo_clause",
"=",
"MongoRunDAO",
".",
... | Convert the query received by the Sacred Web API to a MongoDB query.
Takes a query in format
{"type": "and", "filters": [
{"field": "host.hostname", "operator": "==", "value": "ntbacer"},
{"type": "or", "filters": [
{"field": "result", "operator": "==", "value": 2403.52},
{"field": "host.python_version", "operator": "==", "value":"3.5.2"}
]}]}
and returns an appropriate MongoDB Query.
:param query: A query in the Sacred Web API format.
:return: Mongo Query. | [
"Convert",
"the",
"query",
"received",
"by",
"the",
"Sacred",
"Web",
"API",
"to",
"a",
"MongoDB",
"query",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L114-L146 | train | 35,135 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO._simple_clause_to_query | def _simple_clause_to_query(clause):
"""
Convert a clause from the Sacred Web API format to the MongoDB format.
:param clause: A clause to be converted. It must have "field",
"operator" and "value" fields.
:return: A MongoDB clause.
"""
# It's a regular clause
mongo_clause = {}
value = clause["value"]
if clause["field"] == "status" and clause["value"] in ["DEAD",
"RUNNING"]:
return MongoRunDAO. \
_status_filter_to_query(clause)
if clause["operator"] == "==":
mongo_clause[clause["field"]] = value
elif clause["operator"] == ">":
mongo_clause[clause["field"]] = {"$gt": value}
elif clause["operator"] == ">=":
mongo_clause[clause["field"]] = {"$gte": value}
elif clause["operator"] == "<":
mongo_clause[clause["field"]] = {"$lt": value}
elif clause["operator"] == "<=":
mongo_clause[clause["field"]] = {"$lte": value}
elif clause["operator"] == "!=":
mongo_clause[clause["field"]] = {"$ne": value}
elif clause["operator"] == "regex":
mongo_clause[clause["field"]] = {"$regex": value}
return mongo_clause | python | def _simple_clause_to_query(clause):
"""
Convert a clause from the Sacred Web API format to the MongoDB format.
:param clause: A clause to be converted. It must have "field",
"operator" and "value" fields.
:return: A MongoDB clause.
"""
# It's a regular clause
mongo_clause = {}
value = clause["value"]
if clause["field"] == "status" and clause["value"] in ["DEAD",
"RUNNING"]:
return MongoRunDAO. \
_status_filter_to_query(clause)
if clause["operator"] == "==":
mongo_clause[clause["field"]] = value
elif clause["operator"] == ">":
mongo_clause[clause["field"]] = {"$gt": value}
elif clause["operator"] == ">=":
mongo_clause[clause["field"]] = {"$gte": value}
elif clause["operator"] == "<":
mongo_clause[clause["field"]] = {"$lt": value}
elif clause["operator"] == "<=":
mongo_clause[clause["field"]] = {"$lte": value}
elif clause["operator"] == "!=":
mongo_clause[clause["field"]] = {"$ne": value}
elif clause["operator"] == "regex":
mongo_clause[clause["field"]] = {"$regex": value}
return mongo_clause | [
"def",
"_simple_clause_to_query",
"(",
"clause",
")",
":",
"# It's a regular clause",
"mongo_clause",
"=",
"{",
"}",
"value",
"=",
"clause",
"[",
"\"value\"",
"]",
"if",
"clause",
"[",
"\"field\"",
"]",
"==",
"\"status\"",
"and",
"clause",
"[",
"\"value\"",
"]... | Convert a clause from the Sacred Web API format to the MongoDB format.
:param clause: A clause to be converted. It must have "field",
"operator" and "value" fields.
:return: A MongoDB clause. | [
"Convert",
"a",
"clause",
"from",
"the",
"Sacred",
"Web",
"API",
"format",
"to",
"the",
"MongoDB",
"format",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L149-L178 | train | 35,136 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO._status_filter_to_query | def _status_filter_to_query(clause):
"""
Convert a clause querying for an experiment state RUNNING or DEAD.
Queries that check for experiment state RUNNING and DEAD need to be
replaced by the logic that decides these two states as both of them
are stored in the Mongo Database as "RUNNING". We use querying by last
heartbeat time.
:param clause: A clause whose field is "status" and "value" is one of
RUNNING, DEAD.
:return: A MongoDB clause.
"""
if clause["value"] == "RUNNING":
mongo_clause = MongoRunDAO.RUNNING_NOT_DEAD_CLAUSE
elif clause["value"] == "DEAD":
mongo_clause = MongoRunDAO.RUNNING_DEAD_RUN_CLAUSE
if clause["operator"] == "!=":
mongo_clause = {"$not": mongo_clause}
return mongo_clause | python | def _status_filter_to_query(clause):
"""
Convert a clause querying for an experiment state RUNNING or DEAD.
Queries that check for experiment state RUNNING and DEAD need to be
replaced by the logic that decides these two states as both of them
are stored in the Mongo Database as "RUNNING". We use querying by last
heartbeat time.
:param clause: A clause whose field is "status" and "value" is one of
RUNNING, DEAD.
:return: A MongoDB clause.
"""
if clause["value"] == "RUNNING":
mongo_clause = MongoRunDAO.RUNNING_NOT_DEAD_CLAUSE
elif clause["value"] == "DEAD":
mongo_clause = MongoRunDAO.RUNNING_DEAD_RUN_CLAUSE
if clause["operator"] == "!=":
mongo_clause = {"$not": mongo_clause}
return mongo_clause | [
"def",
"_status_filter_to_query",
"(",
"clause",
")",
":",
"if",
"clause",
"[",
"\"value\"",
"]",
"==",
"\"RUNNING\"",
":",
"mongo_clause",
"=",
"MongoRunDAO",
".",
"RUNNING_NOT_DEAD_CLAUSE",
"elif",
"clause",
"[",
"\"value\"",
"]",
"==",
"\"DEAD\"",
":",
"mongo... | Convert a clause querying for an experiment state RUNNING or DEAD.
Queries that check for experiment state RUNNING and DEAD need to be
replaced by the logic that decides these two states as both of them
are stored in the Mongo Database as "RUNNING". We use querying by last
heartbeat time.
:param clause: A clause whose field is "status" and "value" is one of
RUNNING, DEAD.
:return: A MongoDB clause. | [
"Convert",
"a",
"clause",
"querying",
"for",
"an",
"experiment",
"state",
"RUNNING",
"or",
"DEAD",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L181-L200 | train | 35,137 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/rundao.py | MongoRunDAO.delete | def delete(self, run_id):
"""
Delete run with the given id from the backend.
:param run_id: Id of the run to delete.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed
even if the run does not exist.
"""
return self.generic_dao.delete_record(self.collection_name,
self._parse_id(run_id)) | python | def delete(self, run_id):
"""
Delete run with the given id from the backend.
:param run_id: Id of the run to delete.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed
even if the run does not exist.
"""
return self.generic_dao.delete_record(self.collection_name,
self._parse_id(run_id)) | [
"def",
"delete",
"(",
"self",
",",
"run_id",
")",
":",
"return",
"self",
".",
"generic_dao",
".",
"delete_record",
"(",
"self",
".",
"collection_name",
",",
"self",
".",
"_parse_id",
"(",
"run_id",
")",
")"
] | Delete run with the given id from the backend.
:param run_id: Id of the run to delete.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed
even if the run does not exist. | [
"Delete",
"run",
"with",
"the",
"given",
"id",
"from",
"the",
"backend",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L202-L213 | train | 35,138 |
chovanecm/sacredboard | sacredboard/bootstrap.py | add_mongo_config | def add_mongo_config(app, simple_connection_string,
mongo_uri, collection_name):
"""
Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exclusive with mongo_uri
:param mongo_uri: Expects mongodb://... as defined
in https://docs.mongodb.com/manual/reference/connection-string/
Mutually exclusive with simple_connection_string (must be None)
:param collection_name: The collection containing Sacred's runs
:return:
"""
if mongo_uri != (None, None):
add_mongo_config_with_uri(app, mongo_uri[0], mongo_uri[1],
collection_name)
if simple_connection_string is not None:
print("Ignoring the -m option. Overridden by "
"a more specific option (-mu).", file=sys.stderr)
else:
# Use the default value 'sacred' when not specified
if simple_connection_string is None:
simple_connection_string = "sacred"
add_mongo_config_simple(app, simple_connection_string, collection_name) | python | def add_mongo_config(app, simple_connection_string,
mongo_uri, collection_name):
"""
Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exclusive with mongo_uri
:param mongo_uri: Expects mongodb://... as defined
in https://docs.mongodb.com/manual/reference/connection-string/
Mutually exclusive with simple_connection_string (must be None)
:param collection_name: The collection containing Sacred's runs
:return:
"""
if mongo_uri != (None, None):
add_mongo_config_with_uri(app, mongo_uri[0], mongo_uri[1],
collection_name)
if simple_connection_string is not None:
print("Ignoring the -m option. Overridden by "
"a more specific option (-mu).", file=sys.stderr)
else:
# Use the default value 'sacred' when not specified
if simple_connection_string is None:
simple_connection_string = "sacred"
add_mongo_config_simple(app, simple_connection_string, collection_name) | [
"def",
"add_mongo_config",
"(",
"app",
",",
"simple_connection_string",
",",
"mongo_uri",
",",
"collection_name",
")",
":",
"if",
"mongo_uri",
"!=",
"(",
"None",
",",
"None",
")",
":",
"add_mongo_config_with_uri",
"(",
"app",
",",
"mongo_uri",
"[",
"0",
"]",
... | Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exclusive with mongo_uri
:param mongo_uri: Expects mongodb://... as defined
in https://docs.mongodb.com/manual/reference/connection-string/
Mutually exclusive with simple_connection_string (must be None)
:param collection_name: The collection containing Sacred's runs
:return: | [
"Configure",
"the",
"application",
"to",
"use",
"MongoDB",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/bootstrap.py#L133-L158 | train | 35,139 |
chovanecm/sacredboard | sacredboard/bootstrap.py | add_mongo_config_simple | def add_mongo_config_simple(app, connection_string, collection_name):
"""
Configure the app to use MongoDB.
:param app: Flask Application
:type app: Flask
:param connection_string: in format host:port:database or database
(default: sacred)
:type connection_string: str
:param collection_name: Name of the collection
:type collection_name: str
"""
split_string = connection_string.split(":")
config = {"host": "localhost", "port": 27017, "db": "sacred"}
if len(split_string) > 0 and len(split_string[-1]) > 0:
config["db"] = split_string[-1]
if len(split_string) > 1:
config["port"] = int(split_string[-2])
if len(split_string) > 2:
config["host"] = split_string[-3]
app.config["data"] = PyMongoDataAccess.build_data_access(
config["host"], config["port"], config["db"], collection_name) | python | def add_mongo_config_simple(app, connection_string, collection_name):
"""
Configure the app to use MongoDB.
:param app: Flask Application
:type app: Flask
:param connection_string: in format host:port:database or database
(default: sacred)
:type connection_string: str
:param collection_name: Name of the collection
:type collection_name: str
"""
split_string = connection_string.split(":")
config = {"host": "localhost", "port": 27017, "db": "sacred"}
if len(split_string) > 0 and len(split_string[-1]) > 0:
config["db"] = split_string[-1]
if len(split_string) > 1:
config["port"] = int(split_string[-2])
if len(split_string) > 2:
config["host"] = split_string[-3]
app.config["data"] = PyMongoDataAccess.build_data_access(
config["host"], config["port"], config["db"], collection_name) | [
"def",
"add_mongo_config_simple",
"(",
"app",
",",
"connection_string",
",",
"collection_name",
")",
":",
"split_string",
"=",
"connection_string",
".",
"split",
"(",
"\":\"",
")",
"config",
"=",
"{",
"\"host\"",
":",
"\"localhost\"",
",",
"\"port\"",
":",
"2701... | Configure the app to use MongoDB.
:param app: Flask Application
:type app: Flask
:param connection_string: in format host:port:database or database
(default: sacred)
:type connection_string: str
:param collection_name: Name of the collection
:type collection_name: str | [
"Configure",
"the",
"app",
"to",
"use",
"MongoDB",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/bootstrap.py#L161-L183 | train | 35,140 |
chovanecm/sacredboard | sacredboard/bootstrap.py | add_mongo_config_with_uri | def add_mongo_config_with_uri(app, connection_string_uri,
database_name, collection_name):
"""
Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred database name
:param collection_name: Sacred's collection with runs
:return:
"""
app.config["data"] = PyMongoDataAccess.build_data_access_with_uri(
connection_string_uri, database_name, collection_name
) | python | def add_mongo_config_with_uri(app, connection_string_uri,
database_name, collection_name):
"""
Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred database name
:param collection_name: Sacred's collection with runs
:return:
"""
app.config["data"] = PyMongoDataAccess.build_data_access_with_uri(
connection_string_uri, database_name, collection_name
) | [
"def",
"add_mongo_config_with_uri",
"(",
"app",
",",
"connection_string_uri",
",",
"database_name",
",",
"collection_name",
")",
":",
"app",
".",
"config",
"[",
"\"data\"",
"]",
"=",
"PyMongoDataAccess",
".",
"build_data_access_with_uri",
"(",
"connection_string_uri",
... | Configure PyMongo with a MongoDB connection string.
:param app: Flask application
:param connection_string_uri: MongoDB connection string
:param database_name: Sacred database name
:param collection_name: Sacred's collection with runs
:return: | [
"Configure",
"PyMongo",
"with",
"a",
"MongoDB",
"connection",
"string",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/bootstrap.py#L186-L199 | train | 35,141 |
chovanecm/sacredboard | sacredboard/app/process/tensorboard.py | stop_all_tensorboards | def stop_all_tensorboards():
"""Terminate all TensorBoard instances."""
for process in Process.instances:
print("Process '%s', running %d" % (process.command[0],
process.is_running()))
if process.is_running() and process.command[0] == "tensorboard":
process.terminate() | python | def stop_all_tensorboards():
"""Terminate all TensorBoard instances."""
for process in Process.instances:
print("Process '%s', running %d" % (process.command[0],
process.is_running()))
if process.is_running() and process.command[0] == "tensorboard":
process.terminate() | [
"def",
"stop_all_tensorboards",
"(",
")",
":",
"for",
"process",
"in",
"Process",
".",
"instances",
":",
"print",
"(",
"\"Process '%s', running %d\"",
"%",
"(",
"process",
".",
"command",
"[",
"0",
"]",
",",
"process",
".",
"is_running",
"(",
")",
")",
")"... | Terminate all TensorBoard instances. | [
"Terminate",
"all",
"TensorBoard",
"instances",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/process/tensorboard.py#L11-L17 | train | 35,142 |
chovanecm/sacredboard | sacredboard/app/process/tensorboard.py | run_tensorboard | def run_tensorboard(logdir, listen_on="0.0.0.0", port=0, tensorboard_args=None, timeout=10):
"""
Launch a new TensorBoard instance.
:param logdir: Path to a TensorFlow summary directory
:param listen_on: The IP address TensorBoard should listen on.
:param port: Port number to listen on. 0 for a random port.
:param tensorboard_args: Additional TensorBoard arguments.
:param timeout: Timeout after which the Timeout
:type timeout: float
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError
:raise TensorboardNotFoundError
:raise TimeoutError
"""
if tensorboard_args is None:
tensorboard_args = []
tensorboard_instance = Process.create_process(
TENSORBOARD_BINARY.split(" ") +
["--logdir", logdir, "--host", listen_on, "--port", str(port)] + tensorboard_args)
try:
tensorboard_instance.run()
except FileNotFoundError as ex:
raise TensorboardNotFoundError(ex)
# Wait for a message that signaliezes start of Tensorboard
start = time.time()
data = ""
while time.time() - start < timeout:
line = tensorboard_instance.read_line_stderr(time_limit=timeout)
data += line
if "at http://" in line:
port = parse_port_from_tensorboard_output(line)
# Good case
return port
elif "TensorBoard attempted to bind to port" in line:
break
tensorboard_instance.terminate()
raise UnexpectedOutputError(
data,
expected="Confirmation that Tensorboard has started"
) | python | def run_tensorboard(logdir, listen_on="0.0.0.0", port=0, tensorboard_args=None, timeout=10):
"""
Launch a new TensorBoard instance.
:param logdir: Path to a TensorFlow summary directory
:param listen_on: The IP address TensorBoard should listen on.
:param port: Port number to listen on. 0 for a random port.
:param tensorboard_args: Additional TensorBoard arguments.
:param timeout: Timeout after which the Timeout
:type timeout: float
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError
:raise TensorboardNotFoundError
:raise TimeoutError
"""
if tensorboard_args is None:
tensorboard_args = []
tensorboard_instance = Process.create_process(
TENSORBOARD_BINARY.split(" ") +
["--logdir", logdir, "--host", listen_on, "--port", str(port)] + tensorboard_args)
try:
tensorboard_instance.run()
except FileNotFoundError as ex:
raise TensorboardNotFoundError(ex)
# Wait for a message that signaliezes start of Tensorboard
start = time.time()
data = ""
while time.time() - start < timeout:
line = tensorboard_instance.read_line_stderr(time_limit=timeout)
data += line
if "at http://" in line:
port = parse_port_from_tensorboard_output(line)
# Good case
return port
elif "TensorBoard attempted to bind to port" in line:
break
tensorboard_instance.terminate()
raise UnexpectedOutputError(
data,
expected="Confirmation that Tensorboard has started"
) | [
"def",
"run_tensorboard",
"(",
"logdir",
",",
"listen_on",
"=",
"\"0.0.0.0\"",
",",
"port",
"=",
"0",
",",
"tensorboard_args",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"tensorboard_args",
"is",
"None",
":",
"tensorboard_args",
"=",
"[",
"]",... | Launch a new TensorBoard instance.
:param logdir: Path to a TensorFlow summary directory
:param listen_on: The IP address TensorBoard should listen on.
:param port: Port number to listen on. 0 for a random port.
:param tensorboard_args: Additional TensorBoard arguments.
:param timeout: Timeout after which the Timeout
:type timeout: float
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError
:raise TensorboardNotFoundError
:raise TimeoutError | [
"Launch",
"a",
"new",
"TensorBoard",
"instance",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/process/tensorboard.py#L26-L68 | train | 35,143 |
chovanecm/sacredboard | sacredboard/app/process/tensorboard.py | parse_port_from_tensorboard_output | def parse_port_from_tensorboard_output(tensorboard_output: str) -> int:
"""
Parse tensorboard port from its outputted message.
:param tensorboard_output: Output message of Tensorboard
in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError
"""
search = re.search("at http://[^:]+:([0-9]+)", tensorboard_output)
if search is not None:
port = search.group(1)
return int(port)
else:
raise UnexpectedOutputError(tensorboard_output, "Address and port where Tensorboard has started,"
" e.g. TensorBoard 1.8.0 at http://martin-VirtualBox:36869") | python | def parse_port_from_tensorboard_output(tensorboard_output: str) -> int:
"""
Parse tensorboard port from its outputted message.
:param tensorboard_output: Output message of Tensorboard
in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError
"""
search = re.search("at http://[^:]+:([0-9]+)", tensorboard_output)
if search is not None:
port = search.group(1)
return int(port)
else:
raise UnexpectedOutputError(tensorboard_output, "Address and port where Tensorboard has started,"
" e.g. TensorBoard 1.8.0 at http://martin-VirtualBox:36869") | [
"def",
"parse_port_from_tensorboard_output",
"(",
"tensorboard_output",
":",
"str",
")",
"->",
"int",
":",
"search",
"=",
"re",
".",
"search",
"(",
"\"at http://[^:]+:([0-9]+)\"",
",",
"tensorboard_output",
")",
"if",
"search",
"is",
"not",
"None",
":",
"port",
... | Parse tensorboard port from its outputted message.
:param tensorboard_output: Output message of Tensorboard
in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869
:return: Returns the port TensorBoard is listening on.
:raise UnexpectedOutputError | [
"Parse",
"tensorboard",
"port",
"from",
"its",
"outputted",
"message",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/process/tensorboard.py#L71-L86 | train | 35,144 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/mongodb.py | PyMongoDataAccess.connect | def connect(self):
"""Initialize the database connection."""
self._client = self._create_client()
self._db = getattr(self._client, self._db_name)
self._generic_dao = GenericDAO(self._client, self._db_name) | python | def connect(self):
"""Initialize the database connection."""
self._client = self._create_client()
self._db = getattr(self._client, self._db_name)
self._generic_dao = GenericDAO(self._client, self._db_name) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_client",
"=",
"self",
".",
"_create_client",
"(",
")",
"self",
".",
"_db",
"=",
"getattr",
"(",
"self",
".",
"_client",
",",
"self",
".",
"_db_name",
")",
"self",
".",
"_generic_dao",
"=",
"Gene... | Initialize the database connection. | [
"Initialize",
"the",
"database",
"connection",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/mongodb.py#L44-L48 | train | 35,145 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/mongodb.py | PyMongoDataAccess.build_data_access | def build_data_access(host, port, database_name, collection_name):
"""
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type database_name: str
:param collection_name: Name of the collection with Sacred runs.
:type collection_name: str
"""
return PyMongoDataAccess("mongodb://%s:%d" % (host, port),
database_name, collection_name) | python | def build_data_access(host, port, database_name, collection_name):
"""
Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type database_name: str
:param collection_name: Name of the collection with Sacred runs.
:type collection_name: str
"""
return PyMongoDataAccess("mongodb://%s:%d" % (host, port),
database_name, collection_name) | [
"def",
"build_data_access",
"(",
"host",
",",
"port",
",",
"database_name",
",",
"collection_name",
")",
":",
"return",
"PyMongoDataAccess",
"(",
"\"mongodb://%s:%d\"",
"%",
"(",
"host",
",",
"port",
")",
",",
"database_name",
",",
"collection_name",
")"
] | Create data access gateway.
:param host: The database server to connect to.
:type host: str
:param port: Database port.
:type port: int
:param database_name: Database name.
:type database_name: str
:param collection_name: Name of the collection with Sacred runs.
:type collection_name: str | [
"Create",
"data",
"access",
"gateway",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/mongodb.py#L55-L69 | train | 35,146 |
chovanecm/sacredboard | sacredboard/app/webapi/routes.py | run_tensorboard | def run_tensorboard(run_id, tflog_id):
"""Launch TensorBoard for a given run ID and log ID of that run."""
data = current_app.config["data"]
# optimisticaly suppose the run exists...
run = data.get_run_dao().get(run_id)
base_dir = Path(run["experiment"]["base_dir"])
log_dir = Path(run["info"]["tensorflow"]["logdirs"][tflog_id])
# TODO ugly!!!
if log_dir.is_absolute():
path_to_log_dir = log_dir
else:
path_to_log_dir = base_dir.joinpath(log_dir)
port = int(tensorboard.run_tensorboard(str(path_to_log_dir)))
url_root = request.url_root
url_parts = re.search("://([^:/]+)", url_root)
redirect_to_address = url_parts.group(1)
return redirect("http://%s:%d" % (redirect_to_address, port)) | python | def run_tensorboard(run_id, tflog_id):
"""Launch TensorBoard for a given run ID and log ID of that run."""
data = current_app.config["data"]
# optimisticaly suppose the run exists...
run = data.get_run_dao().get(run_id)
base_dir = Path(run["experiment"]["base_dir"])
log_dir = Path(run["info"]["tensorflow"]["logdirs"][tflog_id])
# TODO ugly!!!
if log_dir.is_absolute():
path_to_log_dir = log_dir
else:
path_to_log_dir = base_dir.joinpath(log_dir)
port = int(tensorboard.run_tensorboard(str(path_to_log_dir)))
url_root = request.url_root
url_parts = re.search("://([^:/]+)", url_root)
redirect_to_address = url_parts.group(1)
return redirect("http://%s:%d" % (redirect_to_address, port)) | [
"def",
"run_tensorboard",
"(",
"run_id",
",",
"tflog_id",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"# optimisticaly suppose the run exists...",
"run",
"=",
"data",
".",
"get_run_dao",
"(",
")",
".",
"get",
"(",
"run_id",
")",
... | Launch TensorBoard for a given run ID and log ID of that run. | [
"Launch",
"TensorBoard",
"for",
"a",
"given",
"run",
"ID",
"and",
"log",
"ID",
"of",
"that",
"run",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/routes.py#L39-L56 | train | 35,147 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/metricsdao.py | MongoMetricsDAO.get | def get(self, run_id, metric_id):
"""
Read a metric of the given id and run.
The returned object has the following format (timestamps are datetime
objects).
.. code::
{"steps": [0,1,20,40,...],
"timestamps": [timestamp1,timestamp2,timestamp3,...],
"values": [0,1 2,3,4,5,6,...],
"name": "name of the metric",
"metric_id": "metric_id",
"run_id": "run_id"}
:param run_id: ID of the Run that the metric belongs to.
:param metric_id: The ID fo the metric.
:return: The whole metric as specified.
:raise NotFoundError
"""
run_id = self._parse_run_id(run_id)
query = self._build_query(run_id, metric_id)
row = self._read_metric_from_db(metric_id, run_id, query)
metric = self._to_intermediary_object(row)
return metric | python | def get(self, run_id, metric_id):
"""
Read a metric of the given id and run.
The returned object has the following format (timestamps are datetime
objects).
.. code::
{"steps": [0,1,20,40,...],
"timestamps": [timestamp1,timestamp2,timestamp3,...],
"values": [0,1 2,3,4,5,6,...],
"name": "name of the metric",
"metric_id": "metric_id",
"run_id": "run_id"}
:param run_id: ID of the Run that the metric belongs to.
:param metric_id: The ID fo the metric.
:return: The whole metric as specified.
:raise NotFoundError
"""
run_id = self._parse_run_id(run_id)
query = self._build_query(run_id, metric_id)
row = self._read_metric_from_db(metric_id, run_id, query)
metric = self._to_intermediary_object(row)
return metric | [
"def",
"get",
"(",
"self",
",",
"run_id",
",",
"metric_id",
")",
":",
"run_id",
"=",
"self",
".",
"_parse_run_id",
"(",
"run_id",
")",
"query",
"=",
"self",
".",
"_build_query",
"(",
"run_id",
",",
"metric_id",
")",
"row",
"=",
"self",
".",
"_read_metr... | Read a metric of the given id and run.
The returned object has the following format (timestamps are datetime
objects).
.. code::
{"steps": [0,1,20,40,...],
"timestamps": [timestamp1,timestamp2,timestamp3,...],
"values": [0,1 2,3,4,5,6,...],
"name": "name of the metric",
"metric_id": "metric_id",
"run_id": "run_id"}
:param run_id: ID of the Run that the metric belongs to.
:param metric_id: The ID fo the metric.
:return: The whole metric as specified.
:raise NotFoundError | [
"Read",
"a",
"metric",
"of",
"the",
"given",
"id",
"and",
"run",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/metricsdao.py#L29-L55 | train | 35,148 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/metricsdao.py | MongoMetricsDAO.delete | def delete(self, run_id):
"""
Delete all metrics belonging to the given run.
:param run_id: ID of the Run that the metric belongs to.
"""
self.generic_dao.delete_record(
self.metrics_collection_name,
{"run_id": self._parse_run_id(run_id)}) | python | def delete(self, run_id):
"""
Delete all metrics belonging to the given run.
:param run_id: ID of the Run that the metric belongs to.
"""
self.generic_dao.delete_record(
self.metrics_collection_name,
{"run_id": self._parse_run_id(run_id)}) | [
"def",
"delete",
"(",
"self",
",",
"run_id",
")",
":",
"self",
".",
"generic_dao",
".",
"delete_record",
"(",
"self",
".",
"metrics_collection_name",
",",
"{",
"\"run_id\"",
":",
"self",
".",
"_parse_run_id",
"(",
"run_id",
")",
"}",
")"
] | Delete all metrics belonging to the given run.
:param run_id: ID of the Run that the metric belongs to. | [
"Delete",
"all",
"metrics",
"belonging",
"to",
"the",
"given",
"run",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/metricsdao.py#L57-L65 | train | 35,149 |
chovanecm/sacredboard | sacredboard/app/business/runfacade.py | RunFacade.delete_run | def delete_run(self, run_id):
"""
Delete run of the given run_id.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist.
"""
ds = self.datastorage
ds.get_metrics_dao().delete(run_id)
# TODO: implement
# ds.get_artifact_dao().delete(run_id)
# ds.get_resource_dao().delete(run_id)
ds.get_run_dao().delete(run_id) | python | def delete_run(self, run_id):
"""
Delete run of the given run_id.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist.
"""
ds = self.datastorage
ds.get_metrics_dao().delete(run_id)
# TODO: implement
# ds.get_artifact_dao().delete(run_id)
# ds.get_resource_dao().delete(run_id)
ds.get_run_dao().delete(run_id) | [
"def",
"delete_run",
"(",
"self",
",",
"run_id",
")",
":",
"ds",
"=",
"self",
".",
"datastorage",
"ds",
".",
"get_metrics_dao",
"(",
")",
".",
"delete",
"(",
"run_id",
")",
"# TODO: implement",
"# ds.get_artifact_dao().delete(run_id)",
"# ds.get_resource_dao().delet... | Delete run of the given run_id.
:raise NotImplementedError If not supported by the backend.
:raise DataSourceError General data source error.
:raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist. | [
"Delete",
"run",
"of",
"the",
"given",
"run_id",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/business/runfacade.py#L11-L24 | train | 35,150 |
chovanecm/sacredboard | sacredboard/app/data/filestorage/rundao.py | FileStoreRunDAO.get_runs | def get_runs(self, sort_by=None, sort_direction=None, start=0, limit=None, query={"type": "and", "filters": []}):
"""
Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotImplemented
:param query: NotImplemented
:return: FileStoreCursor
"""
all_run_ids = os.listdir(self.directory)
def run_iterator():
blacklist = set(["_sources"])
for id in all_run_ids:
if id in blacklist:
continue
try:
yield self.get(id)
except FileNotFoundError:
# An incomplete experiment is a corrupt experiment.
# Skip it for now.
# TODO
pass
count = len(all_run_ids)
return FileStoreCursor(count, run_iterator()) | python | def get_runs(self, sort_by=None, sort_direction=None, start=0, limit=None, query={"type": "and", "filters": []}):
"""
Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotImplemented
:param query: NotImplemented
:return: FileStoreCursor
"""
all_run_ids = os.listdir(self.directory)
def run_iterator():
blacklist = set(["_sources"])
for id in all_run_ids:
if id in blacklist:
continue
try:
yield self.get(id)
except FileNotFoundError:
# An incomplete experiment is a corrupt experiment.
# Skip it for now.
# TODO
pass
count = len(all_run_ids)
return FileStoreCursor(count, run_iterator()) | [
"def",
"get_runs",
"(",
"self",
",",
"sort_by",
"=",
"None",
",",
"sort_direction",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
",",
"query",
"=",
"{",
"\"type\"",
":",
"\"and\"",
",",
"\"filters\"",
":",
"[",
"]",
"}",
")",
":"... | Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotImplemented
:param query: NotImplemented
:return: FileStoreCursor | [
"Return",
"all",
"runs",
"in",
"the",
"file",
"store",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/filestorage/rundao.py#L20-L49 | train | 35,151 |
chovanecm/sacredboard | sacredboard/app/data/filestorage/rundao.py | FileStoreRunDAO.get | def get(self, run_id):
"""
Return the run associated with a particular `run_id`.
:param run_id:
:return: dict
:raises FileNotFoundError
"""
config = _read_json(_path_to_config(self.directory, run_id))
run = _read_json(_path_to_run(self.directory, run_id))
try:
info = _read_json(_path_to_info(self.directory, run_id))
except IOError:
info = {}
return _create_run(run_id, run, config, info) | python | def get(self, run_id):
"""
Return the run associated with a particular `run_id`.
:param run_id:
:return: dict
:raises FileNotFoundError
"""
config = _read_json(_path_to_config(self.directory, run_id))
run = _read_json(_path_to_run(self.directory, run_id))
try:
info = _read_json(_path_to_info(self.directory, run_id))
except IOError:
info = {}
return _create_run(run_id, run, config, info) | [
"def",
"get",
"(",
"self",
",",
"run_id",
")",
":",
"config",
"=",
"_read_json",
"(",
"_path_to_config",
"(",
"self",
".",
"directory",
",",
"run_id",
")",
")",
"run",
"=",
"_read_json",
"(",
"_path_to_run",
"(",
"self",
".",
"directory",
",",
"run_id",
... | Return the run associated with a particular `run_id`.
:param run_id:
:return: dict
:raises FileNotFoundError | [
"Return",
"the",
"run",
"associated",
"with",
"a",
"particular",
"run_id",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/filestorage/rundao.py#L51-L66 | train | 35,152 |
chovanecm/sacredboard | sacredboard/app/webapi/metrics.py | get_metric | def get_metric(run_id, metric_id):
"""
Get a specific Sacred metric from the database.
Returns a JSON response or HTTP 404 if not found.
Issue: https://github.com/chovanecm/sacredboard/issues/58
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_metrics_dao()
metric = dao.get(run_id, metric_id)
return Response(render_template(
"api/metric.js",
run_id=metric["run_id"],
metric_id=metric["metric_id"],
name=metric["name"],
steps=metric["steps"],
timestamps=metric["timestamps"],
values=metric["values"]),
mimetype="application/json") | python | def get_metric(run_id, metric_id):
"""
Get a specific Sacred metric from the database.
Returns a JSON response or HTTP 404 if not found.
Issue: https://github.com/chovanecm/sacredboard/issues/58
"""
data = current_app.config["data"] # type: DataStorage
dao = data.get_metrics_dao()
metric = dao.get(run_id, metric_id)
return Response(render_template(
"api/metric.js",
run_id=metric["run_id"],
metric_id=metric["metric_id"],
name=metric["name"],
steps=metric["steps"],
timestamps=metric["timestamps"],
values=metric["values"]),
mimetype="application/json") | [
"def",
"get_metric",
"(",
"run_id",
",",
"metric_id",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"# type: DataStorage",
"dao",
"=",
"data",
".",
"get_metrics_dao",
"(",
")",
"metric",
"=",
"dao",
".",
"get",
"(",
"run_id",
... | Get a specific Sacred metric from the database.
Returns a JSON response or HTTP 404 if not found.
Issue: https://github.com/chovanecm/sacredboard/issues/58 | [
"Get",
"a",
"specific",
"Sacred",
"metric",
"from",
"the",
"database",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/metrics.py#L15-L34 | train | 35,153 |
chovanecm/sacredboard | sacredboard/app/webapi/wsgi_server.py | ServerRunner.initialize | def initialize(self, app: Flask, app_config):
"""
Prepare the server to run and determine the port.
:param app: The Flask Application.
:param app_config: Configuration dictionary. This module uses the `debug`
(`True`/`False`) and `http.port` attributes.
"""
debug = app_config["debug"]
port = app_config["http.port"]
if debug:
self.started_on_port = port
app.run(host="0.0.0.0", debug=True, port=port)
else:
for port in range(port, port + 50):
self.http_server = WSGIServer(('0.0.0.0', port), app)
try:
self.http_server.start()
except OSError:
# try next port
continue
self.started_on_port = port
break | python | def initialize(self, app: Flask, app_config):
"""
Prepare the server to run and determine the port.
:param app: The Flask Application.
:param app_config: Configuration dictionary. This module uses the `debug`
(`True`/`False`) and `http.port` attributes.
"""
debug = app_config["debug"]
port = app_config["http.port"]
if debug:
self.started_on_port = port
app.run(host="0.0.0.0", debug=True, port=port)
else:
for port in range(port, port + 50):
self.http_server = WSGIServer(('0.0.0.0', port), app)
try:
self.http_server.start()
except OSError:
# try next port
continue
self.started_on_port = port
break | [
"def",
"initialize",
"(",
"self",
",",
"app",
":",
"Flask",
",",
"app_config",
")",
":",
"debug",
"=",
"app_config",
"[",
"\"debug\"",
"]",
"port",
"=",
"app_config",
"[",
"\"http.port\"",
"]",
"if",
"debug",
":",
"self",
".",
"started_on_port",
"=",
"po... | Prepare the server to run and determine the port.
:param app: The Flask Application.
:param app_config: Configuration dictionary. This module uses the `debug`
(`True`/`False`) and `http.port` attributes. | [
"Prepare",
"the",
"server",
"to",
"run",
"and",
"determine",
"the",
"port",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/wsgi_server.py#L14-L36 | train | 35,154 |
chovanecm/sacredboard | sacredboard/app/webapi/runs.py | api_run_delete | def api_run_delete(run_id):
"""Delete the given run and corresponding entities."""
data = current_app.config["data"] # type: DataStorage
RunFacade(data).delete_run(run_id)
return "DELETED run %s" % run_id | python | def api_run_delete(run_id):
"""Delete the given run and corresponding entities."""
data = current_app.config["data"] # type: DataStorage
RunFacade(data).delete_run(run_id)
return "DELETED run %s" % run_id | [
"def",
"api_run_delete",
"(",
"run_id",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"# type: DataStorage",
"RunFacade",
"(",
"data",
")",
".",
"delete_run",
"(",
"run_id",
")",
"return",
"\"DELETED run %s\"",
"%",
"run_id"
] | Delete the given run and corresponding entities. | [
"Delete",
"the",
"given",
"run",
"and",
"corresponding",
"entities",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/runs.py#L20-L24 | train | 35,155 |
chovanecm/sacredboard | sacredboard/app/webapi/runs.py | api_run_get | def api_run_get(run_id):
"""Return a single run as a JSON object."""
data = current_app.config["data"]
run = data.get_run_dao().get(run_id)
records_total = 1 if run is not None else 0
if records_total == 0:
return Response(
render_template(
"api/error.js",
error_code=404,
error_message="Run %s not found." % run_id),
status=404,
mimetype="application/json")
records_filtered = records_total
return Response(render_template("api/runs.js", runs=[run], draw=1,
recordsTotal=records_total,
recordsFiltered=records_filtered,
full_object=True),
mimetype="application/json") | python | def api_run_get(run_id):
"""Return a single run as a JSON object."""
data = current_app.config["data"]
run = data.get_run_dao().get(run_id)
records_total = 1 if run is not None else 0
if records_total == 0:
return Response(
render_template(
"api/error.js",
error_code=404,
error_message="Run %s not found." % run_id),
status=404,
mimetype="application/json")
records_filtered = records_total
return Response(render_template("api/runs.js", runs=[run], draw=1,
recordsTotal=records_total,
recordsFiltered=records_filtered,
full_object=True),
mimetype="application/json") | [
"def",
"api_run_get",
"(",
"run_id",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"run",
"=",
"data",
".",
"get_run_dao",
"(",
")",
".",
"get",
"(",
"run_id",
")",
"records_total",
"=",
"1",
"if",
"run",
"is",
"not",
"No... | Return a single run as a JSON object. | [
"Return",
"a",
"single",
"run",
"as",
"a",
"JSON",
"object",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/runs.py#L28-L46 | train | 35,156 |
chovanecm/sacredboard | sacredboard/app/webapi/runs.py | parse_int_arg | def parse_int_arg(name, default):
"""Return a given URL parameter as int or return the default value."""
return default if request.args.get(name) is None \
else int(request.args.get(name)) | python | def parse_int_arg(name, default):
"""Return a given URL parameter as int or return the default value."""
return default if request.args.get(name) is None \
else int(request.args.get(name)) | [
"def",
"parse_int_arg",
"(",
"name",
",",
"default",
")",
":",
"return",
"default",
"if",
"request",
".",
"args",
".",
"get",
"(",
"name",
")",
"is",
"None",
"else",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"name",
")",
")"
] | Return a given URL parameter as int or return the default value. | [
"Return",
"a",
"given",
"URL",
"parameter",
"as",
"int",
"or",
"return",
"the",
"default",
"value",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/runs.py#L49-L52 | train | 35,157 |
chovanecm/sacredboard | sacredboard/app/webapi/runs.py | parse_query_filter | def parse_query_filter():
"""Parse the Run query filter from the URL as a dictionary."""
query_string = request.args.get("queryFilter")
if query_string is None:
return {"type": "and", "filters": []}
query = json.loads(query_string)
assert type(query) == dict
assert type(query.get("type")) == str
return query | python | def parse_query_filter():
"""Parse the Run query filter from the URL as a dictionary."""
query_string = request.args.get("queryFilter")
if query_string is None:
return {"type": "and", "filters": []}
query = json.loads(query_string)
assert type(query) == dict
assert type(query.get("type")) == str
return query | [
"def",
"parse_query_filter",
"(",
")",
":",
"query_string",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"queryFilter\"",
")",
"if",
"query_string",
"is",
"None",
":",
"return",
"{",
"\"type\"",
":",
"\"and\"",
",",
"\"filters\"",
":",
"[",
"]",
"}",
... | Parse the Run query filter from the URL as a dictionary. | [
"Parse",
"the",
"Run",
"query",
"filter",
"from",
"the",
"URL",
"as",
"a",
"dictionary",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/runs.py#L55-L63 | train | 35,158 |
chovanecm/sacredboard | sacredboard/app/webapi/runs.py | get_runs | def get_runs():
"""Get all runs, sort it and return a response."""
data = current_app.config["data"]
draw = parse_int_arg("draw", 1)
start = parse_int_arg("start", 0)
length = parse_int_arg("length", -1)
length = length if length >= 0 else None
order_column = request.args.get("order[0][column]")
order_dir = request.args.get("order[0][dir]")
query = parse_query_filter()
if order_column is not None:
order_column = \
request.args.get("columns[%d][name]" % int(order_column))
if order_column == "hostname":
order_column = "host.hostname"
runs = data.get_run_dao().get_runs(
start=start, limit=length,
sort_by=order_column, sort_direction=order_dir, query=query)
# records_total should be the total size of the records in the database,
# not what was returned
records_total = runs.count()
records_filtered = runs.count()
return Response(render_template(
"api/runs.js", runs=runs,
draw=draw, recordsTotal=records_total,
recordsFiltered=records_filtered),
mimetype="application/json") | python | def get_runs():
"""Get all runs, sort it and return a response."""
data = current_app.config["data"]
draw = parse_int_arg("draw", 1)
start = parse_int_arg("start", 0)
length = parse_int_arg("length", -1)
length = length if length >= 0 else None
order_column = request.args.get("order[0][column]")
order_dir = request.args.get("order[0][dir]")
query = parse_query_filter()
if order_column is not None:
order_column = \
request.args.get("columns[%d][name]" % int(order_column))
if order_column == "hostname":
order_column = "host.hostname"
runs = data.get_run_dao().get_runs(
start=start, limit=length,
sort_by=order_column, sort_direction=order_dir, query=query)
# records_total should be the total size of the records in the database,
# not what was returned
records_total = runs.count()
records_filtered = runs.count()
return Response(render_template(
"api/runs.js", runs=runs,
draw=draw, recordsTotal=records_total,
recordsFiltered=records_filtered),
mimetype="application/json") | [
"def",
"get_runs",
"(",
")",
":",
"data",
"=",
"current_app",
".",
"config",
"[",
"\"data\"",
"]",
"draw",
"=",
"parse_int_arg",
"(",
"\"draw\"",
",",
"1",
")",
"start",
"=",
"parse_int_arg",
"(",
"\"start\"",
",",
"0",
")",
"length",
"=",
"parse_int_arg... | Get all runs, sort it and return a response. | [
"Get",
"all",
"runs",
"sort",
"it",
"and",
"return",
"a",
"response",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/runs.py#L66-L95 | train | 35,159 |
chovanecm/sacredboard | sacredboard/app/data/filestorage/filesdao.py | FileStoreFilesDAO.get | def get(self, file_id: str) -> [typing.BinaryIO, str, datetime.datetime]:
"""Return the file identified by a file_id string, its file name and upload date."""
raise NotImplementedError("Downloading files for downloading files in FileStore has not been implemented yet.") | python | def get(self, file_id: str) -> [typing.BinaryIO, str, datetime.datetime]:
"""Return the file identified by a file_id string, its file name and upload date."""
raise NotImplementedError("Downloading files for downloading files in FileStore has not been implemented yet.") | [
"def",
"get",
"(",
"self",
",",
"file_id",
":",
"str",
")",
"->",
"[",
"typing",
".",
"BinaryIO",
",",
"str",
",",
"datetime",
".",
"datetime",
"]",
":",
"raise",
"NotImplementedError",
"(",
"\"Downloading files for downloading files in FileStore has not been implem... | Return the file identified by a file_id string, its file name and upload date. | [
"Return",
"the",
"file",
"identified",
"by",
"a",
"file_id",
"string",
"its",
"file",
"name",
"and",
"upload",
"date",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/filestorage/filesdao.py#L20-L22 | train | 35,160 |
chovanecm/sacredboard | sacredboard/app/config/jinja_filters.py | timediff | def timediff(time):
"""Return the difference in seconds between now and the given time."""
now = datetime.datetime.utcnow()
diff = now - time
diff_sec = diff.total_seconds()
return diff_sec | python | def timediff(time):
"""Return the difference in seconds between now and the given time."""
now = datetime.datetime.utcnow()
diff = now - time
diff_sec = diff.total_seconds()
return diff_sec | [
"def",
"timediff",
"(",
"time",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"diff",
"=",
"now",
"-",
"time",
"diff_sec",
"=",
"diff",
".",
"total_seconds",
"(",
")",
"return",
"diff_sec"
] | Return the difference in seconds between now and the given time. | [
"Return",
"the",
"difference",
"in",
"seconds",
"between",
"now",
"and",
"the",
"given",
"time",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/config/jinja_filters.py#L25-L30 | train | 35,161 |
chovanecm/sacredboard | sacredboard/app/config/jinja_filters.py | last_line | def last_line(text):
"""
Get the last meaningful line of the text, that is the last non-empty line.
:param text: Text to search the last line
:type text: str
:return:
:rtype: str
"""
last_line_of_text = ""
while last_line_of_text == "" and len(text) > 0:
last_line_start = text.rfind("\n")
# Handle one-line strings (without \n)
last_line_start = max(0, last_line_start)
last_line_of_text = text[last_line_start:].strip("\r\n ")
text = text[:last_line_start]
return last_line_of_text | python | def last_line(text):
"""
Get the last meaningful line of the text, that is the last non-empty line.
:param text: Text to search the last line
:type text: str
:return:
:rtype: str
"""
last_line_of_text = ""
while last_line_of_text == "" and len(text) > 0:
last_line_start = text.rfind("\n")
# Handle one-line strings (without \n)
last_line_start = max(0, last_line_start)
last_line_of_text = text[last_line_start:].strip("\r\n ")
text = text[:last_line_start]
return last_line_of_text | [
"def",
"last_line",
"(",
"text",
")",
":",
"last_line_of_text",
"=",
"\"\"",
"while",
"last_line_of_text",
"==",
"\"\"",
"and",
"len",
"(",
"text",
")",
">",
"0",
":",
"last_line_start",
"=",
"text",
".",
"rfind",
"(",
"\"\\n\"",
")",
"# Handle one-line stri... | Get the last meaningful line of the text, that is the last non-empty line.
:param text: Text to search the last line
:type text: str
:return:
:rtype: str | [
"Get",
"the",
"last",
"meaningful",
"line",
"of",
"the",
"text",
"that",
"is",
"the",
"last",
"non",
"-",
"empty",
"line",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/config/jinja_filters.py#L34-L50 | train | 35,162 |
chovanecm/sacredboard | sacredboard/app/config/jinja_filters.py | dump_json | def dump_json(obj):
"""Dump Python object as JSON string."""
return simplejson.dumps(obj, ignore_nan=True, default=json_util.default) | python | def dump_json(obj):
"""Dump Python object as JSON string."""
return simplejson.dumps(obj, ignore_nan=True, default=json_util.default) | [
"def",
"dump_json",
"(",
"obj",
")",
":",
"return",
"simplejson",
".",
"dumps",
"(",
"obj",
",",
"ignore_nan",
"=",
"True",
",",
"default",
"=",
"json_util",
".",
"default",
")"
] | Dump Python object as JSON string. | [
"Dump",
"Python",
"object",
"as",
"JSON",
"string",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/config/jinja_filters.py#L60-L62 | train | 35,163 |
chovanecm/sacredboard | sacredboard/app/process/process.py | Process.terminate | def terminate(self, wait=False):
"""Terminate the process."""
if self.proc is not None:
self.proc.stdout.close()
try:
self.proc.terminate()
except ProcessLookupError:
pass
if wait:
self.proc.wait() | python | def terminate(self, wait=False):
"""Terminate the process."""
if self.proc is not None:
self.proc.stdout.close()
try:
self.proc.terminate()
except ProcessLookupError:
pass
if wait:
self.proc.wait() | [
"def",
"terminate",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"if",
"self",
".",
"proc",
"is",
"not",
"None",
":",
"self",
".",
"proc",
".",
"stdout",
".",
"close",
"(",
")",
"try",
":",
"self",
".",
"proc",
".",
"terminate",
"(",
")",
... | Terminate the process. | [
"Terminate",
"the",
"process",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/process/process.py#L88-L97 | train | 35,164 |
chovanecm/sacredboard | sacredboard/app/process/process.py | Process.terminate_all | def terminate_all(wait=False):
"""
Terminate all processes.
:param wait: Wait for each to terminate
:type wait: bool
:return:
:rtype:
"""
for instance in Process.instances:
if instance.is_running():
instance.terminate(wait) | python | def terminate_all(wait=False):
"""
Terminate all processes.
:param wait: Wait for each to terminate
:type wait: bool
:return:
:rtype:
"""
for instance in Process.instances:
if instance.is_running():
instance.terminate(wait) | [
"def",
"terminate_all",
"(",
"wait",
"=",
"False",
")",
":",
"for",
"instance",
"in",
"Process",
".",
"instances",
":",
"if",
"instance",
".",
"is_running",
"(",
")",
":",
"instance",
".",
"terminate",
"(",
"wait",
")"
] | Terminate all processes.
:param wait: Wait for each to terminate
:type wait: bool
:return:
:rtype: | [
"Terminate",
"all",
"processes",
"."
] | 47e1c99e3be3c1b099d3772bc077f5666020eb0b | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/process/process.py#L107-L118 | train | 35,165 |
noahbenson/neuropythy | neuropythy/commands/atlas.py | calc_worklog | def calc_worklog(stdout=Ellipsis, stderr=Ellipsis, verbose=False):
'''
calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments.
'''
try: cols = int(os.environ['COLUMNS'])
except Exception: cols = 80
return pimms.worklog(columns=cols, stdout=stdout, stderr=stderr, verbose=verbose) | python | def calc_worklog(stdout=Ellipsis, stderr=Ellipsis, verbose=False):
'''
calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments.
'''
try: cols = int(os.environ['COLUMNS'])
except Exception: cols = 80
return pimms.worklog(columns=cols, stdout=stdout, stderr=stderr, verbose=verbose) | [
"def",
"calc_worklog",
"(",
"stdout",
"=",
"Ellipsis",
",",
"stderr",
"=",
"Ellipsis",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"cols",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'COLUMNS'",
"]",
")",
"except",
"Exception",
":",
"cols",
... | calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments. | [
"calc_worklog",
"constructs",
"the",
"worklog",
"from",
"the",
"stdout",
"stderr",
"stdin",
"and",
"verbose",
"arguments",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L24-L30 | train | 35,166 |
noahbenson/neuropythy | neuropythy/commands/atlas.py | calc_subject | def calc_subject(argv, worklog):
'''
calc_subject converts a subject_id into a subject object.
Afferent parameters:
@ argv
The FreeSurfer subject name(s), HCP subject ID(s), or path(s) of the subject(s) to which the
atlas should be applied.
'''
if len(argv) == 0: raise ValueError('No subject-id given')
elif len(argv) > 1: worklog.warn('WARNING: Unused subject arguments: %s' % (argv[1:],))
subject_id = argv[0]
try:
sub = freesurfer_subject(subject_id)
if sub is not None:
worklog('Using FreeSurfer subject: %s' % sub.path)
return sub
except Exception: pass
try:
sub = hcp_subject(subject_id)
if sub is not None:
worklog('Using HCP subject: %s' % sub.path)
return sub
except Exception: pass
raise ValueError('Could not load subject %s' % subject_id) | python | def calc_subject(argv, worklog):
'''
calc_subject converts a subject_id into a subject object.
Afferent parameters:
@ argv
The FreeSurfer subject name(s), HCP subject ID(s), or path(s) of the subject(s) to which the
atlas should be applied.
'''
if len(argv) == 0: raise ValueError('No subject-id given')
elif len(argv) > 1: worklog.warn('WARNING: Unused subject arguments: %s' % (argv[1:],))
subject_id = argv[0]
try:
sub = freesurfer_subject(subject_id)
if sub is not None:
worklog('Using FreeSurfer subject: %s' % sub.path)
return sub
except Exception: pass
try:
sub = hcp_subject(subject_id)
if sub is not None:
worklog('Using HCP subject: %s' % sub.path)
return sub
except Exception: pass
raise ValueError('Could not load subject %s' % subject_id) | [
"def",
"calc_subject",
"(",
"argv",
",",
"worklog",
")",
":",
"if",
"len",
"(",
"argv",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'No subject-id given'",
")",
"elif",
"len",
"(",
"argv",
")",
">",
"1",
":",
"worklog",
".",
"warn",
"(",
"'WARN... | calc_subject converts a subject_id into a subject object.
Afferent parameters:
@ argv
The FreeSurfer subject name(s), HCP subject ID(s), or path(s) of the subject(s) to which the
atlas should be applied. | [
"calc_subject",
"converts",
"a",
"subject_id",
"into",
"a",
"subject",
"object",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L32-L56 | train | 35,167 |
noahbenson/neuropythy | neuropythy/commands/atlas.py | calc_atlases | def calc_atlases(worklog, atlas_subject_id='fsaverage'):
'''
cacl_atlases finds all available atlases in the possible subject directories of the given atlas
subject.
In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer
curv/morph-data files) named as '<hemi>.<template>_<quantity><ending>' such as the files
'lh.wang2015_mplbl.mgz' and 'rh.wang2015_mplbl.mgz'. They may additionally have a version
prior to the ending, as in 'lh.benson14_angle.v2_5.mgz'. Files without versions are considered
to be of a higher version than all versioned files. All files must be found in the atlas
subject's surf/ directory; however, all subjects in all FreeSurfer subjects paths with the same
subject id are searched if the atlas is not found in the atlas subejct's directory.
Afferent parameters:
@ atlas_subject_id
The FreeSurfer subject name subject path of the subject that is to be used as the atlas
subject from which the atlas is interpolated. HCP subjects are not currently supported.
Efferent values:
@ atlas_map
A persistent map whose keys are atlas names, the values of which are themselves persistent
maps whose keys are the versions of the given atlas (None potentially being included). The
values of these maps are again maps of hemisphere names then finally of the of the quantity
names (such as 'eccen' or 'maxprob') to the property vectors imported from the appropriate
files.
'''
try: sub = freesurfer_subject(atlas_subject_id)
except Exception: sub = None
if sub is None:
try: sub = hcp_subject(atlas_subject_id)
except Exception: sub = None
if sub is None: raise ValueError('Could not load atlas subject %s' % atlas_subject_id)
worklog('Using Atlas subject: %s' % sub.path)
# Now find the requested atlases
atlases = AutoDict()
atlas_patt = r'^([lr]h)\.([^_]+)_([^.]+)(\.(v(\d+(_\d+)*)))?((\.mg[hz])|\.nii(\.gz)?)?$'
atlas_hemi_ii = 1
atlas_atls_ii = 2
atlas_meas_ii = 3
atlas_vrsn_ii = 6
libdir = os.path.join(library_path(), 'data')
for pth in [libdir] + config['freesurfer_subject_paths'] + [sub.path]:
# see if appropriate files are in this directory
pth = os.path.join(pth, sub.name, 'surf')
if not os.path.isdir(pth): continue
for fl in os.listdir(pth):
m = re.match(atlas_patt, fl)
if m is None: continue
fl = os.path.join(pth, fl)
(h, atls, meas, vrsn) = [
m.group(ii) for ii in (atlas_hemi_ii, atlas_atls_ii, atlas_meas_ii, atlas_vrsn_ii)]
if vrsn is not None: vrsn = tuple([int(s) for s in vrsn.split('_')])
atlases[atls][vrsn][h][meas] = curry(nyio.load, fl)
# convert the possible atlas maps into persistent/lazy maps
atlas_map = pyr.pmap({a:pyr.pmap({v:pyr.pmap({h:pimms.lazy_map(hv)
for (h,hv) in six.iteritems(vv)})
for (v,vv) in six.iteritems(av)})
for (a,av) in six.iteritems(atlases)})
return {'atlas_map':atlas_map, 'atlas_subject':sub} | python | def calc_atlases(worklog, atlas_subject_id='fsaverage'):
'''
cacl_atlases finds all available atlases in the possible subject directories of the given atlas
subject.
In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer
curv/morph-data files) named as '<hemi>.<template>_<quantity><ending>' such as the files
'lh.wang2015_mplbl.mgz' and 'rh.wang2015_mplbl.mgz'. They may additionally have a version
prior to the ending, as in 'lh.benson14_angle.v2_5.mgz'. Files without versions are considered
to be of a higher version than all versioned files. All files must be found in the atlas
subject's surf/ directory; however, all subjects in all FreeSurfer subjects paths with the same
subject id are searched if the atlas is not found in the atlas subejct's directory.
Afferent parameters:
@ atlas_subject_id
The FreeSurfer subject name subject path of the subject that is to be used as the atlas
subject from which the atlas is interpolated. HCP subjects are not currently supported.
Efferent values:
@ atlas_map
A persistent map whose keys are atlas names, the values of which are themselves persistent
maps whose keys are the versions of the given atlas (None potentially being included). The
values of these maps are again maps of hemisphere names then finally of the of the quantity
names (such as 'eccen' or 'maxprob') to the property vectors imported from the appropriate
files.
'''
try: sub = freesurfer_subject(atlas_subject_id)
except Exception: sub = None
if sub is None:
try: sub = hcp_subject(atlas_subject_id)
except Exception: sub = None
if sub is None: raise ValueError('Could not load atlas subject %s' % atlas_subject_id)
worklog('Using Atlas subject: %s' % sub.path)
# Now find the requested atlases
atlases = AutoDict()
atlas_patt = r'^([lr]h)\.([^_]+)_([^.]+)(\.(v(\d+(_\d+)*)))?((\.mg[hz])|\.nii(\.gz)?)?$'
atlas_hemi_ii = 1
atlas_atls_ii = 2
atlas_meas_ii = 3
atlas_vrsn_ii = 6
libdir = os.path.join(library_path(), 'data')
for pth in [libdir] + config['freesurfer_subject_paths'] + [sub.path]:
# see if appropriate files are in this directory
pth = os.path.join(pth, sub.name, 'surf')
if not os.path.isdir(pth): continue
for fl in os.listdir(pth):
m = re.match(atlas_patt, fl)
if m is None: continue
fl = os.path.join(pth, fl)
(h, atls, meas, vrsn) = [
m.group(ii) for ii in (atlas_hemi_ii, atlas_atls_ii, atlas_meas_ii, atlas_vrsn_ii)]
if vrsn is not None: vrsn = tuple([int(s) for s in vrsn.split('_')])
atlases[atls][vrsn][h][meas] = curry(nyio.load, fl)
# convert the possible atlas maps into persistent/lazy maps
atlas_map = pyr.pmap({a:pyr.pmap({v:pyr.pmap({h:pimms.lazy_map(hv)
for (h,hv) in six.iteritems(vv)})
for (v,vv) in six.iteritems(av)})
for (a,av) in six.iteritems(atlases)})
return {'atlas_map':atlas_map, 'atlas_subject':sub} | [
"def",
"calc_atlases",
"(",
"worklog",
",",
"atlas_subject_id",
"=",
"'fsaverage'",
")",
":",
"try",
":",
"sub",
"=",
"freesurfer_subject",
"(",
"atlas_subject_id",
")",
"except",
"Exception",
":",
"sub",
"=",
"None",
"if",
"sub",
"is",
"None",
":",
"try",
... | cacl_atlases finds all available atlases in the possible subject directories of the given atlas
subject.
In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer
curv/morph-data files) named as '<hemi>.<template>_<quantity><ending>' such as the files
'lh.wang2015_mplbl.mgz' and 'rh.wang2015_mplbl.mgz'. They may additionally have a version
prior to the ending, as in 'lh.benson14_angle.v2_5.mgz'. Files without versions are considered
to be of a higher version than all versioned files. All files must be found in the atlas
subject's surf/ directory; however, all subjects in all FreeSurfer subjects paths with the same
subject id are searched if the atlas is not found in the atlas subejct's directory.
Afferent parameters:
@ atlas_subject_id
The FreeSurfer subject name subject path of the subject that is to be used as the atlas
subject from which the atlas is interpolated. HCP subjects are not currently supported.
Efferent values:
@ atlas_map
A persistent map whose keys are atlas names, the values of which are themselves persistent
maps whose keys are the versions of the given atlas (None potentially being included). The
values of these maps are again maps of hemisphere names then finally of the of the quantity
names (such as 'eccen' or 'maxprob') to the property vectors imported from the appropriate
files. | [
"cacl_atlases",
"finds",
"all",
"available",
"atlases",
"in",
"the",
"possible",
"subject",
"directories",
"of",
"the",
"given",
"atlas",
"subject",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L58-L116 | train | 35,168 |
noahbenson/neuropythy | neuropythy/commands/atlas.py | calc_filemap | def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog,
output_path=None, overwrite=False, output_format='mgz', create_directory=False):
'''
calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth
map whose keys are filenames and whose values are the interpolated property data.
Afferent parameters
@ output_path
The directory into which the atlas files should be written. If not provided or None then
uses the subject's surf directory. If this directory doesn't exist, then it uses the
subject's directory itself.
@ overwrite
Whether to overwrite existing atlas files. If True, then atlas files that already exist will
be overwritten. If False, then no files are overwritten.
@ create_directory
Whether to create the output path if it doesn't exist. This is False by default.
@ output_format
The desired output format of the files to be written. May be one of the following: 'mgz',
'mgh', or either 'curv' or 'morph'.
Efferent values:
@ filemap
A pimms lazy map whose keys are filenames and whose values are interpolated atlas
properties.
@ export_all_fn
A function of no arguments that, when called, exports all of the files in the filemap to the
output_path.
'''
if output_path is None:
output_path = os.path.join(subject.path, 'surf')
if not os.path.isdir(output_path): output_path = subject.path
output_format = 'mgz' if output_format is None else output_format.lower()
if output_format.startswith('.'): output_format = output_format[1:]
(fmt,ending) = (('mgh','.mgz') if output_format == 'mgz' else
('mgh','.mgh') if output_format == 'mgh' else
('freesurfer_morph',''))
# make the filemap...
worklog('Preparing Filemap...')
fm = AutoDict()
for (atl,atldat) in six.iteritems(atlas_properties):
for (ver,verdat) in six.iteritems(atldat):
vstr = atlas_version_tags[atl][ver]
for (h,hdat) in six.iteritems(verdat):
for m in six.iterkeys(hdat):
flnm = '%s.%s_%s%s%s' % (h, atl, m, vstr, ending)
flnm = os.path.join(output_path, flnm)
fm[flnm] = curry(lambda hdat,m: hdat[m], hdat, m)
# okay, make that a lazy map:
filemap = pimms.lazy_map(fm)
# the function for exporting all properties:
def export_all():
'''
This function will export all files from its associated filemap and return a list of the
filenames.
'''
if not os.path.isdir(output_path):
if not create_directory:
raise ValueError('No such path and create_direcotry is False: %s' % output_path)
os.makedirs(os.path.abspath(output_path), 0o755)
filenames = []
worklog('Extracting Files...')
wl = worklog.indent()
for flnm in six.iterkeys(filemap):
wl(flnm)
filenames.append(nyio.save(flnm, filemap[flnm], fmt))
return filenames
return {'filemap': filemap, 'export_all_fn': export_all} | python | def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog,
output_path=None, overwrite=False, output_format='mgz', create_directory=False):
'''
calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth
map whose keys are filenames and whose values are the interpolated property data.
Afferent parameters
@ output_path
The directory into which the atlas files should be written. If not provided or None then
uses the subject's surf directory. If this directory doesn't exist, then it uses the
subject's directory itself.
@ overwrite
Whether to overwrite existing atlas files. If True, then atlas files that already exist will
be overwritten. If False, then no files are overwritten.
@ create_directory
Whether to create the output path if it doesn't exist. This is False by default.
@ output_format
The desired output format of the files to be written. May be one of the following: 'mgz',
'mgh', or either 'curv' or 'morph'.
Efferent values:
@ filemap
A pimms lazy map whose keys are filenames and whose values are interpolated atlas
properties.
@ export_all_fn
A function of no arguments that, when called, exports all of the files in the filemap to the
output_path.
'''
if output_path is None:
output_path = os.path.join(subject.path, 'surf')
if not os.path.isdir(output_path): output_path = subject.path
output_format = 'mgz' if output_format is None else output_format.lower()
if output_format.startswith('.'): output_format = output_format[1:]
(fmt,ending) = (('mgh','.mgz') if output_format == 'mgz' else
('mgh','.mgh') if output_format == 'mgh' else
('freesurfer_morph',''))
# make the filemap...
worklog('Preparing Filemap...')
fm = AutoDict()
for (atl,atldat) in six.iteritems(atlas_properties):
for (ver,verdat) in six.iteritems(atldat):
vstr = atlas_version_tags[atl][ver]
for (h,hdat) in six.iteritems(verdat):
for m in six.iterkeys(hdat):
flnm = '%s.%s_%s%s%s' % (h, atl, m, vstr, ending)
flnm = os.path.join(output_path, flnm)
fm[flnm] = curry(lambda hdat,m: hdat[m], hdat, m)
# okay, make that a lazy map:
filemap = pimms.lazy_map(fm)
# the function for exporting all properties:
def export_all():
'''
This function will export all files from its associated filemap and return a list of the
filenames.
'''
if not os.path.isdir(output_path):
if not create_directory:
raise ValueError('No such path and create_direcotry is False: %s' % output_path)
os.makedirs(os.path.abspath(output_path), 0o755)
filenames = []
worklog('Extracting Files...')
wl = worklog.indent()
for flnm in six.iterkeys(filemap):
wl(flnm)
filenames.append(nyio.save(flnm, filemap[flnm], fmt))
return filenames
return {'filemap': filemap, 'export_all_fn': export_all} | [
"def",
"calc_filemap",
"(",
"atlas_properties",
",",
"subject",
",",
"atlas_version_tags",
",",
"worklog",
",",
"output_path",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"output_format",
"=",
"'mgz'",
",",
"create_directory",
"=",
"False",
")",
":",
"if... | calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth
map whose keys are filenames and whose values are the interpolated property data.
Afferent parameters
@ output_path
The directory into which the atlas files should be written. If not provided or None then
uses the subject's surf directory. If this directory doesn't exist, then it uses the
subject's directory itself.
@ overwrite
Whether to overwrite existing atlas files. If True, then atlas files that already exist will
be overwritten. If False, then no files are overwritten.
@ create_directory
Whether to create the output path if it doesn't exist. This is False by default.
@ output_format
The desired output format of the files to be written. May be one of the following: 'mgz',
'mgh', or either 'curv' or 'morph'.
Efferent values:
@ filemap
A pimms lazy map whose keys are filenames and whose values are interpolated atlas
properties.
@ export_all_fn
A function of no arguments that, when called, exports all of the files in the filemap to the
output_path. | [
"calc_filemap",
"is",
"a",
"calculator",
"that",
"converts",
"the",
"atlas",
"properties",
"nested",
"-",
"map",
"into",
"a",
"single",
"-",
"depth",
"map",
"whose",
"keys",
"are",
"filenames",
"and",
"whose",
"values",
"are",
"the",
"interpolated",
"property"... | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L245-L311 | train | 35,169 |
noahbenson/neuropythy | neuropythy/mri/images.py | ImageType.parse_type | def parse_type(self, hdat, dataobj=None):
'''
Parses the dtype out of the header data or the array, depending on which is given; if both,
then the header-data overrides the array; if neither, then np.float32.
'''
try: dataobj = dataobj.dataobj
except Exception: pass
dtype = np.asarray(dataobj).dtype if dataobj else self.default_type()
if hdat and 'type' in hdat: dtype = np.dtype(hdat['type'])
elif hdat and 'dtype' in hdat: dtype = np.dtype(hdat['dtype'])
return dtype | python | def parse_type(self, hdat, dataobj=None):
'''
Parses the dtype out of the header data or the array, depending on which is given; if both,
then the header-data overrides the array; if neither, then np.float32.
'''
try: dataobj = dataobj.dataobj
except Exception: pass
dtype = np.asarray(dataobj).dtype if dataobj else self.default_type()
if hdat and 'type' in hdat: dtype = np.dtype(hdat['type'])
elif hdat and 'dtype' in hdat: dtype = np.dtype(hdat['dtype'])
return dtype | [
"def",
"parse_type",
"(",
"self",
",",
"hdat",
",",
"dataobj",
"=",
"None",
")",
":",
"try",
":",
"dataobj",
"=",
"dataobj",
".",
"dataobj",
"except",
"Exception",
":",
"pass",
"dtype",
"=",
"np",
".",
"asarray",
"(",
"dataobj",
")",
".",
"dtype",
"i... | Parses the dtype out of the header data or the array, depending on which is given; if both,
then the header-data overrides the array; if neither, then np.float32. | [
"Parses",
"the",
"dtype",
"out",
"of",
"the",
"header",
"data",
"or",
"the",
"array",
"depending",
"on",
"which",
"is",
"given",
";",
"if",
"both",
"then",
"the",
"header",
"-",
"data",
"overrides",
"the",
"array",
";",
"if",
"neither",
"then",
"np",
"... | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/mri/images.py#L54-L64 | train | 35,170 |
noahbenson/neuropythy | neuropythy/mri/images.py | ImageType.parse_affine | def parse_affine(self, hdat, dataobj=None):
'''
Parses the affine out of the given header data and yields it.
'''
if 'affine' in hdat: return to_affine(hdat['affine'])
else: return to_affine(self.default_affine()) | python | def parse_affine(self, hdat, dataobj=None):
'''
Parses the affine out of the given header data and yields it.
'''
if 'affine' in hdat: return to_affine(hdat['affine'])
else: return to_affine(self.default_affine()) | [
"def",
"parse_affine",
"(",
"self",
",",
"hdat",
",",
"dataobj",
"=",
"None",
")",
":",
"if",
"'affine'",
"in",
"hdat",
":",
"return",
"to_affine",
"(",
"hdat",
"[",
"'affine'",
"]",
")",
"else",
":",
"return",
"to_affine",
"(",
"self",
".",
"default_a... | Parses the affine out of the given header data and yields it. | [
"Parses",
"the",
"affine",
"out",
"of",
"the",
"given",
"header",
"data",
"and",
"yields",
"it",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/mri/images.py#L66-L71 | train | 35,171 |
noahbenson/neuropythy | neuropythy/registration/core.py | _parse_field_arguments | def _parse_field_arguments(arg, faces, edges, coords):
'''See mesh_register.'''
if not hasattr(arg, '__iter__'):
raise RuntimeError('field argument must be a list-like collection of instructions')
pot = [_parse_field_argument(instruct, faces, edges, coords) for instruct in arg]
# make a new Potential sum unless the length is 1
if len(pot) <= 1:
return pot[0]
else:
sp = java_link().jvm.nben.mesh.registration.Fields.newSum()
for field in pot: sp.addField(field)
return sp | python | def _parse_field_arguments(arg, faces, edges, coords):
'''See mesh_register.'''
if not hasattr(arg, '__iter__'):
raise RuntimeError('field argument must be a list-like collection of instructions')
pot = [_parse_field_argument(instruct, faces, edges, coords) for instruct in arg]
# make a new Potential sum unless the length is 1
if len(pot) <= 1:
return pot[0]
else:
sp = java_link().jvm.nben.mesh.registration.Fields.newSum()
for field in pot: sp.addField(field)
return sp | [
"def",
"_parse_field_arguments",
"(",
"arg",
",",
"faces",
",",
"edges",
",",
"coords",
")",
":",
"if",
"not",
"hasattr",
"(",
"arg",
",",
"'__iter__'",
")",
":",
"raise",
"RuntimeError",
"(",
"'field argument must be a list-like collection of instructions'",
")",
... | See mesh_register. | [
"See",
"mesh_register",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/registration/core.py#L96-L107 | train | 35,172 |
noahbenson/neuropythy | neuropythy/graphics/core.py | retino_colors | def retino_colors(vcolorfn, *args, **kwargs):
'See eccen_colors, angle_colors, sigma_colors, and varea_colors.'
if len(args) == 0:
def _retino_color_pass(*args, **new_kwargs):
return retino_colors(vcolorfn, *args,
**{k:(new_kwargs[k] if k in new_kwargs else kwargs[k])
for k in set(kwargs.keys() + new_kwargs.keys())})
return _retino_color_pass
elif len(args) > 1:
raise ValueError('retinotopy color functions accepts at most one argument')
m = args[0]
# we need to handle the arguments
if isinstance(m, (geo.VertexSet, pimms.ITable)):
tbl = m.properties if isinstance(m, geo.VertexSet) else m
n = tbl.row_count
# if the weight or property arguments are lists, we need to thread these along
if 'property' in kwargs:
props = kwargs['property']
del kwargs['property']
if not (pimms.is_vector(props) or pimms.is_matrix(props)):
props = [props for _ in range(n)]
else: props = None
if 'weight' in kwargs:
ws = kwargs['weight']
del kwargs['weight']
if not pimms.is_vector(ws) and not pimms.is_matrix(ws): ws = [ws for _ in range(n)]
else: ws = None
vcolorfn0 = vcolorfn(Ellipsis, **kwargs) if len(kwargs) > 0 else vcolorfn
if props is None and ws is None: vcfn = lambda m,k:vcolorfn0(m)
elif props is None: vcfn = lambda m,k:vcolorfn0(m, weight=ws[k])
elif ws is None: vcfn = lambda m,k:vcolorfn0(m, property=props[k])
else: vcfn = lambda m,k:vcolorfn0(m, property=props[k], weight=ws[k])
return np.asarray([vcfn(r,kk) for (kk,r) in enumerate(tbl.rows)])
else:
return vcolorfn(m, **kwargs) | python | def retino_colors(vcolorfn, *args, **kwargs):
'See eccen_colors, angle_colors, sigma_colors, and varea_colors.'
if len(args) == 0:
def _retino_color_pass(*args, **new_kwargs):
return retino_colors(vcolorfn, *args,
**{k:(new_kwargs[k] if k in new_kwargs else kwargs[k])
for k in set(kwargs.keys() + new_kwargs.keys())})
return _retino_color_pass
elif len(args) > 1:
raise ValueError('retinotopy color functions accepts at most one argument')
m = args[0]
# we need to handle the arguments
if isinstance(m, (geo.VertexSet, pimms.ITable)):
tbl = m.properties if isinstance(m, geo.VertexSet) else m
n = tbl.row_count
# if the weight or property arguments are lists, we need to thread these along
if 'property' in kwargs:
props = kwargs['property']
del kwargs['property']
if not (pimms.is_vector(props) or pimms.is_matrix(props)):
props = [props for _ in range(n)]
else: props = None
if 'weight' in kwargs:
ws = kwargs['weight']
del kwargs['weight']
if not pimms.is_vector(ws) and not pimms.is_matrix(ws): ws = [ws for _ in range(n)]
else: ws = None
vcolorfn0 = vcolorfn(Ellipsis, **kwargs) if len(kwargs) > 0 else vcolorfn
if props is None and ws is None: vcfn = lambda m,k:vcolorfn0(m)
elif props is None: vcfn = lambda m,k:vcolorfn0(m, weight=ws[k])
elif ws is None: vcfn = lambda m,k:vcolorfn0(m, property=props[k])
else: vcfn = lambda m,k:vcolorfn0(m, property=props[k], weight=ws[k])
return np.asarray([vcfn(r,kk) for (kk,r) in enumerate(tbl.rows)])
else:
return vcolorfn(m, **kwargs) | [
"def",
"retino_colors",
"(",
"vcolorfn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"def",
"_retino_color_pass",
"(",
"*",
"args",
",",
"*",
"*",
"new_kwargs",
")",
":",
"return",
"retino_color... | See eccen_colors, angle_colors, sigma_colors, and varea_colors. | [
"See",
"eccen_colors",
"angle_colors",
"sigma_colors",
"and",
"varea_colors",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/graphics/core.py#L482-L516 | train | 35,173 |
noahbenson/neuropythy | neuropythy/hcp/files.py | _load_fsLR_atlasroi | def _load_fsLR_atlasroi(filename, data):
'''
Loads the appropriate atlas for the given data; data may point to a cifti file whose atlas is
needed or to an atlas file.
'''
(fdir, fnm) = os.path.split(filename)
fparts = fnm.split('.')
atl = fparts[-3]
if atl in _load_fsLR_atlasroi.atlases: return _load_fsLR_atlasroi.atlases[atl]
sid = data['id']
fnm = [os.path.join(fdir, '%d.%s.atlasroi.%s.shape.gii' % (sid, h, atl)) for h in ('L', 'R')]
if data['cifti']:
dat = [{'id':data['id'], 'type':'property', 'name':'atlas', 'hemi':h} for h in data['hemi']]
else:
dat = [{'id':data['id'], 'type':'property', 'name':'atlas', 'hemi':(h + data['hemi'][2:])}
for h in ('lh','rh')]
# loading an atlas file; this is easier
rois = tuple([_load(f, d).astype('bool') for (f,d) in zip(fnm, dat)])
# add these to the cache
if atl != 'native': _load_fsLR_atlasroi.atlases[atl] = rois
return rois | python | def _load_fsLR_atlasroi(filename, data):
'''
Loads the appropriate atlas for the given data; data may point to a cifti file whose atlas is
needed or to an atlas file.
'''
(fdir, fnm) = os.path.split(filename)
fparts = fnm.split('.')
atl = fparts[-3]
if atl in _load_fsLR_atlasroi.atlases: return _load_fsLR_atlasroi.atlases[atl]
sid = data['id']
fnm = [os.path.join(fdir, '%d.%s.atlasroi.%s.shape.gii' % (sid, h, atl)) for h in ('L', 'R')]
if data['cifti']:
dat = [{'id':data['id'], 'type':'property', 'name':'atlas', 'hemi':h} for h in data['hemi']]
else:
dat = [{'id':data['id'], 'type':'property', 'name':'atlas', 'hemi':(h + data['hemi'][2:])}
for h in ('lh','rh')]
# loading an atlas file; this is easier
rois = tuple([_load(f, d).astype('bool') for (f,d) in zip(fnm, dat)])
# add these to the cache
if atl != 'native': _load_fsLR_atlasroi.atlases[atl] = rois
return rois | [
"def",
"_load_fsLR_atlasroi",
"(",
"filename",
",",
"data",
")",
":",
"(",
"fdir",
",",
"fnm",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"fparts",
"=",
"fnm",
".",
"split",
"(",
"'.'",
")",
"atl",
"=",
"fparts",
"[",
"-",
"... | Loads the appropriate atlas for the given data; data may point to a cifti file whose atlas is
needed or to an atlas file. | [
"Loads",
"the",
"appropriate",
"atlas",
"for",
"the",
"given",
"data",
";",
"data",
"may",
"point",
"to",
"a",
"cifti",
"file",
"whose",
"atlas",
"is",
"needed",
"or",
"to",
"an",
"atlas",
"file",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/hcp/files.py#L248-L268 | train | 35,174 |
noahbenson/neuropythy | neuropythy/hcp/files.py | _load_fsLR_atlasroi_for_size | def _load_fsLR_atlasroi_for_size(size, sid=100610):
'''
Loads the appropriate atlas for the given size of data; size should be the number of stored
vertices and sub-corticel voxels stored in the cifti file.
'''
from .core import subject
# it doesn't matter what subject we request, so just use any one
fls = _load_fsLR_atlasroi_for_size.sizes
if size not in fls: raise ValueError('unknown fs_LR atlas size: %s' % size)
(n,fls) = _load_fsLR_atlasroi_for_size.sizes[size]
fl = os.path.join(subject(sid).path, 'MNINonLinear', *fls)
dat = {'id':sid, 'cifti':True, 'hemi':('lh_LR%dk_MSMAll' % n ,'rh_LR%dk_MSMAll' % n)}
return _load_fsLR_atlasroi(fl, dat) | python | def _load_fsLR_atlasroi_for_size(size, sid=100610):
'''
Loads the appropriate atlas for the given size of data; size should be the number of stored
vertices and sub-corticel voxels stored in the cifti file.
'''
from .core import subject
# it doesn't matter what subject we request, so just use any one
fls = _load_fsLR_atlasroi_for_size.sizes
if size not in fls: raise ValueError('unknown fs_LR atlas size: %s' % size)
(n,fls) = _load_fsLR_atlasroi_for_size.sizes[size]
fl = os.path.join(subject(sid).path, 'MNINonLinear', *fls)
dat = {'id':sid, 'cifti':True, 'hemi':('lh_LR%dk_MSMAll' % n ,'rh_LR%dk_MSMAll' % n)}
return _load_fsLR_atlasroi(fl, dat) | [
"def",
"_load_fsLR_atlasroi_for_size",
"(",
"size",
",",
"sid",
"=",
"100610",
")",
":",
"from",
".",
"core",
"import",
"subject",
"# it doesn't matter what subject we request, so just use any one",
"fls",
"=",
"_load_fsLR_atlasroi_for_size",
".",
"sizes",
"if",
"size",
... | Loads the appropriate atlas for the given size of data; size should be the number of stored
vertices and sub-corticel voxels stored in the cifti file. | [
"Loads",
"the",
"appropriate",
"atlas",
"for",
"the",
"given",
"size",
"of",
"data",
";",
"size",
"should",
"be",
"the",
"number",
"of",
"stored",
"vertices",
"and",
"sub",
"-",
"corticel",
"voxels",
"stored",
"in",
"the",
"cifti",
"file",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/hcp/files.py#L270-L282 | train | 35,175 |
noahbenson/neuropythy | neuropythy/commands/register_retinotopy.py | calc_arguments | def calc_arguments(args):
'''
calc_arguments is a calculator that parses the command-line arguments for the registration
command and produces the subject, the model, the log function, and the additional options.
'''
(args, opts) = _retinotopy_parser(args)
# We do some of the options right here...
if opts['help']:
print(info, file=sys.stdout)
sys.exit(1)
# and if we are verbose, lets setup a note function
verbose = opts['verbose']
def note(s):
if verbose:
print(s, file=sys.stdout)
sys.stdout.flush()
return verbose
def error(s):
print(s, file=sys.stderr)
sys.stderr.flush()
sys.exit(1)
if len(args) < 1: error('subject argument is required')
# Add the subjects directory, if there is one
if 'subjects_dir' in opts and opts['subjects_dir'] is not None:
add_subject_path(opts['subjects_dir'])
# Get the subject now
try: sub = subject(args[0])
except Exception: error('Failed to load subject %s' % args[0])
# and the model
if len(args) > 1: mdl_name = args[1]
elif opts['model_sym']: mdl_name = 'schira'
else: mdl_name = 'benson17'
try:
if opts['model_sym']:
model = {h:retinotopy_model(mdl_name).persist() for h in ['lh', 'rh']}
else:
model = {h:retinotopy_model(mdl_name, hemi=h).persist() for h in ['lh', 'rh']}
except Exception: error('Could not load retinotopy model %s' % mdl_name)
# Now, we want to run a few filters on the options
# Parse the simple numbers
for o in ['weight_min', 'scale', 'max_step_size', 'max_out_eccen',
'max_in_eccen', 'min_in_eccen', 'field_sign_weight', 'radius_weight']:
opts[o] = float(opts[o])
opts['max_steps'] = int(opts['max_steps'])
# Make a note:
note('Processing subject: %s' % sub.name)
del opts['help']
del opts['verbose']
del opts['subjects_dir']
# That's all we need!
return pimms.merge(opts,
{'subject': sub.persist(),
'model': pyr.pmap(model),
'options': pyr.pmap(opts),
'note': note,
'error': error}) | python | def calc_arguments(args):
'''
calc_arguments is a calculator that parses the command-line arguments for the registration
command and produces the subject, the model, the log function, and the additional options.
'''
(args, opts) = _retinotopy_parser(args)
# We do some of the options right here...
if opts['help']:
print(info, file=sys.stdout)
sys.exit(1)
# and if we are verbose, lets setup a note function
verbose = opts['verbose']
def note(s):
if verbose:
print(s, file=sys.stdout)
sys.stdout.flush()
return verbose
def error(s):
print(s, file=sys.stderr)
sys.stderr.flush()
sys.exit(1)
if len(args) < 1: error('subject argument is required')
# Add the subjects directory, if there is one
if 'subjects_dir' in opts and opts['subjects_dir'] is not None:
add_subject_path(opts['subjects_dir'])
# Get the subject now
try: sub = subject(args[0])
except Exception: error('Failed to load subject %s' % args[0])
# and the model
if len(args) > 1: mdl_name = args[1]
elif opts['model_sym']: mdl_name = 'schira'
else: mdl_name = 'benson17'
try:
if opts['model_sym']:
model = {h:retinotopy_model(mdl_name).persist() for h in ['lh', 'rh']}
else:
model = {h:retinotopy_model(mdl_name, hemi=h).persist() for h in ['lh', 'rh']}
except Exception: error('Could not load retinotopy model %s' % mdl_name)
# Now, we want to run a few filters on the options
# Parse the simple numbers
for o in ['weight_min', 'scale', 'max_step_size', 'max_out_eccen',
'max_in_eccen', 'min_in_eccen', 'field_sign_weight', 'radius_weight']:
opts[o] = float(opts[o])
opts['max_steps'] = int(opts['max_steps'])
# Make a note:
note('Processing subject: %s' % sub.name)
del opts['help']
del opts['verbose']
del opts['subjects_dir']
# That's all we need!
return pimms.merge(opts,
{'subject': sub.persist(),
'model': pyr.pmap(model),
'options': pyr.pmap(opts),
'note': note,
'error': error}) | [
"def",
"calc_arguments",
"(",
"args",
")",
":",
"(",
"args",
",",
"opts",
")",
"=",
"_retinotopy_parser",
"(",
"args",
")",
"# We do some of the options right here...",
"if",
"opts",
"[",
"'help'",
"]",
":",
"print",
"(",
"info",
",",
"file",
"=",
"sys",
"... | calc_arguments is a calculator that parses the command-line arguments for the registration
command and produces the subject, the model, the log function, and the additional options. | [
"calc_arguments",
"is",
"a",
"calculator",
"that",
"parses",
"the",
"command",
"-",
"line",
"arguments",
"for",
"the",
"registration",
"command",
"and",
"produces",
"the",
"subject",
"the",
"model",
"the",
"log",
"function",
"and",
"the",
"additional",
"options"... | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/register_retinotopy.py#L305-L361 | train | 35,176 |
noahbenson/neuropythy | neuropythy/commands/register_retinotopy.py | calc_retinotopy | def calc_retinotopy(note, error, subject, clean, run_lh, run_rh,
invert_rh_angle, max_in_eccen, min_in_eccen,
angle_lh_file, theta_lh_file,
eccen_lh_file, rho_lh_file,
weight_lh_file, radius_lh_file,
angle_rh_file, theta_rh_file,
eccen_rh_file, rho_rh_file,
weight_rh_file, radius_rh_file):
'''
calc_retinotopy extracts the retinotopy options from the command line, loads the relevant files,
and stores them as properties on the subject's lh and rh cortices.
'''
ctcs = {}
for (h,ang,tht,ecc,rho,wgt,rad,run) in [
('lh', angle_lh_file,theta_lh_file, eccen_lh_file,rho_lh_file,
weight_lh_file, radius_lh_file, run_lh),
('rh', angle_rh_file,theta_rh_file, eccen_rh_file,rho_rh_file,
weight_rh_file, radius_rh_file, run_rh)]:
if not run: continue
hemi = getattr(subject, h)
props = {}
# load the properties or find them in the auto-properties
if ang:
try: props['polar_angle'] = _guess_surf_file(ang)
except Exception: error('could not load surface file %s' % ang)
elif tht:
try:
tmp = _guess_surf_file(tht)
props['polar_angle'] = 90.0 - 180.0 / np.pi * tmp
except Exception: error('could not load surface file %s' % tht)
else:
props['polar_angle'] = empirical_retinotopy_data(hemi, 'polar_angle')
if ecc:
try: props['eccentricity'] = _guess_surf_file(ecc)
except Exception: error('could not load surface file %s' % ecc)
elif rho:
try:
tmp = _guess_surf_file(rhp)
props['eccentricity'] = 180.0 / np.pi * tmp
except Exception: error('could not load surface file %s' % rho)
else:
props['eccentricity'] = empirical_retinotopy_data(hemi, 'eccentricity')
if wgt:
try: props['weight'] = _guess_surf_file(wgt)
except Exception: error('could not load surface file %s' % wgt)
else:
props['weight'] = empirical_retinotopy_data(hemi, 'weight')
if rad:
try: props['radius'] = _guess_surf_file(rad)
except Exception: error('could not load surface file %s' % rad)
else:
props['radius'] = empirical_retinotopy_data(hemi, 'radius')
# Check for inverted rh
if h == 'rh' and invert_rh_angle:
props['polar_angle'] = -props['polar_angle']
# and zero-out weights for high eccentricities
props['weight'] = np.array(props['weight'])
if max_in_eccen is not None:
props['weight'][props['eccentricity'] > max_in_eccen] = 0
if min_in_eccen is not None:
props['weight'][props['eccentricity'] < min_in_eccen] = 0
# Do smoothing, if requested
if clean:
note('Cleaning %s retinotopy...' % h.upper())
(ang,ecc) = clean_retinotopy(hemi, retinotopy=props, mask=None, weight='weight')
props['polar_angle'] = ang
props['eccentricity'] = ecc
ctcs[h] = hemi.with_prop(props)
return {'cortices': pyr.pmap(ctcs)} | python | def calc_retinotopy(note, error, subject, clean, run_lh, run_rh,
invert_rh_angle, max_in_eccen, min_in_eccen,
angle_lh_file, theta_lh_file,
eccen_lh_file, rho_lh_file,
weight_lh_file, radius_lh_file,
angle_rh_file, theta_rh_file,
eccen_rh_file, rho_rh_file,
weight_rh_file, radius_rh_file):
'''
calc_retinotopy extracts the retinotopy options from the command line, loads the relevant files,
and stores them as properties on the subject's lh and rh cortices.
'''
ctcs = {}
for (h,ang,tht,ecc,rho,wgt,rad,run) in [
('lh', angle_lh_file,theta_lh_file, eccen_lh_file,rho_lh_file,
weight_lh_file, radius_lh_file, run_lh),
('rh', angle_rh_file,theta_rh_file, eccen_rh_file,rho_rh_file,
weight_rh_file, radius_rh_file, run_rh)]:
if not run: continue
hemi = getattr(subject, h)
props = {}
# load the properties or find them in the auto-properties
if ang:
try: props['polar_angle'] = _guess_surf_file(ang)
except Exception: error('could not load surface file %s' % ang)
elif tht:
try:
tmp = _guess_surf_file(tht)
props['polar_angle'] = 90.0 - 180.0 / np.pi * tmp
except Exception: error('could not load surface file %s' % tht)
else:
props['polar_angle'] = empirical_retinotopy_data(hemi, 'polar_angle')
if ecc:
try: props['eccentricity'] = _guess_surf_file(ecc)
except Exception: error('could not load surface file %s' % ecc)
elif rho:
try:
tmp = _guess_surf_file(rhp)
props['eccentricity'] = 180.0 / np.pi * tmp
except Exception: error('could not load surface file %s' % rho)
else:
props['eccentricity'] = empirical_retinotopy_data(hemi, 'eccentricity')
if wgt:
try: props['weight'] = _guess_surf_file(wgt)
except Exception: error('could not load surface file %s' % wgt)
else:
props['weight'] = empirical_retinotopy_data(hemi, 'weight')
if rad:
try: props['radius'] = _guess_surf_file(rad)
except Exception: error('could not load surface file %s' % rad)
else:
props['radius'] = empirical_retinotopy_data(hemi, 'radius')
# Check for inverted rh
if h == 'rh' and invert_rh_angle:
props['polar_angle'] = -props['polar_angle']
# and zero-out weights for high eccentricities
props['weight'] = np.array(props['weight'])
if max_in_eccen is not None:
props['weight'][props['eccentricity'] > max_in_eccen] = 0
if min_in_eccen is not None:
props['weight'][props['eccentricity'] < min_in_eccen] = 0
# Do smoothing, if requested
if clean:
note('Cleaning %s retinotopy...' % h.upper())
(ang,ecc) = clean_retinotopy(hemi, retinotopy=props, mask=None, weight='weight')
props['polar_angle'] = ang
props['eccentricity'] = ecc
ctcs[h] = hemi.with_prop(props)
return {'cortices': pyr.pmap(ctcs)} | [
"def",
"calc_retinotopy",
"(",
"note",
",",
"error",
",",
"subject",
",",
"clean",
",",
"run_lh",
",",
"run_rh",
",",
"invert_rh_angle",
",",
"max_in_eccen",
",",
"min_in_eccen",
",",
"angle_lh_file",
",",
"theta_lh_file",
",",
"eccen_lh_file",
",",
"rho_lh_file... | calc_retinotopy extracts the retinotopy options from the command line, loads the relevant files,
and stores them as properties on the subject's lh and rh cortices. | [
"calc_retinotopy",
"extracts",
"the",
"retinotopy",
"options",
"from",
"the",
"command",
"line",
"loads",
"the",
"relevant",
"files",
"and",
"stores",
"them",
"as",
"properties",
"on",
"the",
"subject",
"s",
"lh",
"and",
"rh",
"cortices",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/register_retinotopy.py#L363-L431 | train | 35,177 |
noahbenson/neuropythy | neuropythy/commands/register_retinotopy.py | calc_registrations | def calc_registrations(note, error, cortices, model, model_sym,
weight_min, scale, prior, max_out_eccen, max_steps, max_step_size,
radius_weight, field_sign_weight, resample, invert_rh_angle,
part_vol_correct):
'''
calc_registrations is the calculator that performs the registrations for the left and right
hemisphere; these are returned as the immutable maps yielded from the register_retinotopy
command.
'''
rsamp = ('fsaverage_sym' if model_sym else 'fsaverage') if resample else False
# Do the registration
res = {}
for (h,ctx) in six.iteritems(cortices):
note('Preparing %s Registration...' % h.upper())
try:
res[h] = register_retinotopy(ctx, model[h],
model_hemi='sym' if model_sym else h,
polar_angle='polar_angle',
eccentricity='eccentricity',
weight='weight',
weight_min=weight_min,
partial_voluming_correction=part_vol_correct,
field_sign_weight=field_sign_weight,
radius_weight=radius_weight,
scale=scale,
prior=prior,
resample=rsamp,
invert_rh_field_sign=invert_rh_angle,
max_steps=max_steps,
max_step_size=max_step_size,
yield_imap=True)
except Exception: #error('Exception caught while setting-up register_retinotopy (%s)' % h)
raise
return {'registrations': pyr.pmap(res)} | python | def calc_registrations(note, error, cortices, model, model_sym,
weight_min, scale, prior, max_out_eccen, max_steps, max_step_size,
radius_weight, field_sign_weight, resample, invert_rh_angle,
part_vol_correct):
'''
calc_registrations is the calculator that performs the registrations for the left and right
hemisphere; these are returned as the immutable maps yielded from the register_retinotopy
command.
'''
rsamp = ('fsaverage_sym' if model_sym else 'fsaverage') if resample else False
# Do the registration
res = {}
for (h,ctx) in six.iteritems(cortices):
note('Preparing %s Registration...' % h.upper())
try:
res[h] = register_retinotopy(ctx, model[h],
model_hemi='sym' if model_sym else h,
polar_angle='polar_angle',
eccentricity='eccentricity',
weight='weight',
weight_min=weight_min,
partial_voluming_correction=part_vol_correct,
field_sign_weight=field_sign_weight,
radius_weight=radius_weight,
scale=scale,
prior=prior,
resample=rsamp,
invert_rh_field_sign=invert_rh_angle,
max_steps=max_steps,
max_step_size=max_step_size,
yield_imap=True)
except Exception: #error('Exception caught while setting-up register_retinotopy (%s)' % h)
raise
return {'registrations': pyr.pmap(res)} | [
"def",
"calc_registrations",
"(",
"note",
",",
"error",
",",
"cortices",
",",
"model",
",",
"model_sym",
",",
"weight_min",
",",
"scale",
",",
"prior",
",",
"max_out_eccen",
",",
"max_steps",
",",
"max_step_size",
",",
"radius_weight",
",",
"field_sign_weight",
... | calc_registrations is the calculator that performs the registrations for the left and right
hemisphere; these are returned as the immutable maps yielded from the register_retinotopy
command. | [
"calc_registrations",
"is",
"the",
"calculator",
"that",
"performs",
"the",
"registrations",
"for",
"the",
"left",
"and",
"right",
"hemisphere",
";",
"these",
"are",
"returned",
"as",
"the",
"immutable",
"maps",
"yielded",
"from",
"the",
"register_retinotopy",
"co... | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/register_retinotopy.py#L433-L466 | train | 35,178 |
noahbenson/neuropythy | neuropythy/commands/register_retinotopy.py | save_surface_files | def save_surface_files(note, error, registrations, subject,
no_surf_export, no_reg_export, surface_format, surface_path,
angle_tag, eccen_tag, label_tag, radius_tag, registration_name):
'''
save_surface_files is the calculator that saves the registration data out as surface files,
which are put back in the registration as the value 'surface_files'.
'''
if no_surf_export: return {'surface_files': ()}
surface_format = surface_format.lower()
# make an exporter for properties:
if surface_format in ['curv', 'morph', 'auto', 'automatic']:
def export(flnm, p):
fsio.write_morph_data(flnm, p)
return flnm
elif surface_format in ['mgh', 'mgz']:
def export(flnm, p):
flnm = flnm + '.' + surface_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = fsmgh.MGHImage(np.asarray([[p]], dtype=dt), np.eye(4))
img.to_filename(flnm)
return flnm
elif surface_format in ['nifti', 'nii', 'niigz', 'nii.gz']:
surface_format = 'nii' if surface_format == 'nii' else 'nii.gz'
def export(flnm, p):
flnm = flnm + '.' + surface_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = nib.Nifti1Image(np.asarray([[p]], dtype=dt), np.eye(4))
img.to_filename(flnm)
return flnm
else:
error('Could not understand surface file-format %s' % surface_format)
path = surface_path if surface_path else os.path.join(subject.path, 'surf')
files = []
note('Exporting files...')
for h in six.iterkeys(registrations):
hemi = subject.hemis[h]
reg = registrations[h]
note('Extracting %s predicted mesh...' % h.upper())
pmesh = reg['predicted_mesh']
for (pname,tag) in zip(['polar_angle', 'eccentricity', 'visual_area', 'radius'],
[angle_tag, eccen_tag, label_tag, radius_tag]):
flnm = export(os.path.join(path, h + '.' + tag), pmesh.prop(pname))
files.append(flnm)
# last do the registration itself
if registration_name and not no_reg_export:
flnm = os.path.join(path, h + '.' + registration_name + '.sphere.reg')
fsio.write_geometry(flnm, pmesh.coordinates.T, pmesh.tess.faces.T)
return {'surface_files': tuple(files)} | python | def save_surface_files(note, error, registrations, subject,
no_surf_export, no_reg_export, surface_format, surface_path,
angle_tag, eccen_tag, label_tag, radius_tag, registration_name):
'''
save_surface_files is the calculator that saves the registration data out as surface files,
which are put back in the registration as the value 'surface_files'.
'''
if no_surf_export: return {'surface_files': ()}
surface_format = surface_format.lower()
# make an exporter for properties:
if surface_format in ['curv', 'morph', 'auto', 'automatic']:
def export(flnm, p):
fsio.write_morph_data(flnm, p)
return flnm
elif surface_format in ['mgh', 'mgz']:
def export(flnm, p):
flnm = flnm + '.' + surface_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = fsmgh.MGHImage(np.asarray([[p]], dtype=dt), np.eye(4))
img.to_filename(flnm)
return flnm
elif surface_format in ['nifti', 'nii', 'niigz', 'nii.gz']:
surface_format = 'nii' if surface_format == 'nii' else 'nii.gz'
def export(flnm, p):
flnm = flnm + '.' + surface_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = nib.Nifti1Image(np.asarray([[p]], dtype=dt), np.eye(4))
img.to_filename(flnm)
return flnm
else:
error('Could not understand surface file-format %s' % surface_format)
path = surface_path if surface_path else os.path.join(subject.path, 'surf')
files = []
note('Exporting files...')
for h in six.iterkeys(registrations):
hemi = subject.hemis[h]
reg = registrations[h]
note('Extracting %s predicted mesh...' % h.upper())
pmesh = reg['predicted_mesh']
for (pname,tag) in zip(['polar_angle', 'eccentricity', 'visual_area', 'radius'],
[angle_tag, eccen_tag, label_tag, radius_tag]):
flnm = export(os.path.join(path, h + '.' + tag), pmesh.prop(pname))
files.append(flnm)
# last do the registration itself
if registration_name and not no_reg_export:
flnm = os.path.join(path, h + '.' + registration_name + '.sphere.reg')
fsio.write_geometry(flnm, pmesh.coordinates.T, pmesh.tess.faces.T)
return {'surface_files': tuple(files)} | [
"def",
"save_surface_files",
"(",
"note",
",",
"error",
",",
"registrations",
",",
"subject",
",",
"no_surf_export",
",",
"no_reg_export",
",",
"surface_format",
",",
"surface_path",
",",
"angle_tag",
",",
"eccen_tag",
",",
"label_tag",
",",
"radius_tag",
",",
"... | save_surface_files is the calculator that saves the registration data out as surface files,
which are put back in the registration as the value 'surface_files'. | [
"save_surface_files",
"is",
"the",
"calculator",
"that",
"saves",
"the",
"registration",
"data",
"out",
"as",
"surface",
"files",
"which",
"are",
"put",
"back",
"in",
"the",
"registration",
"as",
"the",
"value",
"surface_files",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/register_retinotopy.py#L468-L515 | train | 35,179 |
noahbenson/neuropythy | neuropythy/commands/register_retinotopy.py | save_volume_files | def save_volume_files(note, error, registrations, subject,
no_vol_export, volume_format, volume_path,
angle_tag, eccen_tag, label_tag, radius_tag):
'''
save_volume_files is the calculator that saves the registration data out as volume files,
which are put back in the registration as the value 'volume_files'.
'''
if no_vol_export: return {'volume_files': ()}
volume_format = volume_format.lower()
# make an exporter for properties:
if volume_format in ['mgh', 'mgz', 'auto', 'automatic', 'default']:
volume_format = 'mgh' if volume_format == 'mgh' else 'mgz'
def export(flnm, d):
flnm = flnm + '.' + volume_format
dt = np.int32 if np.issubdtype(d.dtype, np.dtype(int).type) else np.float32
img = fsmgh.MGHImage(np.asarray(d, dtype=dt), subject.voxel_to_native_matrix)
img.to_filename(flnm)
return flnm
elif volume_format in ['nifti', 'nii', 'niigz', 'nii.gz']:
volume_format = 'nii' if volume_format == 'nii' else 'nii.gz'
def export(flnm, p):
flnm = flnm + '.' + volume_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = nib.Nifti1Image(np.asarray(p, dtype=dt), subject.voxel_to_native_matrix)
img.to_filename(flnm)
return flnm
else:
error('Could not understand volume file-format %s' % volume_format)
path = volume_path if volume_path else os.path.join(subject.path, 'mri')
files = []
note('Extracting predicted meshes for volume export...')
hemis = [registrations[h]['predicted_mesh'] if h in registrations else None
for h in ['lh', 'rh']]
for (pname,tag) in zip(['polar_angle', 'eccentricity', 'visual_area', 'radius'],
[angle_tag, eccen_tag, label_tag, radius_tag]):
# we have to make the volume first...
dat = tuple([None if h is None else h.prop(pname) for h in hemis])
(mtd,dt) = ('nearest',np.int32) if pname == 'visual_area' else ('linear',np.float32)
note('Constructing %s image...' % pname)
img = subject.cortex_to_image(dat, method=mtd, dtype=dt)
flnm = export(os.path.join(path, tag), img)
files.append(flnm)
return {'volume_files': tuple(files)} | python | def save_volume_files(note, error, registrations, subject,
no_vol_export, volume_format, volume_path,
angle_tag, eccen_tag, label_tag, radius_tag):
'''
save_volume_files is the calculator that saves the registration data out as volume files,
which are put back in the registration as the value 'volume_files'.
'''
if no_vol_export: return {'volume_files': ()}
volume_format = volume_format.lower()
# make an exporter for properties:
if volume_format in ['mgh', 'mgz', 'auto', 'automatic', 'default']:
volume_format = 'mgh' if volume_format == 'mgh' else 'mgz'
def export(flnm, d):
flnm = flnm + '.' + volume_format
dt = np.int32 if np.issubdtype(d.dtype, np.dtype(int).type) else np.float32
img = fsmgh.MGHImage(np.asarray(d, dtype=dt), subject.voxel_to_native_matrix)
img.to_filename(flnm)
return flnm
elif volume_format in ['nifti', 'nii', 'niigz', 'nii.gz']:
volume_format = 'nii' if volume_format == 'nii' else 'nii.gz'
def export(flnm, p):
flnm = flnm + '.' + volume_format
dt = np.int32 if np.issubdtype(p.dtype, np.dtype(int).type) else np.float32
img = nib.Nifti1Image(np.asarray(p, dtype=dt), subject.voxel_to_native_matrix)
img.to_filename(flnm)
return flnm
else:
error('Could not understand volume file-format %s' % volume_format)
path = volume_path if volume_path else os.path.join(subject.path, 'mri')
files = []
note('Extracting predicted meshes for volume export...')
hemis = [registrations[h]['predicted_mesh'] if h in registrations else None
for h in ['lh', 'rh']]
for (pname,tag) in zip(['polar_angle', 'eccentricity', 'visual_area', 'radius'],
[angle_tag, eccen_tag, label_tag, radius_tag]):
# we have to make the volume first...
dat = tuple([None if h is None else h.prop(pname) for h in hemis])
(mtd,dt) = ('nearest',np.int32) if pname == 'visual_area' else ('linear',np.float32)
note('Constructing %s image...' % pname)
img = subject.cortex_to_image(dat, method=mtd, dtype=dt)
flnm = export(os.path.join(path, tag), img)
files.append(flnm)
return {'volume_files': tuple(files)} | [
"def",
"save_volume_files",
"(",
"note",
",",
"error",
",",
"registrations",
",",
"subject",
",",
"no_vol_export",
",",
"volume_format",
",",
"volume_path",
",",
"angle_tag",
",",
"eccen_tag",
",",
"label_tag",
",",
"radius_tag",
")",
":",
"if",
"no_vol_export",... | save_volume_files is the calculator that saves the registration data out as volume files,
which are put back in the registration as the value 'volume_files'. | [
"save_volume_files",
"is",
"the",
"calculator",
"that",
"saves",
"the",
"registration",
"data",
"out",
"as",
"volume",
"files",
"which",
"are",
"put",
"back",
"in",
"the",
"registration",
"as",
"the",
"value",
"volume_files",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/register_retinotopy.py#L517-L559 | train | 35,180 |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | calc_empirical_retinotopy | def calc_empirical_retinotopy(cortex,
polar_angle=None, eccentricity=None, pRF_radius=None, weight=None,
eccentricity_range=None, weight_min=0,
invert_rh_angle=False,
partial_voluming_correction=False):
'''
calc_empirical_retinotopy computes the value empirical_retinotopy, which is an itable object
storing the retinotopy data for the registration.
Required afferent parameters:
@ cortex Must be the cortex object that is to be registered to the model of retinotopy.
Optional afferent parameters:
@ polar_angle May be an array of polar angle values or a polar angle property name; if None
(the default), attempts to auto-detect an empirical polar angle property.
@ eccentricity May be an array of eccentricity values or an eccentricity property name; if
None (the default), attempts to auto-detect an empirical eccentricity property.
@ pRF_radius May be an array of receptive field radius values or the property name for such an
array; if None (the default), attempts to auto-detect an empirical radius property.
@ weight May be an array of weight values or a weight property name; if None (the default),
attempts to auto-detect an empirical weight property, such as variance_explained.
@ eccentricity_range May be a maximum eccentricity value or a (min, max) eccentricity range
to be used in the registration; if None, then no clipping is done.
@ weight_min May be given to indicate that weight values below this value should not be
included in the registration; the default is 0.
@ partial_voluming_correction May be set to True (default is False) to indicate that partial
voluming correction should be used to adjust the weights.
@ invert_rh_angle May be set to True (default is False) to indicate that the right hemisphere
has its polar angle stored with opposite sign to the model polar angle.
Efferent values:
@ empirical_retinotopy Will be a pimms itable of the empirical retinotopy data to be used in
the registration; the table's keys will be 'polar_angle', 'eccentricity', and 'weight';
values that should be excluded for any reason will have 0 weight and undefined angles.
'''
data = {} # the map we build up in this function
n = cortex.vertex_count
(emin,emax) = (-np.inf,np.inf) if eccentricity_range is None else \
(0,eccentricity_range) if pimms.is_number(eccentricity_range) else \
eccentricity_range
# Step 1: get our properties straight ##########################################################
(ang, ecc, rad, wgt) = [
np.array(extract_retinotopy_argument(cortex, name, arg, default='empirical'))
for (name, arg) in [
('polar_angle', polar_angle),
('eccentricity', eccentricity),
('radius', pRF_radius),
('weight', np.full(n, weight) if pimms.is_number(weight) else weight)]]
if wgt is None: wgt = np.ones(len(ecc))
bad = np.logical_not(np.isfinite(np.prod([ang, ecc, wgt], axis=0)))
ecc[bad] = 0
wgt[bad] = 0
if rad is not None: rad[bad] = 0
# do partial voluming correction if requested
if partial_voluming_correction: wgt = wgt * (1 - cortex.partial_voluming_factor)
# now trim and finalize
bad = bad | (wgt <= weight_min) | (ecc < emin) | (ecc > emax)
wgt[bad] = 0
ang[bad] = 0
ecc[bad] = 0
for x in [ang, ecc, wgt, rad]:
if x is not None:
x.setflags(write=False)
# that's it!
dat = dict(polar_angle=ang, eccentricity=ecc, weight=wgt)
if rad is not None: dat['radius'] = rad
return (pimms.itable(dat),) | python | def calc_empirical_retinotopy(cortex,
polar_angle=None, eccentricity=None, pRF_radius=None, weight=None,
eccentricity_range=None, weight_min=0,
invert_rh_angle=False,
partial_voluming_correction=False):
'''
calc_empirical_retinotopy computes the value empirical_retinotopy, which is an itable object
storing the retinotopy data for the registration.
Required afferent parameters:
@ cortex Must be the cortex object that is to be registered to the model of retinotopy.
Optional afferent parameters:
@ polar_angle May be an array of polar angle values or a polar angle property name; if None
(the default), attempts to auto-detect an empirical polar angle property.
@ eccentricity May be an array of eccentricity values or an eccentricity property name; if
None (the default), attempts to auto-detect an empirical eccentricity property.
@ pRF_radius May be an array of receptive field radius values or the property name for such an
array; if None (the default), attempts to auto-detect an empirical radius property.
@ weight May be an array of weight values or a weight property name; if None (the default),
attempts to auto-detect an empirical weight property, such as variance_explained.
@ eccentricity_range May be a maximum eccentricity value or a (min, max) eccentricity range
to be used in the registration; if None, then no clipping is done.
@ weight_min May be given to indicate that weight values below this value should not be
included in the registration; the default is 0.
@ partial_voluming_correction May be set to True (default is False) to indicate that partial
voluming correction should be used to adjust the weights.
@ invert_rh_angle May be set to True (default is False) to indicate that the right hemisphere
has its polar angle stored with opposite sign to the model polar angle.
Efferent values:
@ empirical_retinotopy Will be a pimms itable of the empirical retinotopy data to be used in
the registration; the table's keys will be 'polar_angle', 'eccentricity', and 'weight';
values that should be excluded for any reason will have 0 weight and undefined angles.
'''
data = {} # the map we build up in this function
n = cortex.vertex_count
(emin,emax) = (-np.inf,np.inf) if eccentricity_range is None else \
(0,eccentricity_range) if pimms.is_number(eccentricity_range) else \
eccentricity_range
# Step 1: get our properties straight ##########################################################
(ang, ecc, rad, wgt) = [
np.array(extract_retinotopy_argument(cortex, name, arg, default='empirical'))
for (name, arg) in [
('polar_angle', polar_angle),
('eccentricity', eccentricity),
('radius', pRF_radius),
('weight', np.full(n, weight) if pimms.is_number(weight) else weight)]]
if wgt is None: wgt = np.ones(len(ecc))
bad = np.logical_not(np.isfinite(np.prod([ang, ecc, wgt], axis=0)))
ecc[bad] = 0
wgt[bad] = 0
if rad is not None: rad[bad] = 0
# do partial voluming correction if requested
if partial_voluming_correction: wgt = wgt * (1 - cortex.partial_voluming_factor)
# now trim and finalize
bad = bad | (wgt <= weight_min) | (ecc < emin) | (ecc > emax)
wgt[bad] = 0
ang[bad] = 0
ecc[bad] = 0
for x in [ang, ecc, wgt, rad]:
if x is not None:
x.setflags(write=False)
# that's it!
dat = dict(polar_angle=ang, eccentricity=ecc, weight=wgt)
if rad is not None: dat['radius'] = rad
return (pimms.itable(dat),) | [
"def",
"calc_empirical_retinotopy",
"(",
"cortex",
",",
"polar_angle",
"=",
"None",
",",
"eccentricity",
"=",
"None",
",",
"pRF_radius",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"eccentricity_range",
"=",
"None",
",",
"weight_min",
"=",
"0",
",",
"inver... | calc_empirical_retinotopy computes the value empirical_retinotopy, which is an itable object
storing the retinotopy data for the registration.
Required afferent parameters:
@ cortex Must be the cortex object that is to be registered to the model of retinotopy.
Optional afferent parameters:
@ polar_angle May be an array of polar angle values or a polar angle property name; if None
(the default), attempts to auto-detect an empirical polar angle property.
@ eccentricity May be an array of eccentricity values or an eccentricity property name; if
None (the default), attempts to auto-detect an empirical eccentricity property.
@ pRF_radius May be an array of receptive field radius values or the property name for such an
array; if None (the default), attempts to auto-detect an empirical radius property.
@ weight May be an array of weight values or a weight property name; if None (the default),
attempts to auto-detect an empirical weight property, such as variance_explained.
@ eccentricity_range May be a maximum eccentricity value or a (min, max) eccentricity range
to be used in the registration; if None, then no clipping is done.
@ weight_min May be given to indicate that weight values below this value should not be
included in the registration; the default is 0.
@ partial_voluming_correction May be set to True (default is False) to indicate that partial
voluming correction should be used to adjust the weights.
@ invert_rh_angle May be set to True (default is False) to indicate that the right hemisphere
has its polar angle stored with opposite sign to the model polar angle.
Efferent values:
@ empirical_retinotopy Will be a pimms itable of the empirical retinotopy data to be used in
the registration; the table's keys will be 'polar_angle', 'eccentricity', and 'weight';
values that should be excluded for any reason will have 0 weight and undefined angles. | [
"calc_empirical_retinotopy",
"computes",
"the",
"value",
"empirical_retinotopy",
"which",
"is",
"an",
"itable",
"object",
"storing",
"the",
"retinotopy",
"data",
"for",
"the",
"registration",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1051-L1117 | train | 35,181 |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | calc_model | def calc_model(cortex, model_argument, model_hemi=Ellipsis, radius=np.pi/3):
'''
calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetinotopyModel object or the name of a model that
can be loaded.
Optional afferent parameters:
@ model_hemi May be used to specify the hemisphere of the model; this is usually only used
when the fsaverage_sym hemisphere is desired, in which case this should be set to None; if
left at the default value (Ellipsis), then it will use the hemisphere of the cortex param.
Provided efferent values:
@ model Will be the RegisteredRetinotopyModel object to which the mesh should be registered.
'''
if pimms.is_str(model_argument):
h = cortex.chirality if model_hemi is Ellipsis else \
None if model_hemi is None else \
model_hemi
model = retinotopy_model(model_argument, hemi=h, radius=radius)
else:
model = model_argument
if not isinstance(model, RegisteredRetinotopyModel):
raise ValueError('model must be a RegisteredRetinotopyModel')
return model | python | def calc_model(cortex, model_argument, model_hemi=Ellipsis, radius=np.pi/3):
'''
calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetinotopyModel object or the name of a model that
can be loaded.
Optional afferent parameters:
@ model_hemi May be used to specify the hemisphere of the model; this is usually only used
when the fsaverage_sym hemisphere is desired, in which case this should be set to None; if
left at the default value (Ellipsis), then it will use the hemisphere of the cortex param.
Provided efferent values:
@ model Will be the RegisteredRetinotopyModel object to which the mesh should be registered.
'''
if pimms.is_str(model_argument):
h = cortex.chirality if model_hemi is Ellipsis else \
None if model_hemi is None else \
model_hemi
model = retinotopy_model(model_argument, hemi=h, radius=radius)
else:
model = model_argument
if not isinstance(model, RegisteredRetinotopyModel):
raise ValueError('model must be a RegisteredRetinotopyModel')
return model | [
"def",
"calc_model",
"(",
"cortex",
",",
"model_argument",
",",
"model_hemi",
"=",
"Ellipsis",
",",
"radius",
"=",
"np",
".",
"pi",
"/",
"3",
")",
":",
"if",
"pimms",
".",
"is_str",
"(",
"model_argument",
")",
":",
"h",
"=",
"cortex",
".",
"chirality",... | calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetinotopyModel object or the name of a model that
can be loaded.
Optional afferent parameters:
@ model_hemi May be used to specify the hemisphere of the model; this is usually only used
when the fsaverage_sym hemisphere is desired, in which case this should be set to None; if
left at the default value (Ellipsis), then it will use the hemisphere of the cortex param.
Provided efferent values:
@ model Will be the RegisteredRetinotopyModel object to which the mesh should be registered. | [
"calc_model",
"loads",
"the",
"appropriate",
"model",
"object",
"given",
"the",
"model",
"argument",
"which",
"may",
"given",
"the",
"name",
"of",
"the",
"model",
"or",
"a",
"model",
"object",
"itself",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1119-L1145 | train | 35,182 |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | calc_anchors | def calc_anchors(preregistration_map, model, model_hemi,
scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0,
invert_rh_field_sign=False):
'''
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field signs will be incorrect relative to the model; this generally should be
used whenever invert_rh_angle is also set to True.
'''
wgts = preregistration_map.prop('weight')
rads = preregistration_map.prop('radius')
if np.isclose(radius_weight, 0): radius_weight = 0
ancs = retinotopy_anchors(preregistration_map, model,
polar_angle='polar_angle',
eccentricity='eccentricity',
radius='radius',
weight=wgts, weight_min=0, # taken care of already
radius_weight=radius_weight, field_sign_weight=field_sign_weight,
scale=scale,
invert_field_sign=(model_hemi == 'rh' and invert_rh_field_sign),
**({} if sigma is Ellipsis else {'sigma':sigma}))
return ancs | python | def calc_anchors(preregistration_map, model, model_hemi,
scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0,
invert_rh_field_sign=False):
'''
calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field signs will be incorrect relative to the model; this generally should be
used whenever invert_rh_angle is also set to True.
'''
wgts = preregistration_map.prop('weight')
rads = preregistration_map.prop('radius')
if np.isclose(radius_weight, 0): radius_weight = 0
ancs = retinotopy_anchors(preregistration_map, model,
polar_angle='polar_angle',
eccentricity='eccentricity',
radius='radius',
weight=wgts, weight_min=0, # taken care of already
radius_weight=radius_weight, field_sign_weight=field_sign_weight,
scale=scale,
invert_field_sign=(model_hemi == 'rh' and invert_rh_field_sign),
**({} if sigma is Ellipsis else {'sigma':sigma}))
return ancs | [
"def",
"calc_anchors",
"(",
"preregistration_map",
",",
"model",
",",
"model_hemi",
",",
"scale",
"=",
"1",
",",
"sigma",
"=",
"Ellipsis",
",",
"radius_weight",
"=",
"0",
",",
"field_sign_weight",
"=",
"0",
",",
"invert_rh_field_sign",
"=",
"False",
")",
":"... | calc_anchors is a calculator that creates a set of anchor instructions for a registration.
Required afferent parameters:
@ invert_rh_field_sign May be set to True (default is False) to indicate that the right
hemisphere's field signs will be incorrect relative to the model; this generally should be
used whenever invert_rh_angle is also set to True. | [
"calc_anchors",
"is",
"a",
"calculator",
"that",
"creates",
"a",
"set",
"of",
"anchor",
"instructions",
"for",
"a",
"registration",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1212-L1236 | train | 35,183 |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | calc_registration | def calc_registration(preregistration_map, anchors,
max_steps=2000, max_step_size=0.05, method='random'):
'''
calc_registration is a calculator that creates the registration coordinates.
'''
# if max steps is a tuple (max, stride) then a trajectory is saved into
# the registered_map meta-data
pmap = preregistration_map
if is_tuple(max_steps) or is_list(max_steps):
(max_steps, stride) = max_steps
traj = [preregistration_map.coordinates]
x = preregistration_map.coordinates
for s in np.arange(0, max_steps, stride):
x = mesh_register(
preregistration_map,
[['edge', 'harmonic', 'scale', 1.0],
['angle', 'infinite-well', 'scale', 1.0],
['perimeter', 'harmonic'],
anchors],
initial_coordinates=x,
method=method,
max_steps=stride,
max_step_size=max_step_size)
traj.append(x)
pmap = pmap.with_meta(trajectory=np.asarray(traj))
else:
x = mesh_register(
preregistration_map,
[['edge', 'harmonic', 'scale', 1.0],
['angle', 'infinite-well', 'scale', 1.0],
['perimeter', 'harmonic'],
anchors],
method=method,
max_steps=max_steps,
max_step_size=max_step_size)
return pmap.copy(coordinates=x) | python | def calc_registration(preregistration_map, anchors,
max_steps=2000, max_step_size=0.05, method='random'):
'''
calc_registration is a calculator that creates the registration coordinates.
'''
# if max steps is a tuple (max, stride) then a trajectory is saved into
# the registered_map meta-data
pmap = preregistration_map
if is_tuple(max_steps) or is_list(max_steps):
(max_steps, stride) = max_steps
traj = [preregistration_map.coordinates]
x = preregistration_map.coordinates
for s in np.arange(0, max_steps, stride):
x = mesh_register(
preregistration_map,
[['edge', 'harmonic', 'scale', 1.0],
['angle', 'infinite-well', 'scale', 1.0],
['perimeter', 'harmonic'],
anchors],
initial_coordinates=x,
method=method,
max_steps=stride,
max_step_size=max_step_size)
traj.append(x)
pmap = pmap.with_meta(trajectory=np.asarray(traj))
else:
x = mesh_register(
preregistration_map,
[['edge', 'harmonic', 'scale', 1.0],
['angle', 'infinite-well', 'scale', 1.0],
['perimeter', 'harmonic'],
anchors],
method=method,
max_steps=max_steps,
max_step_size=max_step_size)
return pmap.copy(coordinates=x) | [
"def",
"calc_registration",
"(",
"preregistration_map",
",",
"anchors",
",",
"max_steps",
"=",
"2000",
",",
"max_step_size",
"=",
"0.05",
",",
"method",
"=",
"'random'",
")",
":",
"# if max steps is a tuple (max, stride) then a trajectory is saved into",
"# the registered_m... | calc_registration is a calculator that creates the registration coordinates. | [
"calc_registration",
"is",
"a",
"calculator",
"that",
"creates",
"the",
"registration",
"coordinates",
"."
] | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1239-L1274 | train | 35,184 |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | calc_prediction | def calc_prediction(registered_map, preregistration_mesh, native_mesh, model):
'''
calc_registration_prediction is a pimms calculator that creates the both the prediction and the
registration_prediction, both of which are pimms itables including the fields 'polar_angle',
'eccentricity', and 'visual_area'. The registration_prediction data describe the vertices for
the registered_map, not necessarily of the native_mesh, while the prediction describes the
native mesh.
Provided efferent values:
@ registered_mesh Will be a mesh object that is equivalent to the preregistration_mesh but
with the coordinates and predicted fields (from the registration) filled in. Note that this
mesh is still in the resampled configuration is resampling was performed.
@ registration_prediction Will be a pimms ITable object with columns 'polar_angle',
'eccentricity', and 'visual_area'. For values outside of the model region, visual_area will
be 0 and other values will be undefined (but are typically 0). The registration_prediction
describes the values on the registrered_mesh.
@ prediction will be a pimms ITable object with columns 'polar_angle', 'eccentricity', and
'visual_area'. For values outside of the model region, visual_area will be 0 and other
values will be undefined (but are typically 0). The prediction describes the values on the
native_mesh and the predicted_mesh.
'''
# invert the map projection to make the registration map into a mesh
coords3d = np.array(preregistration_mesh.coordinates)
idcs = registered_map.labels
coords3d[:,idcs] = registered_map.meta('projection').inverse(registered_map.coordinates)
rmesh = preregistration_mesh.copy(coordinates=coords3d)
# go ahead and get the model predictions...
d = model.cortex_to_angle(registered_map.coordinates)
id2n = model.area_id_to_name
(ang, ecc) = d[0:2]
lbl = np.asarray(d[2], dtype=np.int)
rad = np.asarray([predict_pRF_radius(e, id2n[l]) if l > 0 else 0 for (e,l) in zip(ecc,lbl)])
d = {'polar_angle':ang, 'eccentricity':ecc, 'visual_area':lbl, 'radius':rad}
# okay, put these on the mesh
rpred = {}
for (k,v) in six.iteritems(d):
v.setflags(write=False)
tmp = np.zeros(rmesh.vertex_count, dtype=v.dtype)
tmp[registered_map.labels] = v
tmp.setflags(write=False)
rpred[k] = tmp
rpred = pyr.pmap(rpred)
rmesh = rmesh.with_prop(rpred)
# next, do all of this for the native mesh..
if native_mesh is preregistration_mesh:
pred = rpred
pmesh = rmesh
else:
# we need to address the native coordinates in the prereg coordinates then unaddress them
# in the registered coordinates; this will let us make a native-registered-map and repeat
# the exercise above
addr = preregistration_mesh.address(native_mesh.coordinates)
natreg_mesh = native_mesh.copy(coordinates=rmesh.unaddress(addr))
d = model.cortex_to_angle(natreg_mesh)
(ang,ecc) = d[0:2]
lbl = np.asarray(d[2], dtype=np.int)
rad = np.asarray([predict_pRF_radius(e, id2n[l]) if l > 0 else 0 for (e,l) in zip(ecc,lbl)])
pred = pyr.m(polar_angle=ang, eccentricity=ecc, radius=rad, visual_area=lbl)
pmesh = natreg_mesh.with_prop(pred)
return {'registered_mesh' : rmesh,
'registration_prediction': rpred,
'prediction' : pred,
'predicted_mesh' : pmesh} | python | def calc_prediction(registered_map, preregistration_mesh, native_mesh, model):
'''
calc_registration_prediction is a pimms calculator that creates the both the prediction and the
registration_prediction, both of which are pimms itables including the fields 'polar_angle',
'eccentricity', and 'visual_area'. The registration_prediction data describe the vertices for
the registered_map, not necessarily of the native_mesh, while the prediction describes the
native mesh.
Provided efferent values:
@ registered_mesh Will be a mesh object that is equivalent to the preregistration_mesh but
with the coordinates and predicted fields (from the registration) filled in. Note that this
mesh is still in the resampled configuration is resampling was performed.
@ registration_prediction Will be a pimms ITable object with columns 'polar_angle',
'eccentricity', and 'visual_area'. For values outside of the model region, visual_area will
be 0 and other values will be undefined (but are typically 0). The registration_prediction
describes the values on the registrered_mesh.
@ prediction will be a pimms ITable object with columns 'polar_angle', 'eccentricity', and
'visual_area'. For values outside of the model region, visual_area will be 0 and other
values will be undefined (but are typically 0). The prediction describes the values on the
native_mesh and the predicted_mesh.
'''
# invert the map projection to make the registration map into a mesh
coords3d = np.array(preregistration_mesh.coordinates)
idcs = registered_map.labels
coords3d[:,idcs] = registered_map.meta('projection').inverse(registered_map.coordinates)
rmesh = preregistration_mesh.copy(coordinates=coords3d)
# go ahead and get the model predictions...
d = model.cortex_to_angle(registered_map.coordinates)
id2n = model.area_id_to_name
(ang, ecc) = d[0:2]
lbl = np.asarray(d[2], dtype=np.int)
rad = np.asarray([predict_pRF_radius(e, id2n[l]) if l > 0 else 0 for (e,l) in zip(ecc,lbl)])
d = {'polar_angle':ang, 'eccentricity':ecc, 'visual_area':lbl, 'radius':rad}
# okay, put these on the mesh
rpred = {}
for (k,v) in six.iteritems(d):
v.setflags(write=False)
tmp = np.zeros(rmesh.vertex_count, dtype=v.dtype)
tmp[registered_map.labels] = v
tmp.setflags(write=False)
rpred[k] = tmp
rpred = pyr.pmap(rpred)
rmesh = rmesh.with_prop(rpred)
# next, do all of this for the native mesh..
if native_mesh is preregistration_mesh:
pred = rpred
pmesh = rmesh
else:
# we need to address the native coordinates in the prereg coordinates then unaddress them
# in the registered coordinates; this will let us make a native-registered-map and repeat
# the exercise above
addr = preregistration_mesh.address(native_mesh.coordinates)
natreg_mesh = native_mesh.copy(coordinates=rmesh.unaddress(addr))
d = model.cortex_to_angle(natreg_mesh)
(ang,ecc) = d[0:2]
lbl = np.asarray(d[2], dtype=np.int)
rad = np.asarray([predict_pRF_radius(e, id2n[l]) if l > 0 else 0 for (e,l) in zip(ecc,lbl)])
pred = pyr.m(polar_angle=ang, eccentricity=ecc, radius=rad, visual_area=lbl)
pmesh = natreg_mesh.with_prop(pred)
return {'registered_mesh' : rmesh,
'registration_prediction': rpred,
'prediction' : pred,
'predicted_mesh' : pmesh} | [
"def",
"calc_prediction",
"(",
"registered_map",
",",
"preregistration_mesh",
",",
"native_mesh",
",",
"model",
")",
":",
"# invert the map projection to make the registration map into a mesh",
"coords3d",
"=",
"np",
".",
"array",
"(",
"preregistration_mesh",
".",
"coordina... | calc_registration_prediction is a pimms calculator that creates the both the prediction and the
registration_prediction, both of which are pimms itables including the fields 'polar_angle',
'eccentricity', and 'visual_area'. The registration_prediction data describe the vertices for
the registered_map, not necessarily of the native_mesh, while the prediction describes the
native mesh.
Provided efferent values:
@ registered_mesh Will be a mesh object that is equivalent to the preregistration_mesh but
with the coordinates and predicted fields (from the registration) filled in. Note that this
mesh is still in the resampled configuration is resampling was performed.
@ registration_prediction Will be a pimms ITable object with columns 'polar_angle',
'eccentricity', and 'visual_area'. For values outside of the model region, visual_area will
be 0 and other values will be undefined (but are typically 0). The registration_prediction
describes the values on the registrered_mesh.
@ prediction will be a pimms ITable object with columns 'polar_angle', 'eccentricity', and
'visual_area'. For values outside of the model region, visual_area will be 0 and other
values will be undefined (but are typically 0). The prediction describes the values on the
native_mesh and the predicted_mesh. | [
"calc_registration_prediction",
"is",
"a",
"pimms",
"calculator",
"that",
"creates",
"the",
"both",
"the",
"prediction",
"and",
"the",
"registration_prediction",
"both",
"of",
"which",
"are",
"pimms",
"itables",
"including",
"the",
"fields",
"polar_angle",
"eccentrici... | b588889f6db36ddb9602ae4a72c1c0d3f41586b2 | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1276-L1338 | train | 35,185 |
barnumbirr/coinmarketcap | coinmarketcap/core.py | Market.ticker | def ticker(self, currency="", **kwargs):
"""
This endpoint displays cryptocurrency ticker data in order of rank. The maximum
number of results per call is 100. Pagination is possible by using the
start and limit parameters.
GET /ticker/
Optional parameters:
(int) start - return results from rank [start] and above (default is 1)
(int) limit - return a maximum of [limit] results (default is 100; max is 100)
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
GET /ticker/{id}
Optional parameters:
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
"""
params = {}
params.update(kwargs)
# see https://github.com/barnumbirr/coinmarketcap/pull/28
if currency:
currency = str(currency) + '/'
response = self.__request('ticker/' + currency, params)
return response | python | def ticker(self, currency="", **kwargs):
"""
This endpoint displays cryptocurrency ticker data in order of rank. The maximum
number of results per call is 100. Pagination is possible by using the
start and limit parameters.
GET /ticker/
Optional parameters:
(int) start - return results from rank [start] and above (default is 1)
(int) limit - return a maximum of [limit] results (default is 100; max is 100)
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
GET /ticker/{id}
Optional parameters:
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
"""
params = {}
params.update(kwargs)
# see https://github.com/barnumbirr/coinmarketcap/pull/28
if currency:
currency = str(currency) + '/'
response = self.__request('ticker/' + currency, params)
return response | [
"def",
"ticker",
"(",
"self",
",",
"currency",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"params",
".",
"update",
"(",
"kwargs",
")",
"# see https://github.com/barnumbirr/coinmarketcap/pull/28",
"if",
"currency",
":",
"currency",... | This endpoint displays cryptocurrency ticker data in order of rank. The maximum
number of results per call is 100. Pagination is possible by using the
start and limit parameters.
GET /ticker/
Optional parameters:
(int) start - return results from rank [start] and above (default is 1)
(int) limit - return a maximum of [limit] results (default is 100; max is 100)
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH"
GET /ticker/{id}
Optional parameters:
(string) convert - return pricing info in terms of another currency.
Valid fiat currency values are: "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK",
"DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
"TWD", "ZAR"
Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and "BCH" | [
"This",
"endpoint",
"displays",
"cryptocurrency",
"ticker",
"data",
"in",
"order",
"of",
"rank",
".",
"The",
"maximum",
"number",
"of",
"results",
"per",
"call",
"is",
"100",
".",
"Pagination",
"is",
"possible",
"by",
"using",
"the",
"start",
"and",
"limit",... | d1d76a73bc48a64a4c2883dd28c6199bfbd3ebc6 | https://github.com/barnumbirr/coinmarketcap/blob/d1d76a73bc48a64a4c2883dd28c6199bfbd3ebc6/coinmarketcap/core.py#L59-L96 | train | 35,186 |
HHammond/PrettyPandas | prettypandas/formatters.py | _surpress_formatting_errors | def _surpress_formatting_errors(fn):
"""
I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need.
"""
@wraps(fn)
def inner(*args, **kwargs):
try:
return fn(*args, **kwargs)
except ValueError:
return ""
return inner | python | def _surpress_formatting_errors(fn):
"""
I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need.
"""
@wraps(fn)
def inner(*args, **kwargs):
try:
return fn(*args, **kwargs)
except ValueError:
return ""
return inner | [
"def",
"_surpress_formatting_errors",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"V... | I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need. | [
"I",
"know",
"this",
"is",
"dangerous",
"and",
"the",
"wrong",
"way",
"to",
"solve",
"the",
"problem",
"but",
"when",
"using",
"both",
"row",
"and",
"columns",
"summaries",
"it",
"s",
"easier",
"to",
"just",
"swallow",
"errors",
"so",
"users",
"can",
"fo... | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/formatters.py#L12-L24 | train | 35,187 |
HHammond/PrettyPandas | prettypandas/formatters.py | _format_numer | def _format_numer(number_format, prefix='', suffix=''):
"""Format a number to a string."""
@_surpress_formatting_errors
def inner(v):
if isinstance(v, Number):
return ("{{}}{{:{}}}{{}}"
.format(number_format)
.format(prefix, v, suffix))
else:
raise TypeError("Numberic type required.")
return inner | python | def _format_numer(number_format, prefix='', suffix=''):
"""Format a number to a string."""
@_surpress_formatting_errors
def inner(v):
if isinstance(v, Number):
return ("{{}}{{:{}}}{{}}"
.format(number_format)
.format(prefix, v, suffix))
else:
raise TypeError("Numberic type required.")
return inner | [
"def",
"_format_numer",
"(",
"number_format",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
":",
"@",
"_surpress_formatting_errors",
"def",
"inner",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Number",
")",
":",
"return",
"(",
"\... | Format a number to a string. | [
"Format",
"a",
"number",
"to",
"a",
"string",
"."
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/formatters.py#L27-L37 | train | 35,188 |
HHammond/PrettyPandas | prettypandas/formatters.py | as_percent | def as_percent(precision=2, **kwargs):
"""Convert number to percentage string.
Parameters:
-----------
:param v: numerical value to be converted
:param precision: int
decimal places to round to
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
return _surpress_formatting_errors(
_format_numer(".{}%".format(precision))
) | python | def as_percent(precision=2, **kwargs):
"""Convert number to percentage string.
Parameters:
-----------
:param v: numerical value to be converted
:param precision: int
decimal places to round to
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
return _surpress_formatting_errors(
_format_numer(".{}%".format(precision))
) | [
"def",
"as_percent",
"(",
"precision",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"precision",
",",
"Integral",
")",
":",
"raise",
"TypeError",
"(",
"\"Precision must be an integer.\"",
")",
"return",
"_surpress_formatting_error... | Convert number to percentage string.
Parameters:
-----------
:param v: numerical value to be converted
:param precision: int
decimal places to round to | [
"Convert",
"number",
"to",
"percentage",
"string",
"."
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/formatters.py#L40-L54 | train | 35,189 |
HHammond/PrettyPandas | prettypandas/formatters.py | as_unit | def as_unit(unit, precision=2, location='suffix'):
"""Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
if location == 'prefix':
formatter = partial(_format_numer, prefix=unit)
elif location == 'suffix':
formatter = partial(_format_numer, suffix=unit)
else:
raise ValueError("location must be either 'prefix' or 'suffix'.")
return _surpress_formatting_errors(
formatter("0.{}f".format(precision))
) | python | def as_unit(unit, precision=2, location='suffix'):
"""Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value
"""
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
if location == 'prefix':
formatter = partial(_format_numer, prefix=unit)
elif location == 'suffix':
formatter = partial(_format_numer, suffix=unit)
else:
raise ValueError("location must be either 'prefix' or 'suffix'.")
return _surpress_formatting_errors(
formatter("0.{}f".format(precision))
) | [
"def",
"as_unit",
"(",
"unit",
",",
"precision",
"=",
"2",
",",
"location",
"=",
"'suffix'",
")",
":",
"if",
"not",
"isinstance",
"(",
"precision",
",",
"Integral",
")",
":",
"raise",
"TypeError",
"(",
"\"Precision must be an integer.\"",
")",
"if",
"locatio... | Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value | [
"Convert",
"value",
"to",
"unit",
"."
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/formatters.py#L57-L82 | train | 35,190 |
HHammond/PrettyPandas | prettypandas/summarizer.py | Aggregate.apply | def apply(self, df):
"""Compute aggregate over DataFrame"""
if self.subset:
if _axis_is_rows(self.axis):
df = df[self.subset]
if _axis_is_cols(self.axis):
df = df.loc[self.subset]
result = df.agg(self.func, axis=self.axis, *self.args, **self.kwargs)
result.name = self.title
return result | python | def apply(self, df):
"""Compute aggregate over DataFrame"""
if self.subset:
if _axis_is_rows(self.axis):
df = df[self.subset]
if _axis_is_cols(self.axis):
df = df.loc[self.subset]
result = df.agg(self.func, axis=self.axis, *self.args, **self.kwargs)
result.name = self.title
return result | [
"def",
"apply",
"(",
"self",
",",
"df",
")",
":",
"if",
"self",
".",
"subset",
":",
"if",
"_axis_is_rows",
"(",
"self",
".",
"axis",
")",
":",
"df",
"=",
"df",
"[",
"self",
".",
"subset",
"]",
"if",
"_axis_is_cols",
"(",
"self",
".",
"axis",
")",... | Compute aggregate over DataFrame | [
"Compute",
"aggregate",
"over",
"DataFrame"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L53-L64 | train | 35,191 |
HHammond/PrettyPandas | prettypandas/summarizer.py | Formatter.apply | def apply(self, styler):
"""Apply Summary over Pandas Styler"""
return styler.format(self.formatter, *self.args, **self.kwargs) | python | def apply(self, styler):
"""Apply Summary over Pandas Styler"""
return styler.format(self.formatter, *self.args, **self.kwargs) | [
"def",
"apply",
"(",
"self",
",",
"styler",
")",
":",
"return",
"styler",
".",
"format",
"(",
"self",
".",
"formatter",
",",
"*",
"self",
".",
"args",
",",
"*",
"*",
"self",
".",
"kwargs",
")"
] | Apply Summary over Pandas Styler | [
"Apply",
"Summary",
"over",
"Pandas",
"Styler"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L85-L87 | train | 35,192 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas._apply_summaries | def _apply_summaries(self):
"""Add all summary rows and columns."""
def as_frame(r):
if isinstance(r, pd.Series):
return r.to_frame()
else:
return r
df = self.data
if df.index.nlevels > 1:
raise ValueError(
"You cannot currently have both summary rows and columns on a "
"MultiIndex."
)
_df = df
if self.summary_rows:
rows = pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_rows], axis=1).T
df = pd.concat([df, as_frame(rows)], axis=0)
if self.summary_cols:
cols = pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_cols], axis=1)
df = pd.concat([df, as_frame(cols)], axis=1)
return df | python | def _apply_summaries(self):
"""Add all summary rows and columns."""
def as_frame(r):
if isinstance(r, pd.Series):
return r.to_frame()
else:
return r
df = self.data
if df.index.nlevels > 1:
raise ValueError(
"You cannot currently have both summary rows and columns on a "
"MultiIndex."
)
_df = df
if self.summary_rows:
rows = pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_rows], axis=1).T
df = pd.concat([df, as_frame(rows)], axis=0)
if self.summary_cols:
cols = pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_cols], axis=1)
df = pd.concat([df, as_frame(cols)], axis=1)
return df | [
"def",
"_apply_summaries",
"(",
"self",
")",
":",
"def",
"as_frame",
"(",
"r",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
"pd",
".",
"Series",
")",
":",
"return",
"r",
".",
"to_frame",
"(",
")",
"else",
":",
"return",
"r",
"df",
"=",
"self",
".... | Add all summary rows and columns. | [
"Add",
"all",
"summary",
"rows",
"and",
"columns",
"."
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L162-L190 | train | 35,193 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas.style | def style(self):
"""Add summaries and convert to Pandas Styler"""
row_titles = [a.title for a in self._cleaned_summary_rows]
col_titles = [a.title for a in self._cleaned_summary_cols]
row_ix = pd.IndexSlice[row_titles, :]
col_ix = pd.IndexSlice[:, col_titles]
def handle_na(df):
df.loc[col_ix] = df.loc[col_ix].fillna('')
df.loc[row_ix] = df.loc[row_ix].fillna('')
return df
styler = (
self
.frame
.pipe(handle_na)
.style
.applymap(lambda r: 'font-weight: 900', subset=row_ix)
.applymap(lambda r: 'font-weight: 900', subset=col_ix)
)
for formatter in self.formatters:
styler = formatter.apply(styler)
return styler | python | def style(self):
"""Add summaries and convert to Pandas Styler"""
row_titles = [a.title for a in self._cleaned_summary_rows]
col_titles = [a.title for a in self._cleaned_summary_cols]
row_ix = pd.IndexSlice[row_titles, :]
col_ix = pd.IndexSlice[:, col_titles]
def handle_na(df):
df.loc[col_ix] = df.loc[col_ix].fillna('')
df.loc[row_ix] = df.loc[row_ix].fillna('')
return df
styler = (
self
.frame
.pipe(handle_na)
.style
.applymap(lambda r: 'font-weight: 900', subset=row_ix)
.applymap(lambda r: 'font-weight: 900', subset=col_ix)
)
for formatter in self.formatters:
styler = formatter.apply(styler)
return styler | [
"def",
"style",
"(",
"self",
")",
":",
"row_titles",
"=",
"[",
"a",
".",
"title",
"for",
"a",
"in",
"self",
".",
"_cleaned_summary_rows",
"]",
"col_titles",
"=",
"[",
"a",
".",
"title",
"for",
"a",
"in",
"self",
".",
"_cleaned_summary_cols",
"]",
"row_... | Add summaries and convert to Pandas Styler | [
"Add",
"summaries",
"and",
"convert",
"to",
"Pandas",
"Styler"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L202-L226 | train | 35,194 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas.summary | def summary(self,
func=methodcaller('sum'),
title='Total',
axis=0,
subset=None,
*args,
**kwargs):
"""Add multiple summary rows or columns to the dataframe.
Parameters
----------
:param func: function to be used for a summary.
:param titles: Title for this summary column.
:param axis:
Same as numpy and pandas axis argument. A value of None will cause
the summary to be applied to both rows and columns.
:param args: Positional arguments passed to all the functions.
:param kwargs: Keyword arguments passed to all the functions.
The results of summary can be chained together.
"""
if axis is None:
return (
self
.summary(
func=func,
title=title,
axis=0,
subset=subset,
*args,
**kwargs
)
.summary(
func=func,
title=title,
axis=1,
subset=subset,
*args,
**kwargs
)
)
else:
agg = Aggregate(title, func, subset=subset,
axis=axis, *args, **kwargs)
return self._add_summary(agg) | python | def summary(self,
func=methodcaller('sum'),
title='Total',
axis=0,
subset=None,
*args,
**kwargs):
"""Add multiple summary rows or columns to the dataframe.
Parameters
----------
:param func: function to be used for a summary.
:param titles: Title for this summary column.
:param axis:
Same as numpy and pandas axis argument. A value of None will cause
the summary to be applied to both rows and columns.
:param args: Positional arguments passed to all the functions.
:param kwargs: Keyword arguments passed to all the functions.
The results of summary can be chained together.
"""
if axis is None:
return (
self
.summary(
func=func,
title=title,
axis=0,
subset=subset,
*args,
**kwargs
)
.summary(
func=func,
title=title,
axis=1,
subset=subset,
*args,
**kwargs
)
)
else:
agg = Aggregate(title, func, subset=subset,
axis=axis, *args, **kwargs)
return self._add_summary(agg) | [
"def",
"summary",
"(",
"self",
",",
"func",
"=",
"methodcaller",
"(",
"'sum'",
")",
",",
"title",
"=",
"'Total'",
",",
"axis",
"=",
"0",
",",
"subset",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axis",
"is",
"None",
... | Add multiple summary rows or columns to the dataframe.
Parameters
----------
:param func: function to be used for a summary.
:param titles: Title for this summary column.
:param axis:
Same as numpy and pandas axis argument. A value of None will cause
the summary to be applied to both rows and columns.
:param args: Positional arguments passed to all the functions.
:param kwargs: Keyword arguments passed to all the functions.
The results of summary can be chained together. | [
"Add",
"multiple",
"summary",
"rows",
"or",
"columns",
"to",
"the",
"dataframe",
"."
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L240-L285 | train | 35,195 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas.as_percent | def as_percent(self, precision=2, *args, **kwargs):
"""Format subset as percentages
:param precision: Decimal precision
:param subset: Pandas subset
"""
f = Formatter(as_percent(precision), args, kwargs)
return self._add_formatter(f) | python | def as_percent(self, precision=2, *args, **kwargs):
"""Format subset as percentages
:param precision: Decimal precision
:param subset: Pandas subset
"""
f = Formatter(as_percent(precision), args, kwargs)
return self._add_formatter(f) | [
"def",
"as_percent",
"(",
"self",
",",
"precision",
"=",
"2",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"Formatter",
"(",
"as_percent",
"(",
"precision",
")",
",",
"args",
",",
"kwargs",
")",
"return",
"self",
".",
"_add_formatte... | Format subset as percentages
:param precision: Decimal precision
:param subset: Pandas subset | [
"Format",
"subset",
"as",
"percentages"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L335-L342 | train | 35,196 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas.as_currency | def as_currency(self, currency='USD', locale=LOCALE_OBJ, *args, **kwargs):
"""Format subset as currency
:param currency: Currency
:param locale: Babel locale for currency formatting
:param subset: Pandas subset
"""
f = Formatter(
as_currency(currency=currency, locale=locale),
args,
kwargs
)
return self._add_formatter(f) | python | def as_currency(self, currency='USD', locale=LOCALE_OBJ, *args, **kwargs):
"""Format subset as currency
:param currency: Currency
:param locale: Babel locale for currency formatting
:param subset: Pandas subset
"""
f = Formatter(
as_currency(currency=currency, locale=locale),
args,
kwargs
)
return self._add_formatter(f) | [
"def",
"as_currency",
"(",
"self",
",",
"currency",
"=",
"'USD'",
",",
"locale",
"=",
"LOCALE_OBJ",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"Formatter",
"(",
"as_currency",
"(",
"currency",
"=",
"currency",
",",
"locale",
"=",
... | Format subset as currency
:param currency: Currency
:param locale: Babel locale for currency formatting
:param subset: Pandas subset | [
"Format",
"subset",
"as",
"currency"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L344-L356 | train | 35,197 |
HHammond/PrettyPandas | prettypandas/summarizer.py | PrettyPandas.as_unit | def as_unit(self, unit, location='suffix', *args, **kwargs):
"""Format subset as with units
:param unit: string to use as unit
:param location: prefix or suffix
:param subset: Pandas subset
"""
f = Formatter(
as_unit(unit, location=location),
args,
kwargs
)
return self._add_formatter(f) | python | def as_unit(self, unit, location='suffix', *args, **kwargs):
"""Format subset as with units
:param unit: string to use as unit
:param location: prefix or suffix
:param subset: Pandas subset
"""
f = Formatter(
as_unit(unit, location=location),
args,
kwargs
)
return self._add_formatter(f) | [
"def",
"as_unit",
"(",
"self",
",",
"unit",
",",
"location",
"=",
"'suffix'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"Formatter",
"(",
"as_unit",
"(",
"unit",
",",
"location",
"=",
"location",
")",
",",
"args",
",",
"kwargs"... | Format subset as with units
:param unit: string to use as unit
:param location: prefix or suffix
:param subset: Pandas subset | [
"Format",
"subset",
"as",
"with",
"units"
] | 99a814ffc3aa61f66eaf902afaa4b7802518d33a | https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/summarizer.py#L358-L370 | train | 35,198 |
TUT-ARG/sed_eval | sed_eval/sound_event.py | EventBasedMetrics.validate_onset | def validate_onset(reference_event, estimated_event, t_collar=0.200):
"""Validate estimated event based on event onset
Parameters
----------
reference_event : dict
Reference event.
estimated_event: dict
Estimated event.
t_collar : float > 0, seconds
Time collar with which the estimated onset has to be in order to be consider valid estimation.
Default value 0.2
Returns
-------
bool
"""
# Detect field naming style used and validate onset
if 'event_onset' in reference_event and 'event_onset' in estimated_event:
return math.fabs(reference_event['event_onset'] - estimated_event['event_onset']) <= t_collar
elif 'onset' in reference_event and 'onset' in estimated_event:
return math.fabs(reference_event['onset'] - estimated_event['onset']) <= t_collar | python | def validate_onset(reference_event, estimated_event, t_collar=0.200):
"""Validate estimated event based on event onset
Parameters
----------
reference_event : dict
Reference event.
estimated_event: dict
Estimated event.
t_collar : float > 0, seconds
Time collar with which the estimated onset has to be in order to be consider valid estimation.
Default value 0.2
Returns
-------
bool
"""
# Detect field naming style used and validate onset
if 'event_onset' in reference_event and 'event_onset' in estimated_event:
return math.fabs(reference_event['event_onset'] - estimated_event['event_onset']) <= t_collar
elif 'onset' in reference_event and 'onset' in estimated_event:
return math.fabs(reference_event['onset'] - estimated_event['onset']) <= t_collar | [
"def",
"validate_onset",
"(",
"reference_event",
",",
"estimated_event",
",",
"t_collar",
"=",
"0.200",
")",
":",
"# Detect field naming style used and validate onset",
"if",
"'event_onset'",
"in",
"reference_event",
"and",
"'event_onset'",
"in",
"estimated_event",
":",
"... | Validate estimated event based on event onset
Parameters
----------
reference_event : dict
Reference event.
estimated_event: dict
Estimated event.
t_collar : float > 0, seconds
Time collar with which the estimated onset has to be in order to be consider valid estimation.
Default value 0.2
Returns
-------
bool | [
"Validate",
"estimated",
"event",
"based",
"on",
"event",
"onset"
] | 0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb | https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/sound_event.py#L1604-L1630 | train | 35,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.