_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55900 | Watcher.get_cmd | train | def get_cmd(self):
"""Returns the full command to be executed at runtime"""
cmd = None
if self.test_program in ('nose', 'nosetests'):
cmd = "nosetests %s" % self.file_path
elif self.test_program == 'django':
executable = "%s/manage.py" % self.file_path
... | python | {
"resource": ""
} |
q55901 | Watcher.include | train | def include(self, path):
"""Returns `True` if the file is not ignored"""
for extension in IGNORE_EXTENSIONS:
if path.endswith(extension):
return False
parts = path.split(os.path.sep)
for part in parts:
if part in self.ignore_dirs:
r... | python | {
"resource": ""
} |
q55902 | Watcher.diff_list | train | def diff_list(self, list1, list2):
"""Extracts differences between lists. For debug purposes"""
for key in list1:
if key in list2 and list2[key] != list1[key]:
print key
elif key not in list2:
print key | python | {
"resource": ""
} |
q55903 | Watcher.run | train | def run(self, cmd):
"""Runs the appropriate command"""
print datetime.datetime.now()
output = subprocess.Popen(cmd, shell=True)
output = output.communicate()[0]
print output | python | {
"resource": ""
} |
q55904 | Watcher.loop | train | def loop(self):
"""Main loop daemon."""
while True:
sleep(1)
new_file_list = self.walk(self.file_path, {})
if new_file_list != self.file_list:
if self.debug:
self.diff_list(new_file_list, self.file_list)
self.run_tes... | python | {
"resource": ""
} |
q55905 | format | train | def format(file_metrics, build_metrics):
"""compute output in JSON format."""
metrics = {'files': file_metrics}
if build_metrics:
metrics['build'] = build_metrics
body = json.dumps(metrics, sort_keys=True, indent=4) + '\n'
return body | python | {
"resource": ""
} |
q55906 | split_linear_constraints | train | def split_linear_constraints(A, l, u):
""" Returns the linear equality and inequality constraints.
"""
ieq = []
igt = []
ilt = []
ibx = []
for i in range(len(l)):
if abs(u[i] - l[i]) <= EPS:
ieq.append(i)
elif (u[i] > 1e10) and (l[i] > -1e10):
igt.appe... | python | {
"resource": ""
} |
q55907 | dSbus_dV | train | def dSbus_dV(Y, V):
""" Computes the partial derivative of power injection w.r.t. voltage.
References:
Ray Zimmerman, "dSbus_dV.m", MATPOWER, version 3.2,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/
"""
I = Y * V
diagV = spdiag(V)
diagIbus = spdiag(I)
... | python | {
"resource": ""
} |
q55908 | dIbr_dV | train | def dIbr_dV(Yf, Yt, V):
""" Computes partial derivatives of branch currents w.r.t. voltage.
Ray Zimmerman, "dIbr_dV.m", MATPOWER, version 4.0b1,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/
"""
# nb = len(V)
Vnorm = div(V, abs(V))
diagV = spdiag(V)
diagVnorm = spd... | python | {
"resource": ""
} |
q55909 | dSbr_dV | train | def dSbr_dV(Yf, Yt, V, buses, branches):
""" Computes the branch power flow vector and the partial derivative of
branch power flow w.r.t voltage.
"""
nl = len(branches)
nb = len(V)
f = matrix([l.from_bus._i for l in branches])
t = matrix([l.to_bus._i for l in branches])
# Compute c... | python | {
"resource": ""
} |
q55910 | dAbr_dV | train | def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zer... | python | {
"resource": ""
} |
q55911 | d2Sbus_dV2 | train | def d2Sbus_dV2(Ybus, V, lam):
""" Computes 2nd derivatives of power injection w.r.t. voltage.
"""
n = len(V)
Ibus = Ybus * V
diaglam = spdiag(lam)
diagV = spdiag(V)
A = spmatrix(mul(lam, V), range(n), range(n))
B = Ybus * diagV
C = A * conj(B)
D = Ybus.H * diagV
E = conj(dia... | python | {
"resource": ""
} |
q55912 | d2Ibr_dV2 | train | def d2Ibr_dV2(Ybr, V, lam):
""" Computes 2nd derivatives of complex branch current w.r.t. voltage.
"""
nb = len(V)
diaginvVm = spdiag(div(matrix(1.0, (nb, 1)), abs(V)))
Haa = spdiag(mul(-(Ybr.T * lam), V))
Hva = -1j * Haa * diaginvVm
Hav = Hva
Hvv = spmatrix([], [], [], (nb, nb))
r... | python | {
"resource": ""
} |
q55913 | d2Sbr_dV2 | train | def d2Sbr_dV2(Cbr, Ybr, V, lam):
""" Computes 2nd derivatives of complex power flow w.r.t. voltage.
"""
nb = len(V)
diaglam = spdiag(lam)
diagV = spdiag(V)
A = Ybr.H * diaglam * Cbr
B = conj(diagV) * A * diagV
D = spdiag(mul((A*V), conj(V)))
E = spdiag(mul((A.T * conj(V)), V))
... | python | {
"resource": ""
} |
q55914 | tocvx | train | def tocvx(B):
""" Converts a sparse SciPy matrix into a sparse CVXOPT matrix.
"""
Bcoo = B.tocoo()
return spmatrix(Bcoo.data, Bcoo.row.tolist(), Bcoo.col.tolist()) | python | {
"resource": ""
} |
q55915 | MarketExperiment.doInteractions | train | def doInteractions(self, number=1):
""" Directly maps the agents and the tasks.
"""
t0 = time.time()
for _ in range(number):
self._oneInteraction()
elapsed = time.time() - t0
logger.info("%d interactions executed in %.3fs." % (number, elapsed))
retu... | python | {
"resource": ""
} |
q55916 | DynamicCase.exciter | train | def exciter(self, Xexc, Pexc, Vexc):
""" Exciter model.
Based on Exciter.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
exciters = self.exciters
F = ... | python | {
"resource": ""
} |
q55917 | DynamicCase.governor | train | def governor(self, Xgov, Pgov, Vgov):
""" Governor model.
Based on Governor.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
governors = self.governors
... | python | {
"resource": ""
} |
q55918 | DynamicCase.generator | train | def generator(self, Xgen, Xexc, Xgov, Vgen):
""" Generator model.
Based on Generator.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
generators = self.dyn_gene... | python | {
"resource": ""
} |
q55919 | ReSTWriter._write_data | train | def _write_data(self, file):
""" Writes case data to file in ReStructuredText format.
"""
self.write_case_data(file)
file.write("Bus Data\n")
file.write("-" * 8 + "\n")
self.write_bus_data(file)
file.write("\n")
file.write("Branch Data\n")
file.w... | python | {
"resource": ""
} |
q55920 | ReSTWriter.write_bus_data | train | def write_bus_data(self, file):
""" Writes bus data to a ReST table.
"""
report = CaseReport(self.case)
buses = self.case.buses
col_width = 8
col_width_2 = col_width * 2 + 1
col1_width = 6
sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"
... | python | {
"resource": ""
} |
q55921 | ReSTWriter.write_how_many | train | def write_how_many(self, file):
""" Writes component numbers to a table.
"""
report = CaseReport(self.case)
# Map component labels to attribute names
components = [("Bus", "n_buses"), ("Generator", "n_generators"),
("Committed Generator", "n_online_generators"),
... | python | {
"resource": ""
} |
q55922 | ReSTWriter.write_min_max | train | def write_min_max(self, file):
""" Writes minimum and maximum values to a table.
"""
report = CaseReport(self.case)
col1_header = "Attribute"
col1_width = 19
col2_header = "Minimum"
col3_header = "Maximum"
col_width = 22
sep = "="*col1_width +... | python | {
"resource": ""
} |
q55923 | make_unique_name | train | def make_unique_name(base, existing=[], format="%s_%s"):
""" Return a name, unique within a context, based on the specified name.
@param base: the desired base name of the generated unique name.
@param existing: a sequence of the existing names to avoid returning.
@param format: a formatting specificat... | python | {
"resource": ""
} |
q55924 | call_antlr4 | train | def call_antlr4(arg):
"calls antlr4 on grammar file"
# pylint: disable=unused-argument, unused-variable
antlr_path = os.path.join(ROOT_DIR, "java", "antlr-4.7-complete.jar")
classpath = os.pathsep.join([".", "{:s}".format(antlr_path), "$CLASSPATH"])
generated = os.path.join(ROOT_DIR, 'src', 'pymoca'... | python | {
"resource": ""
} |
q55925 | setup_package | train | def setup_package():
"""
Setup the package.
"""
with open('requirements.txt', 'r') as req_file:
install_reqs = req_file.read().split('\n')
cmdclass_ = {'antlr': AntlrBuildCommand}
cmdclass_.update(versioneer.get_cmdclass())
setup(
version=versioneer.get_version(),
n... | python | {
"resource": ""
} |
q55926 | CaseProperties.body | train | def body(self, frame):
""" Creates the dialog body. Returns the widget that should have
initial focus.
"""
master = Frame(self)
master.pack(padx=5, pady=0, expand=1, fill=BOTH)
title = Label(master, text="Buses")
title.pack(side=TOP)
bus_lb = self.bu... | python | {
"resource": ""
} |
q55927 | OPF.solve | train | def solve(self, solver_klass=None):
""" Solves an optimal power flow and returns a results dictionary.
"""
# Start the clock.
t0 = time()
# Build an OPF model with variables and constraints.
om = self._construct_opf_model(self.case)
if om is None:
ret... | python | {
"resource": ""
} |
q55928 | OPF._construct_opf_model | train | def _construct_opf_model(self, case):
""" Returns an OPF model.
"""
# Zero the case result attributes.
self.case.reset()
base_mva = case.base_mva
# Check for one reference bus.
oneref, refs = self._ref_check(case)
if not oneref: #return {"status": "error... | python | {
"resource": ""
} |
q55929 | OPF._ref_check | train | def _ref_check(self, case):
""" Checks that there is only one reference bus.
"""
refs = [bus._i for bus in case.buses if bus.type == REFERENCE]
if len(refs) == 1:
return True, refs
else:
logger.error("OPF requires a single reference bus.")
ret... | python | {
"resource": ""
} |
q55930 | OPF._remove_isolated | train | def _remove_isolated(self, case):
""" Returns non-isolated case components.
"""
# case.deactivate_isolated()
buses = case.connected_buses
branches = case.online_branches
gens = case.online_generators
return buses, branches, gens | python | {
"resource": ""
} |
q55931 | OPF._pwl1_to_poly | train | def _pwl1_to_poly(self, generators):
""" Converts single-block piecewise-linear costs into linear
polynomial.
"""
for g in generators:
if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2):
g.pwl_to_poly()
return generators | python | {
"resource": ""
} |
q55932 | OPF._get_voltage_angle_var | train | def _get_voltage_angle_var(self, refs, buses):
""" Returns the voltage angle variable set.
"""
Va = array([b.v_angle * (pi / 180.0) for b in buses])
Vau = Inf * ones(len(buses))
Val = -Vau
Vau[refs] = Va[refs]
Val[refs] = Va[refs]
return Variable("Va", l... | python | {
"resource": ""
} |
q55933 | OPF._get_voltage_magnitude_var | train | def _get_voltage_magnitude_var(self, buses, generators):
""" Returns the voltage magnitude variable set.
"""
Vm = array([b.v_magnitude for b in buses])
# For buses with generators initialise Vm from gen data.
for g in generators:
Vm[g.bus._i] = g.v_magnitude
... | python | {
"resource": ""
} |
q55934 | OPF._get_pgen_var | train | def _get_pgen_var(self, generators, base_mva):
""" Returns the generator active power set-point variable.
"""
Pg = array([g.p / base_mva for g in generators])
Pmin = array([g.p_min / base_mva for g in generators])
Pmax = array([g.p_max / base_mva for g in generators])
r... | python | {
"resource": ""
} |
q55935 | OPF._get_qgen_var | train | def _get_qgen_var(self, generators, base_mva):
""" Returns the generator reactive power variable set.
"""
Qg = array([g.q / base_mva for g in generators])
Qmin = array([g.q_min / base_mva for g in generators])
Qmax = array([g.q_max / base_mva for g in generators])
retur... | python | {
"resource": ""
} |
q55936 | OPF._nln_constraints | train | def _nln_constraints(self, nb, nl):
""" Returns non-linear constraints for OPF.
"""
Pmis = NonLinearConstraint("Pmis", nb)
Qmis = NonLinearConstraint("Qmis", nb)
Sf = NonLinearConstraint("Sf", nl)
St = NonLinearConstraint("St", nl)
return Pmis, Qmis, Sf, St | python | {
"resource": ""
} |
q55937 | OPF._const_pf_constraints | train | def _const_pf_constraints(self, gn, base_mva):
""" Returns a linear constraint enforcing constant power factor for
dispatchable loads.
The power factor is derived from the original value of Pmin and either
Qmin (for inductive loads) or Qmax (for capacitive loads). If both Qmin
a... | python | {
"resource": ""
} |
q55938 | OPF._voltage_angle_diff_limit | train | def _voltage_angle_diff_limit(self, buses, branches):
""" Returns the constraint on the branch voltage angle differences.
"""
nb = len(buses)
if not self.ignore_ang_lim:
iang = [i for i, b in enumerate(branches)
if (b.ang_min and (b.ang_min > -360.0))
... | python | {
"resource": ""
} |
q55939 | OPFModel.add_var | train | def add_var(self, var):
""" Adds a variable to the model.
"""
if var.name in [v.name for v in self.vars]:
logger.error("Variable set named '%s' already exists." % var.name)
return
var.i1 = self.var_N
var.iN = self.var_N + var.N - 1
self.vars.appen... | python | {
"resource": ""
} |
q55940 | OPFModel.get_var | train | def get_var(self, name):
""" Returns the variable set with the given name.
"""
for var in self.vars:
if var.name == name:
return var
else:
raise ValueError | python | {
"resource": ""
} |
q55941 | OPFModel.linear_constraints | train | def linear_constraints(self):
""" Returns the linear constraints.
"""
if self.lin_N == 0:
return None, array([]), array([])
A = lil_matrix((self.lin_N, self.var_N), dtype=float64)
l = -Inf * ones(self.lin_N)
u = -l
for lin in self.lin_constraints:
... | python | {
"resource": ""
} |
q55942 | OPFModel.add_constraint | train | def add_constraint(self, con):
""" Adds a constraint to the model.
"""
if isinstance(con, LinearConstraint):
N, M = con.A.shape
if con.name in [c.name for c in self.lin_constraints]:
logger.error("Constraint set named '%s' already exists."
... | python | {
"resource": ""
} |
q55943 | IPOPFSolver._solve | train | def _solve(self, x0, A, l, u, xmin, xmax):
""" Solves using the Interior Point OPTimizer.
"""
# Indexes of constrained lines.
il = [i for i,ln in enumerate(self._ln) if 0.0 < ln.rate_a < 1e10]
nl2 = len(il)
neqnln = 2 * self._nb # no. of non-linear equality constraints
... | python | {
"resource": ""
} |
q55944 | MarketExperiment.doOutages | train | def doOutages(self):
""" Applies branch outtages.
"""
assert len(self.branchOutages) == len(self.market.case.branches)
weights = [[(False, r), (True, 1 - (r))] for r in self.branchOutages]
for i, ln in enumerate(self.market.case.branches):
ln.online = weighted_choic... | python | {
"resource": ""
} |
q55945 | MarketExperiment.reset_case | train | def reset_case(self):
""" Returns the case to its original state.
"""
for bus in self.market.case.buses:
bus.p_demand = self.pdemand[bus]
for task in self.tasks:
for g in task.env.generators:
g.p = task.env._g0[g]["p"]
g.p_max = tas... | python | {
"resource": ""
} |
q55946 | MarketExperiment.doEpisodes | train | def doEpisodes(self, number=1):
""" Do the given numer of episodes, and return the rewards of each
step as a list.
"""
for episode in range(number):
print "Starting episode %d." % episode
# Initialise the profile cycle.
if len(self.profile.shape) ... | python | {
"resource": ""
} |
q55947 | MarketExperiment.reset | train | def reset(self):
""" Sets initial conditions for the experiment.
"""
self.stepid = 0
for task, agent in zip(self.tasks, self.agents):
task.reset()
agent.module.reset()
agent.history.reset() | python | {
"resource": ""
} |
q55948 | RothErev._updatePropensities | train | def _updatePropensities(self, lastState, lastAction, reward):
""" Update the propensities for all actions. The propensity for last
action chosen will be updated using the feedback value that resulted
from performing the action.
If j is the index of the last action chosen, r_j is the rew... | python | {
"resource": ""
} |
q55949 | ProportionalExplorer._forwardImplementation | train | def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summedProps = sum(propensities)
probabilities = propensities / summedProps
action = eventGenerator(probabi... | python | {
"resource": ""
} |
q55950 | ExcelWriter.write | train | def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_filename) | python | {
"resource": ""
} |
q55951 | ExcelWriter.write_bus_data | train | def write_bus_data(self, file):
""" Writes bus data to an Excel spreadsheet.
"""
bus_sheet = self.book.add_sheet("Buses")
for i, bus in enumerate(self.case.buses):
for j, attr in enumerate(BUS_ATTRS):
bus_sheet.write(i, j, getattr(bus, attr)) | python | {
"resource": ""
} |
q55952 | ExcelWriter.write_branch_data | train | def write_branch_data(self, file):
""" Writes branch data to an Excel spreadsheet.
"""
branch_sheet = self.book.add_sheet("Branches")
for i, branch in enumerate(self.case.branches):
for j, attr in enumerate(BRANCH_ATTRS):
branch_sheet.write(i, j, getattr(bran... | python | {
"resource": ""
} |
q55953 | ExcelWriter.write_generator_data | train | def write_generator_data(self, file):
""" Write generator data to file.
"""
generator_sheet = self.book.add_sheet("Generators")
for j, generator in enumerate(self.case.generators):
i = generator.bus._i
for k, attr in enumerate(GENERATOR_ATTRS):
ge... | python | {
"resource": ""
} |
q55954 | CSVWriter.write | train | def write(self, file_or_filename):
""" Writes case data as CSV.
"""
if isinstance(file_or_filename, basestring):
file = open(file_or_filename, "wb")
else:
file = file_or_filename
self.writer = csv.writer(file)
super(CSVWriter, self).write(file) | python | {
"resource": ""
} |
q55955 | CSVWriter.write_case_data | train | def write_case_data(self, file):
""" Writes the case data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(["Name", "base_mva"])
writer.writerow([self.case.name, self.case.base_mva]) | python | {
"resource": ""
} |
q55956 | CSVWriter.write_bus_data | train | def write_bus_data(self, file):
""" Writes bus data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BUS_ATTRS)
for bus in self.case.buses:
writer.writerow([getattr(bus, attr) for attr in BUS_ATTRS]) | python | {
"resource": ""
} |
q55957 | CSVWriter.write_branch_data | train | def write_branch_data(self, file):
""" Writes branch data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BRANCH_ATTRS)
for branch in self.case.branches:
writer.writerow([getattr(branch, a) for a in BRANCH_ATTRS]) | python | {
"resource": ""
} |
q55958 | CSVWriter.write_generator_data | train | def write_generator_data(self, file):
""" Write generator data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(["bus"] + GENERATOR_ATTRS)
for g in self.case.generators:
i = g.bus._i
writer.writerow([i] + [getattr(g,a) for a in GENERATOR_ATTRS]... | python | {
"resource": ""
} |
q55959 | SmartMarket.run | train | def run(self):
""" Computes cleared offers and bids.
"""
# Start the clock.
t0 = time.time()
# Manage reactive power offers/bids.
haveQ = self._isReactiveMarket()
# Withhold offers/bids outwith optional price limits.
self._withholdOffbids()
# Co... | python | {
"resource": ""
} |
q55960 | SmartMarket._runOPF | train | def _runOPF(self):
""" Computes dispatch points and LMPs using OPF.
"""
if self.decommit:
solver = UDOPF(self.case, dc=(self.locationalAdjustment == "dc"))
elif self.locationalAdjustment == "dc":
solver = OPF(self.case, dc=True)
else:
solver = ... | python | {
"resource": ""
} |
q55961 | JSONEncoder.encode | train | def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo":["bar", "baz"]}'
"""
# This doesn't pass the iterator directly to ''.join() because it
# sucks at reporting exceptio... | python | {
"resource": ""
} |
q55962 | compute_file_metrics | train | def compute_file_metrics(processors, language, key, token_list):
"""use processors to compute file metrics."""
# multiply iterator
tli = itertools.tee(token_list, len(processors))
metrics = OrderedDict()
# reset all processors
for p in processors:
p.reset()
# process all tokens
... | python | {
"resource": ""
} |
q55963 | IWNLPWrapper.load | train | def load(self, lemmatizer_path):
"""
This methods load the IWNLP.Lemmatizer json file and creates a dictionary
of lowercased forms which maps each form to its possible lemmas.
"""
self.lemmatizer = {}
with io.open(lemmatizer_path, encoding='utf-8') as data_file:
... | python | {
"resource": ""
} |
q55964 | _CaseWriter.write | train | def write(self, file_or_filename):
""" Writes the case data to file.
"""
if isinstance(file_or_filename, basestring):
file = None
try:
file = open(file_or_filename, "wb")
except Exception, detail:
logger.error("Error opening %s.... | python | {
"resource": ""
} |
q55965 | ProfitTask.performAction | train | def performAction(self, action):
""" The action vector is stripped and the only element is cast to
integer and given to the super class.
"""
self.t += 1
super(ProfitTask, self).performAction(int(action[0]))
self.samples += 1 | python | {
"resource": ""
} |
q55966 | ProfitTask.addReward | train | def addReward(self, r=None):
""" A filtered mapping towards performAction of the underlying
environment.
"""
r = self.getReward() if r is None else r
# by default, the cumulative reward is just the sum over the episode
if self.discount:
self.cumulativeRew... | python | {
"resource": ""
} |
q55967 | StateEstimator.getV0 | train | def getV0(self, v_mag_guess, buses, generators, type=CASE_GUESS):
""" Returns the initial voltage profile.
"""
if type == CASE_GUESS:
Va = array([b.v_angle * (pi / 180.0) for b in buses])
Vm = array([b.v_magnitude for b in buses])
V0 = Vm * exp(1j * Va)
... | python | {
"resource": ""
} |
q55968 | StateEstimator.output_solution | train | def output_solution(self, fd, z, z_est, error_sqrsum):
""" Prints comparison of measurements and their estimations.
"""
col_width = 11
sep = ("=" * col_width + " ") * 4 + "\n"
fd.write("State Estimation\n")
fd.write("-" * 16 + "\n")
fd.write(sep)
fd.write... | python | {
"resource": ""
} |
q55969 | Auction.run | train | def run(self):
""" Clears a set of bids and offers.
"""
# Compute cleared offer/bid quantities from total dispatched quantity.
self._clearQuantities()
# Compute shift values to add to lam to get desired pricing.
# lao, fro, lab, frb = self._first_rejected_last_accepted()
... | python | {
"resource": ""
} |
q55970 | Auction._clearQuantity | train | def _clearQuantity(self, offbids, gen):
""" Computes the cleared bid quantity from total dispatched quantity.
"""
# Filter out offers/bids not applicable to the generator in question.
gOffbids = [offer for offer in offbids if offer.generator == gen]
# Offers/bids within valid pr... | python | {
"resource": ""
} |
q55971 | Auction._clearPrices | train | def _clearPrices(self):
""" Clears prices according to auction type.
"""
for offbid in self.offers + self.bids:
if self.auctionType == DISCRIMINATIVE:
offbid.clearedPrice = offbid.price
elif self.auctionType == FIRST_PRICE:
offbid.clearedPr... | python | {
"resource": ""
} |
q55972 | Auction._clipPrices | train | def _clipPrices(self):
""" Clip cleared prices according to guarantees and limits.
"""
# Guarantee that cleared offer prices are >= offers.
if self.guaranteeOfferPrice:
for offer in self.offers:
if offer.accepted and offer.clearedPrice < offer.price:
... | python | {
"resource": ""
} |
q55973 | wait_for_response | train | def wait_for_response(client, timeout, path='/', expected_status_code=None):
"""
Try make a GET request with an HTTP client against a certain path and
return once any response has been received, ignoring any errors.
:param ContainerHttpClient client:
The HTTP client to use to connect to the con... | python | {
"resource": ""
} |
q55974 | ContainerHttpClient.request | train | def request(self, method, path=None, url_kwargs=None, **kwargs):
"""
Make a request against a container.
:param method:
The HTTP method to use.
:param list path:
The HTTP path (either absolute or relative).
:param dict url_kwargs:
Parameters t... | python | {
"resource": ""
} |
q55975 | ContainerHttpClient.options | train | def options(self, path=None, url_kwargs=None, **kwargs):
"""
Sends an OPTIONS request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
... | python | {
"resource": ""
} |
q55976 | ContainerHttpClient.head | train | def head(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... | python | {
"resource": ""
} |
q55977 | ContainerHttpClient.post | train | def post(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a POST request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... | python | {
"resource": ""
} |
q55978 | iuwt_decomposition | train | def iuwt_decomposition(in1, scale_count, scale_adjust=0, mode='ser', core_count=2, store_smoothed=False,
store_on_gpu=False):
"""
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the
different methods to be used almost interchang... | python | {
"resource": ""
} |
q55979 | iuwt_recomposition | train | def iuwt_recomposition(in1, scale_adjust=0, mode='ser', core_count=1, store_on_gpu=False, smoothed_array=None):
"""
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the
different methods to be used almost interchangeably.
INPUTS:
in1 ... | python | {
"resource": ""
} |
q55980 | ser_iuwt_decomposition | train | def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no... | python | {
"resource": ""
} |
q55981 | ser_iuwt_recomposition | train | def ser_iuwt_recomposition(in1, scale_adjust, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no de... | python | {
"resource": ""
} |
q55982 | mp_iuwt_recomposition | train | def mp_iuwt_recomposition(in1, scale_adjust, core_count, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for multiple CPU cores.
INPUTS:
in1 ... | python | {
"resource": ""
} |
q55983 | gpu_iuwt_decomposition | train | def gpu_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed, store_on_gpu):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a GPU.
INPUTS:
in1 (... | python | {
"resource": ""
} |
q55984 | gpu_iuwt_recomposition | train | def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no ... | python | {
"resource": ""
} |
q55985 | unauth | train | def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('main')) | python | {
"resource": ""
} |
q55986 | info | train | def info(request):
"""
display some user info to show we have authenticated successfully
"""
if check_key(request):
api = get_api(request)
user = api.users(id='self')
print dir(user)
return render_to_response('djfoursquare/info.html', {'user': user})
else:
ret... | python | {
"resource": ""
} |
q55987 | check_key | train | def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... | python | {
"resource": ""
} |
q55988 | stream_timeout | train | def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in ... | python | {
"resource": ""
} |
q55989 | AbstractCallable.get_state | train | def get_state(self, caller):
"""
Get per-program state.
"""
if caller in self.state:
return self.state[caller]
else:
rv = self.state[caller] = DictObject()
return rv | python | {
"resource": ""
} |
q55990 | AbstractCallable.name_to_system_object | train | def name_to_system_object(self, value):
"""
Return object for given name registered in System namespace.
"""
if not self.system:
raise SystemNotReady
if isinstance(value, (str, Object)):
rv = self.system.name_to_system_object(value)
return rv ... | python | {
"resource": ""
} |
q55991 | AbstractCallable.cancel | train | def cancel(self, caller):
"""
Recursively cancel all threaded background processes of this Callable.
This is called automatically for actions if program deactivates.
"""
for o in {i for i in self.children if isinstance(i, AbstractCallable)}:
o.cancel(caller) | python | {
"resource": ""
} |
q55992 | AbstractCallable.give_str | train | def give_str(self):
"""
Give string representation of the callable.
"""
args = self._args[:]
kwargs = self._kwargs
return self._give_str(args, kwargs) | python | {
"resource": ""
} |
q55993 | PolrApi._make_request | train | def _make_request(self, endpoint, params):
"""
Prepares the request and catches common errors and returns tuple of data and the request response.
Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes
:param endpoint: full endpoint url... | python | {
"resource": ""
} |
q55994 | PolrApi.shorten | train | def shorten(self, long_url, custom_ending=None, is_secret=False):
"""
Creates a short url if valid
:param str long_url: The url to shorten.
:param custom_ending: The custom url to create if available.
:type custom_ending: str or None
:param bool is_secret: if not public,... | python | {
"resource": ""
} |
q55995 | PolrApi._get_ending | train | def _get_ending(self, lookup_url):
"""
Returns the short url ending from a short url or an short url ending.
Example:
- Given `<your Polr server>/5N3f8`, return `5N3f8`.
- Given `5N3f8`, return `5N3f8`.
:param lookup_url: A short url or short url ending
:type ... | python | {
"resource": ""
} |
q55996 | PolrApi.lookup | train | def lookup(self, lookup_url, url_key=None):
"""
Looks up the url_ending to obtain information about the short url.
If it exists, the API will return a dictionary with information, including
the long_url that is the destination of the given short url URL.
The lookup object look... | python | {
"resource": ""
} |
q55997 | make_argparser | train | def make_argparser():
"""
Setup argparse arguments.
:return: The parser which :class:`MypolrCli` expects parsed arguments from.
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(prog='mypolr',
description="Interacts with the Polr Project's... | python | {
"resource": ""
} |
q55998 | estimate_threshold | train | def estimate_threshold(in1, edge_excl=0, int_excl=0):
"""
This function estimates the noise using the MAD estimator.
INPUTS:
in1 (no default): The array from which the noise is estimated
OUTPUTS:
out1 An array of per-scale noise estimates.
"""
... | python | {
"resource": ""
} |
q55999 | source_extraction | train | def source_extraction(in1, tolerance, mode="cpu", store_on_gpu=False,
neg_comp=False):
"""
Convenience function for allocating work to cpu or gpu, depending on the selected mode.
INPUTS:
in1 (no default): Array containing the wavelet decomposition.
tolerance (no de... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.