_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q46800 | Node.get_value | train | def get_value(self) -> ScalarType:
"""Returns the value of a Scalar node.
Use is_scalar(type) to check which type the node has.
"""
if self.yaml_node.tag == 'tag:yaml.org,2002:str':
return self.yaml_node.value
if self.yaml_node.tag == 'tag:yaml.org,2002:int':
... | python | {
"resource": ""
} |
q46801 | Node.set_value | train | def set_value(self, value: ScalarType) -> None:
"""Sets the value of the node to a scalar value.
After this, is_scalar(type(value)) will return true.
Args:
value: The value to set this node to, a str, int, float, \
bool, or None.
"""
if isinstanc... | python | {
"resource": ""
} |
q46802 | Node.make_mapping | train | def make_mapping(self) -> None:
"""Replaces the node with a new, empty mapping.
Note that this will work on the Node object that is passed to \
a yatiml_savorize() or yatiml_sweeten() function, but not on \
any of its attributes or items. If you need to set an attribute \
to a c... | python | {
"resource": ""
} |
q46803 | Node.has_attribute | train | def has_attribute(self, attribute: str) -> bool:
"""Whether the node has an attribute with the given name.
Use only if is_mapping() returns True.
Args:
attribute: The name of the attribute to check for.
Returns:
True iff the attribute is present.
"""
... | python | {
"resource": ""
} |
q46804 | Node.has_attribute_type | train | def has_attribute_type(self, attribute: str, typ: Type) -> bool:
"""Whether the given attribute exists and has a compatible type.
Returns true iff the attribute exists and is an instance of \
the given type. Matching between types passed as typ and \
yaml node types is as follows:
... | python | {
"resource": ""
} |
q46805 | Node.get_attribute | train | def get_attribute(self, attribute: str) -> 'Node':
"""Returns the node representing the given attribute's value.
Use only if is_mapping() returns true.
Args:
attribute: The name of the attribute to retrieve.
Raises:
KeyError: If the attribute does not exist.
... | python | {
"resource": ""
} |
q46806 | Node.set_attribute | train | def set_attribute(self, attribute: str,
value: Union[ScalarType, yaml.Node]) -> None:
"""Sets the attribute to the given value.
Use only if is_mapping() returns True.
If the attribute does not exist, this adds a new attribute, \
if it does, it will be overwritten.... | python | {
"resource": ""
} |
q46807 | Node.remove_attribute | train | def remove_attribute(self, attribute: str) -> None:
"""Remove an attribute from the node.
Use only if is_mapping() returns True.
Args:
attribute: The name of the attribute to remove.
"""
attr_index = self.__attr_index(attribute)
if attr_index is not None:
... | python | {
"resource": ""
} |
q46808 | Node.rename_attribute | train | def rename_attribute(self, attribute: str, new_name: str) -> None:
"""Renames an attribute.
Use only if is_mapping() returns true.
If the attribute does not exist, this will do nothing.
Args:
attribute: The (old) name of the attribute to rename.
new_name: The n... | python | {
"resource": ""
} |
q46809 | Node.unders_to_dashes_in_keys | train | def unders_to_dashes_in_keys(self) -> None:
"""Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
... | python | {
"resource": ""
} |
q46810 | Node.dashes_to_unders_in_keys | train | def dashes_to_unders_in_keys(self) -> None:
"""Replaces dashes with underscores in key names.
For each attribute in a mapping, this replaces any dashes in \
its keys with underscores. Handy because Python does not \
accept dashes in identifiers, while some YAML-based file \
form... | python | {
"resource": ""
} |
q46811 | Node.seq_attribute_to_map | train | def seq_attribute_to_map(self,
attribute: str,
key_attribute: str,
value_attribute: Optional[str] = None,
strict: Optional[bool] = True) -> None:
"""Converts a sequence attribute to a map.
... | python | {
"resource": ""
} |
q46812 | Node.map_attribute_to_seq | train | def map_attribute_to_seq(self,
attribute: str,
key_attribute: str,
value_attribute: Optional[str] = None) -> None:
"""Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose va... | python | {
"resource": ""
} |
q46813 | Node.__attr_index | train | def __attr_index(self, attribute: str) -> Optional[int]:
"""Finds an attribute's index in the yaml_node.value list."""
attr_index = None
for i, (key_node, _) in enumerate(self.yaml_node.value):
if key_node.value == attribute:
attr_index = i
break
... | python | {
"resource": ""
} |
q46814 | UnknownNode.require_scalar | train | def require_scalar(self, *args: Type) -> None:
"""Require the node to be a scalar.
If additional arguments are passed, these are taken as a list \
of valid types; if the node matches one of these, then it is \
accepted.
Example:
# Match either an int or a string
... | python | {
"resource": ""
} |
q46815 | UnknownNode.require_mapping | train | def require_mapping(self) -> None:
"""Require the node to be a mapping."""
if not isinstance(self.yaml_node, yaml.MappingNode):
raise RecognitionError(('{}{}A mapping is required here').format(
self.yaml_node.start_mark, os.linesep)) | python | {
"resource": ""
} |
q46816 | UnknownNode.require_sequence | train | def require_sequence(self) -> None:
"""Require the node to be a sequence."""
if not isinstance(self.yaml_node, yaml.SequenceNode):
raise RecognitionError(('{}{}A sequence is required here').format(
self.yaml_node.start_mark, os.linesep)) | python | {
"resource": ""
} |
q46817 | UnknownNode.require_attribute | train | def require_attribute(self, attribute: str, typ: Type = _Any) -> None:
"""Require an attribute on the node to exist.
If `typ` is given, the attribute must have this type.
Args:
attribute: The name of the attribute / mapping key.
typ: The type the attribute must have.
... | python | {
"resource": ""
} |
q46818 | UnknownNode.require_attribute_value | train | def require_attribute_value(
self, attribute: str,
value: Union[int, str, float, bool, None]) -> None:
"""Require an attribute on the node to have a particular value.
This requires the attribute to exist, and to have the given value \
and corresponding type. Handy for in... | python | {
"resource": ""
} |
q46819 | _callback_factory | train | def _callback_factory(callback_imp):
"""Factory for creating a is authenticated callback."""
if callback_imp is None:
try:
pkg_resources.get_distribution('flask-login')
from flask_login import current_user
return lambda: current_user.is_authenticated
except pk... | python | {
"resource": ""
} |
q46820 | moment | train | def moment(arr, moment=1, axis=0, **kwargs):
'''
Uses the scipy.stats.moment to calculate the Nth central
moment about the mean.
If `arr` is a 2D spectrogram returned by
ibmseti.dsp.raw_to_spectrogram(data), where each row
of the `arr` is a power spectrum at a particular time,
this function, then the Nth... | python | {
"resource": ""
} |
q46821 | first_order_gradient | train | def first_order_gradient(arr, axis=0):
'''
Returns the gradient of arr along a particular axis using
the first order forward-difference.
Additionally, the result is padded with 0 so that the
returned array is the same shape as in input array.
'''
grad_arr = difference(arr, n=1, axis=axis)
return np.inse... | python | {
"resource": ""
} |
q46822 | entropy | train | def entropy(p, w):
'''
Computes the entropy for a discrete probability distribution function, as
represented by a histogram, `p`, with bin sizes `w`,
h_p = Sum -1 * p_i * ln(p_i / w_i)
Also computes the maximum allowed entropy for a histogram with bin sizes `w`.
h_max = ln( Sum w_i )
and returns bo... | python | {
"resource": ""
} |
q46823 | download | train | def download(url):
"""Uses requests to download an URL, maybe from a file"""
session = requests.Session()
session.mount('file://', FileAdapter())
try:
res = session.get(url)
except requests.exceptions.ConnectionError as e:
raise e
res.raise_for_status()
return res | python | {
"resource": ""
} |
q46824 | get_uri_name | train | def get_uri_name(url):
"""Gets the file name from the end of the URL. Only useful for PyBEL's testing though since it looks specifically
if the file is from the weird owncloud resources distributed by Fraunhofer"""
url_parsed = urlparse(url)
url_parts = url_parsed.path.split('/')
log.info('url par... | python | {
"resource": ""
} |
q46825 | numbafy | train | def numbafy(fn, args, compiler="jit", **nbkws):
"""
Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic expressions coming... | python | {
"resource": ""
} |
q46826 | summary | train | def summary(raster, geometry=None, all_touched=False, mean_only=False,
bounds=None, exclude_nodata_value=True):
"""Return ``ST_SummaryStats`` style stats for the given raster.
If ``geometry`` is provided, we mask the raster with the given geometry and
return the stats for the intersection. The ... | python | {
"resource": ""
} |
q46827 | parse_template | train | def parse_template(template_path, **kwargs):
""" Load and render template.
First line of template should contain the subject of email.
Return tuple with subject and content.
"""
template = get_template(template_path)
context = Context(kwargs)
data = template.render(context).strip()
... | python | {
"resource": ""
} |
q46828 | substitute | train | def substitute(search, replace, text):
'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``'
return re.sub(re.compile(str(search)), replace, text) | python | {
"resource": ""
} |
q46829 | search | train | def search(pattern, text):
'Regex pattern search. Returns match if ``pattern`` is found in ``text``'
return re.compile(str(pattern)).search(str(text)) | python | {
"resource": ""
} |
q46830 | Object.getmany | train | def getmany(cls, route, args, kwargs, _keys):
"""
1. build name space
2. look locally for copies
3. build group for batch
4. fetch the new ones
5. return found + new list
"""
# copy the list of keys
keys = [] + _keys
# build a list of retur... | python | {
"resource": ""
} |
q46831 | ListNode._make_instance | train | def _make_instance(self, node_data):
"""
Create a ListNode instance from node_data
Args:
node_data (dict): Data to create ListNode item.
Returns:
ListNode item.
"""
node_data['from_db'] = self._from_db
clone = self.__call__(**node_data)
... | python | {
"resource": ""
} |
q46832 | ListNode.clean_value | train | def clean_value(self):
"""
Populates json serialization ready data.
This is the method used to serialize and store the object data in to DB
Returns:
List of dicts.
"""
result = []
for mdl in self:
result.append(super(ListNode, mdl).clean_v... | python | {
"resource": ""
} |
q46833 | ListNode.remove | train | def remove(self):
"""
Removes an item from ListNode.
Raises:
TypeError: If it's called on container ListNode (intstead of ListNode's item)
Note:
Parent object should be explicitly saved.
"""
if not self._is_item:
raise TypeError("Shou... | python | {
"resource": ""
} |
q46834 | XMLEncoder.encode | train | def encode(self):
"""
Encodes the object to a xml.etree.ElementTree.Element
:return: the encoded element
:rtype: xml.etree.ElementTree.Element
"""
root_element = ElementTree.Element(self.TAG_NAME)
for value in [value for value in self.__dict__.values() if isinsta... | python | {
"resource": ""
} |
q46835 | Graph.strings | train | def strings(self):
"""
The structure of the bar graph. A list that contains all the strings
that build up a bar in the given position. thise strings are inside a
list, starting from the top level.
structure: [
1st bar -> ['1st level str', ..., 'height-1 str', 'height... | python | {
"resource": ""
} |
q46836 | Graph.__get_stack_id | train | def __get_stack_id(self, value, values, height):
"""
Returns the index of the column representation of the given value
▁ ▂ ▃ ▄ ▅ ▆ ▇' ...
▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ▇ ▇ ▇ ▇ ▇ ...
▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ... | python | {
"resource": ""
} |
q46837 | check_key | train | def check_key(data_object, key, cardinal=False):
"""
Update the value of an index key by matching values or getting positionals.
"""
itype = (int, np.int32, np.int64)
if not isinstance(key, itype + (slice, tuple, list, np.ndarray)):
raise KeyError("Unknown key type {} for key {}".format(type... | python | {
"resource": ""
} |
q46838 | BaseDataFrame.slice_cardinal | train | def slice_cardinal(self, key):
"""
Get the slice of this object by the value or values of the cardinal
dimension.
"""
cls = self.__class__
key = check_key(self, key, cardinal=True)
return cls(self[self[self._cardinal[0]].isin(key)]) | python | {
"resource": ""
} |
q46839 | DataFrame._revert_categories | train | def _revert_categories(self):
"""
Inplace conversion to categories.
"""
for column, dtype in self._categories.items():
if column in self.columns:
self[column] = self[column].astype(dtype) | python | {
"resource": ""
} |
q46840 | DataFrame._set_categories | train | def _set_categories(self):
"""
Inplace conversion from categories.
"""
for column, _ in self._categories.items():
if column in self.columns:
self[column] = self[column].astype('category') | python | {
"resource": ""
} |
q46841 | Field.memory_usage | train | def memory_usage(self):
"""
Get the combined memory usage of the field data and field values.
"""
data = super(Field, self).memory_usage()
values = 0
for value in self.field_values:
values += value.memory_usage()
data['field_values'] = values
r... | python | {
"resource": ""
} |
q46842 | cli | train | def cli():
"""Function for cli"""
epilog = ('The actions are:\n'
'\tnew\t\tCreate a new torn app\n'
'\trun\t\tRun the app and start a Web server for development\n'
'\tcontroller\tCreate a new controller\n'
'\tversion\t\treturns the current version of torn\n')
... | python | {
"resource": ""
} |
q46843 | State.release | train | def release(self):
"""Destroys the state, along with its functions."""
self.clear()
if hasattr(self, "functions"):
del self.functions
if hasattr(self, "lib") and self.lib is not None:
self.lib._jit_destroy_state(self.state)
self.lib = None | python | {
"resource": ""
} |
q46844 | State.clear | train | def clear(self):
"""Clears state so it can be used for generating entirely new
instructions."""
if not self._clear:
self.lib._jit_clear_state(self.state)
self._clear = True | python | {
"resource": ""
} |
q46845 | State.emit_function | train | def emit_function(self, return_type=None, argtypes=[], proxy=True):
"""Compiles code and returns a Python-callable function."""
if argtypes is not None:
make_func = ctypes.CFUNCTYPE(return_type, *argtypes)
else:
make_func = ctypes.CFUNCTYPE(return_type)
# NOTE: ... | python | {
"resource": ""
} |
q46846 | Attachment.change_url | train | async def change_url(self, url: str, description: str = None):
""" change the url of that attachment
|methcoro|
Args:
url: url you want to change
description: *optional* description for your attachment
Raises:
ValueError: url must not be None
... | python | {
"resource": ""
} |
q46847 | Attachment.change_file | train | async def change_file(self, file_path: str, description: str = None):
""" change the file of that attachment
|methcoro|
Warning:
|unstable|
Args:
file_path: path to the file you want to add / modify
description: *optional* description for your attac... | python | {
"resource": ""
} |
q46848 | cached | train | def cached(namespace=None, service="memory", debug=False):
"""
Wrapper for tornado requests. Example
```
class MainHandler(tornado.web.RequestHandler):
@debris.tornado.cached("home-page")
def get(self):
self.write("Hello, world")
```
"""
_service = getattr(debr... | python | {
"resource": ""
} |
q46849 | which | train | def which(program, environ=None):
"""
Find out if an executable exists in the supplied PATH.
If so, the absolute path to the executable is returned.
If not, an exception is raised.
:type string
:param program: Executable to be checked for
:param dict
:param environ: Any additional ENV ... | python | {
"resource": ""
} |
q46850 | ContactFormView.form_valid | train | def form_valid(self, form):
"""This is what's called when the form is valid."""
instance = form.save(commit=False)
if hasattr(self.request, 'user'):
instance.user = self.request.user
if settings.CONTACT_FORM_FILTER_MESSAGE:
instance.message = bleach.clean(
... | python | {
"resource": ""
} |
q46851 | ContactFormView.form_invalid | train | def form_invalid(self, form):
"""This is what's called when the form is invalid."""
ip = get_user_ip(self.request)
if settings.CONTACT_FORM_USE_SIGNALS:
contact_form_invalid.send(
sender=self,
event=self.invalid_event,
ip=ip,
... | python | {
"resource": ""
} |
q46852 | CreateTagCallMixin.add_tag | train | def add_tag(self, name):
"""
Create a Tag to current object
:param name: the name of the tag
:type name: str
:return: newly created Tag
:rtype: Tag
"""
from highton.models.tag import Tag
created_id = self._post_request(
endpoint=self.E... | python | {
"resource": ""
} |
q46853 | time_bins | train | def time_bins(header):
'''
Returns the time-axis lower bin edge values for the spectrogram.
'''
return np.arange(header['number_of_half_frames'], dtype=np.float64)*constants.bins_per_half_frame\
*(1.0 - header['over_sampling']) / header['subband_spacing_hz'] | python | {
"resource": ""
} |
q46854 | frequency_bins | train | def frequency_bins(header):
'''
Returnes the frequency-axis lower bin edge values for the spectrogram.
'''
center_frequency = 1.0e6*header['rf_center_frequency']
if header["number_of_subbands"] > 1:
center_frequency += header["subband_spacing_hz"]*(header["number_of_subbands"]/2.0 - 0.5)
return np.ff... | python | {
"resource": ""
} |
q46855 | fourier_to_time | train | def fourier_to_time(fcdata, norm=None):
'''
Converts the data from 2D fourier space signal to a 1D time-series.
fcdata: Complex fourier spectrum as a 2D array, The axis=0 is for each "half frame", and axis=1 contains the
fourier-space data for that half frame. Typically there are 129 "half frames" in the data.... | python | {
"resource": ""
} |
q46856 | compamp_to_spectrogram | train | def compamp_to_spectrogram(compamp):
'''
Returns spectrogram, with each row containing the measured power spectrum for a XX second time sample.
Using this function is shorthand for:
aca = ibmseti.compamp.Compamp(raw_data)
power = ibmseti.dsp.complex_to_power(aca.complex_data(), aca.header()['over_sam... | python | {
"resource": ""
} |
q46857 | compamp_to_ac | train | def compamp_to_ac(compamp, window=np.hanning): # convert single or multi-subband compamps into autocorrelation waterfall
'''
Adapted from Gerry Harp at SETI.
'''
header = compamp.header()
cdata = compamp.complex_data()
#Apply Windowing and Padding
cdata = np.multiply(cdata, window(cdata.shape[2]))... | python | {
"resource": ""
} |
q46858 | ac_viz | train | def ac_viz(acdata):
'''
Adapted from Gerry Harp at SETI.
Slightly massages the autocorrelated calculation result for better visualization.
In particular, the natural log of the data are calculated and the
values along the subband edges are set to the maximum value of the data,
and the t=0 delay of the ... | python | {
"resource": ""
} |
q46859 | Allen.relation | train | def relation(x_start, x_end, y_start, y_end):
"""
Returns the relation between two intervals.
:param int x_start: The start point of the first interval.
:param int x_end: The end point of the first interval.
:param int y_start: The start point of the second interval.
:pa... | python | {
"resource": ""
} |
q46860 | WSGIConnection.simple_response | train | def simple_response(self, status, msg=""):
"""Return a operation for writing simple response back to the client."""
status = str(status)
buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
"Content-Length: %s\r\n" % len(msg),
"Content-Type: text/plain\r\n"]
i... | python | {
"resource": ""
} |
q46861 | Lightning.load | train | def load(self, name):
"""Loads and returns foreign library."""
name = ctypes.util.find_library(name)
return ctypes.cdll.LoadLibrary(name) | python | {
"resource": ""
} |
q46862 | Lightning._set_signatures | train | def _set_signatures(self):
"""Sets return and parameter types for the foreign C functions."""
# We currently pass structs as void pointers.
code_t = ctypes.c_int
gpr_t = ctypes.c_int32
int32_t = ctypes.c_int32
node_p = ctypes.c_void_p
pointer_t = ctypes.c_void_p
... | python | {
"resource": ""
} |
q46863 | Constructor.__to_plain_containers | train | def __to_plain_containers(self,
container: Union[CommentedSeq, CommentedMap]
) -> Union[OrderedDict, list]:
"""Converts any sequence or mapping to list or OrderedDict
Stops at anything that isn't a sequence or a mapping.
One day, we'l... | python | {
"resource": ""
} |
q46864 | Constructor.__split_off_extra_attributes | train | def __split_off_extra_attributes(self, mapping: CommentedMap,
known_attrs: List[str]) -> CommentedMap:
"""Separates the extra attributes in mapping into yatiml_extra.
This returns a mapping containing all key-value pairs from \
mapping whose key is in known_... | python | {
"resource": ""
} |
q46865 | Constructor.__type_matches | train | def __type_matches(self, obj: Any, type_: Type) -> bool:
"""Checks that the object matches the given type.
Like isinstance(), but will work with union types using Union, \
Dict and List.
Args:
obj: The object to check
type_: The type to check against
Re... | python | {
"resource": ""
} |
q46866 | Constructor.__check_no_missing_attributes | train | def __check_no_missing_attributes(self, node: yaml.Node,
mapping: CommentedMap) -> None:
"""Checks that all required attributes are present.
Also checks that they're of the correct type.
Args:
mapping: The mapping with subobjects of this object... | python | {
"resource": ""
} |
q46867 | Constructor.__type_check_attributes | train | def __type_check_attributes(self, node: yaml.Node, mapping: CommentedMap,
argspec: inspect.FullArgSpec) -> None:
"""Ensure all attributes have a matching constructor argument.
This checks that there is a constructor argument with a \
matching type for each existi... | python | {
"resource": ""
} |
q46868 | Constructor.__strip_extra_attributes | train | def __strip_extra_attributes(self, node: yaml.Node,
known_attrs: List[str]) -> None:
"""Strips tags from extra attributes.
This prevents nodes under attributes that are not part of our \
data model from being converted to objects. They'll be plain \
Comm... | python | {
"resource": ""
} |
q46869 | Constructor.__strip_tags | train | def __strip_tags(self, node: yaml.Node) -> None:
"""Strips tags from mappings in the tree headed by node.
This keeps yaml from constructing any objects in this tree.
Args:
node: Head of the tree to strip
"""
if isinstance(node, yaml.SequenceNode):
for su... | python | {
"resource": ""
} |
q46870 | has_provider_support | train | def has_provider_support(provider, media_type):
""" Verifies if API provider has support for requested media type
"""
if provider.lower() not in API_ALL:
return False
provider_const = "API_" + media_type.upper()
return provider in globals().get(provider_const, {}) | python | {
"resource": ""
} |
q46871 | provider_factory | train | def provider_factory(provider, **options):
""" Factory function for DB Provider Concrete Classes
"""
try:
return {"tmdb": TMDb, "tvdb": TVDb}[provider.lower()](**options)
except KeyError:
msg = "Attempted to initialize non-existing DB Provider"
log.error(msg)
raise MapiEx... | python | {
"resource": ""
} |
q46872 | Provider._year_expand | train | def _year_expand(s):
""" Parses a year or dash-delimeted year range
"""
regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$"
try:
start, dash, end = match(regex, ustr(s)).groups()
start = start or 1900
end = end or 2099
except AttributeErr... | python | {
"resource": ""
} |
q46873 | TMDb.search | train | def search(self, id_key=None, **parameters):
""" Searches TMDb for movie metadata
"""
id_tmdb = parameters.get("id_tmdb") or id_key
id_imdb = parameters.get("id_imdb")
title = parameters.get("title")
year = parameters.get("year")
if id_tmdb:
yield sel... | python | {
"resource": ""
} |
q46874 | TVDb.search | train | def search(self, id_key=None, **parameters):
""" Searches TVDb for movie metadata
TODO: Consider making parameters for episode ids
"""
episode = parameters.get("episode")
id_tvdb = parameters.get("id_tvdb") or id_key
id_imdb = parameters.get("id_imdb")
season = p... | python | {
"resource": ""
} |
q46875 | _mkdirs | train | def _mkdirs(d):
"""
Make all directories up to d.
No exception is raised if d exists.
"""
try:
os.makedirs(d)
except OSError as e:
if e.errno != errno.EEXIST:
raise | python | {
"resource": ""
} |
q46876 | nest_map | train | def nest_map(control_iter, map_fn):
"""
Apply ``map_fn`` to the directories defined by ``control_iter``
For each control file in control_iter, map_fn is called with the directory
and control file contents as arguments.
Example::
>>> list(nest_map(['run1/control.json', 'run2/control.json']... | python | {
"resource": ""
} |
q46877 | control_iter | train | def control_iter(base_dir, control_name=CONTROL_NAME):
"""
Generate the names of all control files under base_dir
"""
controls = (os.path.join(p, control_name) for p, _, fs in os.walk(base_dir)
if control_name in fs)
return controls | python | {
"resource": ""
} |
q46878 | Nest.build | train | def build(self, root="runs"):
"""
Build a nested directory structure, starting in ``root``
:param root: Root directory for structure
"""
for d, control in self.iter(root):
_mkdirs(d)
with open(os.path.join(d, self.control_name), 'w') as fp:
... | python | {
"resource": ""
} |
q46879 | Nest.add | train | def add(self, name, nestable, create_dir=True, update=False,
label_func=str, template_subs=False):
"""
Add a level to the nest
:param string name: Name of the level. Forms the key in the output
dictionary.
:param nestable: Either an iterable object containing val... | python | {
"resource": ""
} |
q46880 | Composer.get_kwargs | train | def get_kwargs(self):
"""Return kwargs from attached attributes."""
return {k: v for k, v in vars(self).items() if k not in self._ignored} | python | {
"resource": ""
} |
q46881 | lines_from_file | train | def lines_from_file(path, as_interned=False, encoding=None):
"""
Create a list of file lines from a given filepath.
Args:
path (str): File path
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list
"""
lines = None
wi... | python | {
"resource": ""
} |
q46882 | lines_from_stream | train | def lines_from_stream(f, as_interned=False):
"""
Create a list of file lines from a given file stream.
Args:
f (io.TextIOWrapper): File stream
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list
"""
if as_interned:
... | python | {
"resource": ""
} |
q46883 | lines_from_string | train | def lines_from_string(string, as_interned=False):
"""
Create a list of file lines from a given string.
Args:
string (str): File string
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list
"""
if as_interned:
retu... | python | {
"resource": ""
} |
q46884 | Editor.write | train | def write(self, path=None, *args, **kwargs):
"""
Perform formatting and write the formatted string to a file or stdout.
Optional arguments can be used to format the editor's contents. If no
file path is given, prints to standard output.
Args:
path (str): Full file p... | python | {
"resource": ""
} |
q46885 | Editor.format | train | def format(self, *args, **kwargs):
"""
Format the string representation of the editor.
Args:
inplace (bool): If True, overwrite editor's contents with formatted contents
"""
inplace = kwargs.pop("inplace", False)
if not inplace:
return str(self).f... | python | {
"resource": ""
} |
q46886 | Editor.head | train | def head(self, n=10):
"""
Display the top of the file.
Args:
n (int): Number of lines to display
"""
r = self.__repr__().split('\n')
print('\n'.join(r[:n]), end=' ') | python | {
"resource": ""
} |
q46887 | Editor.insert | train | def insert(self, lines=None):
"""
Insert lines into the editor.
Note:
To insert before the first line, use :func:`~exa.core.editor.Editor.preappend`
(or key 0); to insert after the last line use :func:`~exa.core.editor.Editor.append`.
Args:
lines (di... | python | {
"resource": ""
} |
q46888 | Editor._data | train | def _data(self, copy=False):
"""
Get all data associated with the container as key value pairs.
"""
data = {}
for key, obj in self.__dict__.items():
if isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)):
if copy:
... | python | {
"resource": ""
} |
q46889 | Editor.delete_lines | train | def delete_lines(self, lines):
"""
Delete all lines with given line numbers.
Args:
lines (list): List of integers corresponding to line numbers to delete
"""
for k, i in enumerate(lines):
del self[i-k] | python | {
"resource": ""
} |
q46890 | Editor.find | train | def find(self, *strings, **kwargs):
"""
Search the entire editor for lines that match the string.
.. code-block:: Python
string = '''word one
word two
three'''
ed = Editor(string)
ed.find('word') # [(0, "word one"), (1, "word... | python | {
"resource": ""
} |
q46891 | Editor.find_next | train | def find_next(self, *strings, **kwargs):
"""
From the editor's current cursor position find the next instance of the
given string.
Args:
strings (iterable): String or strings to search for
Returns:
tup (tuple): Tuple of cursor position and line or None i... | python | {
"resource": ""
} |
q46892 | Editor.regex | train | def regex(self, *patterns, **kwargs):
"""
Search the editor for lines matching the regular expression.
re.MULTILINE is not currently supported.
Args:
\*patterns: Regular expressions to search each line for
keys_only (bool): Only return keys
flags (re.... | python | {
"resource": ""
} |
q46893 | Editor.replace | train | def replace(self, pattern, replacement):
"""
Replace all instances of a pattern with a replacement.
Args:
pattern (str): Pattern to replace
replacement (str): Text to insert
"""
for i, line in enumerate(self):
if pattern in line:
... | python | {
"resource": ""
} |
q46894 | Editor.pandas_dataframe | train | def pandas_dataframe(self, start, stop, ncol, **kwargs):
"""
Returns the result of tab-separated pandas.read_csv on
a subset of the file.
Args:
start (int): line number where structured data starts
stop (int): line number where structured data stops
n... | python | {
"resource": ""
} |
q46895 | Editor.variables | train | def variables(self):
"""
Display a list of templatable variables present in the file.
Templating is accomplished by creating a bracketed object in the same
way that Python performs `string formatting`_. The editor is able to
replace the placeholder value of the template. Integer... | python | {
"resource": ""
} |
q46896 | Editor.from_file | train | def from_file(cls, path, **kwargs):
"""Create an editor instance from a file on disk."""
lines = lines_from_file(path)
if 'meta' not in kwargs:
kwargs['meta'] = {'from': 'file'}
kwargs['meta']['filepath'] = path
return cls(lines, **kwargs) | python | {
"resource": ""
} |
q46897 | Editor.from_stream | train | def from_stream(cls, f, **kwargs):
"""Create an editor instance from a file stream."""
lines = lines_from_stream(f)
if 'meta' not in kwargs:
kwargs['meta'] = {'from': 'stream'}
kwargs['meta']['filepath'] = f.name if hasattr(f, 'name') else None
return cls(lines, **kwa... | python | {
"resource": ""
} |
q46898 | generic_type_args | train | def generic_type_args(type_: Type) -> List[Type]:
"""Gets the type argument list for the given generic type.
If you give this function List[int], it will return [int], and
if you give it Union[int, str] it will give you [int, str]. Note
that on Python < 3.7, Union[int, bool] collapses to Union[int] and... | python | {
"resource": ""
} |
q46899 | type_to_desc | train | def type_to_desc(type_: Type) -> str:
"""Convert a type to a human-readable description.
This is used for generating nice error messages. We want users \
to see a nice readable text, rather than something like \
"typing.List<~T>[str]".
Args:
type_: The type to represent.
Returns:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.