_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17500 | ModelBase.param_alter | train | def param_alter(self,
param,
default=None,
unit=None,
descr=None,
tomatrix=None,
nonzero=None,
mandatory=None,
power=None,
voltage=None,
... | python | {
"resource": ""
} |
q17501 | ModelBase.eq_add | train | def eq_add(self, expr, var, intf=False):
"""
Add an equation to this model.
An equation is associated with the addresses of a variable. The
number of equations must equal that of variables.
Stored to ``self._equations`` is a tuple of ``(expr, var, intf,
ty)`` where ``t... | python | {
"resource": ""
} |
q17502 | ModelBase.read_data_ext | train | def read_data_ext(self, model: str, field: str, idx=None, astype=None):
"""
Return a field of a model or group at the given indices
:param str model: name of the group or model to retrieve
:param str field: name of the field
:param list, int, float str idx: idx of elements to ac... | python | {
"resource": ""
} |
q17503 | ModelBase.copy_data_ext | train | def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):
"""
Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of th... | python | {
"resource": ""
} |
q17504 | ModelBase.elem_add | train | def elem_add(self, idx=None, name=None, **kwargs):
"""
Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx
"""
idx = self.system.devman.register_element(... | python | {
"resource": ""
} |
q17505 | ModelBase.elem_remove | train | def elem_remove(self, idx=None):
"""
Remove elements labeled by idx from this model instance.
:param list,matrix idx: indices of elements to be removed
:return: None
"""
if idx is not None:
if idx in self.uid:
key = idx
item = ... | python | {
"resource": ""
} |
q17506 | ModelBase.data_to_elem_base | train | def data_to_elem_base(self):
"""
Convert parameter data to element base
Returns
-------
None
"""
if self._flags['sysbase'] is False:
return
for key, val in self._store.items():
self.__dict__[key] = val
self._flags['sysbas... | python | {
"resource": ""
} |
q17507 | ModelBase._intf_network | train | def _intf_network(self):
"""
Retrieve the ac and dc network interface variable indices.
:Example:
``self._ac = {'bus1': (a1, v1)}`` gives
- indices: self.bus1
- system.Bus.a -> self.a1
- system.Bus.v -> self.v1
``self._dc = {'node... | python | {
"resource": ""
} |
q17508 | ModelBase._intf_ctrl | train | def _intf_ctrl(self):
"""
Retrieve variable indices of controlled models.
Control interfaces are specified in ``self._ctrl``.
Each ``key:value`` pair has ``key`` being the variable names
for the reference idx and ``value`` being a tuple of
``(model name, field to read, d... | python | {
"resource": ""
} |
q17509 | ModelBase._addr | train | def _addr(self):
"""
Assign dae addresses for algebraic and state variables.
Addresses are stored in ``self.__dict__[var]``.
``dae.m`` and ``dae.n`` are updated accordingly.
Returns
-------
None
"""
group_by = self._config['address_group_by']
... | python | {
"resource": ""
} |
q17510 | ModelBase._varname | train | def _varname(self):
"""
Set up variable names in ``self.system.varname``.
Variable names follows the convention ``VariableName,Model Name``.
A maximum of 24 characters are allowed for each variable.
:return: None
"""
if not self._flags['address']:
se... | python | {
"resource": ""
} |
q17511 | ModelBase._param_to_matrix | train | def _param_to_matrix(self):
"""
Convert parameters defined in `self._params` to `cvxopt.matrix`
:return None
"""
for item in self._params:
self.__dict__[item] = matrix(self.__dict__[item], tc='d') | python | {
"resource": ""
} |
q17512 | ModelBase._param_to_list | train | def _param_to_list(self):
"""
Convert parameters defined in `self._param` to list
:return None
"""
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | python | {
"resource": ""
} |
q17513 | ModelBase.log | train | def log(self, msg, level=INFO):
"""Record a line of log in logger
:param str msg: content of the messag
:param level: logging level
:return: None
"""
logger.log(level, '<{}> - '.format(self._name) + msg) | python | {
"resource": ""
} |
q17514 | ModelBase.init_limit | train | def init_limit(self, key, lower=None, upper=None, limit=False):
""" check if data is within limits. reset if violates"""
above = agtb(self.__dict__[key], upper)
for idx, item in enumerate(above):
if item == 0.:
continue
maxval = upper[idx]
self... | python | {
"resource": ""
} |
q17515 | ModelBase.doc | train | def doc(self, export='plain'):
"""
Build help document into a Texttable table
:param ('plain', 'latex') export: export format
:param save: save to file ``help_model.extension`` or not
:param writemode: file write mode
:return: None
"""
title = '<{}.{}>'.... | python | {
"resource": ""
} |
q17516 | ModelBase.check_limit | train | def check_limit(self, varname, vmin=None, vmax=None):
"""
Check if the variable values are within the limits.
Return False if fails.
"""
retval = True
assert varname in self.__dict__
if varname in self._algebs:
val = self.system.dae.y[self.__dict__[... | python | {
"resource": ""
} |
q17517 | ModelBase.on_bus | train | def on_bus(self, bus_idx):
"""
Return the indices of elements on the given buses for shunt-connected
elements
:param bus_idx: idx of the buses to which the elements are connected
:return: idx of elements connected to bus_idx
"""
assert hasattr(self, 'bus')
... | python | {
"resource": ""
} |
q17518 | ModelBase.link_bus | train | def link_bus(self, bus_idx):
"""
Return the indices of elements linking the given buses
:param bus_idx:
:return:
"""
ret = []
if not self._config['is_series']:
self.log(
'link_bus function is not valid for non-series model <{}>'.
... | python | {
"resource": ""
} |
q17519 | ModelBase.elem_find | train | def elem_find(self, field, value):
"""
Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of fiel... | python | {
"resource": ""
} |
q17520 | ModelBase._check_Vn | train | def _check_Vn(self):
"""Check data consistency of Vn and Vdcn if connected to Bus or Node
:return None
"""
if hasattr(self, 'bus') and hasattr(self, 'Vn'):
bus_Vn = self.read_data_ext('Bus', field='Vn', idx=self.bus)
for name, bus, Vn, Vn0 in zip(self.name, self.... | python | {
"resource": ""
} |
q17521 | PFLOW.reset | train | def reset(self):
"""
Reset all internal storage to initial status
Returns
-------
None
"""
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | python | {
"resource": ""
} |
q17522 | PFLOW.pre | train | def pre(self):
"""
Initialize system for power flow study
Returns
-------
None
"""
logger.info('-> Power flow study: {} method, {} start'.format(
self.config.method.upper(), 'flat' if self.config.flatstart else 'non-flat')
)
t, s = el... | python | {
"resource": ""
} |
q17523 | PFLOW.run | train | def run(self, **kwargs):
"""
call the power flow solution routine
Returns
-------
bool
True for success, False for fail
"""
ret = None
# initialization Y matrix and inital guess
self.pre()
t, _ = elapsed()
# call solu... | python | {
"resource": ""
} |
q17524 | PFLOW.newton | train | def newton(self):
"""
Newton power flow routine
Returns
-------
(bool, int)
success flag, number of iterations
"""
dae = self.system.dae
while True:
inc = self.calc_inc()
dae.x += inc[:dae.n]
dae.y += inc[d... | python | {
"resource": ""
} |
q17525 | PFLOW.dcpf | train | def dcpf(self):
"""
Calculate linearized power flow
Returns
-------
(bool, int)
success flag, number of iterations
"""
dae = self.system.dae
self.system.Bus.init0(dae)
self.system.dae.init_g()
Va0 = self.system.Bus.angle
... | python | {
"resource": ""
} |
q17526 | PFLOW._iter_info | train | def _iter_info(self, niter, level=logging.INFO):
"""
Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None
"""
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max misma... | python | {
"resource": ""
} |
q17527 | PFLOW.calc_inc | train | def calc_inc(self):
"""
Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b``
"""
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[... | python | {
"resource": ""
} |
q17528 | PFLOW.newton_call | train | def newton_call(self):
"""
Function calls for Newton power flow
Returns
-------
None
"""
# system = self.system
# exec(system.call.newton)
system = self.system
dae = self.system.dae
system.dae.init_fg()
system.dae.reset_... | python | {
"resource": ""
} |
q17529 | PFLOW.post | train | def post(self):
"""
Post processing for solved systems.
Store load, generation data on buses.
Store reactive power generation on PVs and slack generators.
Calculate series flows and area flows.
Returns
-------
None
"""
if not self.solved:... | python | {
"resource": ""
} |
q17530 | PV.init0 | train | def init0(self, dae):
"""
Set initial voltage and reactive power for PQ.
Overwrites Bus.voltage values
"""
dae.y[self.v] = self.v0
dae.y[self.q] = mul(self.u, self.qg) | python | {
"resource": ""
} |
q17531 | PV.disable_gen | train | def disable_gen(self, idx):
"""
Disable a PV element for TDS
Parameters
----------
idx
Returns
-------
"""
self.u[self.uid[idx]] = 0
self.system.dae.factorize = True | python | {
"resource": ""
} |
q17532 | PQ.init0 | train | def init0(self, dae):
"""Set initial p and q for power flow"""
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | python | {
"resource": ""
} |
q17533 | PQ.init1 | train | def init1(self, dae):
"""Set initial voltage for time domain simulation"""
self.v0 = matrix(dae.y[self.v]) | python | {
"resource": ""
} |
q17534 | Monitor.update_status | train | def update_status(self, header, message):
"""Process incoming status message. Acquire lock for status dictionary before updating."""
with self._lock:
if self.message_box:
self.message_box.erase()
self.message_box.move(0, 0)
for n, field in enum... | python | {
"resource": ""
} |
q17535 | Monitor._redraw_screen | train | def _redraw_screen(self, stdscr):
"""Redraw screen. This could be to initialize, or to redraw after resizing."""
with self._lock:
stdscr.clear()
stdscr.addstr(
0, 0, "workflows service monitor -- quit with Ctrl+C", curses.A_BOLD
)
stdscr.re... | python | {
"resource": ""
} |
q17536 | Monitor._erase_card | train | def _erase_card(self, number):
"""Destroy cards with this or higher number."""
with self._lock:
if number < (len(self.cards) - 1):
self._erase_card(number + 1)
if number > (len(self.cards) - 1):
return
max_cards_horiz = int(curses.COLS ... | python | {
"resource": ""
} |
q17537 | Monitor._run | train | def _run(self, stdscr):
"""Start the actual service monitor"""
with self._lock:
curses.use_default_colors()
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_BLACK, -1)
curses.init_pair(3, curses.... | python | {
"resource": ""
} |
q17538 | VSC.disable | train | def disable(self, idx):
"""Disable an element and reset the outputs"""
if idx not in self.uid.keys():
self.log('Element index {0} does not exist.'.format(idx))
return
self.u[self.uid[idx]] = 0 | python | {
"resource": ""
} |
q17539 | ConfigBase.get_alt | train | def get_alt(self, option):
"""
Return the alternative values of an option
Parameters
----------
option: str
option name
Returns
-------
str
a string of alternative options
"""
assert hasattr(self, option)
... | python | {
"resource": ""
} |
q17540 | ConfigBase.doc | train | def doc(self, export='plain'):
"""
Dump help document for setting classes
"""
rows = []
title = '<{:s}> config options'.format(self.__class__.__name__)
table = Tab(export=export, title=title)
for opt in sorted(self.config_descr):
if hasattr(self, opt)... | python | {
"resource": ""
} |
q17541 | ConfigBase.dump_conf | train | def dump_conf(self, conf=None):
"""
Dump settings to an rc config file
Parameters
----------
conf
configparser.ConfigParser() object
Returns
-------
None
"""
if conf is None:
conf = configparser.ConfigParser()
... | python | {
"resource": ""
} |
q17542 | ConfigBase.load_config | train | def load_config(self, conf):
"""
Load configurations from an rc file
Parameters
----------
rc: str
path to the rc file
Returns
-------
None
"""
section = self.__class__.__name__
if section not in conf.sections():
... | python | {
"resource": ""
} |
q17543 | UtilizationStatistics.update_status | train | def update_status(self, new_status):
"""Record a status change with a current timestamp."""
timestamp = time.time()
self.status_history[-1]["end"] = timestamp
self.status_history.append(
{"start": timestamp, "end": None, "status": new_status}
) | python | {
"resource": ""
} |
q17544 | UtilizationStatistics.report | train | def report(self):
"""Return a dictionary of different status codes and the percentage of time
spent in each throughout the last summation_period seconds.
Truncate the aggregated history appropriately."""
timestamp = time.time()
cutoff = timestamp - self.period
truncate = ... | python | {
"resource": ""
} |
q17545 | generate_unique_host_id | train | def generate_unique_host_id():
"""Generate a unique ID, that is somewhat guaranteed to be unique among all
instances running at the same time."""
host = ".".join(reversed(socket.gethostname().split(".")))
pid = os.getpid()
return "%s.%d" % (host, pid) | python | {
"resource": ""
} |
q17546 | GovernorBase.data_to_sys_base | train | def data_to_sys_base(self):
"""Custom system base conversion function"""
if not self.n or self._flags['sysbase'] is True:
return
self.copy_data_ext(model='Synchronous', field='Sn', dest='Sn', idx=self.gen)
super(GovernorBase, self).data_to_sys_base()
self._store['R']... | python | {
"resource": ""
} |
q17547 | GovernorBase.data_to_elem_base | train | def data_to_elem_base(self):
"""Custom system base unconversion function"""
if not self.n or self._flags['sysbase'] is False:
return
self.R = mul(self.R, self.Sn) / self.system.mva
super(GovernorBase, self).data_to_elem_base() | python | {
"resource": ""
} |
q17548 | add_suffix | train | def add_suffix(fullname, suffix):
""" Add suffix to a full file name"""
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext | python | {
"resource": ""
} |
q17549 | FileMan.get_fullpath | train | def get_fullpath(self, fullname=None, relative_to=None):
"""
Return the original full path if full path is specified, otherwise
search in the case file path
"""
# if is an empty path
if not fullname:
return fullname
isabs = os.path.isabs(fullname)
... | python | {
"resource": ""
} |
q17550 | eAGC.switch | train | def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> act... | python | {
"resource": ""
} |
q17551 | get_command | train | def get_command(all_pkg, hook):
"""
Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
-------
list
... | python | {
"resource": ""
} |
q17552 | EventBase.get_times | train | def get_times(self):
"""
Return a list of occurrance times of the events
:return: list of times
"""
if not self.n:
return list()
ret = list()
for item in self._event_times:
ret += list(self.__dict__[item])
return ret + list(matr... | python | {
"resource": ""
} |
q17553 | Line.build_y | train | def build_y(self):
"""Build transmission line admittance matrix into self.Y"""
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.ta... | python | {
"resource": ""
} |
q17554 | Line.incidence | train | def incidence(self):
"""Build incidence matrix into self.C"""
self.C = \
spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\
spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd') | python | {
"resource": ""
} |
q17555 | Line.connectivity | train | def connectivity(self, bus):
"""check connectivity of network using Goderya's algorithm"""
if not self.n:
return
n = self.nb
fr = self.a1
to = self.a2
os = [0] * self.n
# find islanded buses
diag = list(
matrix(
spm... | python | {
"resource": ""
} |
q17556 | Line.build_gy | train | def build_gy(self, dae):
"""Build line Jacobian matrix"""
if not self.n:
idx = range(dae.m)
dae.set_jac(Gy, 1e-6, idx, idx)
return
Vn = polar(1.0, dae.y[self.a])
Vc = mul(dae.y[self.v], Vn)
Ic = self.Y * Vc
diagVn = spdiag(Vn)
... | python | {
"resource": ""
} |
q17557 | Line.seriesflow | train | def seriesflow(self, dae):
"""
Compute the flow through the line after solving PF.
Compute terminal injections, line losses
"""
# Vm = dae.y[self.v]
# Va = dae.y[self.a]
# V1 = polar(Vm[self.a1], Va[self.a1])
# V2 = polar(Vm[self.a2], Va[self.a2])
... | python | {
"resource": ""
} |
q17558 | Line.switch | train | def switch(self, idx, u):
"""switch the status of Line idx"""
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)) | python | {
"resource": ""
} |
q17559 | Line.get_flow_by_idx | train | def get_flow_by_idx(self, idx, bus):
"""Return seriesflow based on the external idx on the `bus` side"""
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... | python | {
"resource": ""
} |
q17560 | Line.leaf_bus | train | def leaf_bus(self, df=False):
"""
Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame
"""
# leafs - leaf bus idx
# lines - line idx
# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking... | python | {
"resource": ""
} |
q17561 | Utilities.truncate | train | 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:
lis... | python | {
"resource": ""
} |
q17562 | VarName.resize_for_flows | train | def resize_for_flows(self):
"""Extend `unamey` and `fnamey` for bus injections and line flows"""
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 + \
... | python | {
"resource": ""
} |
q17563 | VarName.append | train | def append(self, listname, xy_idx, var_name, element_name):
"""Append variable names to the name lists"""
self.resize()
string = '{0} {1}'
if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:
logger.error('Wrong list name for varname.')
return
elif... | python | {
"resource": ""
} |
q17564 | VarName.bus_line_names | train | def bus_line_names(self):
"""Append bus injection and line flow names to `varname`"""
if self.system.tds.config.compute_flows:
self.system.Bus._varname_inj()
self.system.Line._varname_flow()
self.system.Area._varname_inter() | python | {
"resource": ""
} |
q17565 | VarName.get_xy_name | train | def get_xy_name(self, yidx, xidx=0):
"""
Return variable names for the given indices
:param yidx:
:param xidx:
:return:
"""
assert isinstance(xidx, int)
if isinstance(yidx, int):
yidx = [yidx]
uname = ['Time [s]'] + self.uname
... | python | {
"resource": ""
} |
q17566 | cli_parse | train | def cli_parse():
"""command line input parser"""
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 in... | python | {
"resource": ""
} |
q17567 | add_plot | train | def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):
"""Add plots to an existing plot"""
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_d... | python | {
"resource": ""
} |
q17568 | check_init | train | def check_init(yval, yl):
""""Check initialization by comparing t=0 and t=end values"""
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))
els... | python | {
"resource": ""
} |
q17569 | TDSData.load_lst | train | def load_lst(self):
"""
Load the lst file into internal data structures
"""
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 = ... | python | {
"resource": ""
} |
q17570 | TDSData.find_var | train | def find_var(self, query, formatted=False):
"""
Return variable names and indices matching ``query``
"""
# 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 zi... | python | {
"resource": ""
} |
q17571 | TDSData.load_dat | train | def load_dat(self, delimiter=','):
"""
Load the dat file into internal data structures, ``self._data``
"""
try:
data = np.loadtxt(self._dat_file, delimiter=',')
except ValueError:
data = np.loadtxt(self._dat_file)
self._data = data | python | {
"resource": ""
} |
q17572 | TDSData.get_values | train | def get_values(self, idx):
"""
Return the variable values at the given indices
"""
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | python | {
"resource": ""
} |
q17573 | TDSData.get_header | train | def get_header(self, idx, formatted=False):
"""
Return a list of the variable names at the given indices
"""
header = self._uname if not formatted else self._fname
return [header[x] for x in idx] | python | {
"resource": ""
} |
q17574 | TDSData.export_csv | train | 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 indice... | python | {
"resource": ""
} |
q17575 | Tab.auto_style | train | def auto_style(self):
"""
automatic styling according to _row_size
76 characters in a row
"""
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'])
... | python | {
"resource": ""
} |
q17576 | Tab.draw | train | def draw(self):
"""generate texttable formatted string"""
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... | python | {
"resource": ""
} |
q17577 | simpletab.guess_width | train | def guess_width(self):
"""auto fit column width"""
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
# ... | python | {
"resource": ""
} |
q17578 | JIT.jit_load | train | def jit_load(self):
"""
Import and instantiate this JIT object
Returns
-------
"""
try:
model = importlib.import_module('.' + self.model, 'andes.models')
device = getattr(model, self.device)
self.system.__dict__[self.name] = device(se... | python | {
"resource": ""
} |
q17579 | JIT.elem_add | train | def elem_add(self, idx=None, name=None, **kwargs):
"""overloading elem_add function of a JIT class"""
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | python | {
"resource": ""
} |
q17580 | SampleTxn.initializing | train | def initializing(self):
"""Subscribe to a channel. Received messages must be acknowledged."""
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | python | {
"resource": ""
} |
q17581 | SampleTxn.receive_message | train | def receive_message(self, header, message):
"""Receive a message"""
print("=== Receive ===")
print(header)
print(message)
print("MsgID: {0}".format(header["message-id"]))
assert header["message-id"]
txn = self._transport.transaction_begin()
print(" 1. T... | python | {
"resource": ""
} |
q17582 | SampleTxnProducer.create_message | train | def create_message(self):
"""Create and send a unique message for this service."""
self.counter += 1
self._transport.send(
"transient.transaction",
"TXMessage #%d\n++++++++Produced@ %f"
% (self.counter, (time.time() % 1000) * 1000),
)
self.log.... | python | {
"resource": ""
} |
q17583 | elapsed | train | def elapsed(t0=0.0):
"""get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string
"""
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
if dt_sec <= 1:
dt_str = str(dt... | python | {
"resource": ""
} |
q17584 | PSS1.set_flag | train | def set_flag(self, value, flag, reset_val=False):
"""Set a flag to 0 if the corresponding value is 0"""
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__... | python | {
"resource": ""
} |
q17585 | Report._update_summary | train | def _update_summary(self, system):
"""
Update the summary data
Parameters
----------
system
Returns
-------
None
"""
self.basic.update({
'nbus': system.Bus.n,
'ngen': system.PV.n + system.SW.n,
'ngen_on... | python | {
"resource": ""
} |
q17586 | Report._update_extended | train | def _update_extended(self, system):
"""Update the extended data"""
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.up... | python | {
"resource": ""
} |
q17587 | Report.update | train | def update(self, content=None):
"""
Update values based on the requested content
Parameters
----------
content
Returns
-------
"""
if not content:
return
if content == 'summary' or 'extended' or 'powerflow':
self.... | python | {
"resource": ""
} |
q17588 | RecipeWrapper.send | train | 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.
"""
i... | python | {
"resource": ""
} |
q17589 | RecipeWrapper._generate_full_recipe_message | train | def _generate_full_recipe_message(self, destination, message, add_path_step):
"""Factory function to generate independent message objects for
downstream recipients with different destinations."""
if add_path_step and self.recipe_pointer:
recipe_path = self.recipe_path + [self.recipe_... | python | {
"resource": ""
} |
q17590 | RecipeWrapper._send_to_destinations | train | 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.
"""
if not isinstance(destinations, list):
destinations = (destinations,)
... | python | {
"resource": ""
} |
q17591 | RecipeWrapper._send_to_destination | train | 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."""
if header:
header = header.copy()
header["workflows-recipe"] = True
else:
... | python | {
"resource": ""
} |
q17592 | RtmBot.on_message | train | def on_message(self, event):
'''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=meta... | python | {
"resource": ""
} |
q17593 | RtmBot.find_and_replace_userids | train | 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.
'''
match = True
... | python | {
"resource": ""
} |
q17594 | RtmBot.find_and_replace_channel_refs | train | 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.
... | python | {
"resource": ""
} |
q17595 | RtmBot.get_channels | train | 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
... | python | {
"resource": ""
} |
q17596 | RtmBot.get_users | train | 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
... | python | {
"resource": ""
} |
q17597 | RtmBot.get_user_display_name | train | 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
'''
user_info = self.slack_client.api_call('u... | python | {
"resource": ""
} |
q17598 | RtmBot.get_dm_channel | train | 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
'''
dm_open = self.slack_client.api_call('im.open', user=userid)
... | python | {
"resource": ""
} |
q17599 | RtmBot.get_username | train | 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
'''
username = self.user_map.get(userid)
if not userna... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.