code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a2], Va[self.a2]) | def v2(self) | Return voltage phasors at the "to buses" (bus2) | 7.318374 | 5.910769 | 1.238143 |
self.u[self.uid[idx]] = u
self.rebuild = True
self.system.dae.factorize = True
logger.debug('<Line> Status switch to {} on idx {}.'.format(u, idx)) | def switch(self, idx, u) | switch the status of Line idx | 15.872754 | 13.134926 | 1.208439 |
if not self.n:
return
mpq = self.system.dae.m + 2 * self.system.Bus.n
nl = self.n
# Pij
xy_idx = range(mpq, mpq + nl)
self.system.varname.append(
listname='unamey',
xy_idx=xy_idx,
var_name='Pij',
eleme... | def _varname_flow(self) | Build variable names for Pij, Pji, Qij, Qji, Sij, Sji | 1.415877 | 1.378361 | 1.027219 |
P, Q = [], []
if type(idx) is not list:
idx = [idx]
if type(bus) is not list:
bus = [bus]
for line_idx, bus_idx in zip(idx, bus):
line_int = self.uid[line_idx]
if bus_idx == self.bus1[line_int]:
P.append(self.P1[li... | def get_flow_by_idx(self, idx, bus) | Return seriesflow based on the external idx on the `bus` side | 2.175023 | 2.146079 | 1.013487 |
# leafs - leaf bus idx
# lines - line idx
# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus
leafs, lines, fkeys = list(), list(), list()
# convert to unique, ordered list
buses = sorted(list(set(self.bus1 + self.bus2)))
links = sel... | def leaf_bus(self, df=False) | Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame | 4.330393 | 3.798107 | 1.140145 |
lines = []
i = 0
while i < len(text) - 1:
try:
lines.append(text[i:i+length])
i += length
except IndexError as e:
lines.append(text[i:])
return lines | def truncate(text, length=255) | Splits the message into a list of strings of of length `length`
Args:
text (str): The text to be divided
length (int, optional): The length of the chunks of text. \
Defaults to 255.
Returns:
list: Text divided into chunks of length `length` | 3.116817 | 2.903828 | 1.073348 |
yext = self.system.dae.m - len(self.unamey)
xext = self.system.dae.n - len(self.unamex)
if yext > 0:
self.unamey.extend([''] * yext)
self.fnamey.extend([''] * yext)
if xext > 0:
self.unamex.extend([''] * xext)
self.fnamex.extend(['... | def resize(self) | Resize (extend) the list for variable names | 2.983856 | 2.801812 | 1.064974 |
if self.system.config.dime_enable:
self.system.tds.config.compute_flows = True
if self.system.tds.config.compute_flows:
nflows = 2 * self.system.Bus.n + \
8 * self.system.Line.n + \
2 * self.system.Area.n_combination
... | def resize_for_flows(self) | Extend `unamey` and `fnamey` for bus injections and line flows | 7.105388 | 5.396403 | 1.31669 |
self.resize()
string = '{0} {1}'
if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:
logger.error('Wrong list name for varname.')
return
elif listname in ['fnamex', 'fnamey']:
string = '${0}\\ {1}$'
if isinstance(element_name... | def append(self, listname, xy_idx, var_name, element_name) | Append variable names to the name lists | 4.354812 | 4.294639 | 1.014011 |
if self.system.tds.config.compute_flows:
self.system.Bus._varname_inj()
self.system.Line._varname_flow()
self.system.Area._varname_inter() | def bus_line_names(self) | Append bus injection and line flow names to `varname` | 17.921675 | 10.007618 | 1.790803 |
assert isinstance(xidx, int)
if isinstance(yidx, int):
yidx = [yidx]
uname = ['Time [s]'] + self.uname
fname = ['$Time\\ [s]$'] + self.fname
xname = [list(), list()]
yname = [list(), list()]
xname[0] = uname[xidx]
xname[1] = fname[x... | def get_xy_name(self, yidx, xidx=0) | Return variable names for the given indices
:param yidx:
:param xidx:
:return: | 2.870815 | 2.921149 | 0.982769 |
if not hasattr(get_known_services, "cache"):
setattr(
get_known_services,
"cache",
{
e.name: e.load()
for e in pkg_resources.iter_entry_points("workflows.services")
},
)
register = get_known_services.cache.copy(... | def get_known_services() | Return a dictionary of all known services.
:return: A dictionary containing entries { service name : service class }
Future: This will change to a dictionary containing references to
factories: { service name : service class factory }
A factory is a function that takes no ... | 3.683178 | 3.539325 | 1.040644 |
parser = ArgumentParser(prog='andesplot')
parser.add_argument('datfile', nargs=1, default=[], help='dat file name.')
parser.add_argument('x', nargs=1, type=int, help='x axis variable index')
parser.add_argument('y', nargs='*', help='y axis variable index')
parser.add_argument('--xmax', type=flo... | def cli_parse() | command line input parser | 2.431638 | 2.412513 | 1.007927 |
if LATEX:
xl_data = xl[1] # NOQA
yl_data = yl[1]
else:
xl_data = xl[0] # NOQA
yl_data = yl[0]
for idx in range(len(y)):
ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)
ax.legend(loc='upper right')
ax.set_ylim(auto=True) | def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs) | Add plots to an existing plot | 2.595372 | 2.567317 | 1.010928 |
suspect = []
for var, label in zip(yval, yl):
if abs(var[0] - var[-1]) >= 1e-6:
suspect.append(label)
if suspect:
print('Initialization failure:')
print(', '.join(suspect))
else:
print('Initialization is correct.') | def check_init(yval, yl) | Check initialization by comparing t=0 and t=end values | 3.800006 | 3.423071 | 1.110116 |
with open(self._lst_file, 'r') as fd:
lines = fd.readlines()
idx, uname, fname = list(), list(), list()
for line in lines:
values = line.split(',')
values = [x.strip() for x in values]
# preserve the idx ordering here in case variables ... | def load_lst(self) | Load the lst file into internal data structures | 3.747838 | 3.506667 | 1.068775 |
# load the variable list to search in
names = self._uname if formatted is False else self._fname
found_idx, found_names = list(), list()
for idx, name in zip(self._idx, names):
if re.search(query, name):
found_idx.append(idx)
found_... | def find_var(self, query, formatted=False) | Return variable names and indices matching ``query`` | 3.916055 | 3.875189 | 1.010546 |
try:
data = np.loadtxt(self._dat_file, delimiter=',')
except ValueError:
data = np.loadtxt(self._dat_file)
self._data = data | def load_dat(self, delimiter=',') | Load the dat file into internal data structures, ``self._data`` | 3.02887 | 3.023318 | 1.001836 |
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | def get_values(self, idx) | Return the variable values at the given indices | 4.520028 | 3.85023 | 1.173963 |
header = self._uname if not formatted else self._fname
return [header[x] for x in idx] | def get_header(self, idx, formatted=False) | Return a list of the variable names at the given indices | 9.93535 | 7.368437 | 1.348366 |
if not idx:
idx = self._idx
if not header:
header = self.get_header(idx, formatted=formatted)
assert len(idx) == len(header), \
"Idx length does not match header length"
body = self.get_values(idx)
with open(path, 'w') as fd:
... | def export_csv(self, path, idx=None, header=None, formatted=False,
sort_idx=True, fmt='%.18e') | Export to a csv file
Parameters
----------
path : str
path of the csv file to save
idx : None or array-like, optional
the indices of the variables to export. Export all by default
header : None or array-like, optional
customized header if not ... | 2.652094 | 2.956842 | 0.896935 |
if self._row_size is None:
return
elif self._row_size == 3:
self.set_cols_align(['l', 'l', 'l'])
self.set_cols_valign(['t', 't', 't'])
self.set_cols_width([12, 54, 12])
elif self._row_size == 4:
self.set_cols_align(['l', 'l', '... | def auto_style(self) | automatic styling according to _row_size
76 characters in a row | 2.065826 | 1.782128 | 1.159191 |
sp = ' ' * nspace
for item in self._rows:
item[0] = sp + item[0] | def add_left_space(self, nspace=1) | elem_add n cols of spaces before the first col.
(for texttable 0.8.3) | 5.995852 | 4.921463 | 1.218307 |
self.guess_header()
self.add_left_space(
)
# for Texttable, elem_add a column of whitespace on the left for
# better visual effect
if self._title and self._descr:
pre = self._title + '\n' + self._descr + '\n\n'
elif self._title:
pr... | def draw(self) | generate texttable formatted string | 6.641047 | 5.960825 | 1.114115 |
if len(self.header) <= 4:
nspace = 6
elif len(self.header) <= 6:
nspace = 5
else:
nspace = 4
ncol = len(self.header)
self._width = [nspace] * ncol
width = [0] * ncol
# set initial width from header
for idx, ite... | def guess_width(self) | auto fit column width | 2.706399 | 2.59695 | 1.042145 |
self.__subscription_id += 1
def mangled_callback(header, message):
return callback(header, self._mangle_for_receiving(message))
if "disable_mangling" in kwargs:
if kwargs["disable_mangling"]:
mangled_callback = callback
del kwargs["d... | def subscribe(self, channel, callback, **kwargs) | Listen to a queue, notify via callback function.
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
dictionary structure, and the message.
... | 2.917994 | 2.559369 | 1.140123 |
if subscription not in self.__subscriptions:
raise workflows.Error("Attempting to unsubscribe unknown subscription")
if self.__subscriptions[subscription]["unsubscribed"]:
raise workflows.Error(
"Attempting to unsubscribe already unsubscribed subscription... | def unsubscribe(self, subscription, drop_callback_reference=False, **kwargs) | Stop listening to a queue or a broadcast
:param subscription: Subscription ID to cancel
:param drop_callback_reference: Drop the reference to the registered
callback function immediately. This
means any buffered messages sti... | 2.845482 | 3.23198 | 0.880414 |
if subscription not in self.__subscriptions:
raise workflows.Error(
"Attempting to drop callback reference for unknown subscription"
)
if not self.__subscriptions[subscription]["unsubscribed"]:
raise workflows.Error(
"Attemptin... | def drop_callback_reference(self, subscription) | Drop reference to the callback function after unsubscribing.
Any future messages arriving for that subscription will result in
exceptions being raised.
:param subscription: Subscription ID to delete callback reference for. | 4.072871 | 3.88716 | 1.047775 |
self.__subscription_id += 1
def mangled_callback(header, message):
return callback(header, self._mangle_for_receiving(message))
if "disable_mangling" in kwargs:
if kwargs["disable_mangling"]:
mangled_callback = callback
del kwargs["d... | def subscribe_broadcast(self, channel, callback, **kwargs) | Listen to a broadcast topic, notify via callback function.
:param channel: Topic name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
dictionary structure, and the m... | 2.824335 | 2.630685 | 1.073612 |
subscription_record = self.__subscriptions.get(subscription)
if not subscription_record:
raise workflows.Error("Attempting to callback on unknown subscription")
callback = subscription_record["callback"]
if self.__callback_interceptor:
return self.__callb... | def subscription_callback(self, subscription) | Retrieve the callback function for a subscription. Raise a
workflows.Error if the subscription does not exist.
All transport callbacks can be intercepted by setting an
interceptor function with subscription_callback_intercept().
:param subscription: Subscription ID to look up
:re... | 6.038634 | 3.932572 | 1.535543 |
message = self._mangle_for_sending(message)
self._send(destination, message, **kwargs) | def send(self, destination, message, **kwargs) | Send a message to a queue.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay transport of message by this many seconds
h... | 5.396978 | 8.140754 | 0.662958 |
self._send(destination, message, **kwargs) | def raw_send(self, destination, message, **kwargs) | Send a raw (unmangled) message to a queue.
This may cause errors if the receiver expects a mangled message.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For examp... | 5.959243 | 7.637609 | 0.78025 |
message = self._mangle_for_sending(message)
self._broadcast(destination, message, **kwargs) | def broadcast(self, destination, message, **kwargs) | Broadcast a message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay transport of message by this many seconds
headers... | 5.979517 | 8.920269 | 0.670329 |
self._broadcast(destination, message, **kwargs) | def raw_broadcast(self, destination, message, **kwargs) | Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
... | 6.660147 | 9.089373 | 0.73274 |
if isinstance(message, dict):
message_id = message.get("message-id")
if not subscription_id:
subscription_id = message.get("subscription")
else:
message_id = message
if not message_id:
raise workflows.Error("Cannot acknowle... | def ack(self, message, subscription_id=None, **kwargs) | Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be acknowledged, OR a dictionary
containing a field 'message-id'.
:param subscription_id: ID of the associat... | 2.447862 | 2.329658 | 1.050739 |
if isinstance(message, dict):
message_id = message.get("message-id")
if not subscription_id:
subscription_id = message.get("subscription")
else:
message_id = message
if not message_id:
raise workflows.Error("Cannot reject m... | def nack(self, message, subscription_id=None, **kwargs) | Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be rejected, OR a dictionary
containing a field 'message-id'.
:param subscription_id: ID of the associated subscr... | 2.561317 | 2.34154 | 1.09386 |
self.__transaction_id += 1
self.__transactions.add(self.__transaction_id)
self.log.debug("Starting transaction with ID %d", self.__subscription_id)
self._transaction_begin(self.__transaction_id, **kwargs)
return self.__transaction_id | def transaction_begin(self, **kwargs) | Start a new transaction.
:param **kwargs: Further parameters for the transport layer. For example
:return: A transaction ID that can be passed to other functions. | 3.63536 | 3.640781 | 0.998511 |
if transaction_id not in self.__transactions:
raise workflows.Error("Attempting to abort unknown transaction")
self.log.debug("Aborting transaction %s", transaction_id)
self.__transactions.remove(transaction_id)
self._transaction_abort(transaction_id, **kwargs) | def transaction_abort(self, transaction_id, **kwargs) | Abort a transaction and roll back all operations.
:param transaction_id: ID of transaction to be aborted.
:param **kwargs: Further parameters for the transport layer. | 3.607054 | 4.05151 | 0.890299 |
if transaction_id not in self.__transactions:
raise workflows.Error("Attempting to commit unknown transaction")
self.log.debug("Committing transaction %s", transaction_id)
self.__transactions.remove(transaction_id)
self._transaction_commit(transaction_id, **kwargs) | def transaction_commit(self, transaction_id, **kwargs) | Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer. | 3.57551 | 4.141679 | 0.8633 |
if not self.n:
return
Ysh = matrix(self.g,
(self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd')
uYsh = mul(self.u, Ysh)
Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z') | def full_y(self, Y) | Add self(shunt) into full Jacobian Y | 6.241746 | 5.489526 | 1.137028 |
try:
model = importlib.import_module('.' + self.model, 'andes.models')
device = getattr(model, self.device)
self.system.__dict__[self.name] = device(self.system, self.name)
g = self.system.__dict__[self.name]._group
self.system.group_add(g)
... | def jit_load(self) | Import and instantiate this JIT object
Returns
------- | 3.93428 | 3.81959 | 1.030027 |
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | def elem_add(self, idx=None, name=None, **kwargs) | overloading elem_add function of a JIT class | 7.779336 | 6.364852 | 1.222234 |
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | def initializing(self) | Subscribe to a channel. Received messages must be acknowledged. | 28.839771 | 17.501413 | 1.647854 |
print("=== Receive ===")
print(header)
print(message)
print("MsgID: {0}".format(header["message-id"]))
assert header["message-id"]
txn = self._transport.transaction_begin()
print(" 1. Txn: {0}".format(str(txn)))
if self.crashpoint():
... | def receive_message(self, header, message) | Receive a message | 3.458576 | 3.5046 | 0.986868 |
self.counter += 1
self._transport.send(
"transient.transaction",
"TXMessage #%d\n++++++++Produced@ %f"
% (self.counter, (time.time() % 1000) * 1000),
)
self.log.info("Created message %d", self.counter) | def create_message(self) | Create and send a unique message for this service. | 10.278676 | 8.990042 | 1.14334 |
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
if dt_sec <= 1:
dt_str = str(dt_sec) + ' second'
else:
dt_str = str(dt_sec) + ' seconds'
return now, dt_str | def elapsed(t0=0.0) | get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string | 2.518105 | 2.588575 | 0.972777 |
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__[value]):
if item == 0:
self.__dict__[flag][idx] = 0
if res... | def set_flag(self, value, flag, reset_val=False) | Set a flag to 0 if the corresponding value is 0 | 2.801239 | 2.656142 | 1.054627 |
self.basic.update({
'nbus': system.Bus.n,
'ngen': system.PV.n + system.SW.n,
'ngen_on': sum(system.PV.u) + sum(system.SW.u),
'nload': system.PQ.n,
'nshunt': system.Shunt.n,
'nline': system.Line.n,
'ntransf': system.Line... | def _update_summary(self, system) | Update the summary data
Parameters
----------
system
Returns
-------
None | 4.331319 | 4.250705 | 1.018965 |
if self.system.pflow.solved is False:
logger.warning(
'Cannot update extended summary. Power flow not solved.')
return
Sloss = sum(system.Line.S1 + system.Line.S2)
self.extended.update({
'Ptot':
sum(system.PV.pmax) + sum(s... | def _update_extended(self, system) | Update the extended data | 2.717103 | 2.673504 | 1.016308 |
if not content:
return
if content == 'summary' or 'extended' or 'powerflow':
self._update_summary(self.system)
if content == 'extended' or 'powerflow':
self._update_extended(self.system) | def update(self, content=None) | Update values based on the requested content
Parameters
----------
content
Returns
------- | 6.46333 | 5.902077 | 1.095094 |
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if not self.recipe_step:
raise ValueError(
"This RecipeWrapper object does not conta... | def send(self, *args, **kwargs) | Send messages to another service that is connected to the currently
running service via the recipe. The 'send' method will either use a
default channel name, set via the set_default_channel method, or an
unnamed output definition. | 3.746649 | 3.141623 | 1.192584 |
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if self.recipe_step:
raise ValueError("This recipe has already been started.")
for destinat... | def start(self, header=None, **kwargs) | Trigger the start of a recipe, sending the defined payloads to the
recipients set in the recipe. Any parameters to this function are
passed to the transport send/broadcast methods.
If the wrapped recipe has already been started then a ValueError will
be raised. | 7.091691 | 4.974186 | 1.425699 |
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if not self.recipe_step:
raise ValueError(
"This RecipeWrapper object does not conta... | def checkpoint(self, message, header=None, delay=0, **kwargs) | Send a message to the current recipe destination. This can be used to
keep a state for longer processing tasks.
:param delay: Delay transport of message by this many seconds | 6.393996 | 5.996743 | 1.066245 |
self.recipe.apply_parameters(parameters)
self.recipe_step = self.recipe[self.recipe_pointer] | def apply_parameters(self, parameters) | Recursively apply parameter replacement (see recipe.py) to the wrapped
recipe, updating internal references afterwards.
While this operation is useful for testing it should not be used in
production. Replacing parameters means that the recipe changes as it is
passed down the chain of ser... | 8.334971 | 6.14631 | 1.356093 |
if add_path_step and self.recipe_pointer:
recipe_path = self.recipe_path + [self.recipe_pointer]
else:
recipe_path = self.recipe_path
return {
"environment": self.environment,
"payload": message,
"recipe": self.recipe.recipe,
... | def _generate_full_recipe_message(self, destination, message, add_path_step) | Factory function to generate independent message objects for
downstream recipients with different destinations. | 3.333814 | 3.409115 | 0.977912 |
if not isinstance(destinations, list):
destinations = (destinations,)
for destination in destinations:
self._send_to_destination(destination, header, message, kwargs) | def _send_to_destinations(self, destinations, message, header=None, **kwargs) | Send messages to a list of numbered destinations. This is an internal
helper method used by the public 'send' methods. | 2.834399 | 2.794474 | 1.014287 |
if header:
header = header.copy()
header["workflows-recipe"] = True
else:
header = {"workflows-recipe": True}
dest_kwargs = transport_kwargs.copy()
if (
"transport-delay" in self.recipe[destination]
and "delay" not in ... | def _send_to_destination(
self, destination, header, payload, transport_kwargs, add_path_step=True
) | Helper function to send a message to a specific recipe destination. | 2.67955 | 2.479641 | 1.08062 |
'''Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge
'''
metadata = self._parse_metadata(event)
message = Message(text=metadata['text'],
metadata=metadata).__dict__
if mes... | def on_message(self, event) | Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge | 6.543231 | 4.094957 | 1.597876 |
'''Extends the run() method of threading.Thread
'''
self.connect()
while True:
for event in self.slack_client.rtm_read():
logger.debug(event)
if 'type' in event and event['type'] in self.supported_events:
event_type = event... | def run(self) | Extends the run() method of threading.Thread | 5.061318 | 4.444094 | 1.138886 |
'''Finds occurrences of Slack userids and attempts to replace them with
display names.
Args:
text (string): The message text
Returns:
string: The message text with userids replaced.
'''
match = True
pattern = re.compile('<@([A-Z0-9]{9}... | def find_and_replace_userids(self, text) | Finds occurrences of Slack userids and attempts to replace them with
display names.
Args:
text (string): The message text
Returns:
string: The message text with userids replaced. | 3.439909 | 2.178088 | 1.579325 |
'''Find occurrences of Slack channel referenfces and attempts to
replace them with just channel names.
Args:
text (string): The message text
Returns:
string: The message text with channel references replaced.
'''
match = True
pattern =... | def find_and_replace_channel_refs(self, text) | Find occurrences of Slack channel referenfces and attempts to
replace them with just channel names.
Args:
text (string): The message text
Returns:
string: The message text with channel references replaced. | 4.051169 | 2.132125 | 1.900062 |
'''Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list
'''
channel_list = self.sl... | def get_channels(self, condensed=False) | Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list | 3.692305 | 1.91205 | 1.931072 |
'''Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict ... | def get_users(self, condensed=False) | Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict of users in... | 3.58801 | 1.729891 | 2.074125 |
'''Given a Slack userid, grabs user display_name from api.
Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response
'''
user_info = self.slack_client.api_call('users.info', user=userid)
if user_... | def get_user_display_name(self, userid) | Given a Slack userid, grabs user display_name from api.
Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response | 2.972882 | 1.796592 | 1.654734 |
'''Perform a lookup of users to resolve a userid to a DM channel
Args:
userid (string): Slack userid to lookup.
Returns:
string: DM channel ID of user
'''
dm_open = self.slack_client.api_call('im.open', user=userid)
return dm_open['channel']['id... | def get_dm_channel(self, userid) | Perform a lookup of users to resolve a userid to a DM channel
Args:
userid (string): Slack userid to lookup.
Returns:
string: DM channel ID of user | 5.598773 | 2.557775 | 2.188923 |
'''Perform a lookup of users to resolve a userid to a username
Args:
userid (string): Slack userid to lookup.
Returns:
string: Human-friendly name of the user
'''
username = self.user_map.get(userid)
if not username:
users = self.get... | def get_username(self, userid) | Perform a lookup of users to resolve a userid to a username
Args:
userid (string): Slack userid to lookup.
Returns:
string: Human-friendly name of the user | 3.494892 | 2.470287 | 1.414771 |
'''Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value
'''
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if botinfo['ok'] is True:
retur... | def get_userid_from_botid(self, botid) | Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value | 4.230135 | 2.097873 | 2.016392 |
'''Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata
'''
# Try to handle all the fields of events we care about.
... | def _parse_metadata(self, message) | Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata | 3.258196 | 2.5161 | 1.294939 |
'''Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data.
'''
attachment = {
'as_user': True,
'text': text,
'channel': target,
... | def build_attachment(self, text, target, attachment, thread) | Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data. | 4.253322 | 2.104922 | 2.020656 |
'''Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metadata']['opts']):
targe... | def handle(self, message) | Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send. | 2.939016 | 2.455001 | 1.197155 |
files = system.files
maybe = []
if files.input_format:
maybe.append(files.input_format)
# first, guess by extension
for key, val in input_formats.items():
if type(val) == list:
for item in val:
if files.ext.strip('.').lower() == item:
... | def guess(system) | input format guess function. First guess by extension, then test by lines | 3.088683 | 2.951452 | 1.046496 |
t, _ = elapsed()
input_format = system.files.input_format
add_format = system.files.add_format
# exit when no input format is given
if not input_format:
logger.error(
'No input format found. Specify or guess a format before parsing.')
return False
# exit if th... | def parse(system) | Parse input file with the given format in system.files.input_format | 2.941806 | 2.826175 | 1.040914 |
system = self.system
Gyx = matrix(system.dae.Gx)
self.solver.linsolve(system.dae.Gy, Gyx)
self.As = matrix(system.dae.Fx - system.dae.Fy * Gyx)
# ------------------------------------------------------
# TODO: use scipy eigs
# self.As = sparse(self.As)
... | def calc_state_matrix(self) | Return state matrix and store to ``self.As``
Returns
-------
matrix
state matrix | 4.498807 | 4.348986 | 1.03445 |
self.eigs = numpy.linalg.eigvals(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
return self.eigs | def calc_eigvals(self) | Solve eigenvalues of the state matrix ``self.As``
Returns
-------
None | 5.780078 | 5.184093 | 1.114964 |
mu, N = numpy.linalg.eig(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
N = matrix(N)
n = len(mu)
idx = range(n)
W = matrix(spmatrix(1.0, idx, idx, (n, n), N.typecode))
gesv(N, W)
partfact = mul(abs(W.T), abs(N))
b = matrix(1.0... | def calc_part_factor(self) | Compute participation factor of states in eigenvalues
Returns
------- | 4.725015 | 4.447582 | 1.062378 |
system = self.system
mu = self.mu
partfact = self.part_fact
if system.files.no_output:
return
text = []
header = []
rowname = []
data = []
neig = len(mu)
mu_real = mu.real()
mu_imag = mu.imag()
nposit... | def dump_results(self) | Save eigenvalue analysis reports
Returns
-------
None | 3.142249 | 3.052855 | 1.029282 |
if not self.n:
return []
self.times = list(mul(self.u1, self.t1)) + \
list(mul(self.u2, self.t2)) + \
list(mul(self.u3, self.t3)) + \
list(mul(self.u4, self.t4))
self.times = matrix(list(set(self.times)))
self.times = list(self.ti... | def get_times(self) | Return all the action times and times-1e-6 in a list | 3.054767 | 2.623855 | 1.164229 |
payload = {'op': 1, 'd': seq}
payload = json.dumps(payload)
logger.debug("Sending heartbeat with payload {}".format(payload))
ws.send(payload)
return | def send(self, ws, seq) | Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat | 4.293795 | 3.643048 | 1.178627 |
baseurl = self.rest_baseurl + \
'/channels/{}/messages'.format(channel_id)
requests.post(baseurl,
headers=self.headers,
data=json.dumps({'content': text})) | def create_message(self, channel_id, text) | Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message | 4.494324 | 4.202945 | 1.069327 |
payload = {
'op': 2,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'legobot',
'$device': 'legobot'
},
'compress': False,
... | def identify(self, token) | Identifies to the websocket endpoint
Args:
token (string): Discord bot token | 3.213862 | 2.843008 | 1.130444 |
logger.info("Got a hello")
self.identify(self.token)
self.heartbeat_thread = Heartbeat(self.ws,
message['d']['heartbeat_interval'])
self.heartbeat_thread.start()
return | def on_hello(self, message) | Runs on a hello event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | 7.272665 | 5.209585 | 1.396016 |
logger.info("Got a heartbeat")
logger.info("Heartbeat message: {}".format(message))
self.heartbeat_thread.update_sequence(message['d'])
return | def on_heartbeat(self, message) | Runs on a heartbeat event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | 8.798882 | 6.987982 | 1.259145 |
if 'content' in message['d']:
metadata = self._parse_metadata(message)
message = Message(text=message['d']['content'],
metadata=metadata).__dict__
logger.debug(message)
self.baseplate.tell(message) | def on_message(self, message) | Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | 9.515918 | 9.002151 | 1.057072 |
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' in message['d']:
metadata['source_user'] = message['d']['author']['username']
else:
metadata['source_user'] = None
if 'channel_id' in message['d']:
metadata['source_channel'] = m... | def _parse_metadata(self, message) | Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata | 3.32986 | 3.454375 | 0.963954 |
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode == 11:
self.on_heartbeat(message)
elif opcode == 0:
self.on_message(message)
else:
logger.debug("Not a message we handle: OPCODE {}".format(opcode)... | def handle(self, message) | Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection | 3.622779 | 3.277856 | 1.105228 |
self.ws = self.connect()
while True:
try:
data = json.loads(self.ws.recv())
self.handle(data)
except json.decoder.JSONDecodeError as e:
logger.fatal("No data on socket...") | def run(self) | Overrides run method of threading.Thread.
Called by DiscoBot.start(), inherited from threading.Thread | 4.948243 | 4.222627 | 1.17184 |
'''
Attempts to send a message to the specified destination in Discord.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metadata']['opts']):
... | def handle(self, message) | Attempts to send a message to the specified destination in Discord.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send. | 11.866632 | 3.995701 | 2.96985 |
yext = self.m - len(self.y)
xext = self.n - len(self.x)
if yext > 0:
yzeros = zeros(yext, 1)
yones = ones(yext, 1)
self.y = matrix([self.y, yzeros], (self.m, 1), 'd')
self.g = matrix([self.g, yzeros], (self.m, 1), 'd')
self.uy ... | def resize(self) | Resize dae and and extend for init1 variables | 1.643412 | 1.595608 | 1.02996 |
yidx = matrix(yidx)
yval = self.y[yidx]
ny = len(yidx)
if isinstance(ymin, (int, float, list)):
ymin = matrix(ymin, (ny, 1), 'd')
if isinstance(ymax, (int, float, list)):
ymax = matrix(ymax, (ny, 1), 'd')
if not min_set:
min_... | def hard_limit(self, yidx, ymin, ymax, min_set=None, max_set=None) | Set hard limits for algebraic variables and reset the equation mismatches
:param yidx: algebraic variable indices
:param ymin: lower limit to check for
:param ymax: upper limit to check for
:param min_set: optional lower limit to set (``ymin`` as default)
:param max_set: optiona... | 2.087649 | 2.054239 | 1.016264 |
ny = len(yidx)
assert ny == len(
ridx), "Length of output vars and remote vars does not match"
assert rtype in ('x',
'y'), "ridx must be either y (algeb) or x (state)"
if isinstance(min_yset, (int, float)):
min_yset = matrix(min_... | def hard_limit_remote(self,
yidx,
ridx,
rtype='y',
rmin=None,
rmax=None,
min_yset=0,
max_yset=0) | Limit the output of yidx if the remote y is not within the limits
This function needs to be modernized. | 3.53763 | 3.485177 | 1.01505 |
xidx = matrix(xidx)
xval = self.x[xidx]
fval = self.f[xidx]
if isinstance(xmin, (float, int, list)):
xmin = matrix(xmin, xidx.size, 'd')
if isinstance(xmax, (float, int, list)):
xmax = matrix(xmax, xidx.size, 'd')
x_above = ageb(xval, x... | def anti_windup(self, xidx, xmin, xmax) | Anti-windup limiter for state variables.
Resets the limited variables and differential equations.
:param xidx: state variable indices
:param xmin: lower limit
:param xmax: upper limit
:type xidx: matrix, list
:type xmin: matrix, float, int, list
:type xmax: mat... | 2.386915 | 2.435137 | 0.980197 |
if self.ac_reset is False:
return
mn = self.m + self.n
x = index(aandb(self.zxmin, self.zxmax), 0.)
y = [i + self.n for i in index(aandb(self.zymin, self.zymax), 0.)]
xy = list(x) + y
eye = spdiag([1.0] * mn)
H = spmatrix(1.0, xy, xy, (mn, ... | def reset_Ac(self) | Reset ``dae.Ac`` sparse matrix for disabled equations
due to hard_limit and anti_windup limiters.
:return: None | 6.987867 | 6.630096 | 1.053962 |
nrow, ncol = 0, 0
if m[0] == 'F':
nrow = self.n
elif m[0] == 'G':
nrow = self.m
if m[1] == 'x':
ncol = self.n
elif m[1] == 'y':
ncol = self.m
return nrow, ncol | def get_size(self, m) | Return the 2-D size of a Jacobian matrix in tuple | 2.503706 | 2.37374 | 1.054751 |
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \
'Wrong Jacobian matrix name <{0}>'.format(m)
if isinstance(val, (int, float)):
val = val * ones(len(row), 1)
self._temp[m]['I'] = matrix([self._temp[m]['I'], matrix(row)])
self._temp[m]... | def add_jac(self, m, val, row, col) | Add tuples (val, row, col) to the Jacobian matrix ``m``
Implemented in numpy.arrays for temporary storage. | 2.919921 | 2.923321 | 0.998837 |
assert ty in ('jac0', 'jac')
jac0s = ['Fx0', 'Fy0', 'Gx0', 'Gy0']
jacs = ['Fx', 'Fy', 'Gx', 'Gy']
if ty == 'jac0':
todo = jac0s
elif ty == 'jac':
todo = jacs
for m in todo:
self.__dict__[m] = spmatrix(self._temp[m]['V'],
... | def temp_to_spmatrix(self, ty) | Convert Jacobian tuples to matrices
:param ty: name of the matrices to convert in ``('jac0','jac')``
:return: None | 3.645483 | 3.299998 | 1.104693 |
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \
'Wrong Jacobian matrix name <{0}>'.format(m)
if isinstance(val,
(int, float)) and isinstance(row,
(np.ndarray, matrix, list)):
va... | def set_jac(self, m, val, row, col) | Set the values at (row, col) to val in Jacobian m
:param m: Jacobian name
:param val: values to set
:param row: row indices
:param col: col indices
:return: None | 3.399104 | 3.375294 | 1.007054 |
assert ty in ('jac0', 'jac')
if ty == 'jac0':
todo = ['Fx0', 'Fy0', 'Gx0', 'Gy0']
else:
todo = ['Fx', 'Fy', 'Gx', 'Gy']
for m in todo:
for idx in range(len(self._set[m]['I'])):
i = self._set[m]['I'][idx]
j = s... | def apply_set(self, ty) | Apply Jacobian set values to matrices
:param ty: Jacobian type in ``('jac0', 'jac')``
:return: | 3.11083 | 2.646528 | 1.175438 |
if eq in ['f', 'x']:
key = 'unamex'
elif eq in ['g', 'y']:
key = 'unamey'
if value:
value = list(value)
else:
value = list(self.__dict__[eq])
out = ''
for name, val, idx in zip(self.system.varname.__dict__[key], v... | def show(self, eq, value=None) | Show equation or variable array along with the names | 4.530451 | 4.267943 | 1.061507 |
if eq not in ('f', 'g', 'q'):
return
elif eq in ('f', 'q'):
key = 'unamex'
elif eq == 'g':
key = 'unamey'
idx = 0
for m, n in zip(self.system.varname.__dict__[key], self.__dict__[eq]):
if n == val:
return m,... | def find_val(self, eq, val) | Return the name of the equation having the given value | 5.873533 | 5.309058 | 1.106323 |
assert eq in ('f', 'g')
for idx, var in enumerate(self.__dict__[eq]):
if abs(var) <= 1e-12:
self.__dict__[eq][idx] = 0 | def reset_small(self, eq) | Reset numbers smaller than 1e-12 in f and g equations | 4.435478 | 3.067378 | 1.446016 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.