_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261500 | OPCN2.config | validation | def config(self):
"""Read the configuration variables and returns them as a dictionary
:rtype: dictionary
:Example:
>>> alpha.config()
{
'BPD 13': 1.6499,
'BPD 12': 1.6499,
'BPD 11': 1.6499,
'BPD 10': 1.6499,
'BPD 15': 1.6499,
'BPD 14': 1.6499,
'BSVW 15': 1.0,
...
}
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x3C])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(256):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
# Add the bin bounds to the dictionary of data [bytes 0-29]
for i in range(0, 15):
data["Bin Boundary {0}".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])
# Add the Bin Particle Volumes (BPV) [bytes 32-95]
for i in range(0, 16):
data["BPV {0}".format(i)] = self._calculate_float(config[4*i + 32:4*i + 36])
# Add the Bin Particle Densities (BPD) [bytes 96-159]
for i in range(0, 16):
data["BPD {0}".format(i)] = self._calculate_float(config[4*i + 96:4*i + 100])
# | python | {
"resource": ""
} |
q261501 | OPCN2.config2 | validation | def config2(self):
"""Read the second set of configuration variables and return as a dictionary.
**NOTE: This method is supported by firmware v18+.**
:rtype: dictionary
:Example:
>>> a.config2()
{
'AMFanOnIdle': 0,
'AMIdleIntervalCount': 0,
'AMMaxDataArraysInFile': 61798,
'AMSamplingInterval': 1,
'AMOnlySavePMData': 0,
'AMLaserOnIdle': 0
}
"""
config = []
| python | {
"resource": ""
} |
q261502 | OPCN2.set_fan_power | validation | def set_fan_power(self, power):
"""Set only the Fan power.
:param power: Fan power value as an integer between 0-255.
:type power: int
:rtype: boolean
:Example:
>>> alpha.set_fan_power(255)
True
"""
# Check to make sure the value is a single byte
if power > 255:
raise ValueError("The fan power should be a single byte (0-255).")
# Send the command byte and wait 10 ms
a = self.cnxn.xfer([0x42])[0]
| python | {
"resource": ""
} |
q261503 | OPCN2.toggle_laser | validation | def toggle_laser(self, state):
"""Toggle the power state of the laser.
:param state: Boolean state of the laser
:type state: boolean
:rtype: boolean
:Example:
>>> alpha.toggle_laser(True)
True
"""
# Send the command byte and wait 10 ms
a = self.cnxn.xfer([0x03])[0]
sleep(10e-3)
# If state is true, turn the laser ON, else OFF
| python | {
"resource": ""
} |
q261504 | OPCN2.sn | validation | def sn(self):
"""Read the Serial Number string. This method is only available on OPC-N2
firmware versions 18+.
:rtype: string
:Example:
>>> alpha.sn()
'OPC-N2 123456789'
"""
| python | {
"resource": ""
} |
q261505 | OPCN2.read_firmware | validation | def read_firmware(self):
"""Read the firmware version of the OPC-N2. Firmware v18+ only.
:rtype: dict
:Example:
>>> alpha.read_firmware()
{
'major': 18,
'minor': 2,
'version': 18.2
}
"""
# Send the command byte and sleep for 9 ms
self.cnxn.xfer([0x12])
sleep(10e-3) | python | {
"resource": ""
} |
q261506 | OPCN2.pm | validation | def pm(self):
"""Read the PM data and reset the histogram
**NOTE: This method is supported by firmware v18+.**
:rtype: dictionary
:Example:
>>> alpha.pm()
{
'PM1': 0.12,
'PM2.5': 0.24,
'PM10': 1.42
}
"""
resp = []
data = {}
# Send the command byte
self.cnxn.xfer([0x32])
# Wait 10 ms
sleep(10e-3)
# read the histogram
for i in range(12):
| python | {
"resource": ""
} |
q261507 | OPCN1.read_gsc_sfr | validation | def read_gsc_sfr(self):
"""Read the gain-scaling-coefficient and sample flow rate.
:returns: dictionary containing GSC and SFR
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
| python | {
"resource": ""
} |
q261508 | OPCN1.read_bin_boundaries | validation | def read_bin_boundaries(self):
"""Return the bin boundaries.
:returns: dictionary with 17 bin boundaries.
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
| python | {
"resource": ""
} |
q261509 | OPCN1.read_bin_particle_density | validation | def read_bin_particle_density(self):
"""Read the bin particle density
:returns: float
"""
config = []
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes | python | {
"resource": ""
} |
q261510 | HDLController.start | validation | def start(self):
"""
Starts HDLC controller's threads.
"""
self.receiver = self.Receiver(
self.read,
self.write,
self.send_lock,
self.senders,
| python | {
"resource": ""
} |
q261511 | HDLController.stop | validation | def stop(self):
"""
Stops HDLC controller's threads.
"""
if self.receiver != None:
| python | {
"resource": ""
} |
q261512 | HDLController.send | validation | def send(self, data):
"""
Sends a new data frame.
This method will block until a new room is available for
a new sender. This limit is determined by the size of the window.
"""
while len(self.senders) >= self.window:
pass
self.senders[self.new_seq_no] = self.Sender(
self.write,
self.send_lock,
data,
| python | {
"resource": ""
} |
q261513 | Range.cut | validation | def cut(self, by, from_start=True):
""" Cuts this object from_start to the number requestd
returns new instance
| python | {
"resource": ""
} |
q261514 | Date.replace | validation | def replace(self, **k):
"""Note returns a new Date obj"""
if self.date != | python | {
"resource": ""
} |
q261515 | findall | validation | def findall(text):
"""Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),
('august 15th at 7:20 am', <timestring.Date 2014-08-15 07:20:00 4483019344>)
]
"""
results = TIMESTRING_RE.findall(text)
dates = []
| python | {
"resource": ""
} |
q261516 | OAuthAuthentication.validate_token | validation | def validate_token(self, request, consumer, token):
"""
Check the token and raise an `oauth.Error` exception if invalid.
"""
| python | {
"resource": ""
} |
q261517 | OAuthAuthentication.check_nonce | validation | def check_nonce(self, request, oauth_request):
"""
Checks nonce of request, and return True if valid.
"""
oauth_nonce = oauth_request['oauth_nonce']
| python | {
"resource": ""
} |
q261518 | WebhookTargetRedisDetailView.deliveries | validation | def deliveries(self):
""" Get delivery log from Redis"""
key = make_key(
event=self.object.event,
owner_name=self.object.owner.username,
| python | {
"resource": ""
} |
q261519 | event_choices | validation | def event_choices(events):
""" Get the possible events from settings """
if events is None:
msg = "Please add some events in settings.WEBHOOK_EVENTS."
raise ImproperlyConfigured(msg)
try:
choices = [(x, x) for x in events]
except TypeError:
""" | python | {
"resource": ""
} |
q261520 | worker | validation | def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs):
"""
This is an asynchronous sender callable that uses the Django ORM to store
webhooks. Redis is used to handle the message queue.
dkwargs argument requires the following key/values:
:event: A string representing an event.
kwargs argument requires the following key/values
:owner: The user who created/owns the event
"""
if "event" not in dkwargs:
msg = "djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator."
raise TypeError(msg)
event = dkwargs['event']
if "owner" not in kwargs:
msg = "djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function."
| python | {
"resource": ""
} |
q261521 | Faraday.send | validation | def send(self, msg):
"""Encodes data to slip protocol and then sends over serial port
Uses the SlipLib module to convert the message data into SLIP format.
The message is then sent over the serial port opened with the instance
of the Faraday class used when invoking send().
Args:
msg (bytes): Bytes format message to send over serial port.
Returns:
int: Number of bytes transmitted over the serial port.
"""
# Create a sliplib | python | {
"resource": ""
} |
q261522 | Monitor.checkTUN | validation | def checkTUN(self):
"""
Checks the TUN adapter for data and returns any that is found.
Returns:
packet: Data read from the TUN adapter
"""
| python | {
"resource": ""
} |
q261523 | Monitor.monitorTUN | validation | def monitorTUN(self):
"""
Monitors the TUN adapter and sends data over serial port.
Returns:
ret: Number of bytes sent over serial port
"""
packet = self.checkTUN()
if packet:
try:
# TODO Do I need to strip off [4:] before sending?
ret = self._faraday.send(packet)
| python | {
"resource": ""
} |
q261524 | Monitor.checkSerial | validation | def checkSerial(self):
"""
Check the serial port for data to write to the TUN adapter.
"""
for item in self.rxSerial(self._TUN._tun.mtu):
# print("about to send: {0}".format(item))
try:
| python | {
"resource": ""
} |
q261525 | Monitor.run | validation | def run(self):
"""
Wrapper function for TUN and serial port monitoring
Wraps the necessary functions to loop over until self._isRunning
threading.Event() is set(). This checks for data on the TUN/serial
interfaces and then sends data over the appropriate interface. This
function is automatically run when Threading.start() is called on the
Monitor class.
"""
while self.isRunning.is_set():
try:
try:
| python | {
"resource": ""
} |
q261526 | RichTextWidget.get_field_settings | validation | def get_field_settings(self):
"""
Get the field settings, if the configured setting is a string try
to get a 'profile' from the global config.
"""
field_settings = None
if self.field_settings:
if isinstance(self.field_settings, six.string_types):
profiles = settings.CONFIG.get(self.PROFILE_KEY, {}) | python | {
"resource": ""
} |
q261527 | RichTextWidget.value_from_datadict | validation | def value_from_datadict(self, *args, **kwargs):
"""
Pass the submitted value through the sanitizer before returning it.
| python | {
"resource": ""
} |
q261528 | SanitizerMixin.get_sanitizer | validation | def get_sanitizer(self):
"""
Get the field sanitizer.
The priority is the first defined in the following order:
- A sanitizer provided to the widget.
- Profile (field settings) specific sanitizer, if defined in settings.
- Global sanitizer defined in settings.
- Simple no-op sanitizer which just returns the provided value.
"""
sanitizer = self.sanitizer
if not sanitizer:
default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY)
field_settings = getattr(self, 'field_settings', None)
if isinstance(field_settings, six.string_types):
| python | {
"resource": ""
} |
q261529 | heappop_max | validation | def heappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
| python | {
"resource": ""
} |
q261530 | heapreplace_max | validation | def heapreplace_max(heap, item):
"""Maxheap version of a heappop followed by a heappush."""
| python | {
"resource": ""
} |
q261531 | heappush_max | validation | def heappush_max(heap, item):
"""Push item onto heap, maintaining | python | {
"resource": ""
} |
q261532 | heappushpop_max | validation | def heappushpop_max(heap, item):
"""Fast version of a heappush followed by a heappop."""
if heap and heap[0] > item:
# if item >= heap[0], it will be | python | {
"resource": ""
} |
q261533 | validate_response | validation | def validate_response(expected_responses):
""" Decorator to validate responses from QTM """
def internal_decorator(function):
@wraps(function)
async def wrapper(*args, **kwargs):
response = await function(*args, **kwargs)
for expected_response in expected_responses:
if response.startswith(expected_response): | python | {
"resource": ""
} |
q261534 | connect | validation | async def connect(
host,
port=22223,
version="1.19",
on_event=None,
on_disconnect=None,
timeout=5,
loop=None,
) -> QRTConnection:
"""Async function to connect to QTM
:param host: Address of the computer running QTM.
:param port: Port number to connect to, should be the port configured for little endian.
:param version: What version of the protocol to use, tested for 1.17 and above but could
work with lower versions as well.
:param on_disconnect: Function to be called when a disconnect from QTM occurs.
:param on_event: Function to be called when there's an event from QTM.
:param timeout: The default timeout time for calls to QTM.
:param loop: Alternative event loop, will use asyncio default if None.
:rtype: A :class:`.QRTConnection`
"""
loop = loop or asyncio.get_event_loop()
try:
_, protocol = await loop.create_connection(
lambda: QTMProtocol(
loop=loop, on_event=on_event, on_disconnect=on_disconnect
),
host,
port,
| python | {
"resource": ""
} |
q261535 | QRTConnection.qtm_version | validation | async def qtm_version(self):
"""Get the QTM version.
"""
| python | {
"resource": ""
} |
q261536 | QRTConnection.await_event | validation | async def await_event(self, event=None, timeout=30):
"""Wait for an event from QTM.
:param event: A :class:`qtm.QRTEvent`
to wait for a | python | {
"resource": ""
} |
q261537 | QRTConnection.get_current_frame | validation | async def get_current_frame(self, components=None) -> QRTPacket:
"""Get measured values from QTM for a single frame.
:param components: A list of components to receive, could be 'all' or any combination of
'2d', '2dlin', '3d', '3dres', '3dnolabels',
'3dnolabelsres', 'force', 'forcesingle', '6d', '6dres',
'6deuler', '6deulerres', 'gazevector', 'image', 'timecode',
'skeleton', 'skeleton:global'
:rtype: A :class:`qtm.QRTPacket` containing requested components
"""
| python | {
"resource": ""
} |
q261538 | QRTConnection.stream_frames_stop | validation | async def stream_frames_stop(self):
"""Stop streaming frames."""
self._protocol.set_on_packet(None)
| python | {
"resource": ""
} |
q261539 | QRTConnection.take_control | validation | async def take_control(self, password):
"""Take control of QTM.
:param password: Password as entered in QTM.
| python | {
"resource": ""
} |
q261540 | QRTConnection.release_control | validation | async def release_control(self):
"""Release control of QTM.
"""
cmd = "releasecontrol"
return await asyncio.wait_for(
| python | {
"resource": ""
} |
q261541 | QRTConnection.start | validation | async def start(self, rtfromfile=False):
"""Start RT from file. You need to be in control of QTM to be able to do this.
"""
cmd = "start" + (" rtfromfile" if rtfromfile else "")
return | python | {
"resource": ""
} |
q261542 | QRTConnection.load | validation | async def load(self, filename):
"""Load a measurement.
:param filename: Path to measurement you want to load. | python | {
"resource": ""
} |
q261543 | QRTConnection.save | validation | async def save(self, filename, overwrite=False):
"""Save a measurement.
:param filename: Filename you wish to save as.
:param overwrite: If QTM should | python | {
"resource": ""
} |
q261544 | QRTConnection.load_project | validation | async def load_project(self, project_path):
"""Load a project.
:param project_path: Path to project you want to load. | python | {
"resource": ""
} |
q261545 | QRTConnection.set_qtm_event | validation | async def set_qtm_event(self, event=None):
"""Set event in QTM."""
cmd = "event%s" % ("" if event is None else " " + event)
return | python | {
"resource": ""
} |
q261546 | QRTConnection.send_xml | validation | async def send_xml(self, xml):
"""Used to update QTM settings, see QTM RT protocol for more information.
:param xml: XML document as a str. See QTM RT Documentation for details.
"""
return await asyncio.wait_for(
| python | {
"resource": ""
} |
q261547 | Receiver.data_received | validation | def data_received(self, data):
""" Received from QTM and route accordingly """
self._received_data += data
h_size = RTheader.size
data = self._received_data
size, type_ = RTheader.unpack_from(data, 0)
while len(data) >= size:
self._parse_received(data[h_size:size], type_)
| python | {
"resource": ""
} |
q261548 | QRTPacket.get_analog | validation | def get_analog(self, component_info=None, data=None, component_position=None):
"""Get analog data."""
components = []
append_components = components.append
for _ in range(component_info.device_count):
component_position, device = QRTPacket._get_exact(
RTAnalogDevice, data, component_position
)
if device.sample_count > 0:
| python | {
"resource": ""
} |
q261549 | QRTPacket.get_analog_single | validation | def get_analog_single(
self, component_info=None, data=None, component_position=None
):
"""Get a single analog data channel."""
components = []
append_components = components.append
for _ in range(component_info.device_count):
component_position, device = QRTPacket._get_exact(
| python | {
"resource": ""
} |
q261550 | QRTPacket.get_force | validation | def get_force(self, component_info=None, data=None, component_position=None):
"""Get force data."""
components = []
append_components = components.append
for _ in range(component_info.plate_count):
component_position, plate = QRTPacket._get_exact(
RTForcePlate, data, component_position
)
force_list = []
for _ in range(plate.force_count):
| python | {
"resource": ""
} |
q261551 | QRTPacket.get_force_single | validation | def get_force_single(self, component_info=None, data=None, component_position=None):
"""Get a single force data channel."""
components = []
append_components = components.append
for _ in range(component_info.plate_count):
component_position, plate = QRTPacket._get_exact(
RTForcePlateSingle, data, component_position
| python | {
"resource": ""
} |
q261552 | QRTPacket.get_6d | validation | def get_6d(self, component_info=None, data=None, component_position=None):
"""Get 6D data."""
components = []
append_components = components.append
for _ in range(component_info.body_count):
component_position, position = QRTPacket._get_exact(
RT6DBodyPosition, data, component_position
| python | {
"resource": ""
} |
q261553 | QRTPacket.get_6d_euler | validation | def get_6d_euler(self, component_info=None, data=None, component_position=None):
"""Get 6D data with euler rotations."""
components = []
append_components = components.append
for _ in range(component_info.body_count):
component_position, position = QRTPacket._get_exact(
RT6DBodyPosition, data, component_position
| python | {
"resource": ""
} |
q261554 | QRTPacket.get_image | validation | def get_image(self, component_info=None, data=None, component_position=None):
"""Get image."""
components = []
append_components = components.append
for _ in range(component_info.image_count):
component_position, image_info = QRTPacket._get_exact(
RTImage, | python | {
"resource": ""
} |
q261555 | QRTPacket.get_3d_markers | validation | def get_3d_markers(self, component_info=None, data=None, component_position=None):
"""Get 3D markers."""
return self._get_3d_markers(
| python | {
"resource": ""
} |
q261556 | QRTPacket.get_3d_markers_residual | validation | def get_3d_markers_residual(
self, component_info=None, data=None, component_position=None
):
"""Get 3D markers with residual."""
return self._get_3d_markers( | python | {
"resource": ""
} |
q261557 | QRTPacket.get_3d_markers_no_label | validation | def get_3d_markers_no_label(
self, component_info=None, data=None, component_position=None
):
"""Get 3D markers without label."""
return self._get_3d_markers( | python | {
"resource": ""
} |
q261558 | QRTPacket.get_3d_markers_no_label_residual | validation | def get_3d_markers_no_label_residual(
self, component_info=None, data=None, component_position=None
):
"""Get 3D markers without label with residual."""
return self._get_3d_markers(
| python | {
"resource": ""
} |
q261559 | QRTPacket.get_2d_markers | validation | def get_2d_markers(
self, component_info=None, data=None, component_position=None, index=None
):
"""Get 2D markers.
:param index: Specify which camera to get 2D from, will be returned as
first entry in | python | {
"resource": ""
} |
q261560 | QRTPacket.get_2d_markers_linearized | validation | def get_2d_markers_linearized(
self, component_info=None, data=None, component_position=None, index=None
):
"""Get 2D linearized markers.
:param index: Specify which camera to get 2D from, will be returned as
first entry | python | {
"resource": ""
} |
q261561 | QTMProtocol.await_event | validation | async def await_event(self, event=None, timeout=None):
""" Wait for any or specified event """
if self.event_future is not None:
raise Exception("Can't wait | python | {
"resource": ""
} |
q261562 | QTMProtocol.send_command | validation | def send_command(
self, command, callback=True, command_type=QRTPacketType.PacketCommand
):
""" Sends commands to QTM """
if self.transport is not None:
cmd_length = len(command)
LOG.debug("S: %s", command)
self.transport.write(
struct.pack(
RTCommand % cmd_length,
RTheader.size + cmd_length + 1,
command_type.value,
command.encode(),
b"\0",
)
)
| python | {
"resource": ""
} |
q261563 | reboot | validation | async def reboot(ip_address):
""" async function to reboot QTM cameras """
_, protocol = await asyncio.get_event_loop().create_datagram_endpoint(
| python | {
"resource": ""
} |
q261564 | on_packet | validation | def on_packet(packet):
""" Callback function that is called everytime a data packet arrives from QTM """
print("Framenumber: {}".format(packet.framenumber))
header, markers = packet.get_3d_markers() | python | {
"resource": ""
} |
q261565 | QRTDiscoveryProtocol.connection_made | validation | def connection_made(self, transport):
""" On socket creation """
self.transport = transport
| python | {
"resource": ""
} |
q261566 | QRTDiscoveryProtocol.datagram_received | validation | def datagram_received(self, datagram, address):
""" Parse response from QTM instances """
size, _ = RTheader.unpack_from(datagram, 0)
info, = struct.unpack_from("{0}s".format(size - | python | {
"resource": ""
} |
q261567 | QRTDiscoveryProtocol.send_discovery_packet | validation | def send_discovery_packet(self):
""" Send discovery packet for QTM to respond to """
if self.port is None:
return
self.transport.sendto(
QRTDiscoveryP1.pack(
| python | {
"resource": ""
} |
q261568 | choose_qtm_instance | validation | async def choose_qtm_instance(interface):
""" List running QTM instances, asks for input and return chosen QTM """
instances = {}
print("Available QTM instances:")
async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1):
instances[i] = qtm_instance
print("{} - {}".format(i, qtm_instance.info))
try:
| python | {
"resource": ""
} |
q261569 | create_body_index | validation | def create_body_index(xml_string):
""" Extract a name to index dictionary from 6dof settings xml """
xml = ET.fromstring(xml_string)
| python | {
"resource": ""
} |
q261570 | find_x | validation | def find_x(path1):
'''Return true if substring is in string for files
in specified path''' | python | {
"resource": ""
} |
q261571 | find_fann | validation | def find_fann():
'''Find doublefann library'''
# FANN possible libs directories (as $LD_LIBRARY_PATH), also includes
# pkgsrc framework support.
if sys.platform == "win32":
dirs = sys.path
for ver in dirs:
if os.path.isdir(ver):
| python | {
"resource": ""
} |
q261572 | build_swig | validation | def build_swig():
'''Run SWIG with specified parameters'''
print("Looking for FANN libs...")
find_fann()
print("running SWIG...")
swig_bin = find_swig()
swig_cmd | python | {
"resource": ""
} |
q261573 | experiment | validation | def experiment(ctx, project, experiment): # pylint:disable=redefined-outer-name
"""Commands for | python | {
"resource": ""
} |
q261574 | get | validation | def get(ctx, job):
"""Get experiment or experiment job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples for getting an experiment:
\b
```bash
$ polyaxon experiment get # if experiment is cached
```
\b
```bash
$ polyaxon experiment --experiment=1 get
```
\b
```bash
$ polyaxon experiment -xp 1 --project=cats-vs-dogs get
```
\b
```bash
$ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get
```
Examples for getting an experiment job:
\b
```bash
$ polyaxon experiment get -j 1 # if experiment is cached
```
\b
```bash
$ polyaxon experiment --experiment=1 get --job=10
```
\b
```bash
$ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2
```
\b
```bash
$ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2
```
"""
def get_experiment():
try:
response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment)
cache.cache(config_manager=ExperimentManager, response=response)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not load experiment `{}` info.'.format(_experiment))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
get_experiment_details(response)
def get_experiment_job():
try:
response = PolyaxonClient().experiment_job.get_job(user,
project_name,
_experiment,
_job)
| python | {
"resource": ""
} |
q261575 | delete | validation | def delete(ctx):
"""Delete experiment.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon experiment delete
```
"""
user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),
ctx.obj.get('experiment'))
if not click.confirm("Are sure you want to delete experiment `{}`".format(_experiment)):
click.echo('Existing without deleting experiment.')
sys.exit(1)
try:
response = PolyaxonClient().experiment.delete_experiment(
user, project_name, _experiment)
# Purge caching
ExperimentManager.purge() | python | {
"resource": ""
} |
q261576 | update | validation | def update(ctx, name, description, tags):
"""Update experiment.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon experiment -xp 2 update --description="new description for my experiments"
```
\b
```bash
$ polyaxon experiment -xp 2 update --tags="foo, bar" --name="unique-name"
```
"""
user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),
ctx.obj.get('experiment'))
update_dict = {}
if name:
update_dict['name'] = name
if description:
update_dict['description'] = description
tags = validate_tags(tags)
if tags:
update_dict['tags'] = tags
| python | {
"resource": ""
} |
q261577 | stop | validation | def stop(ctx, yes):
"""Stop experiment.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon experiment stop
```
\b
```bash
$ polyaxon experiment -xp 2 stop
```
"""
user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),
ctx.obj.get('experiment'))
if not yes and not click.confirm("Are sure you want to stop "
"experiment `{}`".format(_experiment)):
click.echo('Existing without stopping experiment.')
| python | {
"resource": ""
} |
q261578 | restart | validation | def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin
"""Restart experiment.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon experiment --experiment=1 restart
```
"""
config = None
update_code = None
if file:
config = rhea.read(file)
# Check if we need to upload
if u:
ctx.invoke(upload, sync=False)
update_code = True
user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),
ctx.obj.get('experiment'))
try:
if copy:
response = PolyaxonClient().experiment.copy(
user, project_name, _experiment, config=config, update_code=update_code)
Printer.print_success('Experiment was copied with id {}'.format(response.id))
else:
response = PolyaxonClient().experiment.restart(
| python | {
"resource": ""
} |
q261579 | statuses | validation | def statuses(ctx, job, page):
"""Get experiment or experiment job statuses.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples getting experiment statuses:
\b
```bash
$ polyaxon experiment statuses
```
\b
```bash
$ polyaxon experiment -xp 1 statuses
```
Examples getting experiment job statuses:
\b
```bash
$ polyaxon experiment statuses -j 3
```
\b
```bash
$ polyaxon experiment -xp 1 statuses --job 1
```
"""
def get_experiment_statuses():
try:
response = PolyaxonClient().experiment.get_statuses(
user, project_name, _experiment, page=page)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could get status for experiment `{}`.'.format(_experiment))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
meta = get_meta_response(response)
if meta:
Printer.print_header('Statuses for experiment `{}`.'.format(_experiment))
Printer.print_header('Navigation:')
dict_tabulate(meta)
else:
Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment))
objects = list_dicts_to_tabulate(
[Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status')
for o in response['results']])
if objects:
Printer.print_header("Statuses:")
objects.pop('experiment', None)
dict_tabulate(objects, is_list_dict=True)
def get_experiment_job_statuses():
try:
response = PolyaxonClient().experiment_job.get_statuses(user,
project_name,
_experiment,
| python | {
"resource": ""
} |
q261580 | resources | validation | def resources(ctx, job, gpu):
"""Get experiment or experiment job resources.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples for getting experiment resources:
\b
```bash
$ polyaxon experiment -xp 19 resources
```
For GPU resources
\b
```bash
$ polyaxon experiment -xp 19 resources --gpu
```
Examples for getting experiment job resources:
\b
```bash
$ polyaxon experiment -xp 19 resources -j 1
```
For GPU resources
\b
```bash
$ polyaxon experiment -xp 19 resources -j 1 --gpu
```
"""
def get_experiment_resources():
try:
message_handler = Printer.gpu_resources if gpu else Printer.resources
PolyaxonClient().experiment.resources(
user, project_name, _experiment, message_handler=message_handler)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
| python | {
"resource": ""
} |
q261581 | logs | validation | def logs(ctx, job, past, follow, hide_time):
"""Get experiment or experiment job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples for getting experiment logs:
\b
```bash
$ polyaxon experiment logs
```
\b
```bash
$ polyaxon experiment -xp 10 -p mnist logs
```
Examples for getting experiment job logs:
\b
```bash
$ polyaxon experiment -xp 1 -j 1 logs
```
"""
def get_experiment_logs():
if past:
try:
response = PolyaxonClient().experiment.logs(
user, project_name, _experiment, stream=False)
get_logs_handler(handle_job_info=True,
show_timestamp=not hide_time,
stream=False)(response.content.decode().split('\n'))
print()
if not follow:
return
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
if not follow:
Printer.print_error(
'Could not get logs for experiment `{}`.'.format(_experiment))
Printer.print_error(
'Error message `{}`.'.format(e))
sys.exit(1)
try:
PolyaxonClient().experiment.logs(
user,
project_name,
_experiment,
message_handler=get_logs_handler(handle_job_info=True,
show_timestamp=not hide_time))
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
def get_experiment_job_logs():
if past:
try:
response = PolyaxonClient().experiment_job.logs(
user,
project_name,
_experiment,
_job,
stream=False)
get_logs_handler(handle_job_info=True,
| python | {
"resource": ""
} |
q261582 | unbookmark | validation | def unbookmark(ctx):
"""Unbookmark experiment.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon experiment unbookmark
```
\b
```bash
$ polyaxon experiment -xp 2 unbookmark
```
"""
user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),
ctx.obj.get('experiment'))
| python | {
"resource": ""
} |
q261583 | upload | validation | def upload(sync=True): # pylint:disable=assign-to-new-keyword
"""Upload code of the current directory while respecting the .polyaxonignore file."""
project = ProjectManager.get_config_or_raise()
files = IgnoreManager.get_unignored_file_paths()
try:
with create_tarfile(files, project.name) as file_path:
with get_files_in_current_directory('repo', [file_path]) as (files, files_size):
try:
PolyaxonClient().project.upload_repo(project.user,
project.name,
files,
files_size,
sync=sync)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error(
'Could not upload code for project `{}`.'.format(project.name))
| python | {
"resource": ""
} |
q261584 | cluster | validation | def cluster(node):
"""Get cluster and nodes info."""
cluster_client = PolyaxonClient().cluster
if node:
try:
node_config = cluster_client.get_node(node)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not load node `{}` info.'.format(node))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
get_node_info(node_config)
else:
try:
cluster_config = cluster_client.get_cluster()
| python | {
"resource": ""
} |
q261585 | check | validation | def check(file, # pylint:disable=redefined-builtin
version,
definition):
"""Check a polyaxonfile."""
file = file or 'polyaxonfile.yaml'
specification = check_polyaxonfile(file).specification
if version:
Printer.decorate_format_value('The version is: {}',
specification.version,
'yellow')
if definition:
job_condition = (specification.is_job or
specification.is_build or
specification.is_notebook or
specification.is_tensorboard)
if specification.is_experiment:
Printer.decorate_format_value('This polyaxon specification has {}',
'One experiment',
'yellow')
| python | {
"resource": ""
} |
q261586 | clean_outputs | validation | def clean_outputs(fn):
"""Decorator for CLI with Sentry client handling.
see https://github.com/getsentry/raven-python/issues/904 for more details.
"""
@wraps(fn)
def clean_outputs_wrapper(*args, **kwargs):
| python | {
"resource": ""
} |
q261587 | job | validation | def job(ctx, project, job): # pylint:disable=redefined-outer-name
"""Commands for jobs."""
ctx.obj = ctx.obj | python | {
"resource": ""
} |
q261588 | get | validation | def get(ctx):
"""Get job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job --job=1 get
```
\b
```bash
$ polyaxon job --job=1 --project=project_name get
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
| python | {
"resource": ""
} |
q261589 | delete | validation | def delete(ctx):
"""Delete job.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon job delete
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
if not click.confirm("Are sure you want to delete job `{}`".format(_job)):
click.echo('Existing without deleting job.')
| python | {
"resource": ""
} |
q261590 | update | validation | def update(ctx, name, description, tags):
"""Update job.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon job -j 2 update --description="new description for my job"
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
update_dict = {}
if name:
update_dict['name'] = name
if description:
update_dict['description'] = description
tags = validate_tags(tags)
if tags:
update_dict['tags'] = tags
if not update_dict:
Printer.print_warning('No argument was provided to update the job.')
sys.exit(0)
try:
| python | {
"resource": ""
} |
q261591 | stop | validation | def stop(ctx, yes):
"""Stop job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job stop
```
\b
```bash
$ polyaxon job -xp 2 stop
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
if not yes and not click.confirm("Are sure you want to stop "
"job `{}`".format(_job)):
click.echo('Existing without stopping job.')
sys.exit(0)
try:
| python | {
"resource": ""
} |
q261592 | restart | validation | def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin
"""Restart job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job --job=1 restart
```
"""
config = None
update_code = None
if file:
config = rhea.read(file)
# Check if we need to upload
if u:
ctx.invoke(upload, sync=False)
update_code = True
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
try:
if copy:
response = PolyaxonClient().job.copy(
user, project_name, _job, config=config, update_code=update_code)
else:
| python | {
"resource": ""
} |
q261593 | statuses | validation | def statuses(ctx, page):
"""Get job statuses.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 statuses
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
page = page or 1
try:
response = PolyaxonClient().job.get_statuses(user, project_name, _job, page=page)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not get status for job `{}`.'.format(_job))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
meta = get_meta_response(response)
if meta:
Printer.print_header('Statuses for Job `{}`.'.format(_job))
Printer.print_header('Navigation:')
dict_tabulate(meta)
| python | {
"resource": ""
} |
q261594 | resources | validation | def resources(ctx, gpu):
"""Get job resources.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 resources
```
For GPU resources
\b
```bash
$ polyaxon job -j 2 resources --gpu
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
try:
message_handler = Printer.gpu_resources if gpu else Printer.resources
PolyaxonClient().job.resources(user,
project_name,
_job,
| python | {
"resource": ""
} |
q261595 | logs | validation | def logs(ctx, past, follow, hide_time):
"""Get job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 logs
```
\b
```bash
$ polyaxon job logs
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
if past:
try:
response = PolyaxonClient().job.logs(
user, project_name, _job, stream=False)
get_logs_handler(handle_job_info=False,
show_timestamp=not hide_time,
stream=False)(response.content.decode().split('\n'))
print()
if not follow:
return
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
if not follow:
Printer.print_error('Could not get logs for job `{}`.'.format(_job))
Printer.print_error('Error message `{}`.'.format(e))
| python | {
"resource": ""
} |
q261596 | outputs | validation | def outputs(ctx):
"""Download outputs for job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 1 outputs
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
| python | {
"resource": ""
} |
q261597 | pprint | validation | def pprint(value):
"""Prints as formatted JSON"""
click.echo(
json.dumps(value,
| python | {
"resource": ""
} |
q261598 | login | validation | def login(token, username, password):
"""Login to Polyaxon."""
auth_client = PolyaxonClient().auth
if username:
# Use username / password login
if not password:
password = click.prompt('Please enter your password', type=str, hide_input=True)
password = password.strip()
if not password:
logger.info('You entered an empty string. '
'Please make sure you enter your password correctly.')
sys.exit(1)
credentials = CredentialsConfig(username=username, password=password)
try:
access_code = auth_client.login(credentials=credentials)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not login.')
Printer.print_error('Error Message `{}`.'.format(e))
sys.exit(1)
if not access_code:
Printer.print_error("Failed to login")
return
else:
if not token:
token_url = "{}/app/token".format(auth_client.config.http_host)
click.confirm('Authentication token page will | python | {
"resource": ""
} |
q261599 | whoami | validation | def whoami():
"""Show current logged Polyaxon user."""
try:
user = PolyaxonClient().auth.get_user()
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not load user info.')
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.