INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Given an URI, detects plugin and encoding and imports into a `rows.Table` | def import_from_uri(
uri, default_encoding="utf-8", verify_ssl=True, progress=False, *args, **kwargs
):
"Given an URI, detects plugin and encoding and imports into a `rows.Table`"
# TODO: support '-' also
# TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can
# skip encod... |
Given a `rows.Table` and an URI, detects plugin (from URI) and exports | def export_to_uri(table, uri, *args, **kwargs):
"Given a `rows.Table` and an URI, detects plugin (from URI) and exports"
# TODO: support '-' also
plugin_name = plugin_name_by_uri(uri)
try:
export_function = getattr(rows, "export_to_{}".format(plugin_name))
except AttributeError:
ra... |
Return a text-based file object from a filename, even if compressed | def open_compressed(filename, mode="r", encoding=None):
"Return a text-based file object from a filename, even if compressed"
# TODO: integrate this function in the library itself, using
# get_filename_and_fobj
binary_mode = "b" in mode
extension = str(filename).split(".")[-1].lower()
if binary... |
Export a CSV file to SQLite, based on field type detection from samples | def csv_to_sqlite(
input_filename,
output_filename,
samples=None,
dialect=None,
batch_size=10000,
encoding="utf-8",
callback=None,
force_types=None,
chunk_size=8388608,
table_name="table1",
schema=None,
):
"Export a CSV file to SQLite, based on field type detection from s... |
Export a table inside a SQLite database to CSV | def sqlite_to_csv(
input_filename,
table_name,
output_filename,
dialect=csv.excel,
batch_size=10000,
encoding="utf-8",
callback=None,
query=None,
):
"""Export a table inside a SQLite database to CSV"""
# TODO: should be able to specify fields
# TODO: should be able to specif... |
Execute a command and return its output | def execute_command(command):
"""Execute a command and return its output"""
command = shlex.split(command)
try:
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFou... |
Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value. | def uncompressed_size(filename):
"""Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value.
"""
quoted_filename = shlex.quote(filename)
# TODO: get filetype from file-magic, if avail... |
Import data from CSV into PostgreSQL using the fastest method
Required: psql command | def pgimport(
filename,
database_uri,
table_name,
encoding="utf-8",
dialect=None,
create_table=True,
schema=None,
callback=None,
timeout=0.1,
chunk_size=8388608,
max_samples=10000,
):
"""Import data from CSV into PostgreSQL using the fastest method
Required: psql com... |
Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command | def pgexport(
database_uri,
table_name,
filename,
encoding="utf-8",
dialect=csv.excel,
callback=None,
timeout=0.1,
chunk_size=8388608,
):
"""Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command
"""
if isinstance(dialect, six.text_t... |
Generate table schema for a specific output format and write
Current supported output formats: 'txt', 'sql' and 'django'.
The table name and all fields names pass for a slugifying process (table
name is taken from file name). | def generate_schema(table, export_fields, output_format, output_fobj):
"""Generate table schema for a specific output format and write
Current supported output formats: 'txt', 'sql' and 'django'.
The table name and all fields names pass for a slugifying process (table
name is taken from file name).
... |
Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField} | def load_schema(filename, context=None):
"""Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField... |
Return a callable that fetches the given indexes of an object
Always return a tuple even when len(indexes) == 1.
Similar to `operator.itemgetter`, but will insert `None` when the object
does not have the desired index (instead of raising IndexError). | def get_items(*indexes):
"""Return a callable that fetches the given indexes of an object
Always return a tuple even when len(indexes) == 1.
Similar to `operator.itemgetter`, but will insert `None` when the object
does not have the desired index (instead of raising IndexError).
"""
return lambd... |
Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen' | def slug(text, separator="_", permitted_chars=SLUG_CHARS):
"""Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen'
"""
text = six.text_type(text or "")
# Strip non-ASCII characters
# Example: u' ... |
Return a unique name based on `name_format` and `name`. | def make_unique_name(name, existing_names, name_format="{name}_{index}", start=2):
"""Return a unique name based on `name_format` and `name`."""
index = start
new_name = name
while new_name in existing_names:
new_name = name_format.format(name=name, index=index)
index += 1
return ne... |
Return unique and slugged field names. | def make_header(field_names, permit_not=False):
"""Return unique and slugged field names."""
slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^"
header = [
slug(field_name, permitted_chars=slug_chars) for field_name in field_names
]
result = []
for index, field_name in enume... |
Detect column types (or "where the magic happens") | def detect_types(
field_names,
field_values,
field_types=DEFAULT_TYPES,
skip_indexes=None,
type_detector=TypeDetector,
fallback_type=TextField,
*args,
**kwargs
):
"""Detect column types (or "where the magic happens")"""
# TODO: look strategy of csv.Sniffer.has_header
# TODO:... |
Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`. | def deserialize(cls, value, *args, **kwargs):
"""Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`.
"""
if isinstance(value, cls.TYPE):
return value
elif is_null(value):
return... |
Filter out objects outside table boundaries | def selected_objects(self):
"""Filter out objects outside table boundaries"""
return [
obj
for obj in self.text_objects
if contains_or_overlap(self.table_bbox, obj.bbox)
] |
Extract links from "project" field and remove HTML from all | def transform(row, table):
'Extract links from "project" field and remove HTML from all'
data = row._asdict()
data["links"] = " ".join(extract_links(row.project))
for key, value in data.items():
if isinstance(value, six.text_type):
data[key] = extract_text(value)
return data |
Transform row "link" into full URL and add "state" based on "name" | def transform(row, table):
'Transform row "link" into full URL and add "state" based on "name"'
data = row._asdict()
data["link"] = urljoin("https://pt.wikipedia.org", data["link"])
data["name"], data["state"] = regexp_city_state.findall(data["name"])[0]
return data |
Import data from a Parquet file and return with rows.Table. | def import_from_parquet(filename_or_fobj, *args, **kwargs):
"""Import data from a Parquet file and return with rows.Table."""
source = Source.from_file(filename_or_fobj, plugin_name="parquet", mode="rb")
# TODO: should look into `schema.converted_type` also
types = OrderedDict(
[
(s... |
Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used). | def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
cached_rows, headers = [], []
for in... |
Export a `rows.Table` to a list of dicts | def export_to_dicts(table, *args, **kwargs):
"""Export a `rows.Table` to a list of dicts"""
field_names = table.field_names
return [{key: getattr(row, key) for key in field_names} for row in table] |
>>> extract_intervals("1,2,3")
[1, 2, 3]
>>> extract_intervals("1,2,5-10")
[1, 2, 5, 6, 7, 8, 9, 10]
>>> extract_intervals("1,2,5-10,3")
[1, 2, 3, 5, 6, 7, 8, 9, 10]
>>> extract_intervals("1,2,5-10,6,7")
[1, 2, 5, 6, 7, 8, 9, 10] | def extract_intervals(text, repeat=False, sort=True):
"""
>>> extract_intervals("1,2,3")
[1, 2, 3]
>>> extract_intervals("1,2,5-10")
[1, 2, 5, 6, 7, 8, 9, 10]
>>> extract_intervals("1,2,5-10,3")
[1, 2, 3, 5, 6, 7, 8, 9, 10]
>>> extract_intervals("1,2,5-10,6,7")
[1, 2, 5, 6, 7, 8, 9, ... |
Return the cell value of the table passed by argument, based in row and column. | def cell_value(sheet, row, col):
"""Return the cell value of the table passed by argument, based in row and column."""
cell = sheet.cell(row, col)
field_type = CELL_TYPES[cell.ctype]
# TODO: this approach will not work if using locale
value = cell.value
if field_type is None:
return No... |
Return a rows.Table created from imported XLS file. | def import_from_xls(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLS file."""
source = Source.from_file(filename_or_fobj, mode="rb", plugin... |
Export the rows.Table to XLS file and return the saved file. | def export_to_xls(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLS file and return the saved file."""
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(sheet_name)
prepared_table = prepare_to_export(table, *args, **kwargs)
field_names = next... |
Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _ | def _valid_table_name(name):
"""Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _
"""
if name[0] not in "_" + string.ascii_letters or not set(name).issubset(
"_" + string.... |
Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles) | def _parse_col_positions(frame_style, header_line):
"""Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles)
"""
separator = re.escape(FRAMES[frame_... |
Return a rows.Table created from imported TXT file. | def import_from_txt(
filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
"""Return a rows.Table created from imported TXT file."""
# TODO: (maybe)
# enable parsing of non-fixed-width-columns
# with old algorithm - that would just split columns
# at the vertical se... |
Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding` could be `None` if no filename/file-like object is specified,
then the return type will be `six.text_type`.
`frame_style`: will select the frame style t... | def export_to_txt(
table,
filename_or_fobj=None,
encoding=None,
frame_style="ASCII",
safe_none_frame=True,
*args,
**kwargs
):
"""Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding`... |
Return a rows.Table with data from SQLite database. | def import_from_sqlite(
filename_or_connection,
table_name="table1",
query=None,
query_args=None,
*args,
**kwargs
):
"""Return a rows.Table with data from SQLite database."""
source = get_source(filename_or_connection)
connection = source.fobj
cursor = connection.cursor()
if... |
Convert a PyOpenXL's `Cell` object to the corresponding Python object. | def _cell_to_python(cell):
"""Convert a PyOpenXL's `Cell` object to the corresponding Python object."""
data_type, value = cell.data_type, cell.value
if type(cell) is EmptyCell:
return None
elif data_type == "f" and value == "=TRUE()":
return True
elif data_type == "f" and value == ... |
Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to openpyxl.load_workbook | def import_from_xlsx(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
workbook_kwargs=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to op... |
Export the rows.Table to XLSX file and return the saved file. | def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLSX file and return the saved file."""
workbook = Workbook()
sheet = workbook.active
sheet.title = sheet_name
prepared_table = prepare_to_export(table, *args, **kwargs)
# Write ... |
Download organizations JSON and extract its properties | def download_organizations():
"Download organizations JSON and extract its properties"
response = requests.get(URL)
data = response.json()
organizations = [organization["properties"] for organization in data["features"]]
return rows.import_from_dicts(organizations) |
Define table name based on its metadata (filename used on import)
If `filename` is not available, return `table1`. | def name(self):
"""Define table name based on its metadata (filename used on import)
If `filename` is not available, return `table1`.
"""
from rows.plugins.utils import slug
name = self.meta.get("name", None)
if name is not None:
return slug(name)
... |
Return rows.Table from HTML file. | def import_from_html(
filename_or_fobj,
encoding="utf-8",
index=0,
ignore_colspan=True,
preserve_html=False,
properties=False,
table_tag="table",
row_tag="tr",
column_tag="td|th",
*args,
**kwargs
):
"""Return rows.Table from HTML file."""
source = Source.from_file(
... |
Export and return rows.Table data to HTML file. | def export_to_html(
table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
"""Export and return rows.Table data to HTML file."""
serialized_table = serialize(table, *args, **kwargs)
fields = next(serialized_table)
result = ["<table>\n\n"]
if caption and table.name:
... |
Extract text from a given lxml node. | def _extract_node_text(node):
"""Extract text from a given lxml node."""
texts = map(
six.text_type.strip, map(six.text_type, map(unescape, node.xpath(".//text()")))
)
return " ".join(text for text in texts if text) |
Read a file passed by arg and return your table HTML tag count. | def count_tables(filename_or_fobj, encoding="utf-8", table_tag="table"):
"""Read a file passed by arg and return your table HTML tag count."""
source = Source.from_file(
filename_or_fobj, plugin_name="html", mode="rb", encoding=encoding
)
html = source.fobj.read().decode(source.encoding)
ht... |
Extract tag's attributes into a `dict`. | def tag_to_dict(html):
"""Extract tag's attributes into a `dict`."""
element = document_fromstring(html).xpath("//html/body/child::*")[0]
attributes = dict(element.attrib)
attributes["text"] = element.text_content()
return attributes |
Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is set
- `samples` is only used if `fields` is `None`. If samples=None, all data
is filled in memory - use with caution.
- `force_types` is only used if `fields` is `None`
- `import_fiel... | def create_table(
data,
meta=None,
fields=None,
skip_header=True,
import_fields=None,
samples=None,
force_types=None,
max_rows=None,
*args,
**kwargs
):
"""Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is se... |
Return the object ready to be exported or only data if filename_or_fobj is not passed. | def export_data(filename_or_fobj, data, mode="w"):
"""Return the object ready to be exported or only data if filename_or_fobj is not passed."""
if filename_or_fobj is None:
return data
_, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode)
source = Source.from_file(filename_or_fobj, mode... |
Read `sample` bytes from `fobj` and return the cursor to where it was. | def read_sample(fobj, sample):
"""Read `sample` bytes from `fobj` and return the cursor to where it was."""
cursor = fobj.tell()
data = fobj.read(sample)
fobj.seek(cursor)
return data |
Import data from a CSV file (automatically detects dialect).
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='rb')`. | def import_from_csv(
filename_or_fobj,
encoding="utf-8",
dialect=None,
sample_size=262144,
*args,
**kwargs
):
"""Import data from a CSV file (automatically detects dialect).
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='rb')`.
"""
... |
Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='wb')`.
If not filename/fobj is provided, the function returns a string with CSV
contents. | def export_to_csv(
table,
filename_or_fobj=None,
encoding="utf-8",
dialect=unicodecsv.excel,
batch_size=100,
callback=None,
*args,
**kwargs
):
"""Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='... |
Merge a list of `Table` objects using `keys` to group rows | def join(keys, tables):
"""Merge a list of `Table` objects using `keys` to group rows"""
# Make new (merged) Table fields
fields = OrderedDict()
for table in tables:
fields.update(table.fields)
# TODO: may raise an error if a same field is different in some tables
# Check if all keys a... |
Return a new table based on other tables and a transformation function | def transform(fields, function, *tables):
"Return a new table based on other tables and a transformation function"
new_table = Table(fields=fields)
for table in tables:
for row in filter(bool, map(lambda row: function(row, table), table)):
new_table.append(row)
return new_table |
Initiate a sniffing task. Make sure we only have one sniff request
running at any given time. If a finished sniffing request is around,
collect its result (which can raise its exception). | def initiate_sniff(self, initial=False):
"""
Initiate a sniffing task. Make sure we only have one sniff request
running at any given time. If a finished sniffing request is around,
collect its result (which can raise its exception).
"""
if self.sniffing_task and self.snif... |
Obtain a list of nodes from the cluster and create a new connection
pool using the information retrieved.
To extract the node connection parameters use the ``nodes_to_host_callback``.
:arg initial: flag indicating if this is during startup
(``sniff_on_start``), ignore the ``sniff_t... | def sniff_hosts(self, initial=False):
"""
Obtain a list of nodes from the cluster and create a new connection
pool using the information retrieved.
To extract the node connection parameters use the ``nodes_to_host_callback``.
:arg initial: flag indicating if this is during star... |
Make a k8s pod specification for running a user notebook.
Parameters
----------
name:
Name of pod. Must be unique within the namespace the object is
going to be created in. Must be a valid DNS label.
image:
Image specification - usually a image name and tag in the form
o... | def make_pod(
name,
cmd,
port,
image,
image_pull_policy,
image_pull_secret=None,
node_selector=None,
run_as_uid=None,
run_as_gid=None,
fs_gid=None,
supplemental_gids=None,
run_privileged=False,
env=None,
working_dir=None,
volumes=None,
volume_mounts=None,
... |
Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
going to be created in. Must be a valid DNS label.
storage_class:
String of the name of the k8s Storage Class ... | def make_pvc(
name,
storage_class,
access_modes,
storage,
labels=None,
annotations=None,
):
"""
Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
... |
Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared. | def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... |
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the objects really are.
If the length of the slug is shorter than the... | def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the o... |
Takes a model instance such as V1PodSpec() and updates it with another
model, which is allowed to be a dict or another model instance of the same
type. The logger is used to warn if any truthy value in the target is is
overridden. The target_name parameter can for example be "pod.spec", and
changes_name... | def update_k8s_model(target, changes, logger=None, target_name=None, changes_name=None):
"""
Takes a model instance such as V1PodSpec() and updates it with another
model, which is allowed to be a dict or another model instance of the same
type. The logger is used to warn if any truthy value in the targe... |
Returns an instance of type specified model_type from an model instance or
represantative dictionary. | def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... |
Returns a dictionary representation of a provided model type | def _get_k8s_model_dict(model_type, model):
"""
Returns a dictionary representation of a provided model type
"""
model = copy.deepcopy(model)
if isinstance(model, model_type):
return model.to_dict()
elif isinstance(model, dict):
return _map_dict_keys_to_model_attributes(model_ty... |
Maps a dict's keys to the provided models attributes using its attribute_map
attribute. This is (always?) the same as converting camelCase to snake_case.
Note that the function will not influence nested object's keys. | def _map_dict_keys_to_model_attributes(model_type, model_dict):
"""
Maps a dict's keys to the provided models attributes using its attribute_map
attribute. This is (always?) the same as converting camelCase to snake_case.
Note that the function will not influence nested object's keys.
"""
new_d... |
Takes a model type and a Kubernetes API resource field name (such as
"serviceAccount") and returns a related attribute name (such as
"service_account") to be used with kubernetes.client.models objects. It is
impossible to prove a negative but it seems like it is always a question of
making camelCase to... | def _get_k8s_model_attribute(model_type, field_name):
"""
Takes a model type and a Kubernetes API resource field name (such as
"serviceAccount") and returns a related attribute name (such as
"service_account") to be used with kubernetes.client.models objects. It is
impossible to prove a negative bu... |
Update current list of resources by doing a full fetch.
Overwrites all current resource info. | def _list_and_update(self):
"""
Update current list of resources by doing a full fetch.
Overwrites all current resource info.
"""
initial_resources = getattr(self.api, self.list_method_name)(
self.namespace,
label_selector=self.label_selector,
... |
Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
local store up-to-date based on these notifications.... | def _watch_and_update(self):
"""
Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
loc... |
Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initialization (when the singleton is being crea... | def start(self):
"""
Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initializat... |
Make a pod manifest that will spawn current user's notebook pod. | def get_pod_manifest(self):
"""
Make a pod manifest that will spawn current user's notebook pod.
"""
if callable(self.uid):
uid = yield gen.maybe_future(self.uid(self))
else:
uid = self.uid
if callable(self.gid):
gid = yield gen.maybe_... |
Make a pvc manifest that will spawn current user's pvc. | def get_pvc_manifest(self):
"""
Make a pvc manifest that will spawn current user's pvc.
"""
labels = self._build_common_labels(self._expand_all(self.storage_extra_labels))
labels.update({
'component': 'singleuser-storage'
})
annotations = self._build_... |
Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object. | def is_pod_running(self, pod):
"""
Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object.
"""
# FIXME: Validate if this is really the best way
is_running = (
pod is not None and
pod.status.phase == 'Ru... |
Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env | def get_env(self):
"""Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env
"""
env = super(KubeSpawner, self).get_env()
# deprecate image
env['JUPYTER_IMAGE_SPEC'] = self.image
env['JUPYTER_IMAGE'] = self.image
return... |
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These are the return values JupyterHub exp... | def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... |
Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start(). | def events(self):
"""Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start().
"""
if not self.event_reflector:
return []
events... |
Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
If replace=False and the pod reflector is already running,
do nothing.... | def _start_reflector(self, key, ReflectorClass, replace=False, **kwargs):
"""Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
... |
Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors). | def _start_watching_events(self, replace=False):
"""Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors).
... |
Start the user's pod | def _start(self):
"""Start the user's pod"""
# load user options (including profile)
yield self.load_user_options()
# record latest event so we don't include old
# events from previous pods in self.events
# track by order and name instead of uid
# so we get even... |
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined. | def _options_form_default(self):
'''
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined.
'''
if not self.profile_list:
... |
get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the form
To access to the value, you can use... | def options_from_form(self, formdata):
"""get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the... |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... |
Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options. | def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... |
Add traits with .tag(config=True) to members list | def get_object_members(self, want_all):
"""Add traits with .tag(config=True) to members list"""
check, members = super().get_object_members(want_all)
get_traits = self.object.class_own_traits if self.options.inherited_members \
else self.object.class_traits
trait_mem... |
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attr... | def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... |
Return the native speed measurement required to achieve desired rotations-per-second | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired rotations-per-second
"""
assert abs(self.rotations_per_second) <= motor.max_rps,\
"invalid rotations-per-second: {} max RPS is {}, {} was requested".format(
motor... |
Return the native speed measurement required to achieve desired rotations-per-minute | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired rotations-per-minute
"""
assert abs(self.rotations_per_minute) <= motor.max_rpm,\
"invalid rotations-per-minute: {} max RPM is {}, {} was requested".format(
motor... |
Return the native speed measurement required to achieve desired degrees-per-second | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired degrees-per-second
"""
assert abs(self.degrees_per_second) <= motor.max_dps,\
"invalid degrees-per-second: {} max DPS is {}, {} was requested".format(
motor, moto... |
Return the native speed measurement required to achieve desired degrees-per-minute | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired degrees-per-minute
"""
assert abs(self.degrees_per_minute) <= motor.max_dpm,\
"invalid degrees-per-minute: {} max DPM is {}, {} was requested".format(
motor, moto... |
Returns the name of the port that this motor is connected to. | def address(self):
"""
Returns the name of the port that this motor is connected to.
"""
self._address, value = self.get_attr_string(self._address, 'address')
return value |
Returns a list of commands that are supported by the motor
controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,
`run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.
- `run-forever` will cause the motor to run until another command is se... | def commands(self):
"""
Returns a list of commands that are supported by the motor
controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,
`run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.
- `run-forever` will cause the ... |
Returns the number of tacho counts in one rotation of the motor. Tacho counts
are used by the position and speed attributes, so you can use this value
to convert rotations or degrees to tacho counts. (rotation motors only) | def count_per_rot(self):
"""
Returns the number of tacho counts in one rotation of the motor. Tacho counts
are used by the position and speed attributes, so you can use this value
to convert rotations or degrees to tacho counts. (rotation motors only)
"""
(self._count_per... |
Returns the number of tacho counts in one meter of travel of the motor. Tacho
counts are used by the position and speed attributes, so you can use this
value to convert from distance to tacho counts. (linear motors only) | def count_per_m(self):
"""
Returns the number of tacho counts in one meter of travel of the motor. Tacho
counts are used by the position and speed attributes, so you can use this
value to convert from distance to tacho counts. (linear motors only)
"""
(self._count_per_m, ... |
Returns the name of the driver that provides this tacho motor device. | def driver_name(self):
"""
Returns the name of the driver that provides this tacho motor device.
"""
(self._driver_name, value) = self.get_cached_attr_string(self._driver_name, 'driver_name')
return value |
Returns the current duty cycle of the motor. Units are percent. Values
are -100 to 100. | def duty_cycle(self):
"""
Returns the current duty cycle of the motor. Units are percent. Values
are -100 to 100.
"""
self._duty_cycle, value = self.get_attr_int(self._duty_cycle, 'duty_cycle')
return value |
Writing sets the duty cycle setpoint. Reading returns the current value.
Units are in percent. Valid values are -100 to 100. A negative value causes
the motor to rotate in reverse. | def duty_cycle_sp(self):
"""
Writing sets the duty cycle setpoint. Reading returns the current value.
Units are in percent. Valid values are -100 to 100. A negative value causes
the motor to rotate in reverse.
"""
self._duty_cycle_sp, value = self.get_attr_int(self._duty_... |
Returns the number of tacho counts in the full travel of the motor. When
combined with the `count_per_m` atribute, you can use this value to
calculate the maximum travel distance of the motor. (linear motors only) | def full_travel_count(self):
"""
Returns the number of tacho counts in the full travel of the motor. When
combined with the `count_per_m` atribute, you can use this value to
calculate the maximum travel distance of the motor. (linear motors only)
"""
(self._full_travel_co... |
Sets the polarity of the motor. With `normal` polarity, a positive duty
cycle will cause the motor to rotate clockwise. With `inversed` polarity,
a positive duty cycle will cause the motor to rotate counter-clockwise.
Valid values are `normal` and `inversed`. | def polarity(self):
"""
Sets the polarity of the motor. With `normal` polarity, a positive duty
cycle will cause the motor to rotate clockwise. With `inversed` polarity,
a positive duty cycle will cause the motor to rotate counter-clockwise.
Valid values are `normal` and `inverse... |
Returns the current position of the motor in pulses of the rotary
encoder. When the motor rotates clockwise, the position will increase.
Likewise, rotating counter-clockwise causes the position to decrease.
Writing will set the position to that value. | def position(self):
"""
Returns the current position of the motor in pulses of the rotary
encoder. When the motor rotates clockwise, the position will increase.
Likewise, rotating counter-clockwise causes the position to decrease.
Writing will set the position to that value.
... |
The proportional constant for the position PID. | def position_p(self):
"""
The proportional constant for the position PID.
"""
self._position_p, value = self.get_attr_int(self._position_p, 'hold_pid/Kp')
return value |
The integral constant for the position PID. | def position_i(self):
"""
The integral constant for the position PID.
"""
self._position_i, value = self.get_attr_int(self._position_i, 'hold_pid/Ki')
return value |
The derivative constant for the position PID. | def position_d(self):
"""
The derivative constant for the position PID.
"""
self._position_d, value = self.get_attr_int(self._position_d, 'hold_pid/Kd')
return value |
Writing specifies the target position for the `run-to-abs-pos` and `run-to-rel-pos`
commands. Reading returns the current value. Units are in tacho counts. You
can use the value returned by `count_per_rot` to convert tacho counts to/from
rotations or degrees. | def position_sp(self):
"""
Writing specifies the target position for the `run-to-abs-pos` and `run-to-rel-pos`
commands. Reading returns the current value. Units are in tacho counts. You
can use the value returned by `count_per_rot` to convert tacho counts to/from
rotations or de... |
Returns the maximum value that is accepted by the `speed_sp` attribute. This
may be slightly different than the maximum speed that a particular motor can
reach - it's the maximum theoretical speed. | def max_speed(self):
"""
Returns the maximum value that is accepted by the `speed_sp` attribute. This
may be slightly different than the maximum speed that a particular motor can
reach - it's the maximum theoretical speed.
"""
(self._max_speed, value) = self.get_cached_at... |
Returns the current motor speed in tacho counts per second. Note, this is
not necessarily degrees (although it is for LEGO motors). Use the `count_per_rot`
attribute to convert this value to RPM or deg/sec. | def speed(self):
"""
Returns the current motor speed in tacho counts per second. Note, this is
not necessarily degrees (although it is for LEGO motors). Use the `count_per_rot`
attribute to convert this value to RPM or deg/sec.
"""
self._speed, value = self.get_attr_int(s... |
Writing sets the target speed in tacho counts per second used for all `run-*`
commands except `run-direct`. Reading returns the current value. A negative
value causes the motor to rotate in reverse with the exception of `run-to-*-pos`
commands where the sign is ignored. Use the `count_per_rot` a... | def speed_sp(self):
"""
Writing sets the target speed in tacho counts per second used for all `run-*`
commands except `run-direct`. Reading returns the current value. A negative
value causes the motor to rotate in reverse with the exception of `run-to-*-pos`
commands where the si... |
Writing sets the ramp up setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will increase from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ramp time is the ratio of the difference betw... | def ramp_up_sp(self):
"""
Writing sets the ramp up setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will increase from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ram... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.