repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
DiamondLightSource/python-workflows | workflows/services/common_service.py | CommonService.__update_service_status | def __update_service_status(self, statuscode):
"""Set the internal status of the service object, and notify frontend."""
if self.__service_status != statuscode:
self.__service_status = statuscode
self.__send_service_status_to_frontend() | python | def __update_service_status(self, statuscode):
"""Set the internal status of the service object, and notify frontend."""
if self.__service_status != statuscode:
self.__service_status = statuscode
self.__send_service_status_to_frontend() | Set the internal status of the service object, and notify frontend. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L296-L300 |
DiamondLightSource/python-workflows | workflows/services/common_service.py | CommonService._set_name | def _set_name(self, name):
"""Set a new name for this service, and notify the frontend accordingly."""
self._service_name = name
self.__send_to_frontend({"band": "set_name", "name": self._service_name}) | python | def _set_name(self, name):
"""Set a new name for this service, and notify the frontend accordingly."""
self._service_name = name
self.__send_to_frontend({"band": "set_name", "name": self._service_name}) | Set a new name for this service, and notify the frontend accordingly. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L312-L315 |
DiamondLightSource/python-workflows | workflows/services/common_service.py | CommonService.initialize_logging | def initialize_logging(self):
"""Reset the logging for the service process. All logged messages are
forwarded to the frontend. If any filtering is desired, then this must
take place on the service side."""
# Reset logging to pass logrecords into the queue to the frontend only.
# ... | python | def initialize_logging(self):
"""Reset the logging for the service process. All logged messages are
forwarded to the frontend. If any filtering is desired, then this must
take place on the service side."""
# Reset logging to pass logrecords into the queue to the frontend only.
# ... | Reset the logging for the service process. All logged messages are
forwarded to the frontend. If any filtering is desired, then this must
take place on the service side. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L325-L355 |
DiamondLightSource/python-workflows | workflows/services/common_service.py | CommonService.start | def start(self, **kwargs):
"""Start listening to command queue, process commands in main loop,
set status, etc...
This function is most likely called by the frontend in a separate
process."""
# Keep a copy of keyword arguments for use in subclasses
self.start_kwargs.upda... | python | def start(self, **kwargs):
"""Start listening to command queue, process commands in main loop,
set status, etc...
This function is most likely called by the frontend in a separate
process."""
# Keep a copy of keyword arguments for use in subclasses
self.start_kwargs.upda... | Start listening to command queue, process commands in main loop,
set status, etc...
This function is most likely called by the frontend in a separate
process. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L357-L433 |
DiamondLightSource/python-workflows | workflows/services/common_service.py | CommonService.process_uncaught_exception | def process_uncaught_exception(self, e):
"""This is called to handle otherwise uncaught exceptions from the service.
The service will terminate either way, but here we can do things such as
gathering useful environment information and logging for posterity."""
# Add information about the... | python | def process_uncaught_exception(self, e):
"""This is called to handle otherwise uncaught exceptions from the service.
The service will terminate either way, but here we can do things such as
gathering useful environment information and logging for posterity."""
# Add information about the... | This is called to handle otherwise uncaught exceptions from the service.
The service will terminate either way, but here we can do things such as
gathering useful environment information and logging for posterity. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/common_service.py#L435-L456 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.connect | def connect(self, *args, **kwargs):
"""
Connect to a server.
This overrides the function in SimpleIRCClient
to provide SSL functionality.
:param args:
:param kwargs:
:return:
"""
if self.use_ssl:
factory = irc.connection.Factory(wrapp... | python | def connect(self, *args, **kwargs):
"""
Connect to a server.
This overrides the function in SimpleIRCClient
to provide SSL functionality.
:param args:
:param kwargs:
:return:
"""
if self.use_ssl:
factory = irc.connection.Factory(wrapp... | Connect to a server.
This overrides the function in SimpleIRCClient
to provide SSL functionality.
:param args:
:param kwargs:
:return: | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L76-L97 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.set_metadata | def set_metadata(self, e):
"""
This function sets the metadata that is common between pub and priv
"""
metadata = Metadata(source=self.actor_urn).__dict__
metadata['source_connector'] = 'irc'
metadata['source_channel'] = e.target
metadata['source_user'] = e.source... | python | def set_metadata(self, e):
"""
This function sets the metadata that is common between pub and priv
"""
metadata = Metadata(source=self.actor_urn).__dict__
metadata['source_connector'] = 'irc'
metadata['source_channel'] = e.target
metadata['source_user'] = e.source... | This function sets the metadata that is common between pub and priv | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L99-L110 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.on_pubmsg | def on_pubmsg(self, c, e):
"""
This function runs when the bot receives a public message.
"""
text = e.arguments[0]
metadata = self.set_metadata(e)
metadata['is_private_message'] = False
message = Message(text=text, metadata=metadata).__dict__
self.basepla... | python | def on_pubmsg(self, c, e):
"""
This function runs when the bot receives a public message.
"""
text = e.arguments[0]
metadata = self.set_metadata(e)
metadata['is_private_message'] = False
message = Message(text=text, metadata=metadata).__dict__
self.basepla... | This function runs when the bot receives a public message. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L112-L120 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.on_privmsg | def on_privmsg(self, c, e):
"""
This function runs when the bot receives a private message (query).
"""
text = e.arguments[0]
logger.debug('{0!s}'.format(e.source))
metadata = self.set_metadata(e)
metadata['is_private_message'] = True
message = Message(tex... | python | def on_privmsg(self, c, e):
"""
This function runs when the bot receives a private message (query).
"""
text = e.arguments[0]
logger.debug('{0!s}'.format(e.source))
metadata = self.set_metadata(e)
metadata['is_private_message'] = True
message = Message(tex... | This function runs when the bot receives a private message (query). | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L122-L131 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.on_welcome | def on_welcome(self, c, e):
"""
This function runs when the bot successfully connects to the IRC server
"""
self.backoff = 1 # Assume we had a good connection. Reset backoff.
if self.nickserv:
if Utilities.isNotEmpty(self.nickserv_pass):
self.identify... | python | def on_welcome(self, c, e):
"""
This function runs when the bot successfully connects to the IRC server
"""
self.backoff = 1 # Assume we had a good connection. Reset backoff.
if self.nickserv:
if Utilities.isNotEmpty(self.nickserv_pass):
self.identify... | This function runs when the bot successfully connects to the IRC server | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L133-L152 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRCBot.run | def run(self):
"""
Run the bot in a thread.
Implementing the IRC listener as a thread allows it to
listen without blocking IRCLego's ability to listen
as a pykka actor.
:return: None
"""
self._connect()
super(irc.bot.SingleServerIRCBot, self).sta... | python | def run(self):
"""
Run the bot in a thread.
Implementing the IRC listener as a thread allows it to
listen without blocking IRCLego's ability to listen
as a pykka actor.
:return: None
"""
self._connect()
super(irc.bot.SingleServerIRCBot, self).sta... | Run the bot in a thread.
Implementing the IRC listener as a thread allows it to
listen without blocking IRCLego's ability to listen
as a pykka actor.
:return: None | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L173-L184 |
Legobot/Legobot | Legobot/Connectors/IRC.py | IRC.handle | def handle(self, message):
'''
Attempts to send a message to the specified destination in IRC
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metad... | python | def handle(self, message):
'''
Attempts to send a message to the specified destination in IRC
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metad... | Attempts to send a message to the specified destination in IRC
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/IRC.py#L200-L217 |
cuihantao/andes | andes/config/system.py | System.check | def check(self):
"""
Check config data consistency
Returns
-------
"""
if self.sparselib not in self.sparselib_alt:
logger.warning("Invalid sparse library <{}>".format(self.sparselib))
self.sparselib = 'umfpack'
if self.sparselib == 'klu... | python | def check(self):
"""
Check config data consistency
Returns
-------
"""
if self.sparselib not in self.sparselib_alt:
logger.warning("Invalid sparse library <{}>".format(self.sparselib))
self.sparselib = 'umfpack'
if self.sparselib == 'klu... | Check config data consistency
Returns
------- | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/config/system.py#L51-L67 |
cuihantao/andes | andes/models/fault.py | Fault.apply | def apply(self, actual_time):
"""Check time and apply faults"""
if self.time != actual_time:
self.time = actual_time
else:
return
for i in range(self.n):
if self.tf[i] == self.time:
logger.info(
' <Fault> Applying f... | python | def apply(self, actual_time):
"""Check time and apply faults"""
if self.time != actual_time:
self.time = actual_time
else:
return
for i in range(self.n):
if self.tf[i] == self.time:
logger.info(
' <Fault> Applying f... | Check time and apply faults | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/fault.py#L67-L93 |
DiamondLightSource/python-workflows | workflows/services/sample_consumer.py | SampleConsumer.consume_message | def consume_message(self, header, message):
"""Consume a message"""
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
if header:
logmessage["header"] = (
json.dumps(header, indent=2) + "... | python | def consume_message(self, header, message):
"""Consume a message"""
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
if header:
logmessage["header"] = (
json.dumps(header, indent=2) + "... | Consume a message | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_consumer.py#L24-L45 |
Legobot/Legobot | Legobot/Lego.py | Lego.on_receive | def on_receive(self, message):
"""
Handle being informed of a message.
This function is called whenever a Lego receives a message, as
specified in the pykka documentation.
Legos should not override this function.
:param message:
:return:
"""
if ... | python | def on_receive(self, message):
"""
Handle being informed of a message.
This function is called whenever a Lego receives a message, as
specified in the pykka documentation.
Legos should not override this function.
:param message:
:return:
"""
if ... | Handle being informed of a message.
This function is called whenever a Lego receives a message, as
specified in the pykka documentation.
Legos should not override this function.
:param message:
:return: | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L47-L71 |
Legobot/Legobot | Legobot/Lego.py | Lego.cleanup | def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + str(self))
self.children = [child for child in self.children if child.is_alive()]
self.lock.release() | python | def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + str(self))
self.children = [child for child in self.children if child.is_alive()]
self.lock.release() | Clean up finished children.
:return: None | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L73-L82 |
Legobot/Legobot | Legobot/Lego.py | Lego.add_child | def add_child(self, child_type, *args, **kwargs):
"""
Initialize and keep track of a child.
:param child_type: a class inheriting from Lego to initialize \
an instance of
:param args: arguments for initializing the child
:param kwargs: keyword argument... | python | def add_child(self, child_type, *args, **kwargs):
"""
Initialize and keep track of a child.
:param child_type: a class inheriting from Lego to initialize \
an instance of
:param args: arguments for initializing the child
:param kwargs: keyword argument... | Initialize and keep track of a child.
:param child_type: a class inheriting from Lego to initialize \
an instance of
:param args: arguments for initializing the child
:param kwargs: keyword arguments for initializing the child
:return: | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L106-L128 |
Legobot/Legobot | Legobot/Lego.py | Lego.reply | def reply(self, message, text, opts=None):
"""
Reply to the sender of the provided message with a message \
containing the provided text.
:param message: the message to reply to
:param text: the text to reply with
:param opts: A dictionary of additional values to add to ... | python | def reply(self, message, text, opts=None):
"""
Reply to the sender of the provided message with a message \
containing the provided text.
:param message: the message to reply to
:param text: the text to reply with
:param opts: A dictionary of additional values to add to ... | Reply to the sender of the provided message with a message \
containing the provided text.
:param message: the message to reply to
:param text: the text to reply with
:param opts: A dictionary of additional values to add to metadata
:return: None | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L130-L149 |
Legobot/Legobot | Legobot/Lego.py | Lego.reply_attachment | def reply_attachment(self, message, text, attachment, opts=None):
"""
Convenience method for formatting reply as attachment (if available)
and passing it on to the reply method. Individual connectors can then
deal with the attachment or simply pass it on as a regular message
:pa... | python | def reply_attachment(self, message, text, attachment, opts=None):
"""
Convenience method for formatting reply as attachment (if available)
and passing it on to the reply method. Individual connectors can then
deal with the attachment or simply pass it on as a regular message
:pa... | Convenience method for formatting reply as attachment (if available)
and passing it on to the reply method. Individual connectors can then
deal with the attachment or simply pass it on as a regular message
:param message: the message to reply to
:param text: the text to reply with
... | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L151-L169 |
Legobot/Legobot | Legobot/Lego.py | Lego.build_reply_opts | def build_reply_opts(self, message):
"""
Convenience method for constructing default options for a
reply message.
:param message: the message to reply to
:return: opts
"""
try:
source = message['metadata']['source_channel']
thread = messag... | python | def build_reply_opts(self, message):
"""
Convenience method for constructing default options for a
reply message.
:param message: the message to reply to
:return: opts
"""
try:
source = message['metadata']['source_channel']
thread = messag... | Convenience method for constructing default options for a
reply message.
:param message: the message to reply to
:return: opts | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Lego.py#L171-L188 |
cuihantao/andes | andes/filters/dome.py | alter | def alter(data, system):
"""Alter data in dm format devices"""
device = data[0]
action = data[1]
if data[2] == '*':
data[2] = '.*'
regex = re.compile(data[2])
prop = data[3]
value = float(data[4])
if action == 'MUL':
for item in range(system.__dict__[device].n):
... | python | def alter(data, system):
"""Alter data in dm format devices"""
device = data[0]
action = data[1]
if data[2] == '*':
data[2] = '.*'
regex = re.compile(data[2])
prop = data[3]
value = float(data[4])
if action == 'MUL':
for item in range(system.__dict__[device].n):
... | Alter data in dm format devices | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/dome.py#L16-L52 |
cuihantao/andes | andes/filters/dome.py | read | def read(file, system, header=True):
"""Read a dm format file and elem_add to system"""
retval = True
fid = open(file, 'r')
sep = re.compile(r'\s*,\s*')
comment = re.compile(r'^#\s*')
equal = re.compile(r'\s*=\s*')
math = re.compile(r'[*/+-]')
double = re.compile(r'[+-]? *(?:\d+(?:\.\d*)... | python | def read(file, system, header=True):
"""Read a dm format file and elem_add to system"""
retval = True
fid = open(file, 'r')
sep = re.compile(r'\s*,\s*')
comment = re.compile(r'^#\s*')
equal = re.compile(r'\s*=\s*')
math = re.compile(r'[*/+-]')
double = re.compile(r'[+-]? *(?:\d+(?:\.\d*)... | Read a dm format file and elem_add to system | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/dome.py#L55-L142 |
cuihantao/andes | andes/filters/dome.py | write | def write(file, system):
"""
Write data in system to a dm file
"""
# TODO: Check for bugs!!!
out = list()
out.append('# DOME format version 1.0')
ppl = 7 # parameter per line
retval = True
dev_list = sorted(system.devman.devices)
for dev in dev_list:
model = system.__d... | python | def write(file, system):
"""
Write data in system to a dm file
"""
# TODO: Check for bugs!!!
out = list()
out.append('# DOME format version 1.0')
ppl = 7 # parameter per line
retval = True
dev_list = sorted(system.devman.devices)
for dev in dev_list:
model = system.__d... | Write data in system to a dm file | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/dome.py#L145-L218 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.add_command_line_options | def add_command_line_options(cls, parser):
"""function to inject command line parameters"""
if "add_argument" in dir(parser):
return cls.add_command_line_options_argparse(parser)
else:
return cls.add_command_line_options_optparse(parser) | python | def add_command_line_options(cls, parser):
"""function to inject command line parameters"""
if "add_argument" in dir(parser):
return cls.add_command_line_options_argparse(parser)
else:
return cls.add_command_line_options_optparse(parser) | function to inject command line parameters | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L65-L70 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.add_command_line_options_argparse | def add_command_line_options_argparse(cls, argparser):
"""function to inject command line parameters into
a Python ArgumentParser."""
import argparse
class SetParameter(argparse.Action):
"""callback object for ArgumentParser"""
def __call__(self, parser, namespa... | python | def add_command_line_options_argparse(cls, argparser):
"""function to inject command line parameters into
a Python ArgumentParser."""
import argparse
class SetParameter(argparse.Action):
"""callback object for ArgumentParser"""
def __call__(self, parser, namespa... | function to inject command line parameters into
a Python ArgumentParser. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L73-L133 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.add_command_line_options_optparse | def add_command_line_options_optparse(cls, optparser):
"""function to inject command line parameters into
a Python OptionParser."""
def set_parameter(option, opt, value, parser):
"""callback function for OptionParser"""
cls.config[opt] = value
if opt == "--st... | python | def add_command_line_options_optparse(cls, optparser):
"""function to inject command line parameters into
a Python OptionParser."""
def set_parameter(option, opt, value, parser):
"""callback function for OptionParser"""
cls.config[opt] = value
if opt == "--st... | function to inject command line parameters into
a Python OptionParser. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L136-L205 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.is_connected | def is_connected(self):
"""Return connection status"""
self._connected = self._connected and self._conn.is_connected()
return self._connected | python | def is_connected(self):
"""Return connection status"""
self._connected = self._connected and self._conn.is_connected()
return self._connected | Return connection status | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L274-L277 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.disconnect | def disconnect(self):
"""Gracefully close connection to stomp server."""
if self._connected:
self._connected = False
self._conn.disconnect() | python | def disconnect(self):
"""Gracefully close connection to stomp server."""
if self._connected:
self._connected = False
self._conn.disconnect() | Gracefully close connection to stomp server. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L279-L283 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport.broadcast_status | def broadcast_status(self, status):
"""Broadcast transient status information to all listeners"""
self._broadcast(
"transient.status",
json.dumps(status),
headers={"expires": str(int((15 + time.time()) * 1000))},
) | python | def broadcast_status(self, status):
"""Broadcast transient status information to all listeners"""
self._broadcast(
"transient.status",
json.dumps(status),
headers={"expires": str(int((15 + time.time()) * 1000))},
) | Broadcast transient status information to all listeners | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L285-L291 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport._subscribe | def _subscribe(self, sub_id, channel, callback, **kwargs):
"""Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
... | python | def _subscribe(self, sub_id, channel, callback, **kwargs):
"""Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
... | Listen to a queue, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received
:param **kwargs: Further parameters for the transport layer. For ex... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L293-L334 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport._subscribe_broadcast | def _subscribe_broadcast(self, sub_id, channel, callback, **kwargs):
"""Listen to a broadcast topic, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Topic name to subscribe to
:param callback: Function to be called when message... | python | def _subscribe_broadcast(self, sub_id, channel, callback, **kwargs):
"""Listen to a broadcast topic, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Topic name to subscribe to
:param callback: Function to be called when message... | Listen to a broadcast topic, notify via callback function.
:param sub_id: ID for this subscription in the transport layer
:param channel: Topic name to subscribe to
:param callback: Function to be called when messages are received
:param **kwargs: Further parameters for the transport lay... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L336-L359 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport._send | def _send(
self, destination, message, headers=None, delay=None, expiration=None, **kwargs
):
"""Send a message to a queue.
:param destination: Queue name to send to
:param message: A string to be sent
:param **kwargs: Further parameters for the transport layer. For example
... | python | def _send(
self, destination, message, headers=None, delay=None, expiration=None, **kwargs
):
"""Send a message to a queue.
:param destination: Queue name to send to
:param message: A string to be sent
:param **kwargs: Further parameters for the transport layer. For example
... | Send a message to a queue.
:param destination: Queue name to send to
:param message: A string to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay transport of message by this many seconds
expiration: Optional expir... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L368-L402 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport._ack | def _ack(self, message_id, subscription_id, **kwargs):
"""Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be acknowledged
:param subscription: ID of the relevant subscri... | python | def _ack(self, message_id, subscription_id, **kwargs):
"""Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be acknowledged
:param subscription: ID of the relevant subscri... | Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be acknowledged
:param subscription: ID of the relevant subscriptiong
:param **kwargs: Further parameters for the transpo... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L455-L464 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | StompTransport._nack | def _nack(self, message_id, subscription_id, **kwargs):
"""Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be rejected
:param subscription: ID of the relevant subscriptiong
... | python | def _nack(self, message_id, subscription_id, **kwargs):
"""Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be rejected
:param subscription: ID of the relevant subscriptiong
... | Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be rejected
:param subscription: ID of the relevant subscriptiong
:param **kwargs: Further parameters for the transport layer.... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L466-L475 |
cuihantao/andes | andes/variables/devman.py | DevMan.register_device | def register_device(self, dev_name):
"""register a device to the device list"""
if dev_name not in self.devices:
self.devices.append(dev_name)
group_name = self.system.__dict__[dev_name]._group
if group_name not in self.group.keys():
self.group[group_name] = {} | python | def register_device(self, dev_name):
"""register a device to the device list"""
if dev_name not in self.devices:
self.devices.append(dev_name)
group_name = self.system.__dict__[dev_name]._group
if group_name not in self.group.keys():
self.group[group_name] = {} | register a device to the device list | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/devman.py#L22-L28 |
cuihantao/andes | andes/variables/devman.py | DevMan.register_element | def register_element(self, dev_name, idx=None):
"""
Register a device element to the group list
Parameters
----------
dev_name : str
model name
idx : str
element idx
Returns
-------
str
assigned idx
"""... | python | def register_element(self, dev_name, idx=None):
"""
Register a device element to the group list
Parameters
----------
dev_name : str
model name
idx : str
element idx
Returns
-------
str
assigned idx
"""... | Register a device element to the group list
Parameters
----------
dev_name : str
model name
idx : str
element idx
Returns
-------
str
assigned idx | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/devman.py#L30-L55 |
cuihantao/andes | andes/variables/devman.py | DevMan.sort_device | def sort_device(self):
"""
Sort device to follow the order of initialization
:return: None
"""
self.devices.sort()
# idx: the indices of order-sensitive models
# names: an ordered list of order-sensitive models
idx = []
names = []
for dev... | python | def sort_device(self):
"""
Sort device to follow the order of initialization
:return: None
"""
self.devices.sort()
# idx: the indices of order-sensitive models
# names: an ordered list of order-sensitive models
idx = []
names = []
for dev... | Sort device to follow the order of initialization
:return: None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/devman.py#L57-L86 |
cuihantao/andes | andes/models/windturbine.py | WTG3.init1 | def init1(self, dae):
"""New initialization function"""
self.servcall(dae)
retval = True
mva = self.system.mva
self.p0 = mul(self.p0, self.gammap)
self.q0 = mul(self.q0, self.gammaq)
dae.y[self.vsd] = mul(dae.y[self.v], -sin(dae.y[self.a]))
dae.y[self.vs... | python | def init1(self, dae):
"""New initialization function"""
self.servcall(dae)
retval = True
mva = self.system.mva
self.p0 = mul(self.p0, self.gammap)
self.q0 = mul(self.q0, self.gammaq)
dae.y[self.vsd] = mul(dae.y[self.v], -sin(dae.y[self.a]))
dae.y[self.vs... | New initialization function | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/windturbine.py#L791-L984 |
cuihantao/andes | andes/routines/tds.py | TDS._calc_time_step_first | def _calc_time_step_first(self):
"""
Compute the first time step and save to ``self.h``
Returns
-------
None
"""
system = self.system
config = self.config
if not system.dae.n:
freq = 1.0
elif system.dae.n == 1:
B =... | python | def _calc_time_step_first(self):
"""
Compute the first time step and save to ``self.h``
Returns
-------
None
"""
system = self.system
config = self.config
if not system.dae.n:
freq = 1.0
elif system.dae.n == 1:
B =... | Compute the first time step and save to ``self.h``
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L51-L92 |
cuihantao/andes | andes/routines/tds.py | TDS.calc_time_step | def calc_time_step(self):
"""
Set the time step during time domain simulations
Parameters
----------
convergence: bool
truth value of the convergence of the last step
niter: int
current iteration count
t: float
current simulati... | python | def calc_time_step(self):
"""
Set the time step during time domain simulations
Parameters
----------
convergence: bool
truth value of the convergence of the last step
niter: int
current iteration count
t: float
current simulati... | Set the time step during time domain simulations
Parameters
----------
convergence: bool
truth value of the convergence of the last step
niter: int
current iteration count
t: float
current simulation time
Returns
-------
... | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L94-L157 |
cuihantao/andes | andes/routines/tds.py | TDS.init | def init(self):
"""
Initialize time domain simulation
Returns
-------
None
"""
system = self.system
config = self.config
dae = self.system.dae
if system.pflow.solved is False:
return
t, s = elapsed()
# Assign ... | python | def init(self):
"""
Initialize time domain simulation
Returns
-------
None
"""
system = self.system
config = self.config
dae = self.system.dae
if system.pflow.solved is False:
return
t, s = elapsed()
# Assign ... | Initialize time domain simulation
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L159-L205 |
cuihantao/andes | andes/routines/tds.py | TDS.run | def run(self):
"""
Run time domain simulation
Returns
-------
bool
Success flag
"""
ret = False
system = self.system
config = self.config
dae = self.system.dae
# maxit = config.maxit
# tol = config.tol
... | python | def run(self):
"""
Run time domain simulation
Returns
-------
bool
Success flag
"""
ret = False
system = self.system
config = self.config
dae = self.system.dae
# maxit = config.maxit
# tol = config.tol
... | Run time domain simulation
Returns
-------
bool
Success flag | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L207-L341 |
cuihantao/andes | andes/routines/tds.py | TDS.restore_values | def restore_values(self):
"""
Restore x, y, and f values if not converged
Returns
-------
None
"""
if self.convergence is True:
return
dae = self.system.dae
system = self.system
inc_g = self.inc[dae.n:dae.m + dae.n]
ma... | python | def restore_values(self):
"""
Restore x, y, and f values if not converged
Returns
-------
None
"""
if self.convergence is True:
return
dae = self.system.dae
system = self.system
inc_g = self.inc[dae.n:dae.m + dae.n]
ma... | Restore x, y, and f values if not converged
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L343-L371 |
cuihantao/andes | andes/routines/tds.py | TDS.implicit_step | def implicit_step(self):
"""
Integrate one step using trapezoidal method. Sets convergence and niter flags.
Returns
-------
None
"""
config = self.config
system = self.system
dae = self.system.dae
# constant short names
In = spdia... | python | def implicit_step(self):
"""
Integrate one step using trapezoidal method. Sets convergence and niter flags.
Returns
-------
None
"""
config = self.config
system = self.system
dae = self.system.dae
# constant short names
In = spdia... | Integrate one step using trapezoidal method. Sets convergence and niter flags.
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L373-L454 |
cuihantao/andes | andes/routines/tds.py | TDS.event_actions | def event_actions(self):
"""
Take actions for timed events
Returns
-------
None
"""
system = self.system
dae = system.dae
if self.switch:
system.Breaker.apply(self.t)
for item in system.check_event(self.t):
... | python | def event_actions(self):
"""
Take actions for timed events
Returns
-------
None
"""
system = self.system
dae = system.dae
if self.switch:
system.Breaker.apply(self.t)
for item in system.check_event(self.t):
... | Take actions for timed events
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L456-L472 |
cuihantao/andes | andes/routines/tds.py | TDS.load_pert | def load_pert(self):
"""
Load perturbation files to ``self.callpert``
Returns
-------
None
"""
system = self.system
if system.files.pert:
try:
sys.path.append(system.files.path)
module = importlib.import_module... | python | def load_pert(self):
"""
Load perturbation files to ``self.callpert``
Returns
-------
None
"""
system = self.system
if system.files.pert:
try:
sys.path.append(system.files.path)
module = importlib.import_module... | Load perturbation files to ``self.callpert``
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L484-L501 |
cuihantao/andes | andes/routines/tds.py | TDS.run_step0 | def run_step0(self):
"""
For the 0th step, store the data and stream data
Returns
-------
None
"""
dae = self.system.dae
system = self.system
self.inc = zeros(dae.m + dae.n, 1)
system.varout.store(self.t, self.step)
self.streamin... | python | def run_step0(self):
"""
For the 0th step, store the data and stream data
Returns
-------
None
"""
dae = self.system.dae
system = self.system
self.inc = zeros(dae.m + dae.n, 1)
system.varout.store(self.t, self.step)
self.streamin... | For the 0th step, store the data and stream data
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L503-L517 |
cuihantao/andes | andes/routines/tds.py | TDS.streaming_step | def streaming_step(self):
"""
Sync, handle and streaming for each integration step
Returns
-------
None
"""
system = self.system
if system.config.dime_enable:
system.streaming.sync_and_handle()
system.streaming.vars_to_modules()
... | python | def streaming_step(self):
"""
Sync, handle and streaming for each integration step
Returns
-------
None
"""
system = self.system
if system.config.dime_enable:
system.streaming.sync_and_handle()
system.streaming.vars_to_modules()
... | Sync, handle and streaming for each integration step
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L519-L531 |
cuihantao/andes | andes/routines/tds.py | TDS.streaming_init | def streaming_init(self):
"""
Send out initialization variables and process init from modules
Returns
-------
None
"""
system = self.system
config = self.config
if system.config.dime_enable:
config.compute_flows = True
syst... | python | def streaming_init(self):
"""
Send out initialization variables and process init from modules
Returns
-------
None
"""
system = self.system
config = self.config
if system.config.dime_enable:
config.compute_flows = True
syst... | Send out initialization variables and process init from modules
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L533-L548 |
cuihantao/andes | andes/routines/tds.py | TDS.compute_flows | def compute_flows(self):
"""
If enabled, compute the line flows after each step
Returns
-------
None
"""
system = self.system
config = self.config
dae = system.dae
if config.compute_flows:
# compute and append series injection... | python | def compute_flows(self):
"""
If enabled, compute the line flows after each step
Returns
-------
None
"""
system = self.system
config = self.config
dae = system.dae
if config.compute_flows:
# compute and append series injection... | If enabled, compute the line flows after each step
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L561-L584 |
cuihantao/andes | andes/routines/tds.py | TDS.dump_results | def dump_results(self, success):
"""
Dump simulation results to ``dat`` and ``lst`` files
Returns
-------
None
"""
system = self.system
t, _ = elapsed()
if success and (not system.files.no_output):
# system.varout.dump()
... | python | def dump_results(self, success):
"""
Dump simulation results to ``dat`` and ``lst`` files
Returns
-------
None
"""
system = self.system
t, _ = elapsed()
if success and (not system.files.no_output):
# system.varout.dump()
... | Dump simulation results to ``dat`` and ``lst`` files
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/tds.py#L586-L603 |
cuihantao/andes | andes/filters/card.py | read | def read(file, system):
"""Parse an ANDES card file into internal variables"""
try:
fid = open(file, 'r')
raw_file = fid.readlines()
except IOError:
print('* IOError while reading input card file.')
return
ret_dict = dict()
ret_dict['outfile'] = file.split('.')[0].lo... | python | def read(file, system):
"""Parse an ANDES card file into internal variables"""
try:
fid = open(file, 'r')
raw_file = fid.readlines()
except IOError:
print('* IOError while reading input card file.')
return
ret_dict = dict()
ret_dict['outfile'] = file.split('.')[0].lo... | Parse an ANDES card file into internal variables | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L26-L110 |
cuihantao/andes | andes/filters/card.py | de_blank | def de_blank(val):
"""Remove blank elements in `val` and return `ret`"""
ret = list(val)
if type(val) == list:
for idx, item in enumerate(val):
if item.strip() == '':
ret.remove(item)
else:
ret[idx] = item.strip()
return ret | python | def de_blank(val):
"""Remove blank elements in `val` and return `ret`"""
ret = list(val)
if type(val) == list:
for idx, item in enumerate(val):
if item.strip() == '':
ret.remove(item)
else:
ret[idx] = item.strip()
return ret | Remove blank elements in `val` and return `ret` | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L117-L126 |
cuihantao/andes | andes/filters/card.py | run | def run(system,
outfile='',
name='',
doc_string='',
group='',
data={},
descr={},
units={},
params=[],
fnamex=[],
fnamey=[],
mandatory=[],
zeros=[],
powers=[],
currents=[],
voltages=[],
z=[],
... | python | def run(system,
outfile='',
name='',
doc_string='',
group='',
data={},
descr={},
units={},
params=[],
fnamex=[],
fnamey=[],
mandatory=[],
zeros=[],
powers=[],
currents=[],
voltages=[],
z=[],
... | Input data consistency check | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L129-L617 |
cuihantao/andes | andes/filters/card.py | stringfy | def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
"""Convert the right-hand-side of an equation into CVXOPT matrix operations"""
if not sym_const:
sym_const = []
if not sym_states:
sym_states = []
if not sym_algebs:
sym_algebs = []
expr_str = []
if typ... | python | def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
"""Convert the right-hand-side of an equation into CVXOPT matrix operations"""
if not sym_const:
sym_const = []
if not sym_states:
sym_states = []
if not sym_algebs:
sym_algebs = []
expr_str = []
if typ... | Convert the right-hand-side of an equation into CVXOPT matrix operations | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L621-L698 |
cuihantao/andes | andes/filters/psse.py | read | def read(file, system):
"""read PSS/E RAW file v32 format"""
blocks = [
'bus', 'load', 'fshunt', 'gen', 'branch', 'transf', 'area',
'twotermdc', 'vscdc', 'impedcorr', 'mtdc', 'msline', 'zone',
'interarea', 'owner', 'facts', 'swshunt', 'gne', 'Q'
]
nol = [1, 1, 1, 1, 1, 4, 1, 0, ... | python | def read(file, system):
"""read PSS/E RAW file v32 format"""
blocks = [
'bus', 'load', 'fshunt', 'gen', 'branch', 'transf', 'area',
'twotermdc', 'vscdc', 'impedcorr', 'mtdc', 'msline', 'zone',
'interarea', 'owner', 'facts', 'swshunt', 'gne', 'Q'
]
nol = [1, 1, 1, 1, 1, 4, 1, 0, ... | read PSS/E RAW file v32 format | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/psse.py#L38-L330 |
cuihantao/andes | andes/filters/psse.py | readadd | def readadd(file, system):
"""read DYR file"""
dyr = {}
data = []
end = 0
retval = True
sep = ','
fid = open(file, 'r')
for line in fid.readlines():
if line.find('/') >= 0:
line = line.split('/')[0]
end = 1
if line.find(',') >= 0: # mixed comma a... | python | def readadd(file, system):
"""read DYR file"""
dyr = {}
data = []
end = 0
retval = True
sep = ','
fid = open(file, 'r')
for line in fid.readlines():
if line.find('/') >= 0:
line = line.split('/')[0]
end = 1
if line.find(',') >= 0: # mixed comma a... | read DYR file | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/psse.py#L333-L391 |
cuihantao/andes | andes/filters/psse.py | add_dyn | def add_dyn(system, model, data):
"""helper function to elem_add a device element to system"""
if model == 'GENCLS':
bus = data[0]
data = data[3:]
if bus in system.PV.bus:
dev = 'PV'
gen_idx = system.PV.idx[system.PV.bus.index(bus)]
elif bus in system.SW.b... | python | def add_dyn(system, model, data):
"""helper function to elem_add a device element to system"""
if model == 'GENCLS':
bus = data[0]
data = data[3:]
if bus in system.PV.bus:
dev = 'PV'
gen_idx = system.PV.idx[system.PV.bus.index(bus)]
elif bus in system.SW.b... | helper function to elem_add a device element to system | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/psse.py#L394-L616 |
DiamondLightSource/python-workflows | workflows/recipe/recipe.py | Recipe._sanitize | def _sanitize(recipe):
"""Clean up a recipe that may have been stored as serialized json string.
Convert any numerical pointers that are stored as strings to integers."""
recipe = recipe.copy()
for k in list(recipe):
if k not in ("start", "error") and int(k) and k != int(k):
... | python | def _sanitize(recipe):
"""Clean up a recipe that may have been stored as serialized json string.
Convert any numerical pointers that are stored as strings to integers."""
recipe = recipe.copy()
for k in list(recipe):
if k not in ("start", "error") and int(k) and k != int(k):
... | Clean up a recipe that may have been stored as serialized json string.
Convert any numerical pointers that are stored as strings to integers. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/recipe.py#L37-L53 |
DiamondLightSource/python-workflows | workflows/recipe/recipe.py | Recipe.validate | def validate(self):
"""Check whether the encoded recipe is valid. It must describe a directed
acyclical graph, all connections must be defined, etc."""
if not self.recipe:
raise workflows.Error("Invalid recipe: No recipe defined")
# Without a 'start' node nothing would happe... | python | def validate(self):
"""Check whether the encoded recipe is valid. It must describe a directed
acyclical graph, all connections must be defined, etc."""
if not self.recipe:
raise workflows.Error("Invalid recipe: No recipe defined")
# Without a 'start' node nothing would happe... | Check whether the encoded recipe is valid. It must describe a directed
acyclical graph, all connections must be defined, etc. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/recipe.py#L92-L189 |
DiamondLightSource/python-workflows | workflows/recipe/recipe.py | Recipe.apply_parameters | def apply_parameters(self, parameters):
"""Recursively apply dictionary entries in 'parameters' to {item}s in recipe
structure, leaving undefined {item}s as they are. A special case is a
{$REPLACE:item}, which replaces the string with a copy of the referenced
parameter item.
Exa... | python | def apply_parameters(self, parameters):
"""Recursively apply dictionary entries in 'parameters' to {item}s in recipe
structure, leaving undefined {item}s as they are. A special case is a
{$REPLACE:item}, which replaces the string with a copy of the referenced
parameter item.
Exa... | Recursively apply dictionary entries in 'parameters' to {item}s in recipe
structure, leaving undefined {item}s as they are. A special case is a
{$REPLACE:item}, which replaces the string with a copy of the referenced
parameter item.
Examples:
parameters = { 'x':'5' }
ap... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/recipe.py#L191-L274 |
DiamondLightSource/python-workflows | workflows/recipe/recipe.py | Recipe.merge | def merge(self, other):
"""Merge two recipes together, returning a single recipe containing all
nodes.
Note: This does NOT yet return a minimal recipe.
:param other: A Recipe object that should be merged with the current
Recipe object.
:return: A new Recipe ... | python | def merge(self, other):
"""Merge two recipes together, returning a single recipe containing all
nodes.
Note: This does NOT yet return a minimal recipe.
:param other: A Recipe object that should be merged with the current
Recipe object.
:return: A new Recipe ... | Merge two recipes together, returning a single recipe containing all
nodes.
Note: This does NOT yet return a minimal recipe.
:param other: A Recipe object that should be merged with the current
Recipe object.
:return: A new Recipe object containing information from ... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/recipe.py#L276-L370 |
sashahart/cookies | cookies.py | strip_spaces_and_quotes | def strip_spaces_and_quotes(value):
"""Remove invalid whitespace and/or single pair of dquotes and return None
for empty strings.
Used to prepare cookie values, path, and domain attributes in a way which
tolerates simple formatting mistakes and standards variations.
"""
value = value.strip() if... | python | def strip_spaces_and_quotes(value):
"""Remove invalid whitespace and/or single pair of dquotes and return None
for empty strings.
Used to prepare cookie values, path, and domain attributes in a way which
tolerates simple formatting mistakes and standards variations.
"""
value = value.strip() if... | Remove invalid whitespace and/or single pair of dquotes and return None
for empty strings.
Used to prepare cookie values, path, and domain attributes in a way which
tolerates simple formatting mistakes and standards variations. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L319-L331 |
sashahart/cookies | cookies.py | parse_string | def parse_string(data, unquote=default_unquote):
"""Decode URL-encoded strings to UTF-8 containing the escaped chars.
"""
if data is None:
return None
# We'll soon need to unquote to recover our UTF-8 data.
# In Python 2, unquote crashes on chars beyond ASCII. So encode functions
# had ... | python | def parse_string(data, unquote=default_unquote):
"""Decode URL-encoded strings to UTF-8 containing the escaped chars.
"""
if data is None:
return None
# We'll soon need to unquote to recover our UTF-8 data.
# In Python 2, unquote crashes on chars beyond ASCII. So encode functions
# had ... | Decode URL-encoded strings to UTF-8 containing the escaped chars. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L334-L357 |
sashahart/cookies | cookies.py | parse_date | def parse_date(value):
"""Parse an RFC 1123 or asctime-like format date string to produce
a Python datetime object (without a timezone).
"""
# Do the regex magic; also enforces 2 or 4 digit years
match = Definitions.DATE_RE.match(value) if value else None
if not match:
return None
# ... | python | def parse_date(value):
"""Parse an RFC 1123 or asctime-like format date string to produce
a Python datetime object (without a timezone).
"""
# Do the regex magic; also enforces 2 or 4 digit years
match = Definitions.DATE_RE.match(value) if value else None
if not match:
return None
# ... | Parse an RFC 1123 or asctime-like format date string to produce
a Python datetime object (without a timezone). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L360-L399 |
sashahart/cookies | cookies.py | parse_value | def parse_value(value, allow_spaces=True, unquote=default_unquote):
"Process a cookie value"
if value is None:
return None
value = strip_spaces_and_quotes(value)
value = parse_string(value, unquote=unquote)
if not allow_spaces:
assert ' ' not in value
return value | python | def parse_value(value, allow_spaces=True, unquote=default_unquote):
"Process a cookie value"
if value is None:
return None
value = strip_spaces_and_quotes(value)
value = parse_string(value, unquote=unquote)
if not allow_spaces:
assert ' ' not in value
return value | Process a cookie value | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L419-L427 |
sashahart/cookies | cookies.py | valid_name | def valid_name(name):
"Validate a cookie name string"
if isinstance(name, bytes):
name = name.decode('ascii')
if not Definitions.COOKIE_NAME_RE.match(name):
return False
# This module doesn't support $identifiers, which are part of an obsolete
# and highly complex standard which is n... | python | def valid_name(name):
"Validate a cookie name string"
if isinstance(name, bytes):
name = name.decode('ascii')
if not Definitions.COOKIE_NAME_RE.match(name):
return False
# This module doesn't support $identifiers, which are part of an obsolete
# and highly complex standard which is n... | Validate a cookie name string | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L430-L440 |
sashahart/cookies | cookies.py | valid_value | def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
"""Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote function... | python | def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
"""Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote function... | Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote functions, use something like this
as a replacement for valid_value::
my_valid_... | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L443-L473 |
sashahart/cookies | cookies.py | valid_date | def valid_date(date):
"Validate an expires datetime object"
# We want something that acts like a datetime. In particular,
# strings indicate a failure to parse down to an object and ints are
# nonstandard and ambiguous at best.
if not hasattr(date, 'tzinfo'):
return False
# Relevant RFCs... | python | def valid_date(date):
"Validate an expires datetime object"
# We want something that acts like a datetime. In particular,
# strings indicate a failure to parse down to an object and ints are
# nonstandard and ambiguous at best.
if not hasattr(date, 'tzinfo'):
return False
# Relevant RFCs... | Validate an expires datetime object | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L476-L487 |
sashahart/cookies | cookies.py | valid_domain | def valid_domain(domain):
"Validate a cookie domain ASCII string"
# Using encoding on domain would confuse browsers into not sending cookies.
# Generate UnicodeDecodeError up front if it can't store as ASCII.
domain.encode('ascii')
# Domains starting with periods are not RFC-valid, but this is very ... | python | def valid_domain(domain):
"Validate a cookie domain ASCII string"
# Using encoding on domain would confuse browsers into not sending cookies.
# Generate UnicodeDecodeError up front if it can't store as ASCII.
domain.encode('ascii')
# Domains starting with periods are not RFC-valid, but this is very ... | Validate a cookie domain ASCII string | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L490-L499 |
sashahart/cookies | cookies.py | valid_path | def valid_path(value):
"Validate a cookie path ASCII string"
# Generate UnicodeDecodeError if path can't store as ASCII.
value.encode("ascii")
# Cookies without leading slash will likely be ignored, raise ASAP.
if not (value and value[0] == "/"):
return False
if not Definitions.PATH_RE.m... | python | def valid_path(value):
"Validate a cookie path ASCII string"
# Generate UnicodeDecodeError if path can't store as ASCII.
value.encode("ascii")
# Cookies without leading slash will likely be ignored, raise ASAP.
if not (value and value[0] == "/"):
return False
if not Definitions.PATH_RE.m... | Validate a cookie path ASCII string | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L502-L511 |
sashahart/cookies | cookies.py | valid_max_age | def valid_max_age(number):
"Validate a cookie Max-Age"
if isinstance(number, basestring):
try:
number = long(number)
except (ValueError, TypeError):
return False
if number >= 0 and number % 1 == 0:
return True
return False | python | def valid_max_age(number):
"Validate a cookie Max-Age"
if isinstance(number, basestring):
try:
number = long(number)
except (ValueError, TypeError):
return False
if number >= 0 and number % 1 == 0:
return True
return False | Validate a cookie Max-Age | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L514-L523 |
sashahart/cookies | cookies.py | encode_cookie_value | def encode_cookie_value(data, quote=default_cookie_quote):
"""URL-encode strings to make them safe for a cookie value.
By default this uses urllib quoting, as used in many other cookie
implementations and in other Python code, instead of an ad hoc escaping
mechanism which includes backslashes (these al... | python | def encode_cookie_value(data, quote=default_cookie_quote):
"""URL-encode strings to make them safe for a cookie value.
By default this uses urllib quoting, as used in many other cookie
implementations and in other Python code, instead of an ad hoc escaping
mechanism which includes backslashes (these al... | URL-encode strings to make them safe for a cookie value.
By default this uses urllib quoting, as used in many other cookie
implementations and in other Python code, instead of an ad hoc escaping
mechanism which includes backslashes (these also being illegal chars in RFC
6265). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L526-L549 |
sashahart/cookies | cookies.py | render_date | def render_date(date):
"""Render a date (e.g. an Expires value) per RFCs 6265/2616/1123.
Don't give this localized (timezone-aware) datetimes. If you use them,
convert them to GMT before passing them to this. There are too many
conversion corner cases to handle this universally.
"""
if not date... | python | def render_date(date):
"""Render a date (e.g. an Expires value) per RFCs 6265/2616/1123.
Don't give this localized (timezone-aware) datetimes. If you use them,
convert them to GMT before passing them to this. There are too many
conversion corner cases to handle this universally.
"""
if not date... | Render a date (e.g. an Expires value) per RFCs 6265/2616/1123.
Don't give this localized (timezone-aware) datetimes. If you use them,
convert them to GMT before passing them to this. There are too many
conversion corner cases to handle this universally. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L561-L575 |
sashahart/cookies | cookies.py | _parse_request | def _parse_request(header_data, ignore_bad_cookies=False):
"""Turn one or more lines of 'Cookie:' header data into a dict mapping
cookie names to cookie values (raw strings).
"""
cookies_dict = {}
for line in Definitions.EOL.split(header_data.strip()):
matches = Definitions.COOKIE_RE.findite... | python | def _parse_request(header_data, ignore_bad_cookies=False):
"""Turn one or more lines of 'Cookie:' header data into a dict mapping
cookie names to cookie values (raw strings).
"""
cookies_dict = {}
for line in Definitions.EOL.split(header_data.strip()):
matches = Definitions.COOKIE_RE.findite... | Turn one or more lines of 'Cookie:' header data into a dict mapping
cookie names to cookie values (raw strings). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L586-L612 |
sashahart/cookies | cookies.py | parse_one_response | def parse_one_response(line, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Turn one 'Set-Cookie:' line into a dict mapping attribute names to
attribute values (raw strings).
"""
cookie_dict = {}
# Basic validation, extract name/value/attrs-chunk
match = Definit... | python | def parse_one_response(line, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Turn one 'Set-Cookie:' line into a dict mapping attribute names to
attribute values (raw strings).
"""
cookie_dict = {}
# Basic validation, extract name/value/attrs-chunk
match = Definit... | Turn one 'Set-Cookie:' line into a dict mapping attribute names to
attribute values (raw strings). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L615-L656 |
sashahart/cookies | cookies.py | _parse_response | def _parse_response(header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
mapping attribute names to attribute values (as plain strings).
"""
cookie_dicts = []
for line in Definitions.EOL.sp... | python | def _parse_response(header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
mapping attribute names to attribute values (as plain strings).
"""
cookie_dicts = []
for line in Definitions.EOL.sp... | Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
mapping attribute names to attribute values (as plain strings). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L659-L678 |
sashahart/cookies | cookies.py | Cookie.from_dict | def from_dict(cls, cookie_dict, ignore_bad_attributes=True):
"""Construct an instance from a dict of strings to parse.
The main difference between this and Cookie(name, value, **kwargs) is
that the values in the argument to this method are parsed.
If ignore_bad_attributes=True (default... | python | def from_dict(cls, cookie_dict, ignore_bad_attributes=True):
"""Construct an instance from a dict of strings to parse.
The main difference between this and Cookie(name, value, **kwargs) is
that the values in the argument to this method are parsed.
If ignore_bad_attributes=True (default... | Construct an instance from a dict of strings to parse.
The main difference between this and Cookie(name, value, **kwargs) is
that the values in the argument to this method are parsed.
If ignore_bad_attributes=True (default), values which did not parse
are set to '' in order to avoid pa... | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L730-L775 |
sashahart/cookies | cookies.py | Cookie.from_string | def from_string(cls, line, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookie object from a line of Set-Cookie header data."
cookie_dict = parse_one_response(
line, ignore_bad_cookies=ignore_bad_cookies,
ignore_bad_attributes=ignore_bad... | python | def from_string(cls, line, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookie object from a line of Set-Cookie header data."
cookie_dict = parse_one_response(
line, ignore_bad_cookies=ignore_bad_cookies,
ignore_bad_attributes=ignore_bad... | Construct a Cookie object from a line of Set-Cookie header data. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L778-L787 |
sashahart/cookies | cookies.py | Cookie.validate | def validate(self, name, value):
"""Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
"""
validator = self.attribute_vali... | python | def validate(self, name, value):
"""Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
"""
validator = self.attribute_vali... | Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L794-L804 |
sashahart/cookies | cookies.py | Cookie.attributes | def attributes(self):
"""Export this cookie's attributes as a dict of encoded values.
This is an important part of the code for rendering attributes, e.g.
render_response().
"""
dictionary = {}
# Only look for attributes registered in attribute_names.
for python_... | python | def attributes(self):
"""Export this cookie's attributes as a dict of encoded values.
This is an important part of the code for rendering attributes, e.g.
render_response().
"""
dictionary = {}
# Only look for attributes registered in attribute_names.
for python_... | Export this cookie's attributes as a dict of encoded values.
This is an important part of the code for rendering attributes, e.g.
render_response(). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L832-L850 |
sashahart/cookies | cookies.py | Cookie.render_request | def render_request(self):
"""Render as a string formatted for HTTP request headers
(simple 'Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
name, value = self.name, self.value
renderer = self.attribute_renderers.get('name', None)
if ... | python | def render_request(self):
"""Render as a string formatted for HTTP request headers
(simple 'Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
name, value = self.name, self.value
renderer = self.attribute_renderers.get('name', None)
if ... | Render as a string formatted for HTTP request headers
(simple 'Cookie: ' style). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L852-L864 |
sashahart/cookies | cookies.py | Cookie.render_response | def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
name, value = self.name, self.value... | python | def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
name, value = self.name, self.value... | Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L866-L883 |
sashahart/cookies | cookies.py | Cookies.add | def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | python | def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as the cookie name and the
value as the ... | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L995-L1016 |
sashahart/cookies | cookies.py | Cookies.parse_request | def parse_request(self, header_data, ignore_bad_cookies=False):
"""Parse 'Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Cookie:' request headers or
header values (as in CGI/WSGI HTTP_COOKIE); if more than one, the... | python | def parse_request(self, header_data, ignore_bad_cookies=False):
"""Parse 'Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Cookie:' request headers or
header values (as in CGI/WSGI HTTP_COOKIE); if more than one, the... | Parse 'Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Cookie:' request headers or
header values (as in CGI/WSGI HTTP_COOKIE); if more than one, they must
be separated by CRLF (\\r\\n).
:arg ignore_bad_cook... | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1022-L1062 |
sashahart/cookies | cookies.py | Cookies.parse_response | def parse_response(self, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Parse 'Set-Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Set-Cookie:' request headers
or their... | python | def parse_response(self, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Parse 'Set-Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Set-Cookie:' request headers
or their... | Parse 'Set-Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Set-Cookie:' request headers
or their corresponding header values; if more than one, they must be
separated by CRLF (\\r\\n).
:arg ignore_bad_cooki... | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1064-L1106 |
sashahart/cookies | cookies.py | Cookies.from_request | def from_request(cls, header_data, ignore_bad_cookies=False):
"Construct a Cookies object from request header data."
cookies = cls()
cookies.parse_request(
header_data, ignore_bad_cookies=ignore_bad_cookies)
return cookies | python | def from_request(cls, header_data, ignore_bad_cookies=False):
"Construct a Cookies object from request header data."
cookies = cls()
cookies.parse_request(
header_data, ignore_bad_cookies=ignore_bad_cookies)
return cookies | Construct a Cookies object from request header data. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1109-L1114 |
sashahart/cookies | cookies.py | Cookies.from_response | def from_response(cls, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookies object from response header data."
cookies = cls()
cookies.parse_response(
header_data,
ignore_bad_cookies=ignore_bad_cookies,
... | python | def from_response(cls, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookies object from response header data."
cookies = cls()
cookies.parse_response(
header_data,
ignore_bad_cookies=ignore_bad_cookies,
... | Construct a Cookies object from response header data. | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1117-L1125 |
sashahart/cookies | cookies.py | Cookies.render_request | def render_request(self, sort=True):
"""Render the dict's Cookie objects into a string formatted for HTTP
request headers (simple 'Cookie: ' style).
"""
if not sort:
return ("; ".join(
cookie.render_request() for cookie in self.values()))
return ("; ".... | python | def render_request(self, sort=True):
"""Render the dict's Cookie objects into a string formatted for HTTP
request headers (simple 'Cookie: ' style).
"""
if not sort:
return ("; ".join(
cookie.render_request() for cookie in self.values()))
return ("; ".... | Render the dict's Cookie objects into a string formatted for HTTP
request headers (simple 'Cookie: ' style). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1127-L1135 |
sashahart/cookies | cookies.py | Cookies.render_response | def render_response(self, sort=True):
"""Render the dict's Cookie objects into list of strings formatted for
HTTP response headers (detailed 'Set-Cookie: ' style).
"""
rendered = [cookie.render_response() for cookie in self.values()]
return rendered if not sort else sorted(render... | python | def render_response(self, sort=True):
"""Render the dict's Cookie objects into list of strings formatted for
HTTP response headers (detailed 'Set-Cookie: ' style).
"""
rendered = [cookie.render_response() for cookie in self.values()]
return rendered if not sort else sorted(render... | Render the dict's Cookie objects into list of strings formatted for
HTTP response headers (detailed 'Set-Cookie: ' style). | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L1137-L1142 |
cuihantao/andes | andes/utils/math.py | aorb | def aorb(a, b):
"""Return a matrix of logic comparison of A or B"""
return matrix(np.logical_or(a, b).astype('float'), a.size) | python | def aorb(a, b):
"""Return a matrix of logic comparison of A or B"""
return matrix(np.logical_or(a, b).astype('float'), a.size) | Return a matrix of logic comparison of A or B | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L47-L49 |
cuihantao/andes | andes/utils/math.py | aandb | def aandb(a, b):
"""Return a matrix of logic comparison of A or B"""
return matrix(np.logical_and(a, b).astype('float'), a.size) | python | def aandb(a, b):
"""Return a matrix of logic comparison of A or B"""
return matrix(np.logical_and(a, b).astype('float'), a.size) | Return a matrix of logic comparison of A or B | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L52-L54 |
cuihantao/andes | andes/utils/math.py | not0 | def not0(a):
"""Return u if u!= 0, return 1 if u == 0"""
return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size) | python | def not0(a):
"""Return u if u!= 0, return 1 if u == 0"""
return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size) | Return u if u!= 0, return 1 if u == 0 | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L87-L89 |
cuihantao/andes | andes/utils/math.py | sort | def sort(m, reverse=False):
"""Return sorted m (default: ascending order)"""
ty = type(m)
if ty == matrix:
m = list(m)
m = sorted(m, reverse=reverse)
if ty == matrix:
m = matrix(m)
return m | python | def sort(m, reverse=False):
"""Return sorted m (default: ascending order)"""
ty = type(m)
if ty == matrix:
m = list(m)
m = sorted(m, reverse=reverse)
if ty == matrix:
m = matrix(m)
return m | Return sorted m (default: ascending order) | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L107-L115 |
cuihantao/andes | andes/utils/math.py | sort_idx | def sort_idx(m, reverse=False):
"""Return the indices of m in sorted order (default: ascending order)"""
return sorted(range(len(m)), key=lambda k: m[k], reverse=reverse) | python | def sort_idx(m, reverse=False):
"""Return the indices of m in sorted order (default: ascending order)"""
return sorted(range(len(m)), key=lambda k: m[k], reverse=reverse) | Return the indices of m in sorted order (default: ascending order) | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L118-L120 |
cuihantao/andes | andes/utils/math.py | index | def index(m, val):
"""
Return the indices of all the ``val`` in ``m``
"""
mm = np.array(m)
idx_tuple = np.where(mm == val)
idx = idx_tuple[0].tolist()
return idx | python | def index(m, val):
"""
Return the indices of all the ``val`` in ``m``
"""
mm = np.array(m)
idx_tuple = np.where(mm == val)
idx = idx_tuple[0].tolist()
return idx | Return the indices of all the ``val`` in ``m`` | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L123-L131 |
cuihantao/andes | andes/utils/math.py | to_number | def to_number(s):
"""
Convert a string to a number.
If not successful, return the string without blanks
"""
ret = s
# try converting to float
try:
ret = float(s)
except ValueError:
ret = ret.strip('\'').strip()
# try converting to uid
try:
ret = int(s)
... | python | def to_number(s):
"""
Convert a string to a number.
If not successful, return the string without blanks
"""
ret = s
# try converting to float
try:
ret = float(s)
except ValueError:
ret = ret.strip('\'').strip()
# try converting to uid
try:
ret = int(s)
... | Convert a string to a number.
If not successful, return the string without blanks | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L134-L159 |
cuihantao/andes | andes/utils/math.py | sdiv | def sdiv(a, b):
"""Safe division: if a == b == 0, sdiv(a, b) == 1"""
if len(a) != len(b):
raise ValueError('Argument a and b does not have the same length')
idx = 0
ret = matrix(0, (len(a), 1), 'd')
for m, n in zip(a, b):
try:
ret[idx] = m / n
except ZeroDivisionE... | python | def sdiv(a, b):
"""Safe division: if a == b == 0, sdiv(a, b) == 1"""
if len(a) != len(b):
raise ValueError('Argument a and b does not have the same length')
idx = 0
ret = matrix(0, (len(a), 1), 'd')
for m, n in zip(a, b):
try:
ret[idx] = m / n
except ZeroDivisionE... | Safe division: if a == b == 0, sdiv(a, b) == 1 | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L162-L175 |
cuihantao/andes | andes/utils/misc.py | get_config_load_path | def get_config_load_path(conf_path=None):
"""
Return config file load path
Priority:
1. conf_path
2. current directory
3. home directory
Parameters
----------
conf_path
Returns
-------
"""
if conf_path is None:
# test ./andes.conf
if o... | python | def get_config_load_path(conf_path=None):
"""
Return config file load path
Priority:
1. conf_path
2. current directory
3. home directory
Parameters
----------
conf_path
Returns
-------
"""
if conf_path is None:
# test ./andes.conf
if o... | Return config file load path
Priority:
1. conf_path
2. current directory
3. home directory
Parameters
----------
conf_path
Returns
------- | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/misc.py#L9-L39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.