_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q28400 | define_passive_branch_flows_with_kirchhoff | train | def define_passive_branch_flows_with_kirchhoff(network,snapshots,skip_vars=False):
""" define passive branch flows with the kirchoff method """
for sub_network in network.sub_networks.obj:
find_tree(sub_network)
find_cycles(sub_network)
#following is necessary to calculate angles post-... | python | {
"resource": ""
} |
q28401 | network_lopf_build_model | train | def network_lopf_build_model(network, snapshots=None, skip_pre=False,
formulation="angles", ptdf_tolerance=0.):
"""
Build pyomo model for linear optimal power flow for a group of snapshots.
Parameters
----------
snapshots : list or index slice
A list of snapshot... | python | {
"resource": ""
} |
q28402 | network_lopf_prepare_solver | train | def network_lopf_prepare_solver(network, solver_name="glpk", solver_io=None):
"""
Prepare solver for linear optimal power flow.
Parameters
----------
solver_name : string
Must be a solver name that pyomo recognises and that is
installed, e.g. "glpk", "gurobi"
| python | {
"resource": ""
} |
q28403 | network_lopf_solve | train | def network_lopf_solve(network, snapshots=None, formulation="angles", solver_options={},solver_logfile=None, keep_files=False,
free_memory={'pyomo'},extra_postprocessing=None):
"""
Solve linear optimal power flow for a group of snapshots and extract results.
Parameters
---------... | python | {
"resource": ""
} |
q28404 | network_lopf | train | def network_lopf(network, snapshots=None, solver_name="glpk", solver_io=None,
skip_pre=False, extra_functionality=None, solver_logfile=None, solver_options={},
keep_files=False, formulation="angles", ptdf_tolerance=0.,
free_memory={},extra_postprocessing=None):
"""... | python | {
"resource": ""
} |
q28405 | replace_gen | train | def replace_gen(network,gen_to_replace):
"""Replace the generator gen_to_replace with a bus for the energy
carrier, a link for the conversion from the energy carrier to electricity
and a store to keep track of the depletion of the energy carrier and its
CO2 emissions."""
gen = network.generato... | python | {
"resource": ""
} |
q28406 | get_switchable_as_dense | train | def get_switchable_as_dense(network, component, attr, snapshots=None, inds=None):
"""
Return a Dataframe for a time-varying component attribute with values for all
non-time-varying components filled in with the default values for the
attribute.
Parameters
----------
network : pypsa.Network
... | python | {
"resource": ""
} |
q28407 | get_switchable_as_iter | train | def get_switchable_as_iter(network, component, attr, snapshots, inds=None):
"""
Return an iterator over snapshots for a time-varying component
attribute with values for all non-time-varying components filled
in with the default values for the attribute.
Parameters
----------
network : pypsa... | python | {
"resource": ""
} |
q28408 | allocate_series_dataframes | train | def allocate_series_dataframes(network, series):
"""
Populate time-varying outputs with default values.
Parameters
----------
network : pypsa.Network
series : dict
Dictionary of components and their attributes to populate (see example)
Returns
-------
None
Examples
... | python | {
"resource": ""
} |
q28409 | network_pf | train | def network_pf(network, snapshots=None, skip_pre=False, x_tol=1e-6, use_seed=False):
"""
Full non-linear power flow for generic network.
Parameters
----------
snapshots : list-like|single snapshot
A subset or an elements of network.snapshots on which to run
the power flow, defaults ... | python | {
"resource": ""
} |
q28410 | network_lpf | train | def network_lpf(network, snapshots=None, skip_pre=False):
"""
Linear power flow for generic network.
Parameters
----------
snapshots : list-like|single snapshot
A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre: b... | python | {
"resource": ""
} |
q28411 | apply_line_types | train | def apply_line_types(network):
"""Calculate line electrical parameters x, r, b, g from standard
types.
"""
lines_with_types_b = network.lines.type != ""
if lines_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.lines.loc[lines_with_types_b, 'type'].unique())
... | python | {
"resource": ""
} |
q28412 | apply_transformer_types | train | def apply_transformer_types(network):
"""Calculate transformer electrical parameters x, r, b, g from
standard types.
"""
trafos_with_types_b = network.transformers.type != ""
if trafos_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.transformers.loc[trafos_with_type... | python | {
"resource": ""
} |
q28413 | apply_transformer_t_model | train | def apply_transformer_t_model(network):
"""Convert given T-model parameters to PI-model parameters using wye-delta transformation"""
z_series = network.transformers.r_pu + 1j*network.transformers.x_pu
y_shunt = network.transformers.g_pu + 1j*network.transformers.b_pu
ts_b = (network.transformers.model... | python | {
"resource": ""
} |
q28414 | calculate_dependent_values | train | def calculate_dependent_values(network):
"""Calculate per unit impedances and append voltages to lines and shunt impedances."""
apply_line_types(network)
apply_transformer_types(network)
network.lines["v_nom"] = network.lines.bus0.map(network.buses.v_nom)
network.lines["x_pu"] = network.lines.x/(... | python | {
"resource": ""
} |
q28415 | find_slack_bus | train | def find_slack_bus(sub_network):
"""Find the slack bus in a connected sub-network."""
gens = sub_network.generators()
if len(gens) == 0:
logger.warning("No generators in sub-network {}, better hope power is already balanced".format(sub_network.name))
sub_network.slack_generator = None
... | python | {
"resource": ""
} |
q28416 | find_bus_controls | train | def find_bus_controls(sub_network):
"""Find slack and all PV and PQ buses for a sub_network.
This function also fixes sub_network.buses_o, a DataFrame
ordered by control type."""
network = sub_network.network
find_slack_bus(sub_network)
gens = sub_network.generators()
buses_i = sub_networ... | python | {
"resource": ""
} |
q28417 | calculate_B_H | train | def calculate_B_H(sub_network,skip_pre=False):
"""Calculate B and H matrices for AC or DC sub-networks."""
network = sub_network.network
if not skip_pre:
calculate_dependent_values(network)
find_bus_controls(sub_network)
if network.sub_networks.at[sub_network.name,"carrier"] == "DC":
... | python | {
"resource": ""
} |
q28418 | find_tree | train | def find_tree(sub_network, weight='x_pu'):
"""Get the spanning tree of the graph, choose the node with the
highest degree as a central "tree slack" and then see for each
branch which paths from the slack to each node go through the
branch.
"""
branches_bus0 = sub_network.branches()["bus0"]
... | python | {
"resource": ""
} |
q28419 | find_cycles | train | def find_cycles(sub_network, weight='x_pu'):
"""
Find all cycles in the sub_network and record them in sub_network.C.
networkx collects the cycles with more than 2 edges; then the 2-edge cycles
from the MultiGraph must be collected separately (for cases where there
are multiple lines between the sa... | python | {
"resource": ""
} |
q28420 | network_lpf_contingency | train | def network_lpf_contingency(network, snapshots=None, branch_outages=None):
"""
Computes linear power flow for a selection of branch outages.
Parameters
----------
snapshots : list-like|single snapshot
A subset or an elements of network.snapshots on which to run
the power flow, defau... | python | {
"resource": ""
} |
q28421 | compute_bbox_with_margins | train | def compute_bbox_with_margins(margin, x, y):
'Helper function to compute bounding box for the plot'
# set margins
pos = np.asarray((x, y))
minxy, maxxy = pos.min(axis=1), pos.max(axis=1)
xy1 = | python | {
"resource": ""
} |
q28422 | projected_area_factor | train | def projected_area_factor(ax, original_crs):
"""
Helper function to get the area scale of the current projection in
reference to the default projection.
"""
if not hasattr(ax, 'projection'):
return 1
if isinstance(ax.projection, ccrs.PlateCarree):
return 1
x1, x2, y1, y2 = ax... | python | {
"resource": ""
} |
q28423 | _export_to_exporter | train | def _export_to_exporter(network, exporter, basename, export_standard_types=False):
"""
Export to exporter.
Both static and series attributes of components are exported, but only
if they have non-default values.
Parameters
----------
exporter : Exporter
Initialized exporter instance... | python | {
"resource": ""
} |
q28424 | import_from_csv_folder | train | def import_from_csv_folder(network, csv_folder_name, encoding=None, skip_time=False):
"""
Import network data from CSVs in a folder.
The CSVs must follow the standard form, see pypsa/examples.
Parameters
----------
csv_folder_name : string
Name of folder
encoding : str, default Non... | python | {
"resource": ""
} |
q28425 | export_to_csv_folder | train | def export_to_csv_folder(network, csv_folder_name, encoding=None, export_standard_types=False):
"""
Export network and components to a folder of CSVs.
Both static and series attributes of components are exported, but only
if they have non-default values.
If csv_folder_name does not already exist, ... | python | {
"resource": ""
} |
q28426 | import_from_hdf5 | train | def import_from_hdf5(network, path, skip_time=False):
"""
Import network data from HDF5 store at `path`.
Parameters
----------
path : string
Name of HDF5 store
skip_time : bool, default False
Skip reading in time dependent attributes
"""
basename = | python | {
"resource": ""
} |
q28427 | export_to_hdf5 | train | def export_to_hdf5(network, path, export_standard_types=False, **kwargs):
"""
Export network and components to an HDF store.
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
Parameters
--... | python | {
"resource": ""
} |
q28428 | import_from_netcdf | train | def import_from_netcdf(network, path, skip_time=False):
"""
Import network data from netCDF file or xarray Dataset at `path`.
Parameters
----------
path : string|xr.Dataset
Path to netCDF dataset or instance of xarray Dataset
skip_time : bool, default False
Skip reading in time ... | python | {
"resource": ""
} |
q28429 | export_to_netcdf | train | def export_to_netcdf(network, path=None, export_standard_types=False,
least_significant_digit=None):
"""Export network and components to a netCDF file.
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already ... | python | {
"resource": ""
} |
q28430 | _import_from_importer | train | def _import_from_importer(network, importer, basename, skip_time=False):
"""
Import network data from importer.
Parameters
----------
skip_time : bool
Skip importing time
"""
attrs = importer.get_attributes()
current_pypsa_version = [int(s) for s in network.pypsa_version.split... | python | {
"resource": ""
} |
q28431 | import_series_from_dataframe | train | def import_series_from_dataframe(network, dataframe, cls_name, attr):
"""
Import time series from a pandas DataFrame.
Parameters
----------
dataframe : pandas.DataFrame
cls_name : string
Name of class of component
attr : string
Name of series attribute
Examples
----... | python | {
"resource": ""
} |
q28432 | graph | train | def graph(network, branch_components=None, weight=None, inf_weight=False):
"""
Build NetworkX graph.
Arguments
---------
network : Network|SubNetwork
branch_components : [str]
Components to use as branches. The default are
passive_branch_components in the case of a SubNetwork a... | python | {
"resource": ""
} |
q28433 | l_constraint | train | def l_constraint(model,name,constraints,*args):
"""A replacement for pyomo's Constraint that quickly builds linear
constraints.
Instead of
model.name = Constraint(index1,index2,...,rule=f)
call instead
l_constraint(model,name,constraints,index1,index2,...)
where constraints is a diction... | python | {
"resource": ""
} |
q28434 | l_objective | train | def l_objective(model,objective=None):
"""
A replacement for pyomo's Objective that quickly builds linear
objectives.
Instead of
model.objective = Objective(expr=sum(vars[i]*coeffs[i] for i in index)+constant)
call instead
l_objective(model,objective)
where objective is an LExpressi... | python | {
"resource": ""
} |
q28435 | Network._build_dataframes | train | def _build_dataframes(self):
"""Function called when network is created to build component pandas.DataFrames."""
for component in self.all_components:
attrs = self.components[component]["attrs"]
static_dtypes = attrs.loc[attrs.static, "dtype"].drop(["name"])
df = ... | python | {
"resource": ""
} |
q28436 | Network.set_snapshots | train | def set_snapshots(self,snapshots):
"""
Set the snapshots and reindex all time-dependent data.
This will reindex all pandas.Panels of time-dependent data; NaNs are filled
with the default value for that quantity.
Parameters
----------
snapshots : list or pandas.I... | python | {
"resource": ""
} |
q28437 | Network.add | train | def add(self, class_name, name, **kwargs):
"""
Add a single component to the network.
Adds it to component DataFrames.
Parameters
----------
class_name : string
Component class name in ["Bus","Generator","Load","StorageUnit","Store","ShuntImpedance","Line","... | python | {
"resource": ""
} |
q28438 | Network.remove | train | def remove(self, class_name, name):
"""
Removes a single component from the network.
Removes it from component DataFrames.
Parameters
----------
class_name : string
Component class name
name : string
Component name
Examples
... | python | {
"resource": ""
} |
q28439 | Network.madd | train | def madd(self, class_name, names, suffix='', **kwargs):
"""
Add multiple components to the network, along with their attributes.
Make sure when adding static attributes as pandas Series that they are indexed
by names. Make sure when adding time-varying attributes as pandas DataFrames th... | python | {
"resource": ""
} |
q28440 | Network.mremove | train | def mremove(self, class_name, names):
"""
Removes multiple components from the network.
Removes them from component DataFrames.
Parameters
----------
class_name : string
Component class name
name : list-like
Component names
Examp... | python | {
"resource": ""
} |
q28441 | Network.copy | train | def copy(self, with_time=True, ignore_standard_types=False):
"""
Returns a deep copy of the Network object with all components and
time-dependent data.
Returns
--------
network : pypsa.Network
Parameters
----------
with_time : boolean, default Tr... | python | {
"resource": ""
} |
q28442 | Network.determine_network_topology | train | def determine_network_topology(self):
"""
Build sub_networks from topology.
"""
adjacency_matrix = self.adjacency_matrix(self.passive_branch_components)
n_components, labels = csgraph.connected_components(adjacency_matrix, directed=False)
# remove all old sub_networks
... | python | {
"resource": ""
} |
q28443 | logger_init | train | def logger_init():
"""Initialize logger instance."""
log = logging.getLogger("pyinotify")
console_handler = logging.StreamHandler()
| python | {
"resource": ""
} |
q28444 | INotifyWrapper.create | train | def create():
"""
Factory method instanciating and returning the right wrapper.
"""
# First, try to use ctypes.
if ctypes:
inotify = _CtypesLibcINotifyWrapper()
if inotify.init():
return inotify
| python | {
"resource": ""
} |
q28445 | Stats.my_init | train | def my_init(self):
"""
Method automatically called from base class constructor.
"""
self._start_time | python | {
"resource": ""
} |
q28446 | Stats.process_default | train | def process_default(self, event):
"""
Processes |event|.
"""
self._stats_lock.acquire()
try:
events = event.maskname.split('|')
| python | {
"resource": ""
} |
q28447 | ThreadedNotifier.stop | train | def stop(self):
"""
Stop notifier's loop. Stop notification. Join the thread.
"""
self._stop_event.set()
os.write(self._pipe[1], b'stop')
threading.Thread.join(self)
| python | {
"resource": ""
} |
q28448 | TornadoAsyncNotifier.handle_read | train | def handle_read(self, *args, **kwargs):
"""
See comment in AsyncNotifier.
"""
self.read_events()
self.process_events() | python | {
"resource": ""
} |
q28449 | WatchManager.del_watch | train | def del_watch(self, wd):
"""
Remove watch entry associated to watch descriptor wd.
@param wd: Watch descriptor.
@type wd: int
"""
try:
| python | {
"resource": ""
} |
q28450 | WatchManager.__add_watch | train | def __add_watch(self, path, mask, proc_fun, auto_add, exclude_filter):
"""
Add a watch on path, build a Watch object and insert it in the
watch manager dictionary. Return the wd value.
"""
path = self.__format_path(path)
if auto_add and not mask & IN_CREATE:
m... | python | {
"resource": ""
} |
q28451 | WatchManager.update_watch | train | def update_watch(self, wd, mask=None, proc_fun=None, rec=False,
auto_add=False, quiet=True):
"""
Update existing watch descriptors |wd|. The |mask| value, the
processing object |proc_fun|, the recursive param |rec| and the
|auto_add| and |quiet| flags can all be upda... | python | {
"resource": ""
} |
q28452 | WatchManager.get_path | train | def get_path(self, wd):
"""
Returns the path associated to WD, if WD is unknown it returns None.
@param wd: Watch descriptor.
@type wd: int
@return: Path or None.
@rtype: string or None | python | {
"resource": ""
} |
q28453 | WatchManager.__walk_rec | train | def __walk_rec(self, top, rec):
"""
Yields each subdirectories of top, doesn't follow symlinks.
If rec is false, only yield top.
@param top: root directory.
@type top: string
| python | {
"resource": ""
} |
q28454 | _SysProcessEvent.process_IN_CREATE | train | def process_IN_CREATE(self, raw_event):
"""
If the event affects a directory and the auto_add flag of the
targetted watch is set to True, a new watch is added on this
new directory, with the same attribute values than those of
this watch.
"""
if raw_event.mask & I... | python | {
"resource": ""
} |
q28455 | Notifier.check_events | train | def check_events(self, timeout=None):
"""
Check for new events available to read, blocks up to timeout
milliseconds.
@param timeout: If specified it overrides the corresponding instance
attribute _timeout. timeout must be sepcified in
mill... | python | {
"resource": ""
} |
q28456 | Notifier.read_events | train | def read_events(self):
"""
Read events from device, build _RawEvents, and enqueue them.
"""
buf_ = array.array('i', [0])
# get event queue size
if fcntl.ioctl(self._fd, termios.FIONREAD, buf_, 1) == -1:
return
queue_size = buf_[0]
if queue_size... | python | {
"resource": ""
} |
q28457 | ensure_conf | train | def ensure_conf(app):
"""
Ensure for the given app the the redbeat_conf
attribute is set to an instance of the RedBeatConfig
class.
"""
name = 'redbeat_conf'
app = app_or_default(app)
try:
config = getattr(app, name)
| python | {
"resource": ""
} |
q28458 | http2time | train | def http2time(text):
"""Returns time in seconds since epoch of time represented by a string.
Return value is an integer.
None is returned if the format of str is unrecognized, the time is outside
the representable range, or the timezone string is not recognized. If the
string contains no timezone... | python | {
"resource": ""
} |
q28459 | unmatched | train | def unmatched(match):
"""Return unmatched part of re.Match object."""
start, end = match.span(0) | python | {
"resource": ""
} |
q28460 | split_header_words | train | def split_header_words(header_values):
r"""Parse header values into a list of lists containing key,value pairs.
The function knows how to deal with ",", ";" and "=" as well as quoted
values after "=". A list of space separated tokens are parsed as if they
were separated by ";".
If the header_valu... | python | {
"resource": ""
} |
q28461 | parse_ns_headers | train | def parse_ns_headers(ns_headers):
"""Ad-hoc parser for Netscape protocol cookie-attributes.
The old Netscape cookie format for Set-Cookie can for instance contain
an unquoted "," in the expires field, so we have to use this ad-hoc
parser instead of split_header_words.
XXX This may not make the bes... | python | {
"resource": ""
} |
q28462 | is_HDN | train | def is_HDN(text):
"""Return True if text is a host domain name."""
# XXX
# This may well be wrong. Which RFC is HDN defined in, if any (for
# the purposes of RFC 2965)?
# For the | python | {
"resource": ""
} |
q28463 | domain_match | train | def domain_match(A, B):
"""Return True if domain A domain-matches domain B, according to RFC 2965.
A and B may be host domain names or IP addresses.
RFC 2965, section 1:
Host names can be specified either as an IP address or a HDN string.
Sometimes we compare one host name with another. (Such co... | python | {
"resource": ""
} |
q28464 | request_path | train | def request_path(request):
"""Path component of request-URI, as defined by RFC 2965."""
url = request.get_full_url()
parts = urlsplit(url)
path = escape_path(parts.path)
| python | {
"resource": ""
} |
q28465 | escape_path | train | def escape_path(path):
"""Escape any invalid characters in HTTP URL, and uppercase all escapes."""
# There's no knowing what character encoding was used to create URLs
# containing %-escapes, but since we have to pick one to escape invalid
# path characters, we pick UTF-8, as recommended in the HTML 4.0... | python | {
"resource": ""
} |
q28466 | reach | train | def reach(h):
"""Return reach of host h, as defined by RFC 2965, section 1.
The reach R of a host name H is defined as follows:
* If
- H is the host domain name of a host; and,
- H has the form A.B; and
- A has no embedded (that is, interior) dots; and
- ... | python | {
"resource": ""
} |
q28467 | deepvalues | train | def deepvalues(mapping):
"""Iterates over nested mapping, depth-first, in sorted order by key."""
values = vals_sorted_by_key(mapping)
for obj in values:
mapping = False | python | {
"resource": ""
} |
q28468 | lwp_cookie_str | train | def lwp_cookie_str(cookie):
"""Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring.
"""
h = [(cookie.name, cookie.value),
("path", cookie.path),
("domain", cookie.domain)]
if cookie.port is not No... | python | {
"resource": ""
} |
q28469 | DefaultCookiePolicy.set_allowed_domains | train | def set_allowed_domains(self, allowed_domains):
"""Set the sequence of allowed domains, or None."""
if allowed_domains is not None:
| python | {
"resource": ""
} |
q28470 | CookieJar._cookies_for_request | train | def _cookies_for_request(self, request):
"""Return a list of cookies to be returned to server."""
| python | {
"resource": ""
} |
q28471 | CookieJar._cookie_attrs | train | def _cookie_attrs(self, cookies):
"""Return a list of cookie-attributes to be returned to server.
like ['foo="bar"; $Path="/"', ...]
The $Version attribute is also added when appropriate (currently only
once per request).
"""
# add cookies in order of most specific (ie... | python | {
"resource": ""
} |
q28472 | CookieJar._normalized_cookie_tuples | train | def _normalized_cookie_tuples(self, attrs_set):
"""Return list of tuples containing normalised cookie information.
attrs_set is the list of lists of key,value pairs extracted from
the Set-Cookie or Set-Cookie2 headers.
Tuples are name, value, standard, rest, where name and value are th... | python | {
"resource": ""
} |
q28473 | CookieJar.make_cookies | train | def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object."""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
ns_hdrs = headers.get_all("Se... | python | {
"resource": ""
} |
q28474 | CookieJar.set_cookie_if_ok | train | def set_cookie_if_ok(self, cookie, request):
"""Set a cookie if policy says it's OK to do so."""
self._cookies_lock.acquire()
| python | {
"resource": ""
} |
q28475 | CookieJar.set_cookie | train | def set_cookie(self, cookie):
"""Set a cookie, without checking whether or not it should be set."""
c = self._cookies
self._cookies_lock.acquire()
try:
if cookie.domain not in c: c[cookie.domain] = {}
c2 = c[cookie.domain]
| python | {
"resource": ""
} |
q28476 | CookieJar.extract_cookies | train | def extract_cookies(self, response, request):
"""Extract cookies from response, where allowable given the request."""
_debug("extract_cookies: %s", response.info())
self._cookies_lock.acquire()
try:
self._policy._now = self._now = int(time.time())
for cookie in s... | python | {
"resource": ""
} |
q28477 | CookieJar.clear | train | def clear(self, domain=None, path=None, name=None):
"""Clear some cookies.
Invoking this method without arguments will clear all cookies. If
given a single argument, only cookies belonging to that domain will be
removed. If given two arguments, cookies belonging to the specified
... | python | {
"resource": ""
} |
q28478 | CookieJar.clear_session_cookies | train | def clear_session_cookies(self):
"""Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
| python | {
"resource": ""
} |
q28479 | CookieJar.clear_expired_cookies | train | def clear_expired_cookies(self):
"""Discard all expired cookies.
You probably don't need to call this method: expired cookies are never
sent back to the server (provided you're using DefaultCookiePolicy),
this method is called by CookieJar itself every so often, and the
.save() ... | python | {
"resource": ""
} |
q28480 | FileCookieJar.load | train | def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Load cookies from a file."""
if filename is None:
if self.filename is not | python | {
"resource": ""
} |
q28481 | FileCookieJar.revert | train | def revert(self, filename=None,
ignore_discard=False, ignore_expires=False):
"""Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens.
"""
if fi... | python | {
"resource": ""
} |
q28482 | LWPCookieJar.as_lwp_str | train | def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
"""Return cookies as a string of "\\n"-separated "Set-Cookie3" headers.
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
"""
now = time.time()
r = []
for cookie in self:
i... | python | {
"resource": ""
} |
q28483 | Address.addr_spec | train | def addr_spec(self):
"""The addr_spec (username@domain) portion of the address, quoted
according to RFC 5322 rules, but with no Content Transfer Encoding.
"""
nameset = set(self.username)
if len(nameset) > len(nameset-parser.DOT_ATOM_ENDS):
lp = parser.quote_string(se... | python | {
"resource": ""
} |
q28484 | BaseHeader.fold | train | def fold(self, **_3to2kwargs):
policy = _3to2kwargs['policy']; del _3to2kwargs['policy']
"""Fold header according to policy.
The parsed representation of the header is folded according to
RFC5322 rules, as modified by the policy. If the parse tree
contains surrogateescaped byte... | python | {
"resource": ""
} |
q28485 | nobody_uid | train | def nobody_uid():
"""Internal routine to get nobody's uid"""
global nobody
if nobody:
return nobody
try:
| python | {
"resource": ""
} |
q28486 | HTTPServer.server_bind | train | def server_bind(self):
"""Override server_bind to store the server name."""
socketserver.TCPServer.server_bind(self)
host, | python | {
"resource": ""
} |
q28487 | BaseHTTPRequestHandler.handle | train | def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
| python | {
"resource": ""
} |
q28488 | BaseHTTPRequestHandler.send_response | train | def send_response(self, code, message=None):
"""Add the response header to the headers buffer and log the
response code.
Also send two standard headers with the server software
version and the current date.
"""
self.log_request(code)
| python | {
"resource": ""
} |
q28489 | BaseHTTPRequestHandler.send_response_only | train | def send_response_only(self, code, message=None):
"""Send the response header only."""
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
| python | {
"resource": ""
} |
q28490 | BaseHTTPRequestHandler.send_header | train | def send_header(self, keyword, value):
"""Send a MIME header to the headers buffer."""
if self.request_version != 'HTTP/0.9':
if not hasattr(self, '_headers_buffer'):
self._headers_buffer = []
self._headers_buffer.append(
("%s: %s\r\n" % (keyword, ... | python | {
"resource": ""
} |
q28491 | BaseHTTPRequestHandler.end_headers | train | def end_headers(self):
"""Send the blank line ending the MIME headers."""
if self.request_version != 'HTTP/0.9':
| python | {
"resource": ""
} |
q28492 | BaseHTTPRequestHandler.log_message | train | def log_message(self, format, *args):
"""Log an arbitrary message.
This is used by all other logging functions. Override
it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the
message to be logged. If the format string contains
| python | {
"resource": ""
} |
q28493 | BaseHTTPRequestHandler.log_date_time_string | train | def log_date_time_string(self):
"""Return the current time formatted for logging."""
now = time.time()
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
| python | {
"resource": ""
} |
q28494 | CGIHTTPRequestHandler.is_cgi | train | def is_cgi(self):
"""Test whether self.path corresponds to a CGI script.
Returns True and updates the cgi_info attribute to the tuple
(dir, rest) if self.path requires running a CGI script.
Returns False otherwise.
If any exception is raised, the caller should assume that
... | python | {
"resource": ""
} |
q28495 | CGIHTTPRequestHandler.is_python | train | def is_python(self, path):
"""Test whether argument path is a Python script."""
| python | {
"resource": ""
} |
q28496 | newrange.index | train | def index(self, value):
"""Return the 0-based position of integer `value` in
the sequence this range represents."""
try:
diff = value - self._start
except TypeError:
raise ValueError('%r is not in range' % value)
quotient, remainder | python | {
"resource": ""
} |
q28497 | newrange.__getitem_slice | train | def __getitem_slice(self, slce):
"""Return a range which represents the requested slce
of the sequence represented by this range.
"""
scaled_indices = (self._step * n for n in slce.indices(self._len))
start_offset, stop_offset, | python | {
"resource": ""
} |
q28498 | RobotFileParser.set_url | train | def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
| python | {
"resource": ""
} |
q28499 | RobotFileParser.read | train | def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
try:
f = urllib.request.urlopen(self.url)
except urllib.error.HTTPError as err:
if err.code in (401, 403):
self.disallow_all | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.