_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55700 | remove_number_words | train | def remove_number_words(text_string):
'''
Removes any integer represented as a word within text_string and returns the new string as
type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if te... | python | {
"resource": ""
} |
q55701 | remove_urls | train | def remove_urls(text_string):
'''
Removes all URLs within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None or text_string == "... | python | {
"resource": ""
} |
q55702 | remove_whitespace | train | def remove_whitespace(text_string):
'''
Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument
'''
if text_st... | python | {
"resource": ""
} |
q55703 | WrappedLogger.log | train | def log(self, level, message, *args, **kwargs):
"""
This is the primary method to override to ensure logging with extra
options gets correctly specified.
"""
extra = self.extras.copy()
extra.update(kwargs.pop('extra', {}))
kwargs['extra'] = extra
self.log... | python | {
"resource": ""
} |
q55704 | WrappedLogger.warning | train | def warning(self, message, *args, **kwargs):
"""
Specialized warnings system. If a warning subclass is passed into
the keyword arguments and raise_warnings is True - the warnning will
be passed to the warnings module.
"""
warncls = kwargs.pop('warning', None)
if w... | python | {
"resource": ""
} |
q55705 | ServiceLogger.log | train | def log(self, level, message, *args, **kwargs):
"""
Provide current user as extra context to the logger
"""
extra = kwargs.pop('extra', {})
extra.update({
'user': self.user
})
kwargs['extra'] = extra
super(ServiceLogger, self).log(level, messa... | python | {
"resource": ""
} |
q55706 | LoggingMixin.logger | train | def logger(self):
"""
Instantiates and returns a ServiceLogger instance
"""
if not hasattr(self, '_logger') or not self._logger:
self._logger = ServiceLogger()
return self._logger | python | {
"resource": ""
} |
q55707 | ot_find_studies | train | def ot_find_studies(arg_dict, exact=True, verbose=False, oti_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of studies
including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyot... | python | {
"resource": ""
} |
q55708 | main | train | def main(argv):
"""This function sets up a command-line option parser and then calls print_matching_trees
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to try to find a tree with the value property pair specified. ' \
'setting --... | python | {
"resource": ""
} |
q55709 | main | train | def main(argv):
"""This function sets up a command-line option parser and then calls
to do all of the real work.
"""
import argparse
import codecs
# have to be ready to deal with utf-8 names
out = codecs.getwriter('utf-8')(sys.stdout)
description = '''Takes a series of at least 2 OTT ids... | python | {
"resource": ""
} |
q55710 | is_sequence | train | def is_sequence(value):
"""Determine if a value is a sequence type.
Returns:
``True`` if `value` is a sequence type (e.g., ``list``, or ``tuple``).
String types will return ``False``.
NOTE: On Python 3, strings have the __iter__ defined, so a simple hasattr
check is insufficient.
"""
... | python | {
"resource": ""
} |
q55711 | import_class | train | def import_class(classpath):
"""Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an error occurs while importing the mo... | python | {
"resource": ""
} |
q55712 | resolve_class | train | def resolve_class(classref):
"""Attempt to return a Python class for the input class reference.
If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.
Args:
classref: A fully-qualified Python path to class,... | python | {
"resource": ""
} |
q55713 | needkwargs | train | def needkwargs(*argnames):
"""Function decorator which checks that the decorated function is called
with a set of required kwargs.
Args:
*argnames: String keyword argument names.
Raises:
ValueError: If a required kwarg is missing in the decorated function
call.
"""
... | python | {
"resource": ""
} |
q55714 | get | train | def get(host="localhost", port=3551, timeout=30):
"""
Connect to the APCUPSd NIS and request its status.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((host, port))
sock.send(CMD_STATUS)
buffr = ""
while not buffr.endswith(EOF):
... | python | {
"resource": ""
} |
q55715 | strip_units_from_lines | train | def strip_units_from_lines(lines):
"""
Removes all units from the ends of the lines.
"""
for line in lines:
for unit in ALL_UNITS:
if line.endswith(" %s" % unit):
line = line[:-1-len(unit)]
yield line | python | {
"resource": ""
} |
q55716 | print_status | train | def print_status(raw_status, strip_units=False):
"""
Print the status to stdout in the same format as the original apcaccess.
"""
lines = split(raw_status)
if strip_units:
lines = strip_units_from_lines(lines)
for line in lines:
print(line) | python | {
"resource": ""
} |
q55717 | _TaxomachineAPIWrapper.get_cached_parent_for_taxon | train | def get_cached_parent_for_taxon(self, child_taxon):
"""If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral TaxonWrapper.
"""
... | python | {
"resource": ""
} |
q55718 | TaxonWrapper.update_empty_fields | train | def update_empty_fields(self, **kwargs):
"""Updates the field of info about an OTU that might not be filled in by a match_names or taxon call."""
if self._is_deprecated is None:
self._is_deprecated = kwargs.get('is_deprecated')
if self._is_dubious is None:
self._is_dubiou... | python | {
"resource": ""
} |
q55719 | _check_rev_dict | train | def _check_rev_dict(tree, ebt):
"""Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`"""
ebs = defaultdict(dict)
for edge in ebt.values():
source_id = edge['@source']
edge_id = edge['@id']
ebs[source_id][edge_id] = edge
assert ebs == tree['edgeBySou... | python | {
"resource": ""
} |
q55720 | NexsonTreeWrapper._create_edge_by_target | train | def _create_edge_by_target(self):
"""creates a edge_by_target dict with the same edge objects as the edge_by_source.
Also adds an '@id' field to each edge."""
ebt = {}
for edge_dict in self._edge_by_source.values():
for edge_id, edge in edge_dict.items():
targ... | python | {
"resource": ""
} |
q55721 | NexsonTreeWrapper.prune_to_ingroup | train | def prune_to_ingroup(self):
"""Remove nodes and edges from tree if they are not the ingroup or a descendant of it."""
# Prune to just the ingroup
if not self._ingroup_node_id:
_LOG.debug('No ingroup node was specified.')
self._ingroup_node_id = self.root_node_id
e... | python | {
"resource": ""
} |
q55722 | NexsonTreeWrapper.prune_clade | train | def prune_clade(self, node_id):
"""Prune `node_id` and the edges and nodes that are tipward of it.
Caller must delete the edge to node_id."""
to_del_nodes = [node_id]
while bool(to_del_nodes):
node_id = to_del_nodes.pop(0)
self._flag_node_as_del_and_del_in_by_targ... | python | {
"resource": ""
} |
q55723 | NexsonTreeWrapper.suppress_deg_one_node | train | def suppress_deg_one_node(self, to_par_edge, nd_id, to_child_edge):
"""Deletes to_par_edge and nd_id. To be used when nd_id is an out-degree= 1 node"""
# circumvent the node with nd_id
to_child_edge_id = to_child_edge['@id']
par = to_par_edge['@source']
self._edge_by_source[par][... | python | {
"resource": ""
} |
q55724 | MethodInfo.describe | train | def describe(self):
"""Describes the method.
:return: Description
:rtype: dict[str, object]
"""
return {
"name": self.name,
"params": self.params,
"returns": self.returns,
"description": self.description,
} | python | {
"resource": ""
} |
q55725 | MethodInfo.params | train | def params(self):
"""The parameters for this method in a JSON-compatible format
:rtype: list[dict[str, str]]
"""
return [{"name": p_name, "type": p_type.__name__}
for (p_name, p_type) in self.signature.parameter_types] | python | {
"resource": ""
} |
q55726 | MethodInfo.returns | train | def returns(self):
"""The return type for this method in a JSON-compatible format.
This handles the special case of ``None`` which allows ``type(None)`` also.
:rtype: str | None
"""
return_type = self.signature.return_type
none_type = type(None)
if return_type i... | python | {
"resource": ""
} |
q55727 | MethodSignature.create | train | def create(parameter_names, parameter_types, return_type):
"""Returns a signature object ensuring order of parameter names and types.
:param parameter_names: A list of ordered parameter names
:type parameter_names: list[str]
:param parameter_types: A dictionary of parameter names to typ... | python | {
"resource": ""
} |
q55728 | Nexml2Nexson._hbf_handle_child_elements | train | def _hbf_handle_child_elements(self, obj, ntl):
"""
Indirect recursion through _gen_hbf_el
"""
# accumulate a list of the children names in ko, and
# the a dictionary of tag to xml elements.
# repetition of a tag means that it will map to a list of
# xml eleme... | python | {
"resource": ""
} |
q55729 | get_xml_parser | train | def get_xml_parser(encoding=None):
"""Returns an ``etree.ETCompatXMLParser`` instance."""
parser = etree.ETCompatXMLParser(
huge_tree=True,
remove_comments=True,
strip_cdata=False,
remove_blank_text=True,
resolve_entities=False,
encoding=encoding
)
return... | python | {
"resource": ""
} |
q55730 | get_etree_root | train | def get_etree_root(doc, encoding=None):
"""Returns an instance of lxml.etree._Element for the given `doc` input.
Args:
doc: The input XML document. Can be an instance of
``lxml.etree._Element``, ``lxml.etree._ElementTree``, a file-like
object, or a string filename.
encod... | python | {
"resource": ""
} |
q55731 | strip_cdata | train | def strip_cdata(text):
"""Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped str... | python | {
"resource": ""
} |
q55732 | TypedList._is_valid | train | def _is_valid(self, value):
"""Return True if the input value is valid for insertion into the
inner list.
Args:
value: An object about to be inserted.
"""
# Entities have an istypeof method that can perform more sophisticated
# type checking.
if hasa... | python | {
"resource": ""
} |
q55733 | TypedList._fix_value | train | def _fix_value(self, value):
"""Attempt to coerce value into the correct type.
Subclasses can override this function.
"""
try:
return self._castfunc(value)
except:
error = "Can't put '{0}' ({1}) into a {2}. Expected a {3} object."
error = erro... | python | {
"resource": ""
} |
q55734 | JSGPairDef.members_entries | train | def members_entries(self, all_are_optional: Optional[bool] = False) -> List[Tuple[str, str]]:
""" Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing
reference types
:param all_are_optional: If true, all types are forced optional
:return: raw... | python | {
"resource": ""
} |
q55735 | JSGPairDef._initializer_for | train | def _initializer_for(self, raw_name: str, cooked_name: str, prefix: Optional[str]) -> List[str]:
"""Create an initializer entry for the entry
:param raw_name: name unadjusted for python compatibility.
:param cooked_name: name that may or may not be python compatible
:param prefix: owne... | python | {
"resource": ""
} |
q55736 | HolderProver._assert_link_secret | train | def _assert_link_secret(self, action: str):
"""
Raise AbsentLinkSecret if link secret is not set.
:param action: action requiring link secret
"""
if self._link_secret is None:
LOGGER.debug('HolderProver._assert_link_secret: action %s requires link secret but it is n... | python | {
"resource": ""
} |
q55737 | HolderProver.rev_regs | train | def rev_regs(self) -> list:
"""
Return list of revocation registry identifiers for which HolderProver has tails files.
:return: list of revocation registry identifiers for which HolderProver has tails files
"""
LOGGER.debug('HolderProver.rev_regs >>>')
rv = [basename(f... | python | {
"resource": ""
} |
q55738 | HolderProver.create_cred_req | train | async def create_cred_req(self, cred_offer_json: str, cd_id: str) -> (str, str):
"""
Create credential request as HolderProver and store in wallet; return credential json and metadata json.
Raise AbsentLinkSecret if link secret not set.
:param cred_offer_json: credential offer json
... | python | {
"resource": ""
} |
q55739 | HolderProver.load_cache | train | async def load_cache(self, archive: bool = False) -> int:
"""
Load caches and archive enough to go offline and be able to generate proof
on all credentials in wallet.
Return timestamp (epoch seconds) of cache load event, also used as subdirectory
for cache archives.
:re... | python | {
"resource": ""
} |
q55740 | HolderProver.get_creds | train | async def get_creds(self, proof_req_json: str, filt: dict = None, filt_dflt_incl: bool = False) -> (Set[str], str):
"""
Get credentials from HolderProver wallet corresponding to proof request and
filter criteria; return credential identifiers from wallet and credentials json.
Return empt... | python | {
"resource": ""
} |
q55741 | HolderProver.get_creds_by_id | train | async def get_creds_by_id(self, proof_req_json: str, cred_ids: set) -> str:
"""
Get creds structure from HolderProver wallet by credential identifiers.
:param proof_req_json: proof request as per get_creds() above
:param cred_ids: set of credential identifiers of interest
:retur... | python | {
"resource": ""
} |
q55742 | histogram | train | def histogram(data):
"""Returns a histogram of your data.
:param data: The data to histogram
:type data: list[object]
:return: The histogram
:rtype: dict[object, int]
"""
ret = {}
for datum in data:
if datum in ret:
ret[datum] += 1
else:
ret[datum... | python | {
"resource": ""
} |
q55743 | print_data | train | def print_data(data):
"""Prints object key-value pairs in a custom format
:param data: The dict to print
:type data: dict
:rtype: None
"""
print(", ".join(["{}=>{}".format(key, value) for key, value in data])) | python | {
"resource": ""
} |
q55744 | subdir_findall | train | def subdir_findall(dir, subdir):
"""
Find all files in a subdirectory and return paths relative to dir
This is similar to (and uses) setuptools.findall
However, the paths returned are in the form needed for package_data
"""
strip_n = len(dir.split('/'))
path = '/'.join((dir, subdir))
re... | python | {
"resource": ""
} |
q55745 | find_package_data | train | def find_package_data(packages):
"""
For a list of packages, find the package_data
This function scans the subdirectories of a package and considers all
non-submodule subdirectories as resources, including them in
the package_data
Returns a dictionary suitable for setup(package_data=<result>)
... | python | {
"resource": ""
} |
q55746 | process_file_metrics | train | def process_file_metrics(context, file_processors):
"""Main routine for metrics."""
file_metrics = OrderedDict()
# TODO make available the includes and excludes feature
gitignore = []
if os.path.isfile('.gitignore'):
with open('.gitignore', 'r') as ifile:
gitignore = ifile.read(... | python | {
"resource": ""
} |
q55747 | process_build_metrics | train | def process_build_metrics(context, build_processors):
"""use processors to collect build metrics."""
build_metrics = OrderedDict()
# reset all processors
for p in build_processors:
p.reset()
# collect metrics from all processors
for p in build_processors:
build_metrics.update(p... | python | {
"resource": ""
} |
q55748 | summary | train | def summary(processors, metrics, context):
"""Print the summary"""
# display aggregated metric values on language level
def display_header(processors, before='', after=''):
"""Display the header for the summary results."""
print(before, end=' ')
for processor in processors:
... | python | {
"resource": ""
} |
q55749 | get_portfolios3 | train | def get_portfolios3():
""" Returns portfolios with U12 and U20 generators removed and generators
of the same type at the same bus aggregated.
"""
g1 = [0]
g2 = [1]
g7 = [2]
g13 = [3]
g14 = [4] # sync cond
g15 = [5]
g16 = [6]
g18 = [7]
g21 = [8]
g22 = [9]
g23 = [10... | python | {
"resource": ""
} |
q55750 | ModelListener.call | train | def call(self, tag_name: str, *args, **kwargs):
"""Convenience method for calling methods with walker."""
if hasattr(self, tag_name):
getattr(self, tag_name)(*args, **kwargs) | python | {
"resource": ""
} |
q55751 | ModelListener.der | train | def der(self, x: Sym):
"""Get the derivative of the variable, create it if it doesn't exist."""
name = 'der({:s})'.format(x.name())
if name not in self.scope['dvar'].keys():
self.scope['dvar'][name] = self.sym.sym(name, *x.shape)
self.scope['states'].append(x.name())
... | python | {
"resource": ""
} |
q55752 | ModelListener.noise_gaussian | train | def noise_gaussian(self, mean, std):
"""Create a gaussian noise variable"""
assert std > 0
ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng'])))
self.scope['ng'].append(ng)
return mean + std*ng | python | {
"resource": ""
} |
q55753 | ModelListener.noise_uniform | train | def noise_uniform(self, lower_bound, upper_bound):
"""Create a uniform noise variable"""
assert upper_bound > lower_bound
nu = self.sym.sym('nu_{:d}'.format(len(self.scope['nu'])))
self.scope['nu'].append(nu)
return lower_bound + nu*(upper_bound - lower_bound) | python | {
"resource": ""
} |
q55754 | ModelListener.log | train | def log(self, *args, **kwargs):
"""Convenience function for printing indenting debug output."""
if self.verbose:
print(' ' * self.depth, *args, **kwargs) | python | {
"resource": ""
} |
q55755 | get_case6ww | train | def get_case6ww():
""" Returns the 6 bus case from Wood & Wollenberg PG&C.
"""
path = os.path.dirname(pylon.__file__)
path = os.path.join(path, "test", "data")
path = os.path.join(path, "case6ww", "case6ww.pkl")
case = pylon.Case.load(path)
case.generators[0].p_cost = (0.0, 4.0, 200.0)
... | python | {
"resource": ""
} |
q55756 | get_case24_ieee_rts | train | def get_case24_ieee_rts():
""" Returns the 24 bus IEEE Reliability Test System.
"""
path = os.path.dirname(pylon.__file__)
path = os.path.join(path, "test", "data")
path = os.path.join(path, "case24_ieee_rts", "case24_ieee_rts.pkl")
case = pylon.Case.load(path)
# FIXME: Correct generator n... | python | {
"resource": ""
} |
q55757 | get_discrete_task_agent | train | def get_discrete_task_agent(generators, market, nStates, nOffer, markups,
withholds, maxSteps, learner, Pd0=None, Pd_min=0.0):
""" Returns a tuple of task and agent for the given learner.
"""
env = pyreto.discrete.MarketEnvironment(generators, market,
numS... | python | {
"resource": ""
} |
q55758 | get_zero_task_agent | train | def get_zero_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always zero.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.ZeroAgent(env.outdim, env.i... | python | {
"resource": ""
} |
q55759 | get_neg_one_task_agent | train | def get_neg_one_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always minus one.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.NegOneAgent(env.out... | python | {
"resource": ""
} |
q55760 | run_experiment | train | def run_experiment(experiment, roleouts, episodes, in_cloud=False,
dynProfile=None):
""" Runs the given experiment and returns the results.
"""
def run():
if dynProfile is None:
maxsteps = len(experiment.profile) # episode length
else:
maxsteps = dy... | python | {
"resource": ""
} |
q55761 | get_full_year | train | def get_full_year():
""" Returns percentages of peak load for all hours of the year.
@return:
Numpy array of doubles with length 8736.
"""
weekly = get_weekly()
daily = get_daily()
hourly_winter_wkdy, hourly_winter_wknd = get_winter_hourly()
hourly_summer_wkdy, hourly_summer_wknd = ... | python | {
"resource": ""
} |
q55762 | get_all_days | train | def get_all_days():
""" Returns percentages of peak load for all days of the year.
Data from the IEEE RTS.
"""
weekly = get_weekly()
daily = get_daily()
return [w * (d / 100.0) for w in weekly for d in daily] | python | {
"resource": ""
} |
q55763 | get_q_experiment | train | def get_q_experiment(case, minor=1):
""" Returns an experiment that uses Q-learning.
"""
gen = case.generators
profile = array([1.0])
maxSteps = len(profile)
if minor == 1:
alpha = 0.3 # Learning rate.
gamma = 0.99 # Discount factor
# The closer epsilon gets to 0, the m... | python | {
"resource": ""
} |
q55764 | Generator.q_limited | train | def q_limited(self):
""" Is the machine at it's limit of reactive power?
"""
if (self.q >= self.q_max) or (self.q <= self.q_min):
return True
else:
return False | python | {
"resource": ""
} |
q55765 | Generator.total_cost | train | def total_cost(self, p=None, p_cost=None, pcost_model=None):
""" Computes total cost for the generator at the given output level.
"""
p = self.p if p is None else p
p_cost = self.p_cost if p_cost is None else p_cost
pcost_model = self.pcost_model if pcost_model is None else pcost... | python | {
"resource": ""
} |
q55766 | Generator.poly_to_pwl | train | def poly_to_pwl(self, n_points=4):
""" Sets the piece-wise linear cost attribute, converting the
polynomial cost variable by evaluating at zero and then at n_points
evenly spaced points between p_min and p_max.
"""
assert self.pcost_model == POLYNOMIAL
p_min = self.p_min
... | python | {
"resource": ""
} |
q55767 | Generator.get_offers | train | def get_offers(self, n_points=6):
""" Returns quantity and price offers created from the cost function.
"""
from pyreto.smart_market import Offer
qtyprc = self._get_qtyprc(n_points)
return [Offer(self, qty, prc) for qty, prc in qtyprc] | python | {
"resource": ""
} |
q55768 | Generator.get_bids | train | def get_bids(self, n_points=6):
""" Returns quantity and price bids created from the cost function.
"""
from pyreto.smart_market import Bid
qtyprc = self._get_qtyprc(n_points)
return [Bid(self, qty, prc) for qty, prc in qtyprc] | python | {
"resource": ""
} |
q55769 | Generator.offers_to_pwl | train | def offers_to_pwl(self, offers):
""" Updates the piece-wise linear total cost function using the given
offer blocks.
Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC
Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
"""
assert no... | python | {
"resource": ""
} |
q55770 | Generator.bids_to_pwl | train | def bids_to_pwl(self, bids):
""" Updates the piece-wise linear total cost function using the given
bid blocks.
Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC
Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
"""
assert self.is_... | python | {
"resource": ""
} |
q55771 | Generator._adjust_limits | train | def _adjust_limits(self):
""" Sets the active power limits, 'p_max' and 'p_min', according to
the pwl cost function points.
"""
if not self.is_load:
# self.p_min = min([point[0] for point in self.p_cost])
self.p_max = max([point[0] for point in self.p_cost])
... | python | {
"resource": ""
} |
q55772 | MarketEnvironment.indim | train | def indim(self):
""" The number of action values that the environment accepts.
"""
indim = self.numOffbids * len(self.generators)
if self.maxWithhold is not None:
return indim * 2
else:
return indim | python | {
"resource": ""
} |
q55773 | MarketEnvironment._getBusVoltageLambdaSensor | train | def _getBusVoltageLambdaSensor(self):
""" Returns an array of length nb where each value is the sum of the
Lagrangian multipliers on the upper and the negative of the Lagrangian
multipliers on the lower voltage limits. """
muVmin = array([b.mu_vmin for b in self.market.case.connected_bus... | python | {
"resource": ""
} |
q55774 | DoxyfileParse | train | def DoxyfileParse(file_contents):
"""
Parse a Doxygen source file and return a dictionary of all the values.
Values will be strings and lists of strings.
"""
data = {}
import shlex
lex = shlex.shlex(instream = file_contents, posix = True)
lex.wordchars += "*+./-:"
lex.whitespace = lex.whites... | python | {
"resource": ""
} |
q55775 | DoxySourceScan | train | def DoxySourceScan(node, env, path):
"""
Doxygen Doxyfile source scanner. This should scan the Doxygen file and add
any files used to generate docs to the list of source files.
"""
default_file_patterns = [
'*.c', '*.cc', '*.cxx', '*.cpp', '*.c++', '*.java', '*.ii', '*.ixx',
'*.ipp', '*.i++'... | python | {
"resource": ""
} |
q55776 | DoxyEmitter | train | def DoxyEmitter(source, target, env):
"""Doxygen Doxyfile emitter"""
# possible output formats and their default values and output locations
output_formats = {
"HTML": ("YES", "html"),
"LATEX": ("YES", "latex"),
"RTF": ("NO", "rtf"),
"MAN": ("YES", "man"),
"XML": ("NO", "xml"),
... | python | {
"resource": ""
} |
q55777 | generate | train | def generate(env):
"""
Add builders and construction variables for the
Doxygen tool. This is currently for Doxygen 1.4.6.
"""
doxyfile_scanner = env.Scanner(
DoxySourceScan,
"DoxySourceScan",
scan_check = DoxySourceScanCheck,
)
import SCons.Builder
doxyfile_builder = SCons.Bu... | python | {
"resource": ""
} |
q55778 | PosMetric.reset | train | def reset(self):
"""Reset metric counter."""
self._positions = []
self._line = 1
self._curr = None # current scope we are analyzing
self._scope = 0
self.language = None | python | {
"resource": ""
} |
q55779 | PosMetric.add_scope | train | def add_scope(self, scope_type, scope_name, scope_start, is_method=False):
"""we identified a scope and add it to positions."""
if self._curr is not None:
self._curr['end'] = scope_start - 1 # close last scope
self._curr = {
'type': scope_type, 'name': scope_name,
... | python | {
"resource": ""
} |
q55780 | PosMetric.process_token | train | def process_token(self, tok):
"""count lines and track position of classes and functions"""
if tok[0] == Token.Text:
count = tok[1].count('\n')
if count:
self._line += count # adjust linecount
if self._detector.process(tok):
pass # works bee... | python | {
"resource": ""
} |
q55781 | _Solver._unpack_model | train | def _unpack_model(self, om):
""" Returns data from the OPF model.
"""
buses = om.case.connected_buses
branches = om.case.online_branches
gens = om.case.online_generators
cp = om.get_cost_params()
# Bf = om._Bf
# Pfinj = om._Pfinj
return buses, bra... | python | {
"resource": ""
} |
q55782 | _Solver._dimension_data | train | def _dimension_data(self, buses, branches, generators):
""" Returns the problem dimensions.
"""
ipol = [i for i, g in enumerate(generators)
if g.pcost_model == POLYNOMIAL]
ipwl = [i for i, g in enumerate(generators)
if g.pcost_model == PW_LINEAR]
n... | python | {
"resource": ""
} |
q55783 | _Solver._linear_constraints | train | def _linear_constraints(self, om):
""" Returns the linear problem constraints.
"""
A, l, u = om.linear_constraints() # l <= A*x <= u
# Indexes for equality, greater than (unbounded above), less than
# (unbounded below) and doubly-bounded box constraints.
# ieq = flatnonze... | python | {
"resource": ""
} |
q55784 | _Solver._var_bounds | train | def _var_bounds(self):
""" Returns bounds on the optimisation variables.
"""
x0 = array([])
xmin = array([])
xmax = array([])
for var in self.om.vars:
x0 = r_[x0, var.v0]
xmin = r_[xmin, var.vl]
xmax = r_[xmax, var.vu]
return ... | python | {
"resource": ""
} |
q55785 | _Solver._initial_interior_point | train | def _initial_interior_point(self, buses, generators, xmin, xmax, ny):
""" Selects an interior initial point for interior point solver.
"""
Va = self.om.get_var("Va")
va_refs = [b.v_angle * pi / 180.0 for b in buses
if b.type == REFERENCE]
x0 = (xmin + xmax) / 2... | python | {
"resource": ""
} |
q55786 | DCOPFSolver.solve | train | def solve(self):
""" Solves DC optimal power flow and returns a results dict.
"""
base_mva = self.om.case.base_mva
Bf = self.om._Bf
Pfinj = self.om._Pfinj
# Unpack the OPF model.
bs, ln, gn, cp = self._unpack_model(self.om)
# Compute problem dimensions.
... | python | {
"resource": ""
} |
q55787 | DCOPFSolver._pwl_costs | train | def _pwl_costs(self, ny, nxyz, ipwl):
""" Returns the piece-wise linear components of the objective function.
"""
any_pwl = int(ny > 0)
if any_pwl:
y = self.om.get_var("y")
# Sum of y vars.
Npwl = csr_matrix((ones(ny), (zeros(ny), array(ipwl) + y.i1)))... | python | {
"resource": ""
} |
q55788 | DCOPFSolver._quadratic_costs | train | def _quadratic_costs(self, generators, ipol, nxyz, base_mva):
""" Returns the quadratic cost components of the objective function.
"""
npol = len(ipol)
rnpol = range(npol)
gpol = [g for g in generators if g.pcost_model == POLYNOMIAL]
if [g for g in gpol if len(g.p_cost) ... | python | {
"resource": ""
} |
q55789 | DCOPFSolver._combine_costs | train | def _combine_costs(self, Npwl, Hpwl, Cpwl, fparm_pwl, any_pwl,
Npol, Hpol, Cpol, fparm_pol, npol, nw):
""" Combines pwl, polynomial and user-defined costs.
"""
NN = vstack([n for n in [Npwl, Npol] if n is not None], "csr")
if (Hpwl is not None) and (Hpol is not No... | python | {
"resource": ""
} |
q55790 | DCOPFSolver._transform_coefficients | train | def _transform_coefficients(self, NN, HHw, CCw, ffparm, polycf,
any_pwl, npol, nw):
""" Transforms quadratic coefficients for w into coefficients for x.
"""
nnw = any_pwl + npol + nw
M = csr_matrix((ffparm[:, 3], (range(nnw), range(nnw))))
MR = M * ... | python | {
"resource": ""
} |
q55791 | PIPSSolver._ref_bus_angle_constraint | train | def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax):
""" Adds a constraint on the reference bus angles.
"""
refs = [bus._i for bus in buses if bus.type == REFERENCE]
Varefs = array([b.v_angle for b in buses if b.type == REFERENCE])
xmin[Va.i1 - 1 + refs] = Varefs
... | python | {
"resource": ""
} |
q55792 | PIPSSolver._f | train | def _f(self, x, user_data=None):
""" Evaluates the objective function.
"""
p_gen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u.
q_gen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u.
# Polynomial cost of P and Q.
xx = r_[p_gen, q_gen] * self._... | python | {
"resource": ""
} |
q55793 | PIPSSolver._df | train | def _df(self, x, user_data=None):
""" Evaluates the cost gradient.
"""
p_gen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u.
q_gen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u.
# Polynomial cost of P and Q.
xx = r_[p_gen, q_gen] * self._base... | python | {
"resource": ""
} |
q55794 | PIPSSolver._d2f | train | def _d2f(self, x):
""" Evaluates the cost Hessian.
"""
d2f_dPg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Pg
d2f_dQg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Qg]
for i in self._ipol:
p_cost = list(self._gn[i].p_cost)
d2f_dPg2[i, 0] = polyval(polyder(p_cos... | python | {
"resource": ""
} |
q55795 | PIPSSolver._gh | train | def _gh(self, x):
""" Evaluates the constraint function values.
"""
Pgen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u.
Qgen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u.
for i, gen in enumerate(self._gn):
gen.p = Pgen[i] * self._base_m... | python | {
"resource": ""
} |
q55796 | PIPSSolver._costfcn | train | def _costfcn(self, x):
""" Evaluates the objective function, gradient and Hessian for OPF.
"""
f = self._f(x)
df = self._df(x)
d2f = self._d2f(x)
return f, df, d2f | python | {
"resource": ""
} |
q55797 | PIPSSolver._consfcn | train | def _consfcn(self, x):
""" Evaluates nonlinear constraints and their Jacobian for OPF.
"""
h, g = self._gh(x)
dh, dg = self._dgh(x)
return h, g, dh, dg | python | {
"resource": ""
} |
q55798 | PickleReader.read | train | def read(self, file_or_filename):
""" Loads a pickled case.
"""
if isinstance(file_or_filename, basestring):
fname = os.path.basename(file_or_filename)
logger.info("Unpickling case file [%s]." % fname)
file = None
try:
file = open(... | python | {
"resource": ""
} |
q55799 | PickleWriter.write | train | def write(self, file_or_filename):
""" Writes the case to file using pickle.
"""
if isinstance(file_or_filename, basestring):
fname = os.path.basename(file_or_filename)
logger.info("Pickling case [%s]." % fname)
file = None
try:
fi... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.