repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
retroxsky06/Final_Project | webpage/run_ml.py | import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from imblearn.over_sampling import RandomOverSampler
def predictions(age, gender, hypertension, heart_disease, ever_married, smoking_status):
stroke_df = pd.read_csv('flktwo_data.csv')
X = stroke_df[['age', 'gender', 'hypertension', 'heart_disease', 'ever_married', 'smoking_status']]
y = stroke_df['stroke']
data_scaler = StandardScaler()
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
data_scaler.fit_transform(stroke_df)
ros = RandomOverSampler(random_state=42)
X_resampled, y_resampled = ros.fit_resample(X_train, y_train)
model = LogisticRegression(random_state=42)
model.fit(X_resampled, y_resampled)
y_pred = model.predict(X_test)
print(f"Training Data Score: {model.score(X_resampled, y_resampled)}")
print(f"Testing Data Score: {model.score(X_test, y_test)}")
return(model.predict([[age, gender, hypertension, heart_disease, ever_married, smoking_status]])) |
aldente05/bluetooth-python | service/BluetoothClient.py | <filename>service/BluetoothClient.py
"""
A simple Python script to send messages to a sever over Bluetooth using
Python sockets (with Python 3.3 or above).
for sending data
"""
import socket
serverMACAddress = '00:1f:e1:dd:08:3d'
port = 3
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
while 1:
text = input()
if text == "quit":
break
s.send(bytes(text, 'UTF-8'))
s.close()
|
aldente05/bluetooth-python | temperatureController/Temperature.py | import Adafruit_GPIO.I2C as I2C
I2C.require_repeated_start()
class Melexis:
def __init__(self, address=0x5A):
self._i2c = I2C.Device(address, busnum=1)
def readAmbient(self):
return self._readTemp(0x06)
def readObject1(self):
return self._readTemp(0x07)
def readObject2(self):
return self._readTemp(0x08)
def _readTemp(self, reg):
temp = self._i2c.readS16(reg)
temp = temp * .02 - 273.15
return temp
# if name == "main":
sensor = Melexis()
t = sensor.readObject1()
a = sensor.readAmbient()
print("Object: {}C , Ambiant: {}C".format(round(t, 3), round(a, 3)))
|
aldente05/bluetooth-python | valve-controller/main.py | <gh_stars>0
# import RPi.GPIO as GPIO
# import time, sys
#
# FLOW_SENSOR = 23
#
# GPIO.setmode(GPIO.BCM)
# GPIO.setup(FLOW_SENSOR, GPIO.IN, pull_up_down = GPIO.PUD_UP)
#
# global count
# count = 0
#
# def countPulse(channel):
# global count
# count = count+1
# print
# count
#
# GPIO.add_event_detect(FLOW_SENSOR, GPIO.FALLING, callback=countPulse)
#
# while True:
# try:
# time.sleep(1)
# except KeyboardInterrupt:
# print
# '\ncaught keyboard interrupt!, bye'
# GPIO.cleanup()
# sys.exit() |
aldente05/bluetooth-python | core/Connection.py | import mysql.connector as mariadb
import datetime
# Open database connection
db = mariadb.connect(user="root", password="<PASSWORD>", database="Raspi")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT start FROM pump")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Database version : %s " % data)
print(data[0])
waktu = datetime.datetime.now()
Start = datetime.time(waktu.hour, waktu.minute, waktu.second).strftime("%H:%M:%S")
print(Start)
if Start > data[0]:
print("SUKSES")
# disconnect from server
db.close()
|
aldente05/bluetooth-python | service/BluetoothTest.py | <reponame>aldente05/bluetooth-python<filename>service/BluetoothTest.py
import socket
print("\n\nperforming inquiry...")
address, services = socket.AF_BLUETOOTH
print("Address: %s" % address)
for name, port in services.items():
print(u"%s : %d" % (name, port)) |
aldente05/bluetooth-python | valve-controller/advance.py | <gh_stars>0
# # aritmatics Q = pulses_measured * 60 / measuring_time / 7.5
# # Import modules
# import smbus
# import time # Library to allow delay times
# import datetime # Library to allow time and date recording
# from array import array # Library to allow working with arrays
# import os # Library to allow command line tasks
# import unicodedata # Library to use unicode characters above value 127
# import math # library with mathematical functions
# import RPi.GPIO as GPIO # library with GPIO read- and write functions
# import grovepi # library with the GrovePi functions
# import struct
#
# # for RPI version 1, use "bus = smbus.SMBus(0)"
# rev = GPIO.RPI_REVISION
#
# if rev == 2:
# bus = smbus.SMBus(1)
# else:
# bus = smbus.SMBus(0)
#
# # Define global variables
#
# global WATER_FLOW_PIN
# global LOGTIME
# global PULSE_OUTPUT_FLOW_METER
# global FLOW_SPEED
# global VALUE
# global FLOWTIME
# global STARTTIME
#
# # Set starting values variables
#
# # This is the address of the Atmega328 on the GrovePi
# address = 0x04
#
# # Set starting values for global variables
# WATER_FLOW_PIN = 5
# FLOWTIME = 0.0
# STARTTIME = 0.0
# now = time.time() # Set now to current time in seconds since Epoch
# date = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H:%M:%S")
# # Set date to current time in YYYY-mm-dd_hh:mm:ss format
# STARTTIME = now # Set WORKTIME at current time in seconds since Epoch
# FLOWTIME = now
# PULSE_OUTPUT_FLOW_METER = 7.5 # This sets the output frequency conversion rate (depending on the Water Flow Meter characteristics)
# FLOW_SPEED = 0.0 # Set FLOW_SPEED start value at 0.0
# LOGTIME = ["2014-04-21_19:00:00","2014-04-21_19:00:00","2014-04-21_19:00:00","2014-04-21_19:00:00","2014-04-21_19:00:00","2014-04-21_19:00:00","2014-04-21_19:00:00"]
# VALUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # Set array VALUE[0 to 6] with 7 readings, start value at 0.0
#
# # Definition of functions
#
# # Main function
# def main():
# global COUNT
# initialise() # Call function initialise() to initalize port setting
# while True: # Start infinitive loop
# COUNT = 0 # Set start value at 0
# read_flow_meter() # Call function read_flow_meter
# time.sleep(5) # Pause 5 secs
#
# def initialise():
# pinMode(WATER_FLOW_PIN,"INPUT")
#
# def read_flow_meter(): # Function to read Water Flow Meter
# global LOGTIME
# global VALUE
# global COUNT
# now = time.time() # Set now to current time in seconds since Epoch
# STARTTIME = now # Set worktime at current time in seconds since Epoch
# FLOWTIME = now # Set flowtime at currect time in seconds since Epoch
# VALUE[6] = 0.0 # Set start value at 0.0
# falling = 0 # Set start value at 0
# rising = 0 # Set start value at 0
# lus_teller = 0 # Set start value at 0
# last_value = 'low' # Set start value at 'low'
# pulse_value = 0
# duration = 0.0
# print( 'Reading Water Flow Meter for 1 second. Please wait ...' )
# while duration < 1.0:
# try:
# pulse_value = digitalRead( WATER_FLOW_PIN ) # Read value from Water Flow Meter
# print( 'lus_teller = ' + str( lus_teller ) + ', pulse_value = ' + str( pulse_value ) )
# # if lus_teller == 0 and pulse_value == 1:
# # last_value = 'high'
# if pulse_value == 0:
# if last_value == 'high':
# falling = falling + 1 # Add 1 to variable low_tick to count the number of changes from high to low (falling pulses)
# last_value = 'low'
# if pulse_value == 1:
# if last_value == 'low':
# rising = rising + 1 # Add 1 to variable high_tick to count the number of changes from low to high (rising pulses)
# last_value = 'high'
# print( 'falling pulses = ' + str( falling ) + ', rising pulses = ' + str( rising ) + ', last_value = ' + last_value )
# now = time.time() # Set now to current time in seconds since Epoch
# print( 'now = ' + str( now ) )
# date = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H:%M:%S")
# # Set date to current time in YYYY-mm-dd_hh:mm:ss format
# print( 'date = ' + date )
# FLOWTIME = now # Set FLOWTIME at currect time in seconds since Epoch
# duration = FLOWTIME - STARTTIME # Calculate duration of measuring in seconds (float)
# print( 'duration = ' + str( duration ) )
# except TypeError:
# print( "Unable to read the Water Flow meter value" )
# lus_teller = lus_teller + 1 # Add 1 to lus_teller to count the number of loops
# LOGTIME[6] = date # Set LOGTIME[6] at current time in YYYY-mm-dd_hh:mm:ss format
# VALUE[6] = round( ( ( ( 60.0 / duration ) * falling ) / PULSE_OUTPUT_FLOW_METER ), 2 )
# # Calculate flow speed in l/min, rounded at 2 decimals (60.0 seconds / duration (measuring time in seconds) * number of rising pulses
# print( 'last_value = ' + last_value )
# print( 'falling pulses = ' + str( falling ) )
# print( 'rising pulses = ' + str( rising ) )
# print( 'lus_teller = ' + str( lus_teller ) + ' (number of times through loop).' )
# print( 'now = ' + str( now ) + ' time in seconds from Epoch at last measuring. ' )
# print( 'date = ' + date + ' (stringvalue of time at last measuring).' )
# print( 'duration = ' + str( duration ) + ' (time elapsed between start en ending measuring).' )
# print( 'LOGTIME[6] = ' + LOGTIME[6] + ' (saved time).' )
# print( 'VALUE[6] = ' + str( VALUE[6] ) + ' (saved value in l/min rounded at 2 decimals).' )
# print( CODE[6] + " (" + DESCRIPTION[6] + "). Flow meter readings during 1 second. Number of falling pulses = " + str( falling ) + ". Flow speed = " + str( VALUE[6] ) + " l/min. Logtime: " + LOGTIME[6] )
# falling = 0 # Reset start value at 0
# rising = 0 # Reset start value at 0
# lus_teller = 0 # Reset start value at 0
# duration = 0.0 # Reset start value at 0.0
#
# main() # Call function main |
aldente05/bluetooth-python | hearbeatController/hearbeat.py | <gh_stars>0
import RPi.GPIO as GPIO
# this input variable for hearbeat sensor
# Sensor and pins variables
pulsePin = 0
blinkPin = 13
GPIO.setmode(GPIO.BCM)
GPIO.setup(pulsePin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(blinkPin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
IBI = 600
# Main function
def main():
global COUNT
initialise() # Call function initialise() to initalize port setting
while True: # Start infinitive loop
COUNT = 0 # Set start value at 0
read_flow_meter() # Call function read_flow_meter
time.sleep(5) # Pause 5 secs
def initialise():
pinMode(WATER_FLOW_PIN,"INPUT") |
aldente05/bluetooth-python | ws/REST.py | # # -*- coding: utf-8 -*-
# from flask import Flask, jsonify, request
# from flask_login import LoginManager, UserMixin, login_required
# from itsdangerous import URLSafeTimedSerializer
#
# import RPi.GPIO as GPIO
# from ws.decorators import crossdomain
#
# app = Flask(__name__)
# app.debug = True
#
# app.secret_key = 'my_#$%^&_security_&*(4_key'
#
# #Login_serializer used to encryt and decrypt the cookie token for the remember
# #me option of flask-login
#
# VALID_BCM_PIN_NUMBERS = [17, 18, 27, 22, 23, 24, 25, 4]
# VALID_HIGH_VALUES = [1, '1', 'HIGH']
# VALID_LOW_VALUES = [0, '0', 'LOW']
# PIN_NAMES = {'17': 'IN1',
# '18': 'IN2',
# '27': 'IN3',
# '22': 'IN4',
# '23': 'IN5',
# '24': 'IN6',
# '25': 'IN7',
# '4': 'IN8'}
#
# GPIO.setmode(GPIO.BCM)
#
# for pin in VALID_BCM_PIN_NUMBERS:
# GPIO.setup(pin, GPIO.OUT)
#
#
# def pin_status(pin_number):
# if pin_number in VALID_BCM_PIN_NUMBERS:
# value = GPIO.input(pin_number)
# data = {'pin_number': pin_number,
# 'pin_name': PIN_NAMES[str(pin_number)],
# 'value': value,
# 'status': 'SUCCESS',
# 'error': None}
# else:
# data = {'status': 'ERROR',
# 'error': 'Invalid pin number.'}
#
# return data
#
#
# def pin_update(pin_number, value):
# if pin_number in VALID_BCM_PIN_NUMBERS:
# GPIO.output(pin_number, value)
# new_value = GPIO.input(pin_number)
# data = {'status': 'SUCCESS',
# 'error': None,
# 'pin_number': pin_number,
# 'pin_name': PIN_NAMES[str(pin_number)],
# 'new_value': new_value}
# else:
# data = {'status': 'ERROR',
# 'error': 'Invalid pin number or value.'}
#
# return data
#
#
# @app.route("/api/v1/ping/", methods=['GET'])
# @crossdomain(origin='*')
# def api_status():
# if request.method == 'GET':
# data = {'api_name': 'RPi GPIO API',
# 'version': '1.0',
# 'status': 'SUCCESS',
# 'response': 'pong'}
# return jsonify(data)
#
#
# @app.route("/api/v1/gpio/<pin_number>/", methods=['POST', 'GET'])
# @crossdomain(origin='*')
# @login_required
# def gpio_pin(pin_number):
# pin_number = int(pin_number)
# if request.method == 'GET':
# data = pin_status(pin_number)
#
# elif request.method == 'POST':
# value = request.values['value']
# if value in VALID_HIGH_VALUES:
# data = pin_update(pin_number, 1)
# elif value in VALID_LOW_VALUES:
# data = pin_update(pin_number, 0)
# else:
# data = {'status': 'ERROR',
# 'error': 'Invalid value.'}
# return jsonify(data)
#
#
# @app.route("/api/v1/gpio/status/", methods=['GET'])
# @crossdomain(origin='*')
# def gpio_status():
# data_list = []
# for pin in VALID_BCM_PIN_NUMBERS:
# data_list.append(pin_status(pin))
#
# data = {'data': data_list}
# return jsonify(data)
#
#
# @app.route("/api/v1/gpio/all-high/", methods=['POST'])
# @crossdomain(origin='*')
# def gpio_all_high():
# data_list = []
# for pin in VALID_BCM_PIN_NUMBERS:
# data_list.append(pin_update(pin, 1))
#
# data = {'data': data_list}
# return jsonify(data)
#
#
# @app.route("/api/v1/gpio/all-low/", methods=['POST'])
# @crossdomain(origin='*')
# def gpio_all_low():
# data_list = []
# for pin in VALID_BCM_PIN_NUMBERS:
# data_list.append(pin_update(pin, 0))
#
# data = {'data': data_list}
# return jsonify(data)
#
#
# if __name__ == "__main__":
# app.run(host='0.0.0.0', port=80, debug=True) |
aldente05/bluetooth-python | service/BluetoothServer.py | <reponame>aldente05/bluetooth-python<gh_stars>0
"""
A simple Python script to receive messages from a client over
Bluetooth using Python sockets (with Python 3.3 or above).
for receiving
"""
import socket
hostMACAddress = '00:1f:e1:dd:08:3d' # The MAC address of a Bluetooth adapter on the server. The server might have multiple Bluetooth adapters.
port = 3 # 3 is an arbitrary choice. However, it must match the port used by the client.
backlog = 1
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((hostMACAddress,port))
s.listen(backlog)
try:
client, address = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
client.send(data)
except:
print("Closing socket")
client.close()
s.close()
|
chumpblocckami/psutil | scripts/internal/print_wheels.py | #!/usr/bin/env python3
# Copyright (c) 2009 <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Nicely print wheels print in dist/ directory."""
import collections
import glob
import os
from psutil._common import print_color
from psutil._common import bytes2human
def main():
def is64bit(name):
return name.endswith(('x86_64.whl', 'amd64.whl'))
groups = collections.defaultdict(list)
for path in glob.glob('dist/*.whl'):
name = os.path.basename(path)
plat = name.split('-')[-1]
pyimpl = name.split('-')[3]
ispypy = 'pypy' in pyimpl
if 'linux' in plat:
if ispypy:
groups['pypy_on_linux'].append(name)
else:
groups['linux'].append(name)
elif 'win' in plat:
if ispypy:
groups['pypy_on_windows'].append(name)
else:
groups['windows'].append(name)
elif 'macosx' in plat:
if ispypy:
groups['pypy_on_macos'].append(name)
else:
groups['macos'].append(name)
else:
assert 0, name
totsize = 0
templ = "%-54s %7s %7s %7s"
for platf, names in groups.items():
ppn = "%s (total = %s)" % (platf.replace('_', ' '), len(names))
s = templ % (ppn, "size", "arch", "pyver")
print_color('\n' + s, color=None, bold=True)
for name in sorted(names):
path = os.path.join('dist', name)
size = os.path.getsize(path)
totsize += size
arch = '64' if is64bit(name) else '32'
pyver = 'pypy' if name.split('-')[3].startswith('pypy') else 'py'
pyver += name.split('-')[2][2:]
s = templ % (name, bytes2human(size), arch, pyver)
if 'pypy' in pyver:
print_color(s, color='violet')
else:
print_color(s, color='brown')
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | scripts/temperatures.py | <filename>scripts/temperatures.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A clone of 'sensors' utility on Linux printing hardware temperatures.
$ python scripts/sensors.py
asus
asus 47.0 °C (high = None °C, critical = None °C)
acpitz
acpitz 47.0 °C (high = 103.0 °C, critical = 103.0 °C)
coretemp
Physical id 0 54.0 °C (high = 100.0 °C, critical = 100.0 °C)
Core 0 47.0 °C (high = 100.0 °C, critical = 100.0 °C)
Core 1 48.0 °C (high = 100.0 °C, critical = 100.0 °C)
Core 2 47.0 °C (high = 100.0 °C, critical = 100.0 °C)
Core 3 54.0 °C (high = 100.0 °C, critical = 100.0 °C)
"""
from __future__ import print_function
import sys
import psutil
def main():
if not hasattr(psutil, "sensors_temperatures"):
sys.exit("platform not supported")
temps = psutil.sensors_temperatures()
if not temps:
sys.exit("can't read any temperature")
for name, entries in temps.items():
print(name)
for entry in entries:
print(" %-20s %s °C (high = %s °C, critical = %s °C)" % (
entry.label or name, entry.current, entry.high,
entry.critical))
print()
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | psutil/_psposix.py | <filename>psutil/_psposix.py<gh_stars>10-100
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Routines common to all posix systems."""
import glob
import os
import signal
import sys
import time
from ._common import memoize
from ._common import sdiskusage
from ._common import TimeoutExpired
from ._common import usage_percent
from ._compat import ChildProcessError
from ._compat import FileNotFoundError
from ._compat import InterruptedError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import PY3
from ._compat import unicode
if sys.version_info >= (3, 4):
import enum
else:
enum = None
__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get here it means this UNIX platform *does* have
# a process with id 0.
return True
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
# EPERM clearly means there's a process to deny access to
return True
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH)
else:
return True
# Python 3.5 signals enum (contributed by me ^^):
# https://bugs.python.org/issue21076
if enum is not None and hasattr(signal, "Signals"):
Negsignal = enum.IntEnum(
'Negsignal', dict([(x.name, -x.value) for x in signal.Signals]))
def negsig_to_enum(num):
"""Convert a negative signal value to an enum."""
try:
return Negsignal(num)
except ValueError:
return num
else:
def negsig_to_enum(num):
return num
def wait_pid(pid, timeout=None, proc_name=None,
_waitpid=os.waitpid,
_timer=getattr(time, 'monotonic', time.time),
_min=min,
_sleep=time.sleep,
_pid_exists=pid_exists):
"""Wait for a process PID to terminate.
If the process terminated normally by calling exit(3) or _exit(2),
or by returning from main(), the return value is the positive integer
passed to *exit().
If it was terminated by a signal it returns the negated value of the
signal which caused the termination (e.g. -SIGTERM).
If PID is not a children of os.getpid() (current process) just
wait until the process disappears and return None.
If PID does not exist at all return None immediately.
If *timeout* != None and process is still alive raise TimeoutExpired.
timeout=0 is also possible (either return immediately or raise).
"""
if pid <= 0:
raise ValueError("can't wait for PID 0") # see "man waitpid"
interval = 0.0001
flags = 0
if timeout is not None:
flags |= os.WNOHANG
stop_at = _timer() + timeout
def sleep(interval):
# Sleep for some time and return a new increased interval.
if timeout is not None:
if _timer() >= stop_at:
raise TimeoutExpired(timeout, pid=pid, name=proc_name)
_sleep(interval)
return _min(interval * 2, 0.04)
# See: https://linux.die.net/man/2/waitpid
while True:
try:
retpid, status = os.waitpid(pid, flags)
except InterruptedError:
interval = sleep(interval)
except ChildProcessError:
# This has two meanings:
# - PID is not a child of os.getpid() in which case
# we keep polling until it's gone
# - PID never existed in the first place
# In both cases we'll eventually return None as we
# can't determine its exit status code.
while _pid_exists(pid):
interval = sleep(interval)
return
else:
if retpid == 0:
# WNOHANG flag was used and PID is still running.
interval = sleep(interval)
continue
elif os.WIFEXITED(status):
# Process terminated normally by calling exit(3) or _exit(2),
# or by returning from main(). The return value is the
# positive integer passed to *exit().
return os.WEXITSTATUS(status)
elif os.WIFSIGNALED(status):
# Process exited due to a signal. Return the negative value
# of that signal.
return negsig_to_enum(-os.WTERMSIG(status))
# elif os.WIFSTOPPED(status):
# # Process was stopped via SIGSTOP or is being traced, and
# # waitpid() was called with WUNTRACED flag. PID is still
# # alive. From now on waitpid() will keep returning (0, 0)
# # until the process state doesn't change.
# # It may make sense to catch/enable this since stopped PIDs
# # ignore SIGTERM.
# interval = sleep(interval)
# continue
# elif os.WIFCONTINUED(status):
# # Process was resumed via SIGCONT and waitpid() was called
# # with WCONTINUED flag.
# interval = sleep(interval)
# continue
else:
# Should never happen.
raise ValueError("unknown process exit status %r" % status)
def disk_usage(path):
"""Return disk usage associated with path.
Note: UNIX usually reserves 5% disk space which is not accessible
by user. In this function "total" and "used" values reflect the
total and used disk space whereas "free" and "percent" represent
the "free" and "used percent" user disk space.
"""
if PY3:
st = os.statvfs(path)
else:
# os.statvfs() does not support unicode on Python 2:
# - https://github.com/giampaolo/psutil/issues/416
# - http://bugs.python.org/issue18695
try:
st = os.statvfs(path)
except UnicodeEncodeError:
if isinstance(path, unicode):
try:
path = path.encode(sys.getfilesystemencoding())
except UnicodeEncodeError:
pass
st = os.statvfs(path)
else:
raise
# Total space which is only available to root (unless changed
# at system level).
total = (st.f_blocks * st.f_frsize)
# Remaining free space usable by root.
avail_to_root = (st.f_bfree * st.f_frsize)
# Remaining free space usable by user.
avail_to_user = (st.f_bavail * st.f_frsize)
# Total space being used in general.
used = (total - avail_to_root)
# Total space which is available to user (same as 'total' but
# for the user).
total_user = used + avail_to_user
# User usage percent compared to the total amount of space
# the user can use. This number would be higher if compared
# to root's because the user has less space (usually -5%).
usage_percent_user = usage_percent(used, total_user, round_=1)
# NB: the percentage is -5% than what shown by df due to
# reserved blocks that we are currently not considering:
# https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
return sdiskusage(
total=total, used=used, free=avail_to_user, percent=usage_percent_user)
@memoize
def get_terminal_map():
"""Get a map of device-id -> path as a dict.
Used by Process.terminal()
"""
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret, name
try:
ret[os.stat(name).st_rdev] = name
except FileNotFoundError:
pass
return ret
|
chumpblocckami/psutil | scripts/internal/download_wheels_github.py | <reponame>chumpblocckami/psutil
#!/usr/bin/env python3
# Copyright (c) 2009 <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script which downloads wheel files hosted on GitHub:
https://github.com/giampaolo/psutil/actions
It needs an access token string generated from personal GitHub profile:
https://github.com/settings/tokens
The token must be created with at least "public_repo" scope/rights.
If you lose it, just generate a new token.
REST API doc:
https://developer.github.com/v3/actions/artifacts/
"""
import argparse
import json
import os
import requests
import zipfile
from psutil._common import bytes2human
from psutil.tests import safe_rmpath
USER = ""
PROJECT = ""
TOKEN = ""
OUTFILE = "wheels-github.zip"
def get_artifacts():
base_url = "https://api.github.com/repos/%s/%s" % (USER, PROJECT)
url = base_url + "/actions/artifacts"
res = requests.get(url=url, headers={"Authorization": "token %s" % TOKEN})
res.raise_for_status()
data = json.loads(res.content)
return data
def download_zip(url):
print("downloading: " + url)
res = requests.get(url=url, headers={"Authorization": "token %s" % TOKEN})
res.raise_for_status()
totbytes = 0
with open(OUTFILE, 'wb') as f:
for chunk in res.iter_content(chunk_size=16384):
f.write(chunk)
totbytes += len(chunk)
print("got %s, size %s)" % (OUTFILE, bytes2human(totbytes)))
def run():
data = get_artifacts()
download_zip(data['artifacts'][0]['archive_download_url'])
os.makedirs('dist', exist_ok=True)
with zipfile.ZipFile(OUTFILE, 'r') as zf:
zf.extractall('dist')
def main():
global USER, PROJECT, TOKEN
parser = argparse.ArgumentParser(description='GitHub wheels downloader')
parser.add_argument('--user', required=True)
parser.add_argument('--project', required=True)
parser.add_argument('--tokenfile', required=True)
args = parser.parse_args()
USER = args.user
PROJECT = args.project
with open(os.path.expanduser(args.tokenfile)) as f:
TOKEN = f.read().strip()
try:
run()
finally:
safe_rmpath(OUTFILE)
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | scripts/internal/bench_oneshot.py | <filename>scripts/internal/bench_oneshot.py<gh_stars>1000+
#!/usr/bin/env python3
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A simple micro benchmark script which prints the speedup when using
Process.oneshot() ctx manager.
See: https://github.com/giampaolo/psutil/issues/799
"""
from __future__ import print_function, division
import sys
import timeit
import textwrap
import psutil
ITERATIONS = 1000
# The list of Process methods which gets collected in one shot and
# as such get advantage of the speedup.
names = [
'cpu_times',
'cpu_percent',
'memory_info',
'memory_percent',
'ppid',
'parent',
]
if psutil.POSIX:
names.append('uids')
names.append('username')
if psutil.LINUX:
names += [
# 'memory_full_info',
# 'memory_maps',
'cpu_num',
'cpu_times',
'gids',
'name',
'num_ctx_switches',
'num_threads',
'ppid',
'status',
'terminal',
'uids',
]
elif psutil.BSD:
names = [
'cpu_times',
'gids',
'io_counters',
'memory_full_info',
'memory_info',
'name',
'num_ctx_switches',
'ppid',
'status',
'terminal',
'uids',
]
if psutil.FREEBSD:
names.append('cpu_num')
elif psutil.SUNOS:
names += [
'cmdline',
'gids',
'memory_full_info',
'memory_info',
'name',
'num_threads',
'ppid',
'status',
'terminal',
'uids',
]
elif psutil.MACOS:
names += [
'cpu_times',
'create_time',
'gids',
'memory_info',
'name',
'num_ctx_switches',
'num_threads',
'ppid',
'terminal',
'uids',
]
elif psutil.WINDOWS:
names += [
'num_ctx_switches',
'num_threads',
# dual implementation, called in case of AccessDenied
'num_handles',
'cpu_times',
'create_time',
'num_threads',
'io_counters',
'memory_info',
]
names = sorted(set(names))
setup = textwrap.dedent("""
from __main__ import names
import psutil
def call_normal(funs):
for fun in funs:
fun()
def call_oneshot(funs):
with p.oneshot():
for fun in funs:
fun()
p = psutil.Process()
funs = [getattr(p, n) for n in names]
""")
def main():
print("%s methods involved on platform %r (%s iterations, psutil %s):" % (
len(names), sys.platform, ITERATIONS, psutil.__version__))
for name in sorted(names):
print(" " + name)
# "normal" run
elapsed1 = timeit.timeit(
"call_normal(funs)", setup=setup, number=ITERATIONS)
print("normal: %.3f secs" % elapsed1)
# "one shot" run
elapsed2 = timeit.timeit(
"call_oneshot(funs)", setup=setup, number=ITERATIONS)
print("onshot: %.3f secs" % elapsed2)
# done
if elapsed2 < elapsed1:
print("speedup: +%.2fx" % (elapsed1 / elapsed2))
elif elapsed2 > elapsed1:
print("slowdown: -%.2fx" % (elapsed2 / elapsed1))
else:
print("same speed")
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | scripts/internal/winmake.py | #!/usr/bin/env python3
# Copyright (c) 2009 <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Shortcuts for various tasks, emulating UNIX "make" on Windows.
This is supposed to be invoked by "make.bat" and not used directly.
This was originally written as a bat file but they suck so much
that they should be deemed illegal!
"""
from __future__ import print_function
import argparse
import atexit
import ctypes
import errno
import fnmatch
import os
import shutil
import site
import ssl
import subprocess
import sys
import tempfile
APPVEYOR = bool(os.environ.get('APPVEYOR'))
if APPVEYOR:
PYTHON = sys.executable
else:
PYTHON = os.getenv('PYTHON', sys.executable)
RUNNER_PY = 'psutil\\tests\\runner.py'
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
PY3 = sys.version_info[0] == 3
HERE = os.path.abspath(os.path.dirname(__file__))
ROOT_DIR = os.path.realpath(os.path.join(HERE, "..", ".."))
PYPY = '__pypy__' in sys.builtin_module_names
DEPS = [
"coverage",
"flake8",
"nose",
"pdbpp",
"pip",
"pyperf",
"pyreadline",
"setuptools",
"wheel",
"requests"
]
if sys.version_info[:2] <= (2, 7):
DEPS.append('unittest2')
if sys.version_info[:2] <= (2, 7):
DEPS.append('mock')
if sys.version_info[:2] <= (3, 2):
DEPS.append('ipaddress')
if sys.version_info[:2] <= (3, 4):
DEPS.append('enum34')
if not PYPY:
DEPS.append("pywin32")
DEPS.append("wmi")
_cmds = {}
if PY3:
basestring = str
GREEN = 2
LIGHTBLUE = 3
YELLOW = 6
RED = 4
DEFAULT_COLOR = 7
# ===================================================================
# utils
# ===================================================================
def safe_print(text, file=sys.stdout, flush=False):
"""Prints a (unicode) string to the console, encoded depending on
the stdout/file encoding (eg. cp437 on Windows). This is to avoid
encoding errors in case of funky path names.
Works with Python 2 and 3.
"""
if not isinstance(text, basestring):
return print(text, file=file)
try:
file.write(text)
except UnicodeEncodeError:
bytes_string = text.encode(file.encoding, 'backslashreplace')
if hasattr(file, 'buffer'):
file.buffer.write(bytes_string)
else:
text = bytes_string.decode(file.encoding, 'strict')
file.write(text)
file.write("\n")
def stderr_handle():
GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
STD_ERROR_HANDLE_ID = ctypes.c_ulong(0xfffffff4)
GetStdHandle.restype = ctypes.c_ulong
handle = GetStdHandle(STD_ERROR_HANDLE_ID)
atexit.register(ctypes.windll.Kernel32.CloseHandle, handle)
return handle
def win_colorprint(s, color=LIGHTBLUE):
color += 8 # bold
handle = stderr_handle()
SetConsoleTextAttribute = ctypes.windll.Kernel32.SetConsoleTextAttribute
SetConsoleTextAttribute(handle, color)
try:
print(s)
finally:
SetConsoleTextAttribute(handle, DEFAULT_COLOR)
def sh(cmd, nolog=False):
if not nolog:
safe_print("cmd: " + cmd)
p = subprocess.Popen(cmd, shell=True, env=os.environ, cwd=os.getcwd())
p.communicate()
if p.returncode != 0:
sys.exit(p.returncode)
def rm(pattern, directory=False):
"""Recursively remove a file or dir by pattern."""
def safe_remove(path):
try:
os.remove(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise
else:
safe_print("rm %s" % path)
def safe_rmtree(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.errno != errno.ENOENT:
raise
existed = os.path.isdir(path)
shutil.rmtree(path, onerror=onerror)
if existed:
safe_print("rmdir -f %s" % path)
if "*" not in pattern:
if directory:
safe_rmtree(pattern)
else:
safe_remove(pattern)
return
for root, subdirs, subfiles in os.walk('.'):
root = os.path.normpath(root)
if root.startswith('.git/'):
continue
found = fnmatch.filter(subdirs if directory else subfiles, pattern)
for name in found:
path = os.path.join(root, name)
if directory:
safe_print("rmdir -f %s" % path)
safe_rmtree(path)
else:
safe_print("rm %s" % path)
safe_remove(path)
def safe_remove(path):
try:
os.remove(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise
else:
safe_print("rm %s" % path)
def safe_rmtree(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.errno != errno.ENOENT:
raise
existed = os.path.isdir(path)
shutil.rmtree(path, onerror=onerror)
if existed:
safe_print("rmdir -f %s" % path)
def recursive_rm(*patterns):
"""Recursively remove a file or matching a list of patterns."""
for root, subdirs, subfiles in os.walk(u'.'):
root = os.path.normpath(root)
if root.startswith('.git/'):
continue
for file in subfiles:
for pattern in patterns:
if fnmatch.fnmatch(file, pattern):
safe_remove(os.path.join(root, file))
for dir in subdirs:
for pattern in patterns:
if fnmatch.fnmatch(dir, pattern):
safe_rmtree(os.path.join(root, dir))
def test_setup():
os.environ['PYTHONWARNINGS'] = 'all'
os.environ['PSUTIL_TESTING'] = '1'
os.environ['PSUTIL_DEBUG'] = '1'
# ===================================================================
# commands
# ===================================================================
def build():
"""Build / compile"""
# Make sure setuptools is installed (needed for 'develop' /
# edit mode).
sh('%s -c "import setuptools"' % PYTHON)
# "build_ext -i" copies compiled *.pyd files in ./psutil directory in
# order to allow "import psutil" when using the interactive interpreter
# from within psutil root directory.
cmd = [PYTHON, "setup.py", "build_ext", "-i"]
if sys.version_info[:2] >= (3, 6) and os.cpu_count() or 1 > 1:
cmd += ['--parallel', str(os.cpu_count())]
# Print coloured warnings in real time.
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
try:
for line in iter(p.stdout.readline, b''):
if PY3:
line = line.decode()
line = line.strip()
if 'warning' in line:
win_colorprint(line, YELLOW)
elif 'error' in line:
win_colorprint(line, RED)
else:
print(line)
# retcode = p.poll()
p.communicate()
if p.returncode:
win_colorprint("failure", RED)
sys.exit(p.returncode)
finally:
p.terminate()
p.wait()
# Make sure it actually worked.
sh('%s -c "import psutil"' % PYTHON)
win_colorprint("build + import successful", GREEN)
def wheel():
"""Create wheel file."""
build()
sh("%s setup.py bdist_wheel" % PYTHON)
def upload_wheels():
"""Upload wheel files on PyPI."""
build()
sh("%s -m twine upload dist/*.whl" % PYTHON)
def install_pip():
"""Install pip"""
try:
sh('%s -c "import pip"' % PYTHON)
except SystemExit:
if PY3:
from urllib.request import urlopen
else:
from urllib2 import urlopen
if hasattr(ssl, '_create_unverified_context'):
ctx = ssl._create_unverified_context()
else:
ctx = None
kw = dict(context=ctx) if ctx else {}
safe_print("downloading %s" % GET_PIP_URL)
req = urlopen(GET_PIP_URL, **kw)
data = req.read()
tfile = os.path.join(tempfile.gettempdir(), 'get-pip.py')
with open(tfile, 'wb') as f:
f.write(data)
try:
sh('%s %s --user' % (PYTHON, tfile))
finally:
os.remove(tfile)
def install():
"""Install in develop / edit mode"""
build()
sh("%s setup.py develop" % PYTHON)
def uninstall():
"""Uninstall psutil"""
# Uninstalling psutil on Windows seems to be tricky.
# On "import psutil" tests may import a psutil version living in
# C:\PythonXY\Lib\site-packages which is not what we want, so
# we try both "pip uninstall psutil" and manually remove stuff
# from site-packages.
clean()
install_pip()
here = os.getcwd()
try:
os.chdir('C:\\')
while True:
try:
import psutil # NOQA
except ImportError:
break
else:
sh("%s -m pip uninstall -y psutil" % PYTHON)
finally:
os.chdir(here)
for dir in site.getsitepackages():
for name in os.listdir(dir):
if name.startswith('psutil'):
rm(os.path.join(dir, name))
elif name == 'easy-install.pth':
# easy_install can add a line (installation path) into
# easy-install.pth; that line alters sys.path.
path = os.path.join(dir, name)
with open(path, 'rt') as f:
lines = f.readlines()
hasit = False
for line in lines:
if 'psutil' in line:
hasit = True
break
if hasit:
with open(path, 'wt') as f:
for line in lines:
if 'psutil' not in line:
f.write(line)
else:
print("removed line %r from %r" % (line, path))
def clean():
"""Deletes dev files"""
recursive_rm(
"$testfn*",
"*.bak",
"*.core",
"*.egg-info",
"*.orig",
"*.pyc",
"*.pyd",
"*.pyo",
"*.rej",
"*.so",
"*.~",
"*__pycache__",
".coverage",
".failed-tests.txt",
".tox",
)
safe_rmtree("build")
safe_rmtree(".coverage")
safe_rmtree("dist")
safe_rmtree("docs/_build")
safe_rmtree("htmlcov")
safe_rmtree("tmp")
def setup_dev_env():
"""Install useful deps"""
install_pip()
install_git_hooks()
sh("%s -m pip install -U %s" % (PYTHON, " ".join(DEPS)))
def lint():
"""Run flake8 against all py files"""
py_files = subprocess.check_output("git ls-files")
if PY3:
py_files = py_files.decode()
py_files = [x for x in py_files.split() if x.endswith('.py')]
py_files = ' '.join(py_files)
sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=True)
def test(name=RUNNER_PY):
"""Run tests"""
build()
test_setup()
sh("%s %s" % (PYTHON, name))
def coverage():
"""Run coverage tests."""
# Note: coverage options are controlled by .coveragerc file
build()
test_setup()
sh("%s -m coverage run %s" % (PYTHON, RUNNER_PY))
sh("%s -m coverage report" % PYTHON)
sh("%s -m coverage html" % PYTHON)
sh("%s -m webbrowser -t htmlcov/index.html" % PYTHON)
def test_process():
"""Run process tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_process.py" % PYTHON)
def test_system():
"""Run system tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_system.py" % PYTHON)
def test_platform():
"""Run windows only tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_windows.py" % PYTHON)
def test_misc():
"""Run misc tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_misc.py" % PYTHON)
def test_unicode():
"""Run unicode tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_unicode.py" % PYTHON)
def test_connections():
"""Run connections tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_connections.py" % PYTHON)
def test_contracts():
"""Run contracts tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_contracts.py" % PYTHON)
def test_testutils():
"""Run test utilities tests"""
build()
test_setup()
sh("%s psutil\\tests\\test_testutils.py" % PYTHON)
def test_by_name(name):
"""Run test by name"""
build()
test_setup()
sh("%s -m unittest -v %s" % (PYTHON, name))
def test_failed():
"""Re-run tests which failed on last run."""
build()
test_setup()
sh("%s %s --last-failed" % (PYTHON, RUNNER_PY))
def test_memleaks():
"""Run memory leaks tests"""
build()
sh("%s psutil\\tests\\test_memleaks.py" % PYTHON)
def install_git_hooks():
"""Install GIT pre-commit hook."""
if os.path.isdir('.git'):
src = os.path.join(
ROOT_DIR, "scripts", "internal", "git_pre_commit.py")
dst = os.path.realpath(
os.path.join(ROOT_DIR, ".git", "hooks", "pre-commit"))
with open(src, "rt") as s:
with open(dst, "wt") as d:
d.write(s.read())
def bench_oneshot():
"""Benchmarks for oneshot() ctx manager (see #799)."""
sh("%s -Wa scripts\\internal\\bench_oneshot.py" % PYTHON)
def bench_oneshot_2():
"""Same as above but using perf module (supposed to be more precise)."""
sh("%s -Wa scripts\\internal\\bench_oneshot_2.py" % PYTHON)
def print_access_denied():
"""Print AD exceptions raised by all Process methods."""
build()
test_setup()
sh("%s -Wa scripts\\internal\\print_access_denied.py" % PYTHON)
def print_api_speed():
"""Benchmark all API calls."""
build()
test_setup()
sh("%s -Wa scripts\\internal\\print_api_speed.py" % PYTHON)
def get_python(path):
if not path:
return sys.executable
if os.path.isabs(path):
return path
# try to look for a python installation given a shortcut name
path = path.replace('.', '')
vers = ('26', '27', '36', '37', '38',
'26-64', '27-64', '36-64', '37-64', '38-64'
'26-32', '27-32', '36-32', '37-32', '38-32')
for v in vers:
pypath = r'C:\\python%s\python.exe' % v
if path in pypath and os.path.isfile(pypath):
return pypath
def main():
global PYTHON
parser = argparse.ArgumentParser()
# option shared by all commands
parser.add_argument(
'-p', '--python',
help="use python executable path")
sp = parser.add_subparsers(dest='command', title='targets')
sp.add_parser('bench-oneshot', help="benchmarks for oneshot()")
sp.add_parser('bench-oneshot_2', help="benchmarks for oneshot() (perf)")
sp.add_parser('build', help="build")
sp.add_parser('clean', help="deletes dev files")
sp.add_parser('coverage', help="run coverage tests.")
sp.add_parser('help', help="print this help")
sp.add_parser('install', help="build + install in develop/edit mode")
sp.add_parser('install-git-hooks', help="install GIT pre-commit hook")
sp.add_parser('install-pip', help="install pip")
sp.add_parser('lint', help="run flake8 against all py files")
sp.add_parser('print-access-denied', help="print AD exceptions")
sp.add_parser('print-api-speed', help="benchmark all API calls")
sp.add_parser('setup-dev-env', help="install deps")
test = sp.add_parser('test', help="[ARG] run tests")
test_by_name = sp.add_parser('test-by-name', help="<ARG> run test by name")
sp.add_parser('test-connections', help="run connections tests")
sp.add_parser('test-contracts', help="run contracts tests")
sp.add_parser('test-failed', help="re-run tests which failed on last run")
sp.add_parser('test-memleaks', help="run memory leaks tests")
sp.add_parser('test-misc', help="run misc tests")
sp.add_parser('test-platform', help="run windows only tests")
sp.add_parser('test-process', help="run process tests")
sp.add_parser('test-system', help="run system tests")
sp.add_parser('test-unicode', help="run unicode tests")
sp.add_parser('test-testutils', help="run test utils tests")
sp.add_parser('uninstall', help="uninstall psutil")
sp.add_parser('upload-wheels', help="upload wheel files on PyPI")
sp.add_parser('wheel', help="create wheel file")
for p in (test, test_by_name):
p.add_argument('arg', type=str, nargs='?', default="", help="arg")
args = parser.parse_args()
# set python exe
PYTHON = get_python(args.python)
if not PYTHON:
return sys.exit(
"can't find any python installation matching %r" % args.python)
os.putenv('PYTHON', PYTHON)
win_colorprint("using " + PYTHON)
if not args.command or args.command == 'help':
parser.print_help(sys.stderr)
sys.exit(1)
fname = args.command.replace('-', '_')
fun = getattr(sys.modules[__name__], fname) # err if fun not defined
funargs = []
# mandatory args
if args.command in ('test-by-name', 'test-script'):
if not args.arg:
sys.exit('command needs an argument')
funargs = [args.arg]
# optional args
if args.command == 'test' and args.arg:
funargs = [args.arg]
fun(*funargs)
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | scripts/internal/purge_installation.py | <reponame>chumpblocckami/psutil
#!/usr/bin/env python3
# Copyright (c) 2009 <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Purge psutil installation by removing psutil-related files and
directories found in site-packages directories. This is needed mainly
because sometimes "import psutil" imports a leftover installation
from site-packages directory instead of the main working directory.
"""
import os
import shutil
import site
PKGNAME = "psutil"
def rmpath(path):
if os.path.isdir(path):
print("rmdir " + path)
shutil.rmtree(path)
else:
print("rm " + path)
os.remove(path)
def main():
locations = [site.getusersitepackages()]
locations += site.getsitepackages()
for root in locations:
if os.path.isdir(root):
for name in os.listdir(root):
if PKGNAME in name:
abspath = os.path.join(root, name)
rmpath(abspath)
main()
|
chumpblocckami/psutil | scripts/internal/fix_flake8.py | #!/usr/bin/env python3
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Fix some flake8 errors by rewriting files for which flake8 emitted
an error/warning. Usage (from the root dir):
$ python3 -m flake8 --exit-zero | python3 scripts/fix_flake8.py
"""
import sys
import tempfile
import shutil
from collections import defaultdict
from collections import namedtuple
from pprint import pprint as pp # NOQA
ntentry = namedtuple('ntentry', 'msg, issue, lineno, pos, descr')
# =====================================================================
# utils
# =====================================================================
def enter_pdb():
from pdb import set_trace as st # trick GIT commit hook
sys.stdin = open('/dev/tty')
st()
def read_lines(fname):
with open(fname, 'rt') as f:
return f.readlines()
def read_line(fname, lineno):
with open(fname, 'rt') as f:
for i, line in enumerate(f, 1):
if i == lineno:
return line
raise ValueError("lineno too big")
def write_file(fname, newlines):
with tempfile.NamedTemporaryFile('wt', delete=False) as f:
for line in newlines:
f.write(line)
shutil.move(f.name, fname)
# =====================================================================
# handlers
# =====================================================================
def handle_f401(fname, lineno):
""" This is 'module imported but not used'
Able to handle this case:
import os
...but not this:
from os import listdir
"""
line = read_line(fname, lineno).strip()
if line.startswith('import '):
return True
else:
mods = line.partition(' import ')[2] # everything after import
return ',' not in mods
# =====================================================================
# converters
# =====================================================================
def remove_lines(fname, entries):
"""Check if we should remove lines, then do it.
Return the numner of lines removed.
"""
to_remove = []
for entry in entries:
msg, issue, lineno, pos, descr = entry
# 'module imported but not used'
if issue == 'F401' and handle_f401(fname, lineno):
to_remove.append(lineno)
# 'blank line(s) at end of file'
elif issue == 'W391':
lines = read_lines(fname)
i = len(lines) - 1
while lines[i] == '\n':
to_remove.append(i + 1)
i -= 1
# 'too many blank lines'
elif issue == 'E303':
howmany = descr.replace('(', '').replace(')', '')
howmany = int(howmany[-1])
for x in range(lineno - howmany, lineno):
to_remove.append(x)
if to_remove:
newlines = []
for i, line in enumerate(read_lines(fname), 1):
if i not in to_remove:
newlines.append(line)
print("removing line(s) from %s" % fname)
write_file(fname, newlines)
return len(to_remove)
def add_lines(fname, entries):
"""Check if we should remove lines, then do it.
Return the numner of lines removed.
"""
EXPECTED_BLANK_LINES = (
'E302', # 'expected 2 blank limes, found 1'
'E305') # ìexpected 2 blank lines after class or fun definition'
to_add = {}
for entry in entries:
msg, issue, lineno, pos, descr = entry
if issue in EXPECTED_BLANK_LINES:
howmany = 2 if descr.endswith('0') else 1
to_add[lineno] = howmany
if to_add:
newlines = []
for i, line in enumerate(read_lines(fname), 1):
if i in to_add:
newlines.append('\n' * to_add[i])
newlines.append(line)
print("adding line(s) to %s" % fname)
write_file(fname, newlines)
return len(to_add)
# =====================================================================
# main
# =====================================================================
def build_table():
table = defaultdict(list)
for line in sys.stdin:
line = line.strip()
if not line:
break
fields = line.split(':')
fname, lineno, pos = fields[:3]
issue = fields[3].split()[0]
descr = fields[3].strip().partition(' ')[2]
lineno, pos = int(lineno), int(pos)
table[fname].append(ntentry(line, issue, lineno, pos, descr))
return table
def main():
table = build_table()
# remove lines (unused imports)
removed = 0
for fname, entries in table.items():
removed += remove_lines(fname, entries)
if removed:
print("%s lines were removed from some file(s); please re-run" %
removed)
return
# add lines (missing \n between functions/classes)
added = 0
for fname, entries in table.items():
added += add_lines(fname, entries)
if added:
print("%s lines were added from some file(s); please re-run" %
added)
return
main()
|
chumpblocckami/psutil | scripts/internal/print_api_speed.py | <filename>scripts/internal/print_api_speed.py<gh_stars>1000+
#!/usr/bin/env python3
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Benchmark all API calls.
$ make print_api_speed
SYSTEM APIS SECONDS
----------------------------------
cpu_count 0.000014
disk_usage 0.000027
cpu_times 0.000037
cpu_percent 0.000045
...
PROCESS APIS SECONDS
----------------------------------
create_time 0.000001
nice 0.000005
cwd 0.000011
cpu_affinity 0.000011
ionice 0.000013
...
"""
from __future__ import print_function, division
from timeit import default_timer as timer
import inspect
import os
import psutil
from psutil._common import print_color
timings = []
templ = "%-25s %s"
def print_timings():
timings.sort(key=lambda x: x[1])
i = 0
while timings[:]:
title, elapsed = timings.pop(0)
s = templ % (title, "%f" % elapsed)
if i > len(timings) - 5:
print_color(s, color="red")
else:
print(s)
def timecall(title, fun, *args, **kw):
t = timer()
fun(*args, **kw)
elapsed = timer() - t
timings.append((title, elapsed))
def main():
# --- system
public_apis = []
ignore = ['wait_procs', 'process_iter', 'win_service_get',
'win_service_iter']
if psutil.MACOS:
ignore.append('net_connections') # raises AD
for name in psutil.__all__:
obj = getattr(psutil, name, None)
if inspect.isfunction(obj):
if name not in ignore:
public_apis.append(name)
print_color(templ % ("SYSTEM APIS", "SECONDS"), color=None, bold=True)
print("-" * 34)
for name in public_apis:
fun = getattr(psutil, name)
args = ()
if name == 'pid_exists':
args = (os.getpid(), )
elif name == 'disk_usage':
args = (os.getcwd(), )
timecall(name, fun, *args)
timecall('cpu_count (cores)', psutil.cpu_count, logical=False)
timecall('process_iter (all)', lambda: list(psutil.process_iter()))
print_timings()
# --- process
print("")
print_color(templ % ("PROCESS APIS", "SECONDS"), color=None, bold=True)
print("-" * 34)
ignore = ['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
'as_dict', 'parent', 'parents', 'memory_info_ex', 'oneshot',
'pid', 'rlimit']
if psutil.MACOS:
ignore.append('memory_maps') # XXX
p = psutil.Process()
for name in sorted(dir(p)):
if not name.startswith('_') and name not in ignore:
fun = getattr(p, name)
timecall(name, fun)
print_timings()
if __name__ == '__main__':
main()
|
chumpblocckami/psutil | psutil/tests/runner.py | #!/usr/bin/env python3
# Copyright (c) 2009, <NAME>'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Unit test runner, providing new features on top of unittest module:
- colourized output
- parallel run (UNIX only)
- print failures/tracebacks on CTRL+C
- re-run failed tests only (make test-failed)
Invocation examples:
- make test
- make test-failed
Parallel:
- make test-parallel
- make test-process ARGS=--parallel
"""
from __future__ import print_function
import atexit
import optparse
import os
import sys
import textwrap
import time
import unittest
try:
import ctypes
except ImportError:
ctypes = None
try:
import concurrencytest # pip install concurrencytest
except ImportError:
concurrencytest = None
import psutil
from psutil._common import hilite
from psutil._common import print_color
from psutil._common import term_supports_colors
from psutil._compat import super
from psutil.tests import CI_TESTING
from psutil.tests import import_module_by_path
from psutil.tests import print_sysinfo
from psutil.tests import reap_children
from psutil.tests import safe_rmpath
VERBOSITY = 2
FAILED_TESTS_FNAME = '.failed-tests.txt'
NWORKERS = psutil.cpu_count() or 1
USE_COLORS = not CI_TESTING and term_supports_colors()
HERE = os.path.abspath(os.path.dirname(__file__))
loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase
def cprint(msg, color, bold=False, file=None):
if file is None:
file = sys.stderr if color == 'red' else sys.stdout
if USE_COLORS:
print_color(msg, color, bold=bold, file=file)
else:
print(msg, file=file)
class TestLoader:
testdir = HERE
skip_files = ['test_memleaks.py']
if "WHEELHOUSE_UPLOADER_USERNAME" in os.environ:
skip_files.extend(['test_osx.py', 'test_linux.py', 'test_posix.py'])
def _get_testmods(self):
return [os.path.join(self.testdir, x)
for x in os.listdir(self.testdir)
if x.startswith('test_') and x.endswith('.py') and
x not in self.skip_files]
def _iter_testmod_classes(self):
"""Iterate over all test files in this directory and return
all TestCase classes in them.
"""
for path in self._get_testmods():
mod = import_module_by_path(path)
for name in dir(mod):
obj = getattr(mod, name)
if isinstance(obj, type) and \
issubclass(obj, unittest.TestCase):
yield obj
def all(self):
suite = unittest.TestSuite()
for obj in self._iter_testmod_classes():
test = loadTestsFromTestCase(obj)
suite.addTest(test)
return suite
def last_failed(self):
# ...from previously failed test run
suite = unittest.TestSuite()
if not os.path.isfile(FAILED_TESTS_FNAME):
return suite
with open(FAILED_TESTS_FNAME, 'rt') as f:
names = f.read().split()
for n in names:
test = unittest.defaultTestLoader.loadTestsFromName(n)
suite.addTest(test)
return suite
def from_name(self, name):
if name.endswith('.py'):
name = os.path.splitext(os.path.basename(name))[0]
return unittest.defaultTestLoader.loadTestsFromName(name)
class ColouredResult(unittest.TextTestResult):
def addSuccess(self, test):
unittest.TestResult.addSuccess(self, test)
cprint("OK", "green")
def addError(self, test, err):
unittest.TestResult.addError(self, test, err)
cprint("ERROR", "red", bold=True)
def addFailure(self, test, err):
unittest.TestResult.addFailure(self, test, err)
cprint("FAIL", "red")
def addSkip(self, test, reason):
unittest.TestResult.addSkip(self, test, reason)
cprint("skipped: %s" % reason.strip(), "brown")
def printErrorList(self, flavour, errors):
flavour = hilite(flavour, "red", bold=flavour == 'ERROR')
super().printErrorList(flavour, errors)
class ColouredTextRunner(unittest.TextTestRunner):
"""
A coloured text runner which also prints failed tests on KeyboardInterrupt
and save failed tests in a file so that they can be re-run.
"""
resultclass = ColouredResult if USE_COLORS else unittest.TextTestResult
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.failed_tnames = set()
def _makeResult(self):
# Store result instance so that it can be accessed on
# KeyboardInterrupt.
self.result = super()._makeResult()
return self.result
def _write_last_failed(self):
if self.failed_tnames:
with open(FAILED_TESTS_FNAME, 'wt') as f:
for tname in self.failed_tnames:
f.write(tname + '\n')
def _save_result(self, result):
if not result.wasSuccessful():
for t in result.errors + result.failures:
tname = t[0].id()
self.failed_tnames.add(tname)
def _run(self, suite):
try:
result = super().run(suite)
except (KeyboardInterrupt, SystemExit):
result = self.runner.result
result.printErrors()
raise sys.exit(1)
else:
self._save_result(result)
return result
def _exit(self, success):
if success:
cprint("SUCCESS", "green", bold=True)
safe_rmpath(FAILED_TESTS_FNAME)
sys.exit(0)
else:
cprint("FAILED", "red", bold=True)
self._write_last_failed()
sys.exit(1)
def run(self, suite):
result = self._run(suite)
self._exit(result.wasSuccessful())
class ParallelRunner(ColouredTextRunner):
@staticmethod
def _parallelize(suite):
def fdopen(fd, mode, *kwds):
stream = orig_fdopen(fd, mode)
atexit.register(stream.close)
return stream
# Monkey patch concurrencytest lib bug (fdopen() stream not closed).
# https://github.com/cgoldberg/concurrencytest/issues/11
orig_fdopen = os.fdopen
concurrencytest.os.fdopen = fdopen
forker = concurrencytest.fork_for_tests(NWORKERS)
return concurrencytest.ConcurrentTestSuite(suite, forker)
@staticmethod
def _split_suite(suite):
serial = unittest.TestSuite()
parallel = unittest.TestSuite()
for test in suite:
if test.countTestCases() == 0:
continue
elif isinstance(test, unittest.TestSuite):
test_class = test._tests[0].__class__
elif isinstance(test, unittest.TestCase):
test_class = test
else:
raise TypeError("can't recognize type %r" % test)
if getattr(test_class, '_serialrun', False):
serial.addTest(test)
else:
parallel.addTest(test)
return (serial, parallel)
def run(self, suite):
ser_suite, par_suite = self._split_suite(suite)
par_suite = self._parallelize(par_suite)
# run parallel
cprint("starting parallel tests using %s workers" % NWORKERS,
"green", bold=True)
t = time.time()
par = self._run(par_suite)
par_elapsed = time.time() - t
# At this point we should have N zombies (the workers), which
# will disappear with wait().
orphans = psutil.Process().children()
gone, alive = psutil.wait_procs(orphans, timeout=1)
if alive:
cprint("alive processes %s" % alive, "red")
reap_children()
# run serial
t = time.time()
ser = self._run(ser_suite)
ser_elapsed = time.time() - t
# print
if not par.wasSuccessful() and ser_suite.countTestCases() > 0:
par.printErrors() # print them again at the bottom
par_fails, par_errs, par_skips = map(len, (par.failures,
par.errors,
par.skipped))
ser_fails, ser_errs, ser_skips = map(len, (ser.failures,
ser.errors,
ser.skipped))
print(textwrap.dedent("""
+----------+----------+----------+----------+----------+----------+
| | total | failures | errors | skipped | time |
+----------+----------+----------+----------+----------+----------+
| parallel | %3s | %3s | %3s | %3s | %.2fs |
+----------+----------+----------+----------+----------+----------+
| serial | %3s | %3s | %3s | %3s | %.2fs |
+----------+----------+----------+----------+----------+----------+
""" % (par.testsRun, par_fails, par_errs, par_skips, par_elapsed,
ser.testsRun, ser_fails, ser_errs, ser_skips, ser_elapsed)))
print("Ran %s tests in %.3fs using %s workers" % (
par.testsRun + ser.testsRun, par_elapsed + ser_elapsed, NWORKERS))
ok = par.wasSuccessful() and ser.wasSuccessful()
self._exit(ok)
def get_runner(parallel=False):
def warn(msg):
cprint(msg + " Running serial tests instead.", "red")
if parallel:
if psutil.WINDOWS:
warn("Can't run parallel tests on Windows.")
elif concurrencytest is None:
warn("concurrencytest module is not installed.")
elif NWORKERS == 1:
warn("Only 1 CPU available.")
else:
return ParallelRunner(verbosity=VERBOSITY)
return ColouredTextRunner(verbosity=VERBOSITY)
# Used by test_*,py modules.
def run_from_name(name):
suite = TestLoader().from_name(name)
runner = get_runner()
runner.run(suite)
def setup():
if 'PSUTIL_TESTING' not in os.environ:
# This won't work on Windows but set_testing() below will do it.
os.environ['PSUTIL_TESTING'] = '1'
psutil._psplatform.cext.set_testing()
def main():
setup()
usage = "python3 -m psutil.tests [opts] [test-name]"
parser = optparse.OptionParser(usage=usage, description="run unit tests")
parser.add_option("--last-failed",
action="store_true", default=False,
help="only run last failed tests")
parser.add_option("--parallel",
action="store_true", default=False,
help="run tests in parallel")
opts, args = parser.parse_args()
if not opts.last_failed:
safe_rmpath(FAILED_TESTS_FNAME)
# loader
loader = TestLoader()
if args:
if len(args) > 1:
parser.print_usage()
return sys.exit(1)
else:
suite = loader.from_name(args[0])
elif opts.last_failed:
suite = loader.last_failed()
else:
suite = loader.all()
if CI_TESTING:
print_sysinfo()
runner = get_runner(opts.parallel)
runner.run(suite)
if __name__ == '__main__':
main()
|
PsycoTodd/TaichiJourney | HM0_tiFire/tiFire.py | <reponame>PsycoTodd/TaichiJourney
import taichi as ti
import math
# ti.init(debug=True, arch=ti.cpu)
ti.init(arch=ti.opengl)
def vec(*xs):
return ti.Vector(list(xs))
def mix(x, y, a):
return x * (1.0 - a) + y * a
GUI_TITLE = "Fire"
w, h = wh = (640, 480) # GUI size
pixels = ti.Vector(3, dt=ti.f32, shape=wh)
iResolution = vec(w, h)
@ti.func
def noise(p):
i = ti.floor(p)
a = i.dot(vec(1.0, 57.0, 21.0)) + vec(0.0, 57.0, 21.0, 78.0)
f = ti.cos((p - i) * math.acos(-1.0)) * (-0.5) + 0.5
a = mix(ti.sin(ti.cos(a) * a), ti.sin(ti.cos(1.0 + a) * (1.0 + a)), f[0])
a[0] = mix(a[0], a[1], f[1])
a[1] = mix(a[2], a[3], f[1])
return mix(a[0], a[1], f[2])
@ti.func
def sphere(p, spr):
spr_xyz = vec(spr[0], spr[1], spr[2])
w = spr[3]
return (spr_xyz - p).norm() - w
@ti.func
def flame(p, t):
d = sphere(p * vec(1.0, 0.5, 1.0), vec(0.0, -1.0, 0.0, 1.0))
return d + (noise(p + vec(0.0, t * 2.0, 0.0)) + noise(p * 3.0) * 0.5) * 0.25 * (p[1])
@ti.func
def scene(p, t):
return min(100.0 - p.norm(), abs(flame(p, t)))
@ti.func
def raymarch(org, dir, t):
d = 0.0
glow = 0.0
eps = 0.02
p = org
glowed = False
for i in range(64):
d = scene(p, t) + eps
p += d * dir
if( d > eps):
if(flame(p, t) < 0.0):
glowed = True
if(glowed):
glow = float(i) / 64.0
return vec(p[0], p[1], p[2], glow)
@ti.func
def mainImage(iTime, i, j):
fragCoord = vec(i, j)
# Normalized pixel coordinates (from 0 to 1)
uv = fragCoord / iResolution
v = -1.0 + 2.0 * uv
org = vec(0.0, -2.0, 4.0)
dir = vec(v[0] * 1.6, -v[1], -1.5)
dir /= dir.norm()
p = raymarch(org, dir, iTime)
glow = p[3]
col = mix(vec(1.0, 0.5, 0.1, 1.0), vec(0.1, 0.5, 1.0, 1.0), p[1] * 0.02 + 0.4)
# Output to screen
fragColor = mix(vec(0.0, 0.0, 0.0, 0.0), col, pow(glow * 2.0, 4.0))
return fragColor
@ti.kernel
def render(t: ti.f32):
"render ??????? mainImage ????"
for i, j in pixels:
col4 = mainImage(t, i, j)
pixels[i, j] = vec(col4[0], col4[1], col4[2])
return
def main(output_img=False):
"output_img: ??????"
gui = ti.GUI(GUI_TITLE, res=wh)
for ts in range(1000000):
if gui.get_event(ti.GUI.ESCAPE):
exit()
render(ts * 0.03)
gui.set_image(pixels.to_numpy())
if output_img:
gui.show(f'{ts:04d}.png')
else:
gui.show()
if __name__ == '__main__':
main(output_img=False) |
XtherDevTeam/XmediaCenter | tests/damuku_parser_test.py | import os,core.plugins.video_player.video_apis,sys
with open('/media/p0010/8d7176d7-fa0b-485b-a2ed-18e2a4537f53/XmediaCenter-Python-Remaked-Version/core/storage/Video/CLANNAD/CLANNAD:第1话 在那落樱缤纷的坡道上.cmt.xml','r') as f:
xmlf = f.read().encode(encoding='utf-8')
result = core.plugins.video_player.video_apis.damuku_parser(xmlf)
for i in result:
print(i)
|
XtherDevTeam/XmediaCenter | core/plugins/FileManager/main.py | from types import CodeType
import flask,core.plugins.FileManager.file_manage,core.api,core.xmcp
from flask.globals import g
from flask.templating import render_template
import json
name = 'FileManager'
requestCPR = None
def cross_plugin_request(args:list):
if type(args[0]).__name__ == 'str' and args[0] == 'get_path':
return '/fm'
else:
return 'denied'
def get_plugins_path_list():
ret = []
#print(requestCPR())
for i in requestCPR():
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def get_plugins_names():
ret = []
for i in requestCPR():
ret.append(i.name)
return ret
def api_request(request:flask.request):
if type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'get_filelist':
return json.dumps(core.plugins.FileManager.file_manage.get_file_list(request.args.get('path')))
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'download':
return core.plugins.FileManager.file_manage.response_with_file(request.args.get('path'),request)
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'is_dir' and flask.session.get('userinfo') != None:
return core.plugins.FileManager.file_manage.is_directory(request.args.get('path'))
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'remove' and flask.session.get('userinfo') != None:
return core.plugins.FileManager.file_manage.remove(request.args.get('path'))
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'create_dir' and flask.session.get('userinfo') != None:
return core.plugins.FileManager.file_manage.create_dir(request.args.get('path'))
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'rename' and flask.session.get('userinfo') != None:
return core.plugins.FileManager.file_manage.rename(request.args.get('path'),request.args.get('new'))
elif type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'upload' and flask.session.get('userinfo') != None:
file = request.files.get("file")
print('request of ' + file.filename)
file.save('core/storage/' + request.args.get('path') + file.filename)
return flask.redirect('/fm?path="' + request.args.get('path') + '"')
else:
return json.dumps({'status':'error','reason':'Invalid Session'})
None
def idx_of_fm():
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
try:
path = core.api.getAbsPath(flask.request.values.get('path'))
if path == None or path == '/' or core.api.getAbsPath(path) == path or core.api.getAbsPath(path) == '"' + path + '"':
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/FileManager/main.html',
is_logined = is_logined,
user = user,
path = core.api.getAbsPath(flask.request.values.get('path')),
filenames=core.plugins.FileManager.file_manage.get_file_list(core.api.getAbsPath(flask.request.values.get('path'))),
modules_list=get_plugins_names()
)
))
else:
return flask.redirect('/fm?path=' + core.api.getAbsPath(path))
except Exception as e:
return json.dumps({'status':'error','reason':str(e)})
def register(server:flask.Flask):
#print(requestCPR)
server.add_url_rule('/fm',view_func=idx_of_fm)
return {
'registered_api': ['fm_api']
} |
XtherDevTeam/XmediaCenter | core/xmcp.py | import hashlib,json,base64
def makeUserInfomation(username:str,password:str):
password += <PASSWORD>'
password = <PASSWORD>(password.encode('utf-8')).<PASSWORD>digest()
final = username + ":" + password
final = str(base64.encodebytes(bytes(final.encode('utf-8'))),encoding='utf-8')
return final
def makeUserInfomation(uinf:dict):
final = uinf['username'] + ":" + uinf['pwd_encoded']
final = str(base64.encodebytes(bytes(final.encode('utf-8'))),encoding='utf-8')
return final
def makeUserAgent(sid:int,ui:str):
final = base64.encodebytes((str(sid) + ":" + ui).encode('utf-8'))
return final.decode('utf-8')
def checkUserAgent(ulist:list,smap:list,ua:str):
ua = base64.decodebytes(ua.encode('utf-8')).decode('utf-8')
sid = int(ua[0:ua.find(':')])
uinf = ua[ua.find(':'):]
if makeUserInfomation(ulist[smap[sid]]) == uinf:
return True
else:
return False
# return a dict like { 'u':name,'p':pwd_encoded }
def parseUserInfo(ui:str):
ui = base64.decodebytes(ui.encode('utf-8')).decode('utf-8')
un = ui[0:ui.find(':')]
up = ui[ui.find(':')+1:]
return { 'u':un,'p':up } |
XtherDevTeam/XmediaCenter | json_test.py | import json,sys
print(json.dumps( { } )) |
XtherDevTeam/XmediaCenter | core/plugins/Login/main.py | <filename>core/plugins/Login/main.py
from types import CodeType
import flask
from flask.templating import render_template
name = 'Login/Logout'
requestCPR = None
def cross_plugin_request(args: list):
if type(args[0]).__name__ == 'str' and args[0] == 'get_path':
return '/login'
else:
return 'denied'
def get_plugins_path_list():
ret = []
print(requestCPR())
for i in requestCPR():
path = i.cross_plugin_request(['get_path'])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path, i.name])
return ret
def idx_of_login():
if flask.session.get('userinfo') != None:
return flask.redirect('/api?action=logout')
return render_template(
"plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(render_template(
'plugins_templates/Login/main.html'))
)
def idx_of_sign_up():
return render_template(
"plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(render_template(
'plugins_templates/Login/signup.html'))
)
def register(server: flask.Flask):
print(requestCPR)
server.add_url_rule('/login', view_func=idx_of_login,
methods=['POST', 'GET'])
server.add_url_rule('/signup', view_func=idx_of_sign_up,
methods=['POST', 'GET'])
return {
'registered_api': None
}
|
XtherDevTeam/XmediaCenter | core/plugins/MusicPlayer/main.py | from types import CodeType
import flask,core.plugins.MusicPlayer.music_apis,core.api,core.xmcp,core.plugins.MusicPlayer.counter,pymediainfo
from werkzeug.utils import redirect
from flask.globals import g
from flask.templating import render_template
import json
name = 'MusicPlayer'
requestCPR = None
def cross_plugin_request(args:list):
if type(args[0]).__name__ == 'str' and args[0] == 'get_path':
return '/music'
else:
return 'denied'
def get_plugins_path_list():
ret = []
#print(requestCPR())
for i in requestCPR():
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def api_request(request:flask.request):
request_item = request.values.get('request')
if request_item == None:
return json.dumps({'status':'error','reason':'unknown request'})
if request_item == 'get_playlist_id':
pname = request.values.get('name')
if pname == None:
return json.dumps({'status':'error','reason':'unknown request'})
if pname[0] == '"':
pname = pname[1:-1]
return json.dumps(core.plugins.MusicPlayer.music_apis.get_playlist_id(pname,flask.session.get('userinfo')))
elif request_item == 'get_playlists':
return json.dumps(core.plugins.MusicPlayer.music_apis.get_playlists(flask.session.get('userinfo')))
elif request_item == 'create_playlist':
pname = request.values.get('name')
if pname == None:
return json.dumps({'status':'error','reason':'unknown request'})
if pname[0] == '"':
pname = pname[1:-1]
return json.dumps(core.plugins.MusicPlayer.music_apis.create_playlist(pname,flask.session.get('userinfo')))
elif request_item == 'half_pasted_detect':
filepath = request.values.get('path')
if filepath == None or filepath == '':
return json.dumps({'status':'error','reason':'unknown request'})
elif flask.session.get('userinfo') == None:
return json.dumps({'status':'error','reason':'Invalid Session'})
try:
audio_info = pymediainfo.MediaInfo.parse('core/storage/' + core.api.getAbsPath(filepath))
return core.plugins.MusicPlayer.counter.update_counter_file(flask.session.get('userinfo'),json.loads(audio_info.to_json())['tracks'][0]['title'])
except Exception as e:
return {'status':'error','reason':str(e)}
elif request_item == 'add_song':
pid = request.values.get('pid')
path = request.values.get('path') # already is abs path
if pid == None or path == None:
return json.dumps({'status':'error','reason':'unknown request'})
pid = int(pid)
path = core.api.getAbsPath(path)
return json.dumps(core.plugins.MusicPlayer.music_apis.append_songs(pid,path,flask.session.get('userinfo')))
elif request_item == 'remove_song':
pid = request.values.get('pid')
path = request.values.get('path') # already is abs path
if pid == None or path == None:
return json.dumps({'status':'error','reason':'unknown request'})
pid = int(pid)
return json.dumps(core.plugins.MusicPlayer.music_apis.remove_song(pid,path,flask.session.get('userinfo')))
elif request_item == 'remove_playlist':
pid = request.values.get('pid')
if pid == None:
return json.dumps({'status':'error','reason':'unknown request'})
pid = int(pid)
return json.dumps(core.plugins.MusicPlayer.music_apis.remove_playlist(pid,flask.session.get('userinfo')))
def idx_of_music():
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/MusicPlayer/main.html',
is_logined = is_logined,
user = user,
playlists = core.plugins.MusicPlayer.music_apis.get_playlists(flask.session.get('userinfo'))
)
))
def idx_of_playlists(name:str):
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/MusicPlayer/playlists.html',
is_logined = is_logined,
user = user,
playlists = core.plugins.MusicPlayer.music_apis.get_playlists(flask.session.get('userinfo')),
pid = core.plugins.MusicPlayer.music_apis.get_playlist_id(name,flask.session.get('userinfo'))['id'],
info = core.plugins.MusicPlayer.music_apis.get_songs_info(core.plugins.MusicPlayer.music_apis.get_playlist_id(name,flask.session.get('userinfo'))['id'],flask.session.get('userinfo')),
name = name
)
))
def idx_of_count():
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/MusicPlayer/counter.html',
is_logined = is_logined,
user = user,
song_count = core.plugins.MusicPlayer.counter.get_program_readable_counter_data(flask.session.get('userinfo')),
playbacktime_count = core.plugins.MusicPlayer.counter.count_all_playbacktime(flask.session.get('userinfo'))
)
))
def register(server:flask.Flask):
#print(requestCPR)
server.add_url_rule('/music',view_func=idx_of_music)
server.add_url_rule('/music/count',view_func=idx_of_count)
server.add_url_rule('/music/playlists/<name>',view_func=idx_of_playlists)
return {
'registered_api': ['music_api']
} |
XtherDevTeam/XmediaCenter | utils.py | #!/bin/python3
import core.XmediaCenterCore as Core,core.xmcp,sys
if sys.argv[1] == 'account':
if sys.argv[2] == 'new':
print(Core.create_account(sys.argv[3],sys.argv[4]))
elif sys.argv[2] == 'remove':
print(Core.remove_account(sys.argv[3],sys.argv[4]))
elif sys.argv[2] == 'modify':
if Core.remove_account(sys.argv[3],sys.argv[4]):
print(Core.create_account(sys.argv[3],sys.argv[5]))
else:
print('False')
|
XtherDevTeam/XmediaCenter | core/plugins/MusicSharing/main.py | <reponame>XtherDevTeam/XmediaCenter<filename>core/plugins/MusicSharing/main.py
from types import CodeType
import flask,core.plugins.FileManager.file_manage,core.api,core.xmcp
from flask.globals import g
from flask.templating import render_template
import json
import pymediainfo
from mutagen import File
name = 'Mini music player'
requestCPR = None
def cross_plugin_request(args:list):
return 'denied'
def get_plugins_path_list():
ret = []
#print(requestCPR())
for i in requestCPR():
if i.name == name:
continue
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def api_request(request:flask.request):
try:
file = File('core/storage/' + core.api.getAbsPath(core.api.getAbsPath(request.values.get('path'))))
except Exception as e:
return {'status':'error', 'reason': str(e)}
return flask.Response(file['APIC:'].data,mimetype='image/jpeg')
def idx_of_mmp():
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
if core.api.getAbsPath(flask.request.values.get('path')) == None:
return {'status':'error', 'reason': 'invalid music path'}
result = None
try:
result = pymediainfo.MediaInfo.parse('core/storage/' + core.api.getAbsPath(core.api.getAbsPath(flask.request.values.get('path'))))
except Exception as e:
return {'status':'error', 'reason': str(e)}
try:
result = {
'title':json.loads(result.to_json())['tracks'][0]['title'],
'track_name':json.loads(result.to_json())['tracks'][0].get('track_name'),
'album':json.loads(result.to_json())['tracks'][0].get('album'),
'performer':json.loads(result.to_json())['tracks'][0].get('performer'),
'path': core.api.getAbsPath(core.api.getAbsPath(flask.request.values.get('path')))
}
except Exception as e:
print('failed: ' + core.api.getAbsPath(core.api.getAbsPath(flask.request.values.get('path'))))
return flask.Markup(
render_template(
'plugins_templates/MusicSharing/main.html',
is_logined = is_logined,
user = user,
song_info = result,
)
)
def register(server:flask.Flask):
#print(requestCPR)
server.add_url_rule('/mmp',view_func=idx_of_mmp)
return {
'registered_api': ['mmp_album_image']
} |
XtherDevTeam/XmediaCenter | core/plugins/FileManager/file_manage.py | <reponame>XtherDevTeam/XmediaCenter<filename>core/plugins/FileManager/file_manage.py
import os,sys,json,core.api,flask,shutil,mimetypes
from posixpath import expanduser
def get_mime(path:str):
# os.getcwd()+'/core/storage/' + core.api.getAbsPath(path)
a = mimetypes.guess_type(path)
if a[0] == None:
return 'application/octet-stream'
else:
return a[0]
def is_directory(path:str):
if path[0] == '"':
path = path[1:-1]
return os.path.isdir('core/storage/' + core.api.getAbsPath(path))
def response_with_file(path,request:flask.request):
if path != None and path[0] == '"':
path = path[1:-1]
try:
is_preview = True
if get_mime(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path)).startswith('application'):
is_preview = False
else:
is_preview = True
if request.headers.get('Range') != None:
startIndex = 0
part_length = 2 * 1024 * 1024
startIndex = int(request.headers.get('Range')[request.headers.get('Range').find('=')+1:request.headers.get('Range').find('-')])
endIndex = startIndex + part_length - 1
fileLength = os.path.getsize(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path))
if endIndex > fileLength:
endIndex = fileLength - 1
response_file = bytes()
with open(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path),'rb') as file:
file.seek(startIndex)
response_file = file.read(part_length)
response = flask.make_response(response_file)
response.headers['Accept-Ranges'] = 'bytes'
response.headers['Content-Range'] = 'bytes ' + str(startIndex) + '-' + str(endIndex) + '/' + str(fileLength)
response.headers['Content-Type'] = get_mime(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path))
if response.headers['Content-Type'].startswith('application'):
response.headers['Content-Disposition'] = "attachment; filename=" + core.api.get_filename(path)
response.status_code = 206
return response
return flask.send_file(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path),as_attachment=not is_preview,attachment_filename=core.api.get_filename(path),mimetype=get_mime(os.getcwd()+'/core/storage/' + core.api.getAbsPath(path)))
except Exception as e:
return json.dumps({ 'status':'error','reason':'Failed:' + str(e) })
def create_dir(path):
if path != None and path[0] == '"':
path = path[1:-1]
if path == None:
return json.dumps({ 'status':'error','reason':'empty argument detected' })
try:
os.mkdir('core/storage/' + core.api.getAbsPath(path))
return json.dumps({ 'status':'success' })
except Exception as e:
return json.dumps({ 'status':'error','reason':str(e) })
def get_file_list(path):
if path != '' and path[0] == '"':
path = path[1:-1]
not_modified = os.listdir('core/storage/' + core.api.getAbsPath(path))
final = []
for i in not_modified:
if is_directory(core.api.getAbsPath(path+'/'+i)):
final.append( { 'filename':i,'type':'dir' } )
else:
print('MIME of ','core/storage/' + core.api.getAbsPath(path+'/'+i),get_mime('core/storage/' + core.api.getAbsPath(path+'/'+i)))
final.append( { 'filename':i,'type':'file','mime':get_mime('core/storage/' + core.api.getAbsPath(path+'/'+i)) } )
return final
def remove(path):
if path != '' and path[0] == '"':
path = path[1:-1]
if path == None:
return json.dumps({ 'status':'error','reason':'empty path detected' })
try:
if is_directory(path):
shutil.rmtree('core/storage/' + core.api.getAbsPath(path))
else:
os.remove('core/storage/' + core.api.getAbsPath(path))
return json.dumps({ 'status':'success' })
except Exception as e:
return json.dumps({ 'status':'error','reason':str(e) })
def rename(path,newname):
if path != '' and path[0] == '"':
path = path[1:-1]
if path == None:
return json.dumps({ 'status':'error','reason':'empty path detected' })
if newname != '' and newname[0] == '"':
newname = newname[1:-1]
if newname == None:
return json.dumps({ 'status':'error','reason':'empty path detected' })
try:
os.rename('core/storage/' + core.api.getAbsPath(path),'core/storage/' + core.api.getAbsPath(newname))
return json.dumps({ 'status':'success' })
except Exception as e:
return json.dumps({ 'status':'error','reason':str(e) }) |
XtherDevTeam/XmediaCenter | core/plugins/EpubReader/main.py | <reponame>XtherDevTeam/XmediaCenter
import mimetypes
from types import CodeType
from typing import final
from xml.etree.ElementTree import ElementTree
import flask,core.plugins.FileManager.file_manage,core.api,core.xmcp
from flask.wrappers import Response
from flask.helpers import make_response
from flask.globals import g
from flask.templating import render_template
import json
import core.plugins.EpubReader.epub_parser
name = 'Book Reader'
requestCPR = None
def cross_plugin_request(args:list):
return 'denied'
def get_plugins_path_list():
ret = []
#print(requestCPR())
for i in requestCPR():
if i.name == name:
continue
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def api_request(request:flask.request):
epub_path = request.args.get('epub')
epub_path = core.api.getAbsPath(epub_path)
result = core.plugins.EpubReader.epub_parser.parse('core/storage/'+epub_path)
if epub_path == None:
return {'status':'error','reason':'No epub file selected'}
if type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'get_epub_detail':
return {'path': epub_path, 'title': result['title'], 'author': result['author'], 'chapters': result['chapters']}
if type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'get_file_in_epub':
file = request.args.get('file')
if file == None:
return {'status':'error','reason':'Filename is null'}
if result['files'].get(file) == None:
return {'status':'error','reason':'File not exist'}
return Response( result['files'][core.api.getAbsPath(file)], mimetype=mimetypes.guess_type( file )[0] )
if type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'get_filelist':
finalresult = []
for i in result['files']:
finalresult.append(i)
return {'filelist':finalresult}
if type(request.args.get('request')).__name__ == 'str' and request.args.get('request') == 'get_iframe_object':
file = request.args.get('file')
file = core.api.getAbsPath(file)
if file == None:
return {'status':'error','reason':'Filename is null'}
if result['files'].get(file) == None:
return {'status':'error','reason':'File not exist'}
if mimetypes.guess_type(file)[0].find('html') == -1:
return {'status':'error','reason':'Not a current xml file'}
return Response(core.plugins.EpubReader.epub_parser.covertToViewableHtml(result['files'][file],epub_path,file),mimetype='application/xhtml+xml')
return {'status':'error','reason':'unsupported api'}
def idx_of_epubreader():
is_logined = flask.session.get('userinfo') != None
user = {}
if flask.request.values.get('path') == None:
return {'status':'error','reason':'path is null'}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
if flask.request.values.get('index') == None:
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/EpubReader/file.html',
is_logined = is_logined,
user = user,
path = core.api.getAbsPath(flask.request.values.get('path')),
book = core.plugins.EpubReader.epub_parser.parse('core/storage/'+core.api.getAbsPath(flask.request.values.get('path'))),
)
))
else:
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/EpubReader/indexing.html',
is_logined = is_logined,
user = user,
path = core.api.getAbsPath(flask.request.values.get('path')),
book = core.plugins.EpubReader.epub_parser.parse('core/storage/'+core.api.getAbsPath(flask.request.values.get('path'))),
now_index = int(flask.request.values.get('index')),
total_index = len(core.plugins.EpubReader.epub_parser.parse('core/storage/'+core.api.getAbsPath(flask.request.values.get('path')))['files']),
)
))
def register(server:flask.Flask):
#print(requestCPR)
server.add_url_rule('/reader',view_func=idx_of_epubreader)
return {
'registered_api': ['epub_api']
} |
XtherDevTeam/XmediaCenter | core/plugins/MusicPlayer/music_apis.py | import json,os,sys,pymediainfo,core.api,hashlib
def init_playlists(userinfo:str):
# init config directory
if os.access('core/plugins/MusicPlayer/.musicplayer',os.F_OK):
None
else:
os.mkdir('core/plugins/MusicPlayer/.musicplayer')
# init user playlists
if os.access('core/plugins/MusicPlayer/.musicplayer/playlists-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json',os.F_OK):
None
else:
with open('core/plugins/MusicPlayer/.musicplayer/playlists-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','w+',encoding='utf-8') as file:
file.write(json.dumps([]))
def get_playlists(userinfo:str):
if userinfo == None or userinfo == '':
return {'status':'error','reason':'Invalid Session'}
init_playlists(userinfo)
try:
with open('core/plugins/MusicPlayer/.musicplayer/playlists-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','r+',encoding='utf-8') as file:
return {'status':'success','playlists':json.loads(file.read())}
except Exception as e:
return {'status':'error','reason':str(e)}
def sync_playlists(pls:dict,userinfo:str):
try:
if userinfo == None or userinfo == '':
None
with open('core/plugins/MusicPlayer/.musicplayer/playlists-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','w+',encoding='utf-8') as file:
file.write(json.dumps(pls['playlists']))
return {'status':'success'}
except Exception as e:
return {'status':'error','reason':str(e)}
def create_playlist(name:str,userinfo:str):
pls = get_playlists(userinfo)
if pls['status'] == 'error':
return pls
else:
pls['playlists'].append({ 'name':name,'songs':[] })
return sync_playlists(pls,userinfo)
def append_songs(pid:int,path:str,userinfo:str):
try:
print('path:',path)
if path != None and path[0] == '"':
path = path[1:-1]
pls = get_playlists(userinfo)
if pls['status'] == 'error':
return pls
elif len(pls['playlists']) <= pid:
return {'status':'error','reason':'Out of range'}
elif pls['playlists'][pid]['songs'].count(path):
return {'status':'success'}
pls['playlists'][pid]['songs'].append(path)
return sync_playlists(pls,userinfo)
except Exception as e:
return {'status':'error','reason':str(e)}
def remove_song(pid:int,path:str,userinfo:str):
try:
pls = get_playlists(userinfo)
if pls['status'] == 'error':
return pls
if pls['playlists'][pid]['songs'].count(path) == 0:
#print(pls['playlists'][pid]['songs'])
return {'status':'error','reason':'song is not in list:' + path}
del pls['playlists'][pid]['songs'][pls['playlists'][pid]['songs'].index(path)]
return sync_playlists(pls,userinfo)
except Exception as e:
return {'status':'error','reason':str(e)}
def remove_playlist(pid:int,userinfo:str):
try:
pls = get_playlists(userinfo)
if pls['status'] == 'error':
return pls
del pls['playlists'][pid]
return sync_playlists(pls,userinfo)
except Exception as e:
return {'status':'error','reason':str(e)}
def get_playlist_id(name:str,userinfo:str):
if name == None:
return {'status':'error','reason':'Invalid playlist name'}
else:
pls = get_playlists(userinfo)
if pls['status'] == 'error':
return pls
else:
for i in pls['playlists']:
if i['name'] == name:
return {'status':'success','id':pls['playlists'].index(i)}
return {'status':'error','reason':'No result'}
def get_songs_info(pid:int,userinfo:str):
pls = get_playlists(userinfo)
#print(pls['playlists'],len(pls['playlists']))
if pls['status'] == 'error':
return pls
elif len(pls['playlists']) <= pid:
return {'status':'error','reason':'Out of range'}
# i -> str
final = { 'status': 'success','playlist':[] }
for i in pls['playlists'][pid]['songs']:
result = pymediainfo.MediaInfo.parse('core/storage/' + core.api.getAbsPath(i))
try:
final['playlist'].append(
{
'title':json.loads(result.to_json())['tracks'][0]['title'],
'track_name':json.loads(result.to_json())['tracks'][0].get('track_name'),
'album':json.loads(result.to_json())['tracks'][0].get('album'),
'performer':json.loads(result.to_json())['tracks'][0].get('performer'),
'path': core.api.getAbsPath(i)
}
)
except Exception as e:
print('failed: ' + core.api.getAbsPath(i))
return final |
XtherDevTeam/XmediaCenter | core/plugins/video_player/main.py | from os import F_OK
import os
from types import CodeType
import flask,core.plugins.FileManager.file_manage,core.api,core.xmcp,core.plugins.video_player.video_apis
from flask.globals import g
from flask.templating import render_template
import json
name = 'Video Player'
requestCPR = None
def cross_plugin_request(args:list):
if type(args[0]).__name__ == 'str' and args[0] == 'get_path':
return '/video'
else:
return 'denied'
def get_plugins_path_list():
ret = []
#print(requestCPR())
for i in requestCPR():
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def api_request(request:flask.request):
request_item = request.values.get('request')
if request_item == 'damuku':
video_path = request.values.get('request_video')
# fetch from bilibili
if video_path.endswith('v3/?id=undefined'):
video_path = video_path[0:0-len('v3/?id=undefined')]
ret = {'code':0,'data':[]}
print('trying access:',('core/storage/' + core.api.getAbsPath(video_path))[0:-4] + '.cmt.xml')
with open(file='core/storage/' + core.api.getAbsPath(video_path)[0:-4] + '.cmt.xml',mode='r') as f:
ret['data'] = core.plugins.video_player.video_apis.damuku_parser(f.read().encode(encoding='utf-8'))
response = flask.make_response(json.dumps(ret))
response.headers['Content-Type']= 'application/json'
return response
None
def idx_of_vp():
is_logined = flask.session.get('userinfo') != None
user = {}
if is_logined:
user = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
return render_template("plugins_templates/main/index.html",
plugins_list=get_plugins_path_list(),
renderText=flask.Markup(
render_template(
'plugins_templates/video_player/main.html',
is_logined = is_logined,
user = user,
path = core.api.getAbsPath(flask.request.values.get('path')),
filename = core.api.get_filename(flask.request.values.get('path'))
)
))
def register(server:flask.Flask):
#print(requestCPR)
server.add_url_rule('/video',view_func=idx_of_vp)
return {
'registered_api': ['vp_api']
} |
XtherDevTeam/XmediaCenter | core/plugins/main/main.py | <gh_stars>1-10
from types import CodeType
import flask
from flask.templating import render_template
import core.xmcp
name = 'main'
requestCPR = None
def cross_plugin_request(args:list):
return "denied"
def get_plugins_path_list():
ret = []
print(requestCPR())
for i in requestCPR():
path = i.cross_plugin_request([ 'get_path' ])
if type(path).__name__ == 'str' and path == 'denied':
pass
else:
ret.append([path,i.name])
return ret
def main():
username = ''
is_logined = False
if flask.session.get('userinfo') == None:
is_logined = False
else:
is_logined = True
username = core.xmcp.parseUserInfo(flask.session.get('userinfo'))
return render_template("plugins_templates/main/index.html",plugins_list=get_plugins_path_list(),renderText=flask.Markup(render_template('plugins_templates/main/main.html',is_logined=is_logined,username=username)))
def register(server:flask.Flask):
print(requestCPR)
server.add_url_rule('/main',view_func=main,methods=['POST','GET'])
return {
'registered_api': None
} |
XtherDevTeam/XmediaCenter | core/plugins/MusicPlayer/counter.py | <gh_stars>1-10
import json,os,sys,hashlib
def init_counter_file(userinfo:str):
if os.access(os.getcwd() + '/core/plugins/MusicPlayer/.musicplayer/counter-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json',os.F_OK):
None
else:
with open(os.getcwd() + '/core/plugins/MusicPlayer/.musicplayer/counter-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','w+') as file:
file.write(json.dumps( { 'type':'Music Counter','content':{} } ))
def get_counter_file(userinfo:str):
init_counter_file(userinfo)
if userinfo == None or userinfo == '':
return {'status':'error','reason':'Invalid Session'}
try:
with open('core/plugins/MusicPlayer/.musicplayer/counter-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','r+',encoding='utf-8') as file:
return {'status':'success','counter':json.loads(file.read())}
except Exception as e:
return {'status':'error','reason':str(e)}
def sync_counter_file(userinfo:str,file_:dict):
init_counter_file(userinfo)
try:
with open(os.getcwd() + '/core/plugins/MusicPlayer/.musicplayer/counter-' + hashlib.md5(userinfo.encode('utf-8')).hexdigest() + '.json','w+') as file:
file.write(json.dumps( file_ ))
return {'status':'success'}
except Exception as e:
return {'status':'error','reason':str(e)}
# song : song title
def update_counter_file(userinfo:str,song:str):
init_counter_file(userinfo)
file = get_counter_file(userinfo)
if file['status'] == 'error':
return file
file = file['counter']
if file['content'].get(song) == None:
file['content'][song] = 0
file['content'][song] += 1
return sync_counter_file(userinfo,file)
def get_program_readable_counter_data(userinfo:str):
if userinfo == None:
return []
file = get_counter_file(userinfo)
if file['status'] == 'error':
return file
file = file['counter']['content']
result = []
for key in file:
result.append( [ file[key] , key ] )
result.sort(reverse=True)
return result
def count_all_playbacktime(session):
obj = get_program_readable_counter_data(session)
first = len(obj)
second = 0
for i in obj:
second += i[0]
return [first,second] |
XtherDevTeam/XmediaCenter | tests/mime.py | <reponame>XtherDevTeam/XmediaCenter<gh_stars>1-10
#!/bin/python3
import sys,mimetypes
print(mimetypes.guess_type(sys.argv[1])[0]) |
XtherDevTeam/XmediaCenter | core/plugins/video_player/video_apis.py | import os,sys,lxml.etree
def damuku_parser(origin_xml):
ret = []
html = lxml.etree.HTML(origin_xml)
for item in html.xpath('//d'):
description = item.xpath('./@p')[0].split(',')
ret.append( [ float(description[0]),int(description[1]),int(description[3]),description[6],item.text ] )
return ret |
cloudconductor-patterns/tomcat_pattern_ansible | lib/cloud_conductor_attributes.py | <reponame>cloudconductor-patterns/tomcat_pattern_ansible
import os
import consul
import json
import ast
def token_key():
return os.environ.get('CONSUL_SECRET_KEY')
def kvs_all_keys():
c = consul.Consul()
index, data = c.kv.get('', token=token_key(), keys=True)
return data
def kvs_cc_keys():
cc_keys= filter(lambda x:x.startswith('cloudconductor/'), kvs_all_keys())
return cc_keys
def kvs_get(key):
c = consul.Consul()
index, data = c.kv.get(key, token=token_key())
return data
def deep_merge(source, destination):
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
deep_merge(value, node)
else:
destination[key] = value
return destination
if __name__ == '__main__':
cc_keys = kvs_cc_keys()
cc_values = map(lambda x:ast.literal_eval(kvs_get(x)['Value']), cc_keys)
cc_attributes = reduce(lambda x, y:deep_merge(x, y), cc_values)
print json.dumps(cc_attributes)
exit(0)
|
cloudconductor-patterns/tomcat_pattern_ansible | playbooks/filter_plugins/cc_filters.py | <filename>playbooks/filter_plugins/cc_filters.py
# Common filters
def deep_get(cc_attributes, nested_keys):
if cc_attributes == None:
return None
current_dict = cc_attributes
for key in nested_keys.split('.'):
if current_dict.has_key(key):
current_dict = current_dict[key]
else:
return None
else:
return current_dict
# CloudConductor Attributes filters
def fetch_role_servers(attrs, role):
servers = attrs['servers']
return dict((x,y) for x,y in filter(lambda x: x[1]['roles'].count(role) > 0, servers.items()))
def first_server(cc_attributes, role):
servers = fetch_role_servers(cc_attributes, role)
first_server_key = sorted(servers.keys())[0]
return {first_server_key: servers[first_server_key]}
def first_db_server(cc_attributes):
return first_server(cc_attributes, 'db')
def first_ap_server(cc_attributes):
return first_server(cc_attributes, 'ap')
def first_server_ip(server):
return server[server.keys()[0]]['private_ip']
def first_ap_server_ip(cc_attributes):
if cc_attributes == None:
return None
try:
server = first_ap_server(cc_attributes)
ret_ip = first_server_ip(server)
except KeyError, e:
ret_ip = None
return ret_ip
def first_db_server_ip(cc_attributes):
if cc_attributes == None:
return None
try:
server = first_db_server(cc_attributes)
ret_ip = first_server_ip(server)
except KeyError, e:
ret_ip = None
return ret_ip
def applications_dict_to_array(applications_dict):
ary = []
for k,v in applications_dict.items():
dict = {'application_name': k}
dict.update(v)
ary.append(dict)
return ary
def first_application(cc_attributes):
if cc_attributes == None or not cc_attributes.has_key('applications'):
return None
applications = cc_attributes['applications']
first_application_name = sorted(applications.keys())[0]
first_application_dict = {first_application_name: applications[first_application_name]}
return applications_dict_to_array(first_application_dict)[0]
class FilterModule(object):
''' Ansible CloudConductor jinja2 filters '''
def filters(self):
return {
'deep_get': deep_get,
'first_ap_server_ip': first_ap_server_ip,
'first_db_server_ip': first_db_server_ip,
'first_application': first_application
}
|
ZhuozhaoLi/funcX | funcx_endpoint/funcx_endpoint/endpoint/endpoint_manager.py | <reponame>ZhuozhaoLi/funcX<gh_stars>0
import glob
import json
import logging
import os
import pathlib
import shutil
import signal
import sys
import time
import uuid
from string import Template
import daemon
import daemon.pidfile
import psutil
import texttable as tt
import typer
from retry.api import retry_call
import funcx
import zmq
from globus_sdk import GlobusAPIError, NetworkError
import funcx_endpoint
from funcx.utils.errors import *
from funcx.utils.response_errors import FuncxResponseError
from funcx_endpoint.endpoint import default_config as endpoint_default_config
from funcx_endpoint.executors.high_throughput import global_config as funcx_default_config
from funcx_endpoint.endpoint.interchange import EndpointInterchange
from funcx.sdk.client import FuncXClient
logger = logging.getLogger("endpoint.endpoint_manager")
class EndpointManager:
""" EndpointManager is primarily responsible for configuring, launching and stopping the Endpoint.
"""
def __init__(self,
funcx_dir=os.path.join(pathlib.Path.home(), '.funcx'),
debug=False):
""" Initialize the EndpointManager
Parameters
----------
funcx_dir: str
Directory path to the root of the funcx dirs. Usually ~/.funcx.
debug: Bool
Enable debug logging. Default: False
"""
self.funcx_config_file_name = 'config.py'
self.debug = debug
self.funcx_dir = funcx_dir
self.funcx_config_file = os.path.join(self.funcx_dir, self.funcx_config_file_name)
self.funcx_default_config_template = funcx_default_config.__file__
self.funcx_config = {}
self.name = 'default'
global logger
self.logger = logger
def init_endpoint_dir(self, endpoint_config=None):
""" Initialize a clean endpoint dir
Returns if an endpoint_dir already exists
Parameters
----------
endpoint_config : str
Path to a config file to be used instead of the funcX default config file
"""
endpoint_dir = os.path.join(self.funcx_dir, self.name)
self.logger.debug(f"Creating endpoint dir {endpoint_dir}")
os.makedirs(endpoint_dir, exist_ok=True)
endpoint_config_target_file = os.path.join(endpoint_dir, self.funcx_config_file_name)
if endpoint_config:
shutil.copyfile(endpoint_config, endpoint_config_target_file)
return endpoint_dir
endpoint_config = endpoint_default_config.__file__
with open(endpoint_config) as r:
endpoint_config_template = Template(r.read())
endpoint_config_template = endpoint_config_template.substitute(name=self.name)
with open(endpoint_config_target_file, "w") as w:
w.write(endpoint_config_template)
return endpoint_dir
def configure_endpoint(self, name, endpoint_config):
self.name = name
endpoint_dir = os.path.join(self.funcx_dir, self.name)
new_config_file = os.path.join(endpoint_dir, self.funcx_config_file_name)
if not os.path.exists(endpoint_dir):
self.init_endpoint_dir(endpoint_config=endpoint_config)
print(f'A default profile has been create for <{self.name}> at {new_config_file}')
print('Configure this file and try restarting with:')
print(f' $ funcx-endpoint start {self.name}')
else:
print(f'config dir <{self.name}> already exsits')
raise Exception('ConfigExists')
def init_endpoint(self):
"""Setup funcx dirs and default endpoint config files
TODO : Every mechanism that will update the config file, must be using a
locking mechanism, ideally something like fcntl https://docs.python.org/3/library/fcntl.html
to ensure that multiple endpoint invocations do not mangle the funcx config files
or the lockfile module.
"""
_ = FuncXClient()
if os.path.exists(self.funcx_config_file):
typer.confirm(
"Are you sure you want to initialize this directory? "
f"This will erase everything in {self.funcx_dir}", abort=True
)
self.logger.info("Wiping all current configs in {}".format(self.funcx_dir))
backup_dir = self.funcx_dir + ".bak"
try:
self.logger.debug(f"Removing old backups in {backup_dir}")
shutil.rmtree(backup_dir)
except OSError:
pass
os.renames(self.funcx_dir, backup_dir)
if os.path.exists(self.funcx_config_file):
self.logger.debug("Config file exists at {}".format(self.funcx_config_file))
return
try:
os.makedirs(self.funcx_dir, exist_ok=True)
except Exception as e:
print("[FuncX] Caught exception during registration {}".format(e))
shutil.copyfile(self.funcx_default_config_template, self.funcx_config_file)
def check_endpoint_json(self, endpoint_json, endpoint_uuid):
if os.path.exists(endpoint_json):
with open(endpoint_json, 'r') as fp:
self.logger.debug("Connection info loaded from prior registration record")
reg_info = json.load(fp)
endpoint_uuid = reg_info['endpoint_id']
elif not endpoint_uuid:
endpoint_uuid = str(uuid.uuid4())
return endpoint_uuid
def start_endpoint(self, name, endpoint_uuid, endpoint_config):
self.name = name
endpoint_dir = os.path.join(self.funcx_dir, self.name)
endpoint_json = os.path.join(endpoint_dir, 'endpoint.json')
# These certs need to be recreated for every registration
keys_dir = os.path.join(endpoint_dir, 'certificates')
os.makedirs(keys_dir, exist_ok=True)
client_public_file, client_secret_file = zmq.auth.create_certificates(keys_dir, "endpoint")
client_public_key, _ = zmq.auth.load_certificate(client_public_file)
client_public_key = client_public_key.decode('utf-8')
# This is to ensure that at least 1 executor is defined
if not endpoint_config.config.executors:
raise Exception(f"Endpoint config file at {endpoint_dir} is missing executor definitions")
funcx_client = FuncXClient(funcx_service_address=endpoint_config.config.funcx_service_address,
check_endpoint_version=True)
endpoint_uuid = self.check_endpoint_json(endpoint_json, endpoint_uuid)
self.logger.info(f"Starting endpoint with uuid: {endpoint_uuid}")
# Create a daemon context
# If we are running a full detached daemon then we will send the output to
# log files, otherwise we can piggy back on our stdout
if endpoint_config.config.detach_endpoint:
stdout = open(os.path.join(endpoint_dir, endpoint_config.config.stdout), 'w+')
stderr = open(os.path.join(endpoint_dir, endpoint_config.config.stderr), 'w+')
else:
stdout = sys.stdout
stderr = sys.stderr
try:
context = daemon.DaemonContext(working_directory=endpoint_dir,
umask=0o002,
pidfile=daemon.pidfile.PIDLockFile(
os.path.join(endpoint_dir, 'daemon.pid')),
stdout=stdout,
stderr=stderr,
detach_process=endpoint_config.config.detach_endpoint)
except Exception:
self.logger.exception("Caught exception while trying to setup endpoint context dirs")
sys.exit(-1)
self.check_pidfile(context.pidfile.path, "funcx-endpoint")
# place registration after everything else so that the endpoint will
# only be registered if everything else has been set up successfully
reg_info = None
try:
reg_info = self.register_endpoint(funcx_client, endpoint_uuid, endpoint_dir)
# if the service sends back an error response, it will be a FuncxResponseError
except FuncxResponseError as e:
# an example of an error that could conceivably occur here would be
# if the service could not register this endpoint with the forwarder
# because the forwarder was unreachable
if e.http_status_code >= 500:
self.logger.exception("Caught exception while attempting endpoint registration")
self.logger.critical("Endpoint registration will be retried in the new endpoint daemon "
"process. The endpoint will not work until it is successfully registered.")
else:
raise e
# if the service has an unexpected internal error and is unable to send
# back a FuncxResponseError
except GlobusAPIError as e:
if e.http_status >= 500:
self.logger.exception("Caught exception while attempting endpoint registration")
self.logger.critical("Endpoint registration will be retried in the new endpoint daemon "
"process. The endpoint will not work until it is successfully registered.")
else:
raise e
# if the service is unreachable due to a timeout or connection error
except NetworkError as e:
# the output of a NetworkError exception is huge and unhelpful, so
# it seems better to just stringify it here and get a concise error
self.logger.exception(f"Caught exception while attempting endpoint registration: {e}")
self.logger.critical("funcx-endpoint is unable to reach the funcX service due to a NetworkError \n"
"Please make sure that the funcX service address you provided is reachable \n"
"and then attempt restarting the endpoint")
exit(-1)
except Exception:
raise
if reg_info:
self.logger.info("Launching endpoint daemon process")
else:
self.logger.critical("Launching endpoint daemon process with errors noted above")
with context:
self.daemon_launch(funcx_client, endpoint_uuid, endpoint_dir, keys_dir, endpoint_config, reg_info)
def daemon_launch(self, funcx_client, endpoint_uuid, endpoint_dir, keys_dir, endpoint_config, reg_info):
if reg_info is None:
# Register the endpoint
self.logger.info("Retrying endpoint registration after initial registration attempt failed")
reg_info = retry_call(self.register_endpoint, fargs=[funcx_client, endpoint_uuid, endpoint_dir], delay=10, max_delay=300, backoff=1.2)
self.logger.info("Endpoint registered with UUID: {}".format(reg_info['endpoint_id']))
# Configure the parameters for the interchange
optionals = {}
optionals['client_address'] = reg_info['public_ip']
optionals['client_ports'] = reg_info['tasks_port'], reg_info['results_port'], reg_info['commands_port'],
if 'endpoint_address' in self.funcx_config:
optionals['interchange_address'] = self.funcx_config['endpoint_address']
optionals['logdir'] = endpoint_dir
if self.debug:
optionals['logging_level'] = logging.DEBUG
ic = EndpointInterchange(endpoint_config.config,
endpoint_id=endpoint_uuid,
keys_dir=keys_dir,
**optionals)
ic.start()
ic.stop()
self.logger.critical("Interchange terminated.")
# Avoid a race condition when starting the endpoint alongside the web service
def register_endpoint(self, funcx_client, endpoint_uuid, endpoint_dir):
"""Register the endpoint and return the registration info.
Parameters
----------
funcx_client : FuncXClient
The auth'd client to communicate with the funcX service
endpoint_uuid : str
The uuid to register the endpoint with
endpoint_dir : str
The directory to write endpoint registration info into.
"""
self.logger.debug("Attempting registration")
self.logger.debug(f"Trying with eid : {endpoint_uuid}")
reg_info = funcx_client.register_endpoint(self.name,
endpoint_uuid,
endpoint_version=funcx_endpoint.__version__)
# this is a backup error handler in case an endpoint ID is not sent back
# from the service or a bad ID is sent back
if 'endpoint_id' not in reg_info:
raise Exception("Endpoint ID was not included in the service's registration response.")
elif not isinstance(reg_info['endpoint_id'], str):
raise Exception("Endpoint ID sent by the service was not a string.")
with open(os.path.join(endpoint_dir, 'endpoint.json'), 'w+') as fp:
json.dump(reg_info, fp)
self.logger.debug("Registration info written to {}".format(os.path.join(endpoint_dir, 'endpoint.json')))
certs_dir = os.path.join(endpoint_dir, 'certificates')
os.makedirs(certs_dir, exist_ok=True)
server_keyfile = os.path.join(certs_dir, 'server.key')
self.logger.debug(f"Writing server key to {server_keyfile}")
try:
with open(server_keyfile, 'w') as f:
f.write(reg_info['forwarder_pubkey'])
os.chmod(server_keyfile, 0o600)
except Exception:
self.logger.exception("Failed to write server certificate")
return reg_info
def stop_endpoint(self, name):
self.name = name
endpoint_dir = os.path.join(self.funcx_dir, self.name)
pid_file = os.path.join(endpoint_dir, "daemon.pid")
if os.path.exists(pid_file):
self.logger.debug(f"{self.name} has a daemon.pid file")
pid = None
with open(pid_file, 'r') as f:
pid = int(f.read())
# Attempt terminating
try:
self.logger.debug("Signalling process: {}".format(pid))
# For all the processes, including the deamon and its child process tree
# Send SIGTERM to the processes
# Wait for 200ms
# Send SIGKILL to the processes that are still alive
parent = psutil.Process(pid)
processes = parent.children(recursive=True)
processes.append(parent)
for p in processes:
p.send_signal(signal.SIGTERM)
terminated, alive = psutil.wait_procs(processes, timeout=0.2)
for p in alive:
p.send_signal(signal.SIGKILL)
# Wait to confirm that the pid file disappears
if not os.path.exists(pid_file):
self.logger.info("Endpoint <{}> is now stopped".format(self.name))
except OSError:
self.logger.warning("Endpoint {} could not be terminated".format(self.name))
self.logger.warning("Attempting Endpoint {} cleanup".format(self.name))
os.remove(pid_file)
sys.exit(-1)
else:
self.logger.info("Endpoint <{}> is not active.".format(self.name))
def delete_endpoint(self, name):
self.name = name
endpoint_dir = os.path.join(self.funcx_dir, self.name)
# If endpoint currently running, stop it.
pid_file = os.path.join(endpoint_dir, "daemon.pid")
active = os.path.exists(pid_file)
if active:
stop_endpoint(self.name)
shutil.rmtree(endpoint_dir)
def check_pidfile(self, filepath, match_name):
""" Helper function to identify possible dead endpoints
"""
if not os.path.exists(filepath):
return
older_pid = int(open(filepath, 'r').read().strip())
try:
proc = psutil.Process(older_pid)
if proc.name() == match_name:
self.logger.info("Endpoint is already active")
except psutil.NoSuchProcess:
self.logger.info("A prior Endpoint instance appears to have been terminated without proper cleanup")
self.logger.info('''Please cleanup using:
$ funcx-endpoint stop {}'''.format(self.name))
sys.exit(-1)
def list_endpoints(self):
table = tt.Texttable()
headings = ['Endpoint Name', 'Status', 'Endpoint ID']
table.header(headings)
config_files = glob.glob(os.path.join(self.funcx_dir, '*', 'config.py'))
for config_file in config_files:
endpoint_dir = os.path.dirname(config_file)
endpoint_name = os.path.basename(endpoint_dir)
status = 'Initialized'
endpoint_id = None
endpoint_json = os.path.join(endpoint_dir, 'endpoint.json')
if os.path.exists(endpoint_json):
with open(endpoint_json, 'r') as f:
endpoint_info = json.load(f)
endpoint_id = endpoint_info['endpoint_id']
if os.path.exists(os.path.join(endpoint_dir, 'daemon.pid')):
status = 'Active'
else:
status = 'Inactive'
table.add_row([endpoint_name, status, endpoint_id])
s = table.draw()
print(s)
|
tomasz-oponowicz/spoken_language_identification | features.py | import glob
import os
import time
import numpy as np
import soundfile as sf
from constants import *
import common
# source1: https://bit.ly/2GSsEgw
# source2: https://bit.ly/2sWxHIc
def generate_fb_and_mfcc(signal, sample_rate):
# Pre-Emphasis
pre_emphasis = 0.97
emphasized_signal = np.append(
signal[0],
signal[1:] - pre_emphasis * signal[:-1])
# Framing
frame_size = 0.025
frame_stride = 0.01
# Convert from seconds to samples
frame_length, frame_step = (
frame_size * sample_rate,
frame_stride * sample_rate)
signal_length = len(emphasized_signal)
frame_length = int(round(frame_length))
frame_step = int(round(frame_step))
# Make sure that we have at least 1 frame
num_frames = int(
np.ceil(float(np.abs(signal_length - frame_length)) / frame_step))
pad_signal_length = num_frames * frame_step + frame_length
z = np.zeros((pad_signal_length - signal_length))
# Pad Signal to make sure that all frames have equal
# number of samples without truncating any samples
# from the original signal
pad_signal = np.append(emphasized_signal, z)
indices = (
np.tile(np.arange(0, frame_length), (num_frames, 1)) +
np.tile(
np.arange(0, num_frames * frame_step, frame_step),
(frame_length, 1)
).T
)
frames = pad_signal[indices.astype(np.int32, copy=False)]
# Window
frames *= np.hamming(frame_length)
# Fourier-Transform and Power Spectrum
NFFT = 512
# Magnitude of the FFT
mag_frames = np.absolute(np.fft.rfft(frames, NFFT))
# Power Spectrum
pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2))
# Filter Banks
nfilt = 40
low_freq_mel = 0
# Convert Hz to Mel
high_freq_mel = (2595 * np.log10(1 + (sample_rate / 2) / 700))
# Equally spaced in Mel scale
mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2)
# Convert Mel to Hz
hz_points = (700 * (10**(mel_points / 2595) - 1))
bin = np.floor((NFFT + 1) * hz_points / sample_rate)
fbank = np.zeros((nfilt, int(np.floor(NFFT / 2 + 1))))
for m in range(1, nfilt + 1):
f_m_minus = int(bin[m - 1]) # left
f_m = int(bin[m]) # center
f_m_plus = int(bin[m + 1]) # right
for k in range(f_m_minus, f_m):
fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
for k in range(f_m, f_m_plus):
fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])
filter_banks = np.dot(pow_frames, fbank.T)
# Numerical Stability
filter_banks = np.where(
filter_banks == 0,
np.finfo(float).eps,
filter_banks)
# dB
filter_banks = 20 * np.log10(filter_banks)
# MFCCs
# num_ceps = 12
# cep_lifter = 22
# ### Keep 2-13
# mfcc = dct(
# filter_banks,
# type=2,
# axis=1,
# norm='ortho'
# )[:, 1 : (num_ceps + 1)]
# (nframes, ncoeff) = mfcc.shape
# n = np.arange(ncoeff)
# lift = 1 + (cep_lifter / 2) * np.sin(np.pi * n / cep_lifter)
# mfcc *= lift
return filter_banks
def process_audio(input_dir, debug=False):
files = []
extensions = ['*.flac']
for extension in extensions:
files.extend(glob.glob(os.path.join(input_dir, extension)))
for file in files:
if debug:
file = ('build/test/'
'de_f_63f5b79c76cf5a1a4bbd1c40f54b166e.fragment1.flac')
start = time.time()
print(file)
signal, sample_rate = sf.read(file)
assert len(signal) > 0
assert sample_rate == 22050
fb = generate_fb_and_mfcc(signal, sample_rate)
fb = fb.astype(DATA_TYPE, copy=False)
assert fb.dtype == DATA_TYPE
assert fb.shape == (WIDTH, FB_HEIGHT)
# .npz extension is added automatically
file_without_ext = os.path.splitext(file)[0]
np.savez_compressed(file_without_ext + '.fb', data=fb)
if debug:
end = time.time()
print("It took [s]: ", end - start)
# data is casted to uint8, i.e. (0, 255)
import imageio
imageio.imwrite('fb_image.png', fb)
exit(0)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description='Generate various features from audio samples.')
parser.add_argument('--debug', dest='debug', action='store_true')
parser.set_defaults(debug=False)
args = parser.parse_args()
if args.debug:
process_audio(os.path.join(common.DATASET_DIST, 'train'), debug=True)
else:
process_audio(os.path.join(common.DATASET_DIST, 'test'))
process_audio(os.path.join(common.DATASET_DIST, 'train'))
|
ipodlipnyak/YureiSim | objects/map.py | <gh_stars>0
import pygame
import random
import numpy as np
class grass():
def __init__(self):
if not pygame.font.get_init():
pygame.font.init()
self.on_init()
# self.on_render()
def on_init(self):
self.f = pygame.font.SysFont ('sawasdee',10,bold=True)
self.g = 'O' #grass symboll
def on_render(self, surface, in_grid = False):
if not in_grid:
self.gr = grid()
else:
self.gr = in_grid
self.gx = 0
self.gy = 0
for x in range(self.gr.w):
# print self.gr.g[x]
if x == 0:
self.gx = 0
else:
self.gx += 10
for y in range(self.gr.h):
self.text = self.f.render(self.g,True,(0,self.gr.g[x][y],0))
# print self.gx
# print self.gy
surface.blit(self.text,(self.gx,self.gy))
if y == 0:
self.gy = 0
else:
self.gy += 10
class grid():
def __init__(self):
self.on_gen()
def on_gen(self):
self.w = 100 #width
self.h = 30 #height
self.t = 0 #type of tile
self.g = [] #grid
for x in range(self.w):
self.g.append([])
for y in range(self.h):
self.g[x].append(self.t)
self.t = random.randrange(100,255)
def mandelbrot( h,w, maxit=20 ):
"""Returns an image of the Mandelbrot fractal of size (h,w)."""
y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z**2 + c
diverge = z*np.conj(z) > 2**2 # who is diverging
div_now = diverge & (divtime==maxit) # who is diverging now
divtime[div_now] = i # note when
z[diverge] = 2 # avoid diverging too much
return divtime
class grid_sample():
def __init__(self):
self.w = 3
self.h = 3
self.g = [[0,255,255],[255,0,255],[0,255,0]]
class map():
def __inist__(self):
pass
def on_render(self):
pass
|
ipodlipnyak/YureiSim | run.py | import sys, random, math, pygame, logging, objects
from sys import exit
from pygame.locals import *
from pygame.sprite import Group, GroupSingle
from objects import observer, grid, var_depo, ghost
class App:
def __init__(self):
self._running = True
self._display_surf = None
self.size = self.weigth, self.height = 1200,750#600, 375 #1024, 368
self.ts = 30 #tile size
self.nerad = 2,2 #neighborhood radius
self.net = 6 #neighborhood type from 1 to 6
self.leb = 1 #left bias for color mix. Weight for old color
self.rib = 2 #right bias for color mix. Weight for new color
self.td = 10 #time delay
self.gc = 2 #count for genies
def on_init(self):
# pygame.init()
pygame.display.init()
pygame.font.init()
self.surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Yep..')
self.font = pygame.font.SysFont('sawasdee', self.ts)
self.clock = pygame.time.Clock()
self.herr = observer.PushModel()
var_depo.grid = grid.Grid(surface=self.surf,font=self.font,notifier=self.herr,tile_value='grass',neighbor_rad=self.nerad,tile_size=self.ts,nt=self.net,lb=self.leb,rb=self.rib)
self.lamp = pygame.sprite.Group()
gc = 1
while gc <= self.gc:
gx = random.randrange(0,self.weigth/self.ts)
gy = random.randrange(0,self.height/self.ts)
ginie = ghost.virus(self.surf, self.herr,x=gx,y=gy,w=self.ts,h=self.ts)
self.lamp.add(ginie)
gc += 1
self._running = True
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self._running = False
if event.key == pygame.K_RIGHT:
pass
elif event.key == pygame.K_LEFT:
pass
def on_loop(self):
self.clock.tick()
self.fps = self.clock.get_fps()
# print self.fps
self.lamp.update()
def on_render(self):
pygame.display.flip()
pygame.time.delay(self.td)
def on_cleanup(self):
pygame.display.quit()
pygame.quit()
sys.exit()
def on_execute(self):
if self.on_init() == False:
self._running = False
while (self._running):
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
self.on_cleanup()
if __name__ == "__main__" :
# logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('App')
logger.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
sh.setFormatter(formatter)
logger.addHandler(sh)
# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
# logging.basicConfig(filename='example.log',format='%(levelname)s:%(message)s',level=logging.DEBUG)
# logging.basicConfig(format='%(message)s',level=logging.DEBUG)
# logging.basicConfig(filename='example.log',format='%(message)s',level=logging.DEBUG)
theApp = App()
theApp.on_execute()
|
ipodlipnyak/YureiSim | objects/ghost.py | <filename>objects/ghost.py<gh_stars>0
import pygame, random
class ghost(pygame.sprite.Sprite,object):
def __init__(self,surface,observer,x=0,y=0,w=15,h=15):
pygame.sprite.Sprite.__init__(self)
self.surf = surface
self.obs = observer
self.rect = pygame.Rect(x,y,w,h)
self.surf_rect = surface.get_rect()
self.R = random.randrange(0,255)
self.G = random.randrange(0,255)
self.B = random.randrange(0,255)
self.symbol = 'Y'
def update(self):
self.on_move()
def on_move(self):
pass
def on_do(self):
pass
def switch_color(self):
self.R = random.randrange(0,255)
self.G = random.randrange(0,255)
self.B = random.randrange(0,255)
class yurei(ghost,object):
def __init__(self,surface,observer,x=0,y=0,w=15,h=15):
super(yurei,self).__init__(surface,observer,x,y,w,h)
self.random_choice()
self.dxx = x
self.dyy = y
def on_move(self):
self.random_move()
self.on_do()
def on_do(self):
self.change_tile()
def random_choice(self):
self.dx = random.choice([-2,-1,0,1,2])
self.dy = random.choice([-2,-1,0,1,2])
def random_move(self):
if (self.dx == 0 and self.dy == 0) or (abs(self.dx) == 2 and abs(self.dy) == 2):
self.random_choice()
if 0 < self.rect.x+self.dx < self.surf_rect.w/self.rect.w:
self.dxx = self.rect.x
self.rect.x += self.dx
if 0 < self.rect.y+self.dy < self.surf_rect.h/self.rect.h:
self.dyy = self.rect.y
self.rect.y += self.dy
else:
self.dyy = self.rect.y
#self.dy *= -1
self.random_choice()
self.switch_color()
else:
self.dxx = self.rect.x
#self.dx *= -1
self.random_choice()
self.switch_color()
def change_tile(self):
self.obs.set_tile(self.rect.x,self.rect.y,'color',(self.R,self.G,self.B))
self.obs.set_tile(self.rect.x,self.rect.y,'symbol',self.symbol)
self.obs.set_tile(self.dxx,self.dyy,'symbol','O')
class virus(ghost,object):
def __init__(self,surface,observer,x=0,y=0,w=15,h=15):
super(virus,self).__init__(surface,observer,x,y,w,h)
self.dy = 1
self.rect.x = random.randrange(0,self.surf_rect.w/self.rect.w)
self.rect.y = random.randrange(0,(self.surf_rect.w/self.rect.w)-(self.surf_rect.w/self.rect.w)/7)
def on_move(self):
self.on_fall()
self.on_do()
def on_do(self):
self.change_tile()
def on_fall(self):
if 0 < self.rect.y+self.dy < self.surf_rect.h/self.rect.h:
self.rect.y += self.dy
else:
self.rect.x = random.randrange(0,self.surf_rect.w/self.rect.w)
self.rect.y = random.randrange(0,(self.surf_rect.h/self.rect.h)-(self.surf_rect.h/self.rect.h)/7)
self.R = random.randrange(0,255)
self.G = random.randrange(0,255)
self.B = random.randrange(0,255)
def change_tile(self):
self.obs.set_tile(self.rect.x,self.rect.y,'color',(self.R,self.G,self.B))
if self.obs.get_tile(self.rect.x,self.rect.y,'symbol') == 'O':
self.obs.set_tile(self.rect.x,self.rect.y,'symbol','X')
elif self.obs.get_tile(self.rect.x,self.rect.y,'symbol') == 'X':
self.obs.set_tile(self.rect.x,self.rect.y,'symbol','G')
else:
self.obs.set_tile(self.rect.x,self.rect.y,'symbol','O')
class rojinbi(ghost,object):
def __init__(self,surface,observer,x=0,y=0,w=15,h=15):
super(rojinbi,self).__init__(surface,observer,x,y,w,h)
self.symbol = 'R'
def on_move(self):
self.spark()
self.on_do()
def on_do(self):
self.change_tile()
def spark(self):
self.rect.x = random.randrange(0,self.surf_rect.w/self.rect.w)
self.rect.y = random.randrange(0,self.surf_rect.h/self.rect.h)
self.R = random.randrange(0,255)
self.G = random.randrange(0,255)
self.B = random.randrange(0,255)
def change_tile(self):
self.obs.set_tile(self.rect.x,self.rect.y,'color',(self.R,self.G,self.B))
if self.obs.get_tile(self.rect.x,self.rect.y,'symbol') != self.symbol:
self.obs.set_tile(self.rect.x,self.rect.y,'symbol',self.symbol)
else:
self.obs.set_tile(self.rect.x,self.rect.y,'symbol','O')
|
ipodlipnyak/YureiSim | objects/observer.py | <filename>objects/observer.py<gh_stars>0
#-- Observer Pattern --
#http://wiki.c2.com/?ObserverPattern
#The two basic styles of notification: PushModel and PullModel.
#If the observed object does not have the necessary hooks for observers,
#the observers must rely on repeatedly polling the observed to note the changes.
#This is a "pull" versus a "push" type of pattern. Quite appropriate for certain applications.
import var_depo, threading, multiprocessing
from threading import Thread
from multiprocessing import Process
#Push notifier
class PushModel(object):
def __init__(self):
self._observers = []
def bind_on(self,x,y,var_name,callback):
result = self.check_call(x,y,var_name,callback)
if result == False:
appe = x,y,var_name,callback
self._observers.append(appe)
def get_tile(self,x,y,var_name):
return getattr(var_depo.grid.g[x][y],str(var_name))
def set_tile(self,x,y,var_name,new_value):
setattr(var_depo.grid.g[x][y],var_name,new_value)
name_str = str(var_name)
for callback in self._observers:
if x == callback[0] and y == callback[1] and var_name == callback[2]:
callback[3]((x,y),var_name,new_value)
# call = callback[3]((x,y),var_name,new_value)
# self.t = Process(target=call)
# self.t.daemon = True
# self.t.start()
# self.t.join()
# print 'callback',str(callback),'has been sent to ',x,'-',
# pass
# for index, number in enumerate(numbers):
# proc = Process(target=doubler, args=(number,))
# procs.append(proc)
# proc.start()
# for proc in procs:
# proc.join()
def check_call(self,x,y,var_name,callback):
result = False
for obs in self._observers:
if x == obs[0] and y == obs[1] and var_name == obs[2] and callback == obs[3]:
result = True
return result
#class PushM_01(object):
# def __init__(self):
# self._observers = []
#
# def bind_on(self,var_name,callback):
# appe = var_name,callback
# self._observers.append(appe)
#
# def get(self,var_name):
# return getattr(var_depo,var_name)
# def set(self,var_name,new_value):
# setattr(var_depo,var_name,new_value)
# name_str = str(var_name)
# for callback in self._observers:
# call_str = str(callback[0])
# if name_str.startswith(call_str):
# callback[1](var_name,new_value)
# print 'callback has been sent to ',call_str
|
ipodlipnyak/YureiSim | objects/var_depo.py | test = 'hi'
grid = []
|
ipodlipnyak/YureiSim | objects/grid.py | <reponame>ipodlipnyak/YureiSim
import pygame
import math, random, scipy, numpy, Queue, threading, logging, os
from numpy import linalg
from objects import map
from decimal import *
from Queue import Queue
from threading import Thread
module_logger = logging.getLogger('App.Grid')
#Return grid with tiles
class Grid(object):
def __init__(self,surface,font,notifier,tile_size=50,tile_value=False,neighbor_rad=False,nt=1,lb=1,rb=10):
self.logger = logging.getLogger('App.Grid.g')
self.font = font
self.notifier = notifier
self.surface = surface
self.s_rect = surface.get_rect()
self.tile_s = tile_size
self.nt = nt
self.lb = lb
self.rb = rb
self.q = Queue()
self.w = self.s_rect.w/tile_size #grid width
self.h = self.s_rect.h/tile_size #grid height
self.v = tile_value #tile value: [1] - color, [2] - type
self.g = [] #grid
self.tiles = pygame.sprite.Group()
self.on_generate()
if neighbor_rad != False:
self.sfn(neighbor_rad)
self.tiles.update()
def on_generate(self):
for x in range(self.w):
self.g.append([])
# print '---------',x
for y in range(self.h):
# print self.a
if self.v==False:
newtile = Dummy_Tile(self.surface,self.font,self.tile_s,self.notifier,x,y)
self.tiles.add(newtile)
self.g[x].append(newtile)
elif self.v == 'grass':
newtile = Grass(self.surface,self.font,self.tile_s,self.notifier,x,y,lb=self.lb,rb=self.rb)
self.tiles.add(newtile)
self.g[x].append(newtile)
# self.t = Thread(target=newtile.update)
# self.t.daemon = True
# self.t.start()
# self.t.join()
# for t in self.g:
# t.color = 120,120,0
# pygame.display.update()
# self.tiles.update()
#search for neighbors algoritm
#Radius for search: neighbor_rad = (x,y)
def sfn(self,neighbor_rad):
progr = 0
dx = neighbor_rad[0]
dy = neighbor_rad[1]
for dxx in range(dx):
for dyy in range(dy):
for x in range(self.w):
for y in range(self.h):
self.g[x][y].neighbor_rad = neighbor_rad
d1 = (x+(dxx+1),y)
d1d = dxx+1,0
d2 = (x+(dxx+1),y+(dyy+1))
d2d = dxx+1,dyy+1
d3 = (x,y+(dyy+1))
d3d = 0,dyy+1
d4 = (x-(dxx+1),y+(dyy+1))
d4d = -1*(dxx+1),dyy+1
d5 = (x-(dxx+1),y)
d5d = -1*(dxx+1),0
d6 = (x-(dxx+1),y-(dyy+1))
d6d = -1*(dxx+1),-1*(dyy+1)
d7 = (x,y-(dyy+1))
d7d = 0,-1*(dyy+1)
d8 = (x+(dxx+1),y-(dyy+1))
d8d = dxx+1,-1*(dyy+1)
if self.nt == 1:
d = (d1,d1d),(d2,d2d),(d3,d3d),(d4,d4d),(d5,d5d),(d6,d6d),(d7,d7d),(d8,d8d)
elif self.nt == 2:
d = (d2,d2d),(d4,d4d),(d6,d6d),(d8,d8d)
elif self.nt == 3:
d = (d1,d1d),(d3,d3d),(d5,d5d),(d7,d7d)
elif self.nt == 4:
d = (d1,d1d),(d5,d5d)
elif self.nt == 5:
d = (d3,d3d),(d7,d7d)
elif self.nt == 6:
d = (d2,d2d),(d3,d3d),(d4,d4d)
for dd in d:
if 0 <= dd[0][0] <= self.w-1 and 0 <= dd[0][1] <= self.h-1:
ul = self.unit_vector((dx,dy),(dd[1][0],dd[1][1]))
app = (dd[0][0],dd[0][1]),((dxx+1),(dyy+1)),ul
self.g[x][y].neighbors.append(app)
progr += 1
self.logger.info(msg=str(progr))
# print progr
def unit_vector(self,rad,tile):
b = numpy.array(tile)
a = numpy.array(rad)
al = numpy.linalg.norm(a)
u = b/al
ul = numpy.linalg.norm(u)
return ul
class Dummy_Tile(pygame.sprite.Sprite,object):
def __init__(self,surface,font,tile_size,notifier,x,y):
pygame.sprite.Sprite.__init__(self)
self.surface = surface
self.font = font
self.notifier = notifier
self.rect = pygame.Rect ((x*tile_size,y*tile_size),(tile_size,tile_size))
self.me = x,y
self.var_tuple = 'grid.g[',str(x),'][',str(y),']'
self.var_string = ''.join(self.var_tuple)
self.notifier.bind_on(x,y,'color',callback=self.callback)
self.notifier.bind_on(x,y,'symbol',callback=self.callback)
self.q = Queue()
# print 'Create callback',self.var_string
self.color = 0,15,0
self.symbol = 'O'
def log_tile(self,**kwarg):
name = ('App.Grid.g',str(self.me))
logger = logging.getLogger(''.join(name))
keys = sorted(kwarg.keys())
for kw in keys: #kwarg:
msg = (str(kw),':',str(kwarg[kw]))
msg_s = ''.join(msg)
logger.info(msg_s)
def callback(self,tile,var_name,new_value):
# print 'Ouch! My name is ',self.var_string
self.update()
#Update model
def set_symbol(self):
self.symbol = 'O'
# if self.symbol == 'O':
# self.symbol = 'H'
# elif self.symbol == 'X':
# self.symbol = 'V'
# elif self.symbol == 'G':
# self.symbol = 'K'
# else:
# self.symbol = 'O'
def set_color(self,color):
self.color = color
# self.set_symbol()
self.render(self.surface)
# self.update()
def update(self):
# self.q.put(True)
self.render(self.surface)
# pass
#Update view
def render(self,surface):
surface.fill(color=(0,0,0),rect=self.rect)
self.text = self.font.render(self.symbol,True,self.color)
self.text_x = self.rect.centerx-self.text.get_size()[0]*0.5
self.text_y = self.rect.centery-self.text.get_size()[1]*0.5
surface.blit(self.text,(self.text_x,self.text_y))
pygame.display.update(self.rect)
class Grass(Dummy_Tile,object):
def __init__(self,surface,font,tile_size,notifier,x,y,lb=1,rb=10,debug=False):
super(Grass,self).__init__(surface,font,tile_size,notifier,x,y)
self.neighbors = []
self.lb = lb
self.rb = rb
self.dbg = debug
# print 'Init complete:',self.me
self.log_tile(Init='complete')
def neighborhood(self):
pass
def update(self):
super(Grass,self).update()
self.voayor()
def voayor(self):
for neighbor in self.neighbors:
self.notifier.bind_on(neighbor[0][0],neighbor[0][1],'color',callback=self.spoocked)
def spoocked(self,tile,var_name,new_value):
# os.system('clear')
# self.log_tile(Tile=self.me)
# self.q.put(True)
# msg = '----------','\n',str(self.me),'----------'
# msg_s = ''.join(msg)
# logging.info(msg)
# logging.info(msg_s)
# if self.dbg != False:
# print '----------',self.me,'----------'
grad = 0.8
if var_name == 'color':
for ne in self.neighbors:
# print ne
if ne[0][0] == tile[0] and ne[0][1] == tile[1]:
dist = ne[2]
#self.logger.info(ne)
#self.logger.info(round(ne[2],2))
# if self.dbg != False:
# print ne
# print round(ne[2],2)
nR = new_value[0]-new_value[0]*dist
nG = new_value[1]-new_value[1]*dist
nB = new_value[2]-new_value[2]*dist
oR = self.color[0]
oG = self.color[1]
oB = self.color[2]
# R = (nR+oR)/2
# G = (nG+oG)/2
# B = (nB+oB)/2
wR = (nR/255)*10+self.lb,(oR/255)*10+self.rb
#self.logger.info(Red_w = str(wR))
# if self.dbg != False:
# print 'Red weight: ',wR
wG = (nG/255)*10+self.lb,(oG/255)*10+self.rb
# if self.dbg != False:
# print 'Green weight: ',wG
wB = (nB/255)*10+self.lb,(oB/255)*10+self.rb
# if self.dbg != False:
# print 'Blue weight: ',wB
R = numpy.average((nR,oR),weights=wR)
G = numpy.average((nG,oG),weights=wG)
B = numpy.average((nB,oB),weights=wB)
self.set_color((R,G,B))
# os.system('clear')
self.log_tile(RedW=wR,GreenW=wG,BlueW=wB,Red=R,Green=G,Blue=B)
# self.log_tile(Red=self.color[0],Green=self.color[1],Blue=self.color[2])
# if self.dbg != False:
# print 'My color: ',R,'',G,'',B
# if self.dbg != False:
# print '**********************'
# print 'Boo, <NAME>'
pass
|
sonalig955/spelling-corrector | spelling corrector.py | from tkinter import*
from textblob import TextBlob
def clearAll():
word_field1.delete(0,END)
word_field2.delete(0,END)
def correction():
input_word=word_field1.get()
blob_obj=TextBlob(input_word)
corrected_word=str(blob_obj.correct())
word_field2.insert(10,corrected_word)
if __name__=="__main__":
root=Tk()
root.title("Spelling Correction")
root.configure(background='light green')
root.geometry("400x300")
headlabel=Label(root,text="Welcome To Spelling Corrector",fg='black',bg='light green',font=('times new roman',20)).place(x=5,y=7)
label1=Label(root,text="Input Word",bg='light green')
label1.place(x=5,y=70)
word_field1=Entry(root,bg='light grey')
word_field1.place(x=85,y=70)
button1=Button(root,text="correction",bg='red',font=(1),command=correction)
button1.place(x=90,y=100)
label2=Label(root,text='Corrected word',bg='light green')
label2.place(x=6,y=150)
word_field2=Entry(root,bg='light grey')
word_field2.place(x=120,y=150)
button2=Button(root,text='Clear',font=(1),bg='light grey',command=clearAll)
button2.place(x=95,y=190)
root.mainloop()
|
sh2439/Algo_stanford | C1: Divide and Conquer/Karger_mincut.py | import random, copy
def read_file(name):
"""
Input the file name and return a dictionary to store the graph.
"""
with open(name, 'r') as data:
line = data.read().strip().split("\n")
graph_dict = {}
for element in line:
line_list = list(map(int, element.strip().split("\t")))
graph_dict[line_list[0]] = line_list[1:]
return graph_dict
def random_pick(new_dict):
"""
Given a graph dictionary, return a randomly selected pair a and b.
"""
a = random.choice(list(new_dict.keys()))
b = random.choice(new_dict[a])
selected_pair = (a,b)
return selected_pair
def karger(new_dict):
"""
Return the min_cut in a single loop/trial.
"""
num = []
while len(new_dict)>2:
a,b = random_pick(new_dict)
# merge two vertices
new_dict[a].extend(new_dict[b])
# add a/delete b in vertices connected with b
for c in new_dict[b]:
new_dict[c].remove(b)
new_dict[c].append(a)
# delete self-loops of vertice a
while a in new_dict[a]:
new_dict[a].remove(a)
# delete vertice b
del new_dict[b]
for key in new_dict:
num.append(len(new_dict[key]))
return num[0]
def combine(n, name):
"""
Arguments
n: the number of iterations/trials.
name: input file name
Output
min_cut: the minimum cut
"""
graph = read_file(name)
min_cut = 1000
for i in range(n):
G = copy.deepcopy(graph)
cut = karger(G)
if cut < min_cut:
min_cut = cut
return min_cut
|
sh2439/Algo_stanford | C2: Graph Search/two_sum_set.py | <gh_stars>10-100
### Straightforward implementation of Two Sum problem using a hash set.
### Slow!
import time
start = time.time()
def read_file(name):
"""
Given the name of the file, return the hashset d.
"""
d = set()
file = open(name, 'r')
data = file.readlines()
for line in data:
items = line.split()
d.add((int)(items[0]))
return d
def two_sum(d,t):
"""Given set d and target value t, return if target value t is the sum of two elements in d.
"""
for key in d:
if t-key in d and key != t/2:
return True
return False
def two_sum_all(name):
"""Given the name of the file, return the total number.
"""
d = read_file(name)
total = 0
for t in range(-10000,1000):
if two_sum(d,t) is True:
total+=1
return total
def main():
total = two_sum_all('two_sum.txt')
return total
if __name__ == '__main__':
total = main()
print(total)
end = time.time()
print(end - start)
|
sh2439/Algo_stanford | C1: Divide and Conquer/Quick_sort_count.py | <reponame>sh2439/Algo_stanford
# Three different partition functions:
# 1. Use the 1st element as pivot.
# 2. Use the last element as pivot
# 3. Use the median of three as pivot(first, last and middle elements).
def partition_1(a,l,r):
"""
partition array a[l...r]
Pivot: Always the 1st element of the array
"""
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp = a[j]
a[j] = a[i]
a[i] = temp
i+=1
j+=1
else:
j+=1
temp = a[l]
a[l] = a[i-1]
a[i-1] = temp
return i-1
def partition_2(a,l,r):
"""
partition array a[l..r]
Pivot: Use the last element of the array. Swap with the first element.
"""
# swap the first and last
temp = a[l]
a[l] = a[r]
a[r] = temp
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp = a[j]
a[j] = a[i]
a[i] = temp
i+=1
j+=1
else:
j+=1
temp = a[l]
a[l] = a[i-1]
a[i-1] = temp
return i-1
def partition_3(a,l,r):
"""
partition array a[l..r]
Pivot: Use median of three. The median of first, last and middle element.
"""
# find the median of the three
mid = l+(r-l)//2
if a[l] > a[mid]:
if a[l]< a[r]:
median = a[l]
elif a[mid] > a[r]:
median = a[mid]
else:
median = a[r]
else:
if a[l] > a[r]:
median = a[l]
elif a[mid] < a[r]:
median = a[mid]
else:
median = a[r]
# swap with the first element
if median == a[r]:
temp = a[r]
a[r] = a[l]
a[l] = temp
elif median == a[mid]:
temp = a[mid]
a[mid] = a[l]
a[l] = temp
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp = a[j]
a[j] = a[i]
a[i] = temp
i+=1
j+=1
else:
j+=1
temp = a[l]
a[l] = a[i-1]
a[i-1] = temp
return i-1
### Main Function: Compute the total comparisons.
def QS_count(a,l,r, pivot = ['first', 'last', 'median']):
"""
Sort array a[l..r] and return the # of comparisons.
"""
count = 0
if r-l+1 <=1:
return 0
if pivot =='first':
p = partition_1(a,l,r)
elif pivot =='last':
p = partition_2(a,l,r)
else:
p = partition_3(a,l,r)
num= r-l
left = QS_count(a,l,p-1,pivot)
right = QS_count(a,p+1,r,pivot)
count= left+right+num
return count
|
sh2439/Algo_stanford | C3: Greedy Algo/huffman.py | import heapq
from collections import namedtuple
Node = namedtuple('Node', ('weight','index'))
def read_file(name):
"""Given the path/name of the text file, return the heap with nodes.
"""
tree = []
file = open(name, 'r')
data = file.readlines()
for index, line in enumerate(data[1:]):
item = line.split()
tree.append(Node(int(item[0]), str(index)))
heapq.heapify(tree)
return tree
def combine(a,b):
"""Combine two nodes into a single one.
"""
return Node(a.weight+b.weight, '+'.join([a.index, b.index]))
def huffman(tree):
"""Given the initial tree, return the length of each node.
"""
code_len = [0]*len(tree)
while(len(tree)>1):
# Pop two min items
a = heapq.heappop(tree)
b = heapq.heappop(tree)
# Reinsert the combined item
new_node = combine(a,b)
heapq.heappush(tree, new_node)
#heapq.heappush(tree,combine(a,b))
# add 1 to the code length for a,b
com = [int(item) for item in new_node.index.split('+')]
for i in com:
code_len[i] += 1
return code_len
def main():
tree = read_file('huffman.txt')
codes = huffman(tree)
print(max(codes), min(codes))
if __name__ == '__main__':
main()
### Test case
a = Node(3,'0')
b = Node(2,'1')
c = Node(6,'2')
d = Node(8,'3')
e = Node(2,'4')
f = Node(6,'5')
tree = [a,b,c,d,e,f]
heapq.heapify(tree)
len_code = huffman(tree)
print(len_code)
|
sh2439/Algo_stanford | C1: Divide and Conquer/Karastuba_mul.py | <filename>C1: Divide and Conquer/Karastuba_mul.py<gh_stars>10-100
def kara_mul(x,y):
"""
The Karatsuba Integer Multiplication Algorithm.
"""
# base case
if len(str(x))==1 or len(str(y))==1:
return x*y
else:
n = max(len(str(x)), len(str(y)))
n_half = n//2
a = x//(10**n_half)
b = x % (10**n_half)
c = y//(10**n_half)
d = y%(10**n_half)
ac = kara_mul(a,c)
bd = kara_mul(b,d)
ad_plus_bc = kara_mul(a+b, c+d) -ac -bd
product = 10**(2*n_half)*ac +10**(n_half)*(ad_plus_bc) + bd
return product
|
sh2439/Algo_stanford | C3: Greedy Algo/MST_Prim.py | <reponame>sh2439/Algo_stanford
import random
def read_file(name):
"""Given path/name of the file, return the undirected graph in list.
list[1] is a tuple, which contains (node, weights) of node 1.
"""
file = open(name, 'r')
data = file.readlines()
num_nodes = 500
graph = [[] for i in range(num_nodes+1)]
for line in data[1:]:
item = line.split()
graph[int(item[0])] += [(int(item[1]), int(item[2]))]
graph[int(item[1])] += [(int(item[0]), int(item[2]))]
return graph
def Prim_MST(graph):
"""Given the graph as a list, return the minimum spanning tree using Prim's method.
"""
# Initialize the visited list
X = set()
X.add(random.choice([i for i in range(1,len(graph))]))
T = 0
while(len(X) < len(graph)-1):
edge = {}
for node in X:
for v in graph[node]:
if v[0] not in X:
edge[(node, v[0])] = v[1]
# find the shortest edge
(u,v),dist = min(edge.items(), key = lambda x : x[1])
X.add(v)
T+=dist
return T
def main():
graph = read_file('edges.txt')
t = Prim_MST(graph)
return t
if __name__ =='__main__':
t = main()
print(t)
|
sh2439/Algo_stanford | C3: Greedy Algo/clustering_small.py | <filename>C3: Greedy Algo/clustering_small.py
from operator import attrgetter
class unionfind:
"""An implementation of union-find data structure by rank.
"""
def __init__(self,n):
"""Initialize an union-find with n items(objects).
"""
self.root = list(range(n))
self.rank = [0]*n
self.num = n # the number of clusters
def find(self, x):
"""Find the root(pointer) of the item x. Using path compression.
"""
s_list = self.root
if s_list[x] != x:
s_list[x] = self.find(s_list[x])
return s_list[x]
def count(self):
return self.num
def union(self, x,y):
"""Union x and y.
"""
s = self.root
rank_list = self.rank
s1 = self.find(x)
s2 = self.find(y)
if s1 == s2:
return
self.num -= 1
if rank_list[s1] == rank_list[s2]:
s[s2] = s1
rank_list[s1] +=1
elif rank_list[s1]>rank_list[s2]:
s[s2] = s1
else:
s[s1] = s2
def connected(self, x, y):
"""Check if x and y are in the same cluster.
"""
return self.find(x) == self.find(y)
class Edge:
"""An instance is an edge with:
the 'from' vertex
the 'to' vertex
the cost of the edge
"""
def __init__(self, from_node, to_node, cost):
self.from_node = from_node
self.to_node = to_node
self.cost = cost
def read_file(name):
"""Given the path/name of the file, return a list of object Edge.
"""
file = open(name, 'r')
data = file.readlines()
# Initialize the edges
edges = []
for line in data[1:]:
item = line.split()
edges.append(Edge(int(item[0]) -1 , int(item[1]) -1 , int(item[2])))
return edges
def clustering(edges, num_clusters, num_vertices):
"""Return the minimum distance of the separate vertices.
"""
# sort the edges
edges = sorted(edges, key = attrgetter('cost'))
UF = unionfind(num_vertices)
for edge in edges:
if not UF.connected(edge.from_node,edge.to_node) and UF.count()!= num_clusters:
UF.union(edge.from_node,edge.to_node)
if not UF.connected(edge.from_node,edge.to_node) and UF.count()== num_clusters:
return edge.cost
def main():
edges = read_file('clustering1.txt')
max_dis = clustering(edges, 4, 500)
return max_dis
if __name__ =='__main__':
t = main()
print(t)
|
sh2439/Algo_stanford | C2: Graph Search/SCC.py | import sys
import threading
def read_file(name):
num_nodes = 875715
file = open(name,"r")
data = file.readlines()
G = [[] for i in range(num_nodes)]
G_rev = [[] for i in range(num_nodes)]
for line in data:
items = line.split()
G[int(items[0])] += [int(items[1])]
G_rev[int(items[1])] += [int(items[0])]
return G, G_rev
def DFS1(graph_rev, i):
global t, visited
visited[i] = True
for edge in graph_rev[i]:
if not visited[edge]:
DFS1(graph_rev, edge)
finish[t] = i
t= t+1
def DFS_loop1(graph_rev, num_nodes):
global t, visited, finish
visited = [False]*num_nodes
finish = [None]*num_nodes
t = 0
for node in reversed(range(num_nodes)):
if not visited[node]:
DFS1(graph_rev, node)
return finish
def DFS2(graph, i):
global scc_size, visited
visited[i] = True
for edge in graph[i]:
if not visited[edge]:
DFS2(graph,edge)
scc_size += 1
def DFS_loop2(graph, num_nodes):
global scc_size, visited, finish
visited = [False]*num_nodes
scc = []
for node in reversed(range(num_nodes)):
if not visited[finish[node]]:
scc_size = 0
DFS2(graph, finish[node])
scc.append(scc_size)
return scc
def combine(graph, graph_rev):
num_nodes = 875715
finish = DFS_loop1(graph_rev, num_nodes)
scc = DFS_loop2(graph, num_nodes)
return scc
def main():
graph, graph_rev = read_file('SCC.txt')
scc = combine(graph, graph_rev)
print(','.join(map(lambda x: str(x), sorted(scc)[::-1][:5])))
#print(sorted(scc)[:5])
if __name__ == '__main__':
threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(2 ** 20) # approx 1 million recursions
thread = threading.Thread(target = main) # instantiate thread object
thread.start() # run program at target
|
sh2439/Algo_stanford | C4: Shortest Path Revisited, NP-Complete/tsp_heuristic.py | ### The following code implements the traveling salesman probblem with a greedy heuristic approach.
from tqdm import tqdm
import numpy as np
def read_file(name):
"""Given the path/name of the file, return the graph (dictionary).
"""
file = open(name,'r')
data = file.readlines()
# initialize the graph
g = {}
#num = int(data[0][0])
for line in data[1:]:
item = line.split()
g[int(item[0])] = (float(item[1]), float(item[2]))
return g
g = read_file('tsp_large.txt')
def euclidean_sq(a,b):
"""Return the square euclidean distance of a(x1,y1) and b(x2,y2)
"""
dis = (a[0] - b[0])**2 + (a[1]- b[1])**2
return dis
def tsp(g):
"""Given the graph, return the heuristic traveling salesman problem value.
"""
# number of cities
num = len(g)
# Initialize visited and unvisited set
visited = []
visited.append(1)
unvisited = list(range(2, len(g)+1))
final_dis = 0
# Main loop: stop when all the cities are visited.
for i in tqdm(range(num-1)):
current_city = visited[-1]
next_city = unvisited[0]
min_dis = euclidean_sq(g[current_city], g[next_city])
if len(unvisited)>1:
for j in unvisited[1:]:
dis = euclidean_sq(g[current_city], g[j])
if dis < min_dis:
min_dis = dis
next_city = j
# break the tie
elif dis == min_dis:
next_city = min(next_city, j)
visited.append(next_city)
unvisited.remove(next_city)
final_dis += np.sqrt(min_dis)
final_dis += np.sqrt(euclidean_sq(g[visited[-1]], g[1]))
return final_dis
def main():
g = read_file('tsp_large.txt')
best_dis = tsp(g)
return best_dis
if __name__ == '__main__':
main()
|
sh2439/Algo_stanford | C4: Shortest Path Revisited, NP-Complete/apsp.py | # The following code implements the Floyd-Warshall algorithm to solve all-pairs shortest paths problem. The algorithm can either
#find the shortest path of all paris or detect a negative cycle.
from tqdm import tqdm
class Edge:
def __init__(self, from_node, to_node, weight):
self.from_node = from_node
self.to_node = to_node
self.weight = weight
def read_file(name):
"""Given the path/name of the file, return the empty 3-d array(n, n, n+1).
"""
file = open(name,'r')
data = file.readlines()
n = int(data[0].split()[0])
m = int(data[0].split()[1])
A = np.zeros((n,n,n+1))
inf = 9999
for i in range(n):
for j in range(n):
if i==j:
A[i,j,0] = 0
else:
A[i,j,0] = inf
for index, line in enumerate(data[1:]):
item = line.split()
A[int(item[0]) -1 ,int(item[1])-1,0] = int(item[2])
return A
def floyd_warshall(A):
"""Given the empth 3-d array, return the minimum path(a numbber or 'Negative cycle').
"""
n = A.shape[0]
for k in tqdm(range(1, n+1)):
for i in range(n):
for j in range(n):
A[i,j,k] = min(A[i,j,k-1], A[i,k-1,k-1]+A[k-1,j,k-1])
for i in range(n):
if A[i,i,n] <0:
min_path = 'Negative cycle'
return min_path
min_path = np.min(A[:,:,n])
return min_path
def main():
A = read_file('g3.txt')
min_path = floyd_warshall(A)
print(min_path)
if __name__ == '__main__':
main()
|
sh2439/Algo_stanford | C2: Graph Search/two_sum_array.py |
import time
from bisect import bisect_left, bisect_right
start = time.time()
def read_file(name):
"""
Given the name of the file, return the sorted array array_a.
"""
d = set()
file = open(name, 'r')
data = file.readlines()
for line in data:
items = line.split()
d.add((int)(items[0]))
array_a = sorted(d)
return array_a
def two_sum(array_a):
"""Given sorted array_a and target value t, return the result.
"""
sum_value = set()
for i in array_a:
# find the indices
left = bisect_left(array_a, -10000 - i)
right = bisect_right(array_a, 10000-i)
for j in array_a[left:right]:
if i != j:
sum_value.add(i+j)
return len(sum_value)
def main():
file = read_file('two_sum.txt')
total = two_sum(file)
return total
if __name__ == '__main__':
total = main()
print(total)
end = time.time()
print(end - start)
|
sh2439/Algo_stanford | C3: Greedy Algo/Schedule_jobs.py | <reponame>sh2439/Algo_stanford
### The code below implements the a scheduling problem which minimizes the weighted sum of completion time of jobs.
def read_file(name):
"""Given the path/name of the file, return nthe jobs list with jobs[][0]: weight and jobs[][1]: length.
"""
file = open(name,'r')
data = file.readlines()
jobs = []
for line in data[1:]:
items = line.split()
jobs.append([int(items[0]),int(items[1])])
return jobs
### according to weight - length(difference) or weight/length(ratio)
def find_order(jobs, key = 'difference' or 'ratio'):
"""Find the order of jobs according to different key(priority).
"""
# find the key of the priority
if key == 'difference':
priority = [(item[0] - item[1],item[0]) for item in jobs]
else:
priority = [(item[0]/item[1], item[0]) for item in jobs]
order = sorted(range(len(priority)), key = priority.__getitem__)
order.reverse()
return order
def compute_sum(jobs, order):
"""Given the jobs list and order, find the weighted sum of the jobs.
"""
finish_time = 0
weighted_sum = 0
for i in order:
finish_time += jobs[i][1]
weighted_sum += finish_time*jobs[i][0]
return weighted_sum
def main():
jobs = read_file('jobs.txt')
order = find_order(jobs, 'ratio')
weighted_sum = compute_sum(jobs, order)
return weighted_sum
if __name__ == '__main__':
answer = main()
print(answer)
|
sh2439/Algo_stanford | C2: Graph Search/Median_Maintenance.py | <filename>C2: Graph Search/Median_Maintenance.py
import heapq
def read_file(name):
"""Given the path of a file, return a list of numbers to be processed.
"""
d = []
file = open(name,'r')
data = file.readlines()
for line in data:
items = line.split()
d.append(int(items[0]))
return d
def insert(h_low, h_high, m ):
"""Insert the item m to the heap.
"""
# Push the m in the heap
if m < h_low[0]:
h_low.append(m)
heapq._siftdown_max(h_low,0,len(h_low)-1)
else:
heapq.heappush(h_high, m)
# Balance the two heaps
size_diff = len(h_low) - len(h_high)
if size_diff > 1:
item = heapq._heappop_max(h_low)
heapq.heappush(h_high,item)
elif size_diff < -1:
item = heapq.heappop(h_high)
h_low.append(item)
heapq._siftdown_max(h_low,0,len(h_low)-1)
def median_heap(d):
"""Output a list with all the medians in nsequennce.
"""
median = []
# initialize empty heaps
h_low = []
h_high = []
heapq._heapify_max(h_low)
heapq.heapify(h_high)
# Push the first item into the h_low
h_low.append(d[0])
median.append(d[0])
# Loop over all other items in d
for m in d[1:]:
insert(h_low, h_high, m)
# Find the median
if len(h_low)<len(h_high):
median.append(h_high[0])
else:
median.append(h_low[0])
return median
def main():
d = read_file('Median.txt')
median = median_heap(d)
result = sum(median)%10000
return result
if __name__ == '__main__':
result = main()
print(result)
|
sh2439/Algo_stanford | C2: Graph Search/Dijkstra.py | <reponame>sh2439/Algo_stanford
import time
from ast import literal_eval
def read_file(name,num_nodes=201):
"""Given the name of the file , return the graph in list.
"""
graph = [None]*num_nodes
file = open(name)
data = file.readlines()
for line in data:
items = line.split()
graph[int(items[0])] = [literal_eval(a) for a in items[1:]]
return graph
def dijkstra(graph, num_nodes=201):
"""The Main function of Dijkatra's shortest path algorithm.
"""
# Store the vertices that have been processed.
visited = []
visited.append(1)
# Store the distances to all other vertices. Initialize with 10000.
dis = [100000]*(num_nodes)
dis[1] = 0
while len(visited) < (num_nodes-1):
# dictionary to store the edge and the distances
short_dist = {}
for node in visited:
for v in graph[node]:
if v[0] not in visited:
short_dist[(node, v[0])] = dis[node] + v[1]
# find the shortest edge
(node, edge), dist = min(short_dist.items(), key=lambda x: x[1])
dis[edge] = dist
visited.append(edge)
return dis
|
sh2439/Algo_stanford | C1: Divide and Conquer/Merge_sort.py | # Helper function: merge
def merge(b, c):
"""
Arguments:
Array1, Array2: Two sorted arrays b and c.
Return:
array_d: The merged version of b and c
"""
i = 0
j = 0
k = 0
n1 = len(b)
n2 = len(c)
array_d = [None]*(n1+n2)
# traverse both arrays
while i<n1 and j<n2:
if b[i] <= c[j]:
array_d[k] = b[i]
i+=1
k+=1
else:
array_d[k] = c[j]
j+=1
k+=1
while i < n1:
array_d[k] = b[i]
i+=1
k+=1
while j < n2:
array_d[k] = c[j]
j+=1
k+=1
return array_d
# Two implementations of merge sort
def merge_sort(array_a, h,k):
"""
Sort the array array_a[h..k]
"""
if k-h+1<=1:
return array_a[h:k+1]
mid = (h+k)//2
left = merge_sort(array_a, h,mid)
right = merge_sort(array_a, mid+1, k)
sorted_a = merge(left, right)
return sorted_a
def merge_sort_all(array_a):
"""
sort the array a
"""
n = len(array_a)
if n <=1:
return array_a
mid = n//2
left = merge_sort_all(array_a[:mid])
right = merge_sort_all(array_a[mid:])
sorted_a = merge(left, right)
return sorted_a
|
sh2439/Algo_stanford | C3: Greedy Algo/knapsack_small.py | <reponame>sh2439/Algo_stanford
# The following code implements the knapsack problem with bottom-up dynamic programming approach.
def read_file(name):
"""Given the path/nname of a file ,return the Values list, Weights list,
capacity and number of jobs.
"""
file = open(name, 'r')
data = file.readlines()
capacity = int(data[0].split()[0])
n =int(data[0].split()[1])
# Create two lists to store values and sizes
V = [0]*(n+1)
W = [0]*(n+1)
for index, line in enumerate(data[1:]):
V[index+1]=int(line.split()[0])
W[index+1]=int(line.split()[1])
return V, W, capacity, n
V,W, capacity, n = read_file('knapsack1.txt')
def knapsack_dynamic(V, W, capacity, numbers):
"""Return the matrix of maximum value
"""
# initialize the 2-d array
A = [[0]*(capacity+1) for x in range(numbers+1)]
for i in range(1,numbers+1):
for j in range(capacity+1):
# make sure the size of current is not larger than the current capacity.
if W[i]>j:
A[i][j] = A[i-1][j]
else:
A[i][j] = max(A[i-1][j],A[i-1][j-W[i]]+V[i])
return A
def main():
V,W, capacity, n = read_file('knapsack1.txt')
A = knapsack_dynamic(V,W, capacity, n)
# return the largest value of the matrix.
print(A[-1][-1])
if __name__ == '__main__':
main()
### Test case:
values = [0,3,2,4,4]
sizes = [0,4,3,2,3]
capacity = 6
numbers = 4
B = knapsack_dynamic(values, sizes, capacity, numbers)
B[-1][-1] # The answer should be 8.
|
sh2439/Algo_stanford | C3: Greedy Algo/MWIS.py | def read_file(name):
"""Given the path/nname of the file, return the list of the weights of the nodes.
"""
file = open(name,'r')
data = file.readlines()
weights = [0]*(int(data[0])+1)
for index,line in enumerate(data[1:]):
item = line.split()
weights[index+1] = int(item[0])
return weights
def WIS(weights):
"""Given the weights, return the A: optimal value, S: optimal path.
"""
A = [0]*(len(weights))
A[0] = 0
A[1] = weights[1]
# Find the optimal value
for i in range(2, len(weights)):
A[i] = max(A[i-1], A[i-2]+weights[i])
# Trace back to find the optimal solution.
S= []
i = len(weights)-1
while i >= 1:
if A[i-1] >= A[i-2]+weights[i]:
i = i-1
else:
S.append(i)
i = i-2
return A, S
def main():
w = read_file('mwis.txt')
A,S = WIS(w)
lista = [1,2,3,4,17,117,517,997]
binary = []
for i in lista:
if i in S:
binary.append(1)
else:
binary.append(0)
print(binary)
if __name__ == '__main__':
main()
def read_file(name):
"""Given the path/nname of the file, return the list of the weights of the nodes.
"""
file = open(name,'r')
data = file.readlines()
weights = [0]*(int(data[0])+1)
for index,line in enumerate(data[1:]):
item = line.split()
weights[index+1] = int(item[0])
return weights
def WIS(weights):
"""Given the weights, return the A: optimal value, S: optimal path.
"""
A = [0]*(len(weights))
A[0] = 0
A[1] = weights[1]
# Find the optimal value
for i in range(2, len(weights)):
A[i] = max(A[i-1], A[i-2]+weights[i])
# Trace back to find the optimal solution.
S= []
i = len(weights)-1
while i >= 1:
if A[i-1] >= A[i-2]+weights[i]:
i = i-1
else:
S.append(i)
i = i-2
return A, S
def main():
w = read_file('mwis.txt')
A,S = WIS(w)
lista = [1,2,3,4,17,117,517,997]
binary = []
for i in lista:
if i in S:
binary.append(1)
else:
binary.append(0)
print(binary)
if __name__ == '__main__':
main()
|
sh2439/Algo_stanford | C1: Divide and Conquer/Count_inversion.py | <filename>C1: Divide and Conquer/Count_inversion.py
# Helper function: merge and count split
def merge_countsplit(b,c):
"""
Given two sorted arrays b and c, output a merged sorted array and the number of inversions.
Output:
d, num_split: Merged array d and number of inversions.
"""
i=0
j=0
k=0
n1 = len(b)
n2 = len(c)
d = [None]*(n1+n2)
num_split = 0
# traverse over b and c
while i<n1 and j<n2:
if(b[i] <= c[j]):
d[k] = b[i]
i+=1
k+=1
else:
d[k] = c[j]
num_split += n1 - i
j+=1
k+=1
while i<n1:
d[k] = b[i]
i+=1
k+=1
while j<n2:
d[k] = c[j]
j+=1
k+=1
return d, num_split
def sort_and_count(a):
"""
Given array a, output a sorted array and the total number of inversions.
Output:
d, num_inv: Sorted array d and number of inversions.
"""
n = len(a)
if n <=1:
return a,0
mid = n//2
b,x = sort_and_count(a[:mid])
c,y = sort_and_count(a[mid:])
d,z = merge_countsplit(b,c)
num_inv = x+y+z
return d, num_inv
num_inv = x+y+z
return d, num_inv
|
sh2439/Algo_stanford | C4: Shortest Path Revisited, NP-Complete/TSP.py | # The following code implements the NP-complete problem 'Traveling Salesman Problem' .
# With dynamic programming approach, the algorithm is able to complete in reasonable time.
import numpy as np
import math
from itertools import combinations
from tqdm.auto import tqdm
def read_file(name):
"""Given the path/name of the text file, return the
"""
file = open(name,'r')
data = file.readlines()
# Initialize the vertices list
vertices = []
num = int(data[0][0])
for line in data[1:]:
item = line.split()
vertices.append((float(item[0]), float(item[1])))
return vertices
def euclidean(a,b):
"""Return the euclidean distance of a(x1,y1) and b(x2,y2)
"""
dis = np.sqrt((a[0] - b[0])**2 + (a[1]- b[1])**2)
return dis
def n_choose_k(n,k):
"""Return the number of combinations of 'n choose k'
"""
return int(math.factorial(n)/(math.factorial(k)*math.factorial(n-k)))
def subset(arr, k):
"""Given array arr and integer k, find the combinations of subsets. With 1 prepend.
"""
sub = []
a = list(combinations(arr, k))
for i in a:
i = tuple([1]+list(i))
sub.append(i)
return sub
def find_min(A, vertices, subset, j):
"""Given subset and j, find the minimum value.
"""
# remove the last vertice.
subset = list(subset)
subset.remove(j)
s_removed = subset
if len(s_removed)>1:
s_removed = tuple(s_removed)
mini = min(A[(s_removed, k)] + euclidean(vertices[k-1],vertices[j-1]) for k in s_removed)
else:
s_removed = 1
mini = A[(1, 1)] + euclidean(vertices[0],vertices[j-1])
return mini
def find_min_final(A,vertices):
"""Given the whole matrix(graph), find the minimum value of traveling salesman problem.
"""
mini = min(A[(tuple(range(1,len(vertices)+1)), j)] + euclidean(vertices[j-1], vertices[0]) for j in range(2,len(vertices)+1))
return mini
def salesman(name):
"""Main function of traveling salesman problem.
Given the path/name of the file, return the minimum value.
"""
vertices = read_file(name)
num = len(vertices)
# Initialize the matrix
inf = 1e6
A = {}
A[(1,1)] = 0
keys = {}
indices = []
for i in range(1, num):
current_keys = []
S = subset(range(2,num+1), i)
for j in S:
A[(j,1)] = inf
indices.append(j)
current_keys.append(j)
keys[i+1] = current_keys
# Fill in the graph(matrix)
for m in tqdm(range(2, num+1)):
for key in tqdm(keys[m]):
s = key
#print(s)
for j in s:
if j !=1:
A[(s,j)] = find_min(A, vertices, s, j)
# Find the minimum value
mini = find_min_final(A, vertices)
return mini
def main():
mini = salesman('tsp.txt')
print(mini)
if __name__ == '__main__':
main()
|
genegr/py-pure-client | pypureclient/flasharray/FA_2_1/client.py | <filename>pypureclient/flasharray/FA_2_1/client.py
import json
import platform
import time
import urllib3
from typing import List, Optional
from ...exceptions import PureError
from ...keywords import Headers, Responses
from ...responses import ValidResponse, ErrorResponse, ApiError, ItemIterator
from ...token_manager import TokenManager
from ...api_token_manager import APITokenManager
from .api_client import ApiClient
from .rest import ApiException
from .configuration import Configuration
from . import api
from . import models
class Client(object):
DEFAULT_TIMEOUT = 15.0
DEFAULT_RETRIES = 5
# Format: client/client_version/endpoint/endpoint_version/system/release
USER_AGENT = ('pypureclient/1.22.0/FA/2.1/{sys}/{rel}'
.format(sys=platform.system(), rel=platform.release()))
def __init__(self, target, id_token=None, private_key_file=None, private_key_password=None,
username=None, client_id=None, key_id=None, issuer=None, api_token=None,
retries=DEFAULT_RETRIES, timeout=DEFAULT_TIMEOUT, ssl_cert=None, user_agent=None):
"""
Initialize a FlashArray Client. id_token is generated based on app ID and private
key info. Either id_token or api_token could be used for authentication. Only one
authentication option is allowed.
Keyword args:
target (str, required):
The target array's IP or hostname.
id_token (str, optional):
The security token that represents the identity of the party on
behalf of whom the request is being made, issued by an enabled
API client on the array. Overrides given private key.
private_key_file (str, optional):
The path of the private key to use. Defaults to None.
private_key_password (str, optional):
The password of the private key. Defaults to None.
username (str, optional):
Username of the user the token should be issued for. This must
be a valid user in the system.
client_id (str, optional):
ID of API client that issued the identity token.
key_id (str, optional):
Key ID of API client that issued the identity token.
issuer (str, optional):
API client's trusted identity issuer on the array.
api_token (str, optional):
API token for the user.
retries (int, optional):
The number of times to retry an API call if it fails for a
non-blocking reason. Defaults to 5.
timeout (float or (float, float), optional):
The timeout duration in seconds, either in total time or
(connect and read) times. Defaults to 15.0 total.
ssl_cert (str, optional):
SSL certificate to use. Defaults to None.
user_agent (str, optional):
User-Agent request header to use.
Raises:
PureError: If it could not create an ID or access token
"""
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
config = Configuration()
config.verify_ssl = ssl_cert is not None
config.ssl_ca_cert = ssl_cert
config.host = self._get_base_url(target)
if id_token and api_token:
raise PureError("Only one authentication option is allowed. Please use either id_token or api_token and try again!")
elif private_key_file and private_key_password and username and \
key_id and client_id and issuer and api_token:
raise PureError("id_token is generated based on app ID and private key info. Please use either id_token or api_token and try again!")
elif api_token:
api_token_auth_endpoint = self._get_api_token_endpoint(target)
self._token_man = APITokenManager(api_token_auth_endpoint, api_token, verify_ssl=False)
else:
auth_endpoint = 'https://{}/oauth2/1.0/token'.format(target)
headers = {
'kid': key_id
}
payload = {
'iss': issuer,
'aud': client_id,
'sub': username,
}
self._token_man = TokenManager(auth_endpoint, id_token, private_key_file, private_key_password,
payload=payload, headers=headers, verify_ssl=False)
self._api_client = ApiClient(configuration=config)
self._api_client.user_agent = user_agent or self.USER_AGENT
self._set_agent_header()
self._set_auth_header()
# Read timeout and retries
self._retries = retries
self._timeout = timeout
# Instantiate APIs
self._api_clients_api = api.APIClientsApi(self._api_client)
self._connections_api = api.ConnectionsApi(self._api_client)
self._host_groups_api = api.HostGroupsApi(self._api_client)
self._hosts_api = api.HostsApi(self._api_client)
self._offloads_api = api.OffloadsApi(self._api_client)
self._pods_api = api.PodsApi(self._api_client)
self._protection_group_snapshots_api = api.ProtectionGroupSnapshotsApi(self._api_client)
self._protection_groups_api = api.ProtectionGroupsApi(self._api_client)
self._remote_pods_api = api.RemotePodsApi(self._api_client)
self._remote_protection_group_snapshots_api = api.RemoteProtectionGroupSnapshotsApi(self._api_client)
self._remote_protection_groups_api = api.RemoteProtectionGroupsApi(self._api_client)
self._remote_volume_snapshots_api = api.RemoteVolumeSnapshotsApi(self._api_client)
self._volume_groups_api = api.VolumeGroupsApi(self._api_client)
self._volume_snapshots_api = api.VolumeSnapshotsApi(self._api_client)
self._volumes_api = api.VolumesApi(self._api_client)
def __del__(self):
# Cleanup this REST API client resources
self._api_client.close()
def get_rest_version(self):
"""Get the REST API version being used by this client.
Returns:
str
"""
return '2.1'
def get_access_token(self, refresh=False):
"""
Get the last used access token.
Args:
refresh (bool, optional):
Whether to retrieve a new access token. Defaults to False.
Returns:
str
Raises:
PureError: If there was an error retrieving an access token.
"""
return self._token_man.get_access_token(refresh)
def delete_api_clients(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Deletes an API client. The `ids` or `names` parameter is required, but cannot be
set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._api_clients_api.api21_api_clients_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_api_clients(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ApiClientGetResponse
"""
Returns a list of API clients.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._api_clients_api.api21_api_clients_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_api_clients(
self,
references=None, # type: List[models.ReferenceType]
api_clients=None, # type: models.ApiClientPatch
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ApiClientResponse
"""
Enables or disables an API client. The `ids` or `names` parameter is required,
but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
api_clients (ApiClientPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
api_clients=api_clients,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._api_clients_api.api21_api_clients_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_api_clients(
self,
references=None, # type: List[models.ReferenceType]
api_clients=None, # type: models.ApiClientPost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ApiClientResponse
"""
Creates an API client. Newly created API clients are disabled by default. Enable
an API client through the `PATCH` method. The `names`, `max_role`, `issuer`, and
`public_key` parameters are required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
api_clients (ApiClientPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
api_clients=api_clients,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._api_clients_api.api21_api_clients_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_connections(
self,
host_groups=None, # type: List[models.ReferenceType]
hosts=None, # type: List[models.ReferenceType]
volumes=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
host_group_names=None, # type: List[str]
host_names=None, # type: List[str]
volume_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Breaks the connection between a volume and its associated host or host group.
The `volume_names` and `host_names` or `host_group_names` query parameters are
required.
Args:
host_groups (list[FixedReference], optional):
A list of host_groups to query for. Overrides host_group_names keyword arguments.
hosts (list[FixedReference], optional):
A list of hosts to query for. Overrides host_names keyword arguments.
volumes (list[FixedReference], optional):
A list of volumes to query for. Overrides volume_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
host_group_names (list[str], optional):
Performs the operation on the host group specified. Enter multiple names in
comma-separated format. A request cannot include a mix of multiple objects with
multiple names. For example, a request cannot include a mix of multiple host
group names and volume names; instead, at least one of the objects (e.g.,
`host_group_names`) must be set to only one name (e.g., `hgroup01`).
host_names (list[str], optional):
Performs the operation on the hosts specified. Enter multiple names in comma-
separated format. For example, `host01,host02`. A request cannot include a mix
of multiple objects with multiple names. For example, a request cannot include a
mix of multiple host names and volume names; instead, at least one of the
objects (e.g., `host_names`) must be set to only one name (e.g., `host01`).
volume_names (list[str], optional):
Performs the operation on the volume specified. Enter multiple names in comma-
separated format. For example, `vol01,vol02`. A request cannot include a mix of
multiple objects with multiple names. For example, a request cannot include a
mix of multiple volume names and host names; instead, at least one of the
objects (e.g., `volume_names`) must be set to only one name (e.g., `vol01`).
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
host_group_names=host_group_names,
host_names=host_names,
volume_names=volume_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._connections_api.api21_connections_delete_with_http_info
_process_references(host_groups, ['host_group_names'], kwargs)
_process_references(hosts, ['host_names'], kwargs)
_process_references(volumes, ['volume_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_connections(
self,
host_groups=None, # type: List[models.ReferenceType]
hosts=None, # type: List[models.ReferenceType]
protocol_endpoints=None, # type: List[models.ReferenceType]
volumes=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
host_group_names=None, # type: List[str]
host_names=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
protocol_endpoint_names=None, # type: List[str]
sort=None, # type: List[str]
total_item_count=None, # type: bool
volume_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ConnectionGetResponse
"""
Returns a list of connections between a volume and its hosts and host groups,
and the LUNs used by the associated hosts to address these volumes.
Args:
host_groups (list[FixedReference], optional):
A list of host_groups to query for. Overrides host_group_names keyword arguments.
hosts (list[FixedReference], optional):
A list of hosts to query for. Overrides host_names keyword arguments.
protocol_endpoints (list[FixedReference], optional):
A list of protocol_endpoints to query for. Overrides protocol_endpoint_names keyword arguments.
volumes (list[FixedReference], optional):
A list of volumes to query for. Overrides volume_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
host_group_names (list[str], optional):
Performs the operation on the host group specified. Enter multiple names in
comma-separated format. A request cannot include a mix of multiple objects with
multiple names. For example, a request cannot include a mix of multiple host
group names and volume names; instead, at least one of the objects (e.g.,
`host_group_names`) must be set to only one name (e.g., `hgroup01`).
host_names (list[str], optional):
Performs the operation on the hosts specified. Enter multiple names in comma-
separated format. For example, `host01,host02`. A request cannot include a mix
of multiple objects with multiple names. For example, a request cannot include a
mix of multiple host names and volume names; instead, at least one of the
objects (e.g., `host_names`) must be set to only one name (e.g., `host01`).
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
protocol_endpoint_names (list[str], optional):
Performs the operation on the protocol endpoints specified. Enter multiple names
in comma-separated format. For example, `pe01,pe02`. A request cannot include a
mix of multiple objects with multiple names. For example, a request cannot
include a mix of multiple protocol endpoint names and host names; instead, at
least one of the objects (e.g., `protocol_endpoint_names`) must be set to one
name (e.g., `pe01`).
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
volume_names (list[str], optional):
Performs the operation on the volume specified. Enter multiple names in comma-
separated format. For example, `vol01,vol02`. A request cannot include a mix of
multiple objects with multiple names. For example, a request cannot include a
mix of multiple volume names and host names; instead, at least one of the
objects (e.g., `volume_names`) must be set to only one name (e.g., `vol01`).
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
host_group_names=host_group_names,
host_names=host_names,
limit=limit,
offset=offset,
protocol_endpoint_names=protocol_endpoint_names,
sort=sort,
total_item_count=total_item_count,
volume_names=volume_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._connections_api.api21_connections_get_with_http_info
_process_references(host_groups, ['host_group_names'], kwargs)
_process_references(hosts, ['host_names'], kwargs)
_process_references(protocol_endpoints, ['protocol_endpoint_names'], kwargs)
_process_references(volumes, ['volume_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_connections(
self,
host_groups=None, # type: List[models.ReferenceType]
hosts=None, # type: List[models.ReferenceType]
volumes=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
host_group_names=None, # type: List[str]
host_names=None, # type: List[str]
volume_names=None, # type: List[str]
connection=None, # type: models.ConnectionPost
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ConnectionResponse
"""
Creates a connection between a volume and a host or host group. The
`volume_names` and `host_names` or `host_group_names` query parameters are
required.
Args:
host_groups (list[FixedReference], optional):
A list of host_groups to query for. Overrides host_group_names keyword arguments.
hosts (list[FixedReference], optional):
A list of hosts to query for. Overrides host_names keyword arguments.
volumes (list[FixedReference], optional):
A list of volumes to query for. Overrides volume_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
host_group_names (list[str], optional):
Performs the operation on the host group specified. Enter multiple names in
comma-separated format. A request cannot include a mix of multiple objects with
multiple names. For example, a request cannot include a mix of multiple host
group names and volume names; instead, at least one of the objects (e.g.,
`host_group_names`) must be set to only one name (e.g., `hgroup01`).
host_names (list[str], optional):
Performs the operation on the hosts specified. Enter multiple names in comma-
separated format. For example, `host01,host02`. A request cannot include a mix
of multiple objects with multiple names. For example, a request cannot include a
mix of multiple host names and volume names; instead, at least one of the
objects (e.g., `host_names`) must be set to only one name (e.g., `host01`).
volume_names (list[str], optional):
Performs the operation on the volume specified. Enter multiple names in comma-
separated format. For example, `vol01,vol02`. A request cannot include a mix of
multiple objects with multiple names. For example, a request cannot include a
mix of multiple volume names and host names; instead, at least one of the
objects (e.g., `volume_names`) must be set to only one name (e.g., `vol01`).
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
host_group_names=host_group_names,
host_names=host_names,
volume_names=volume_names,
connection=connection,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._connections_api.api21_connections_post_with_http_info
_process_references(host_groups, ['host_group_names'], kwargs)
_process_references(hosts, ['host_names'], kwargs)
_process_references(volumes, ['volume_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_host_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Deletes a host group. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostGroupGetResponse
"""
Returns a list of host groups.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_host_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host from a host group. Removing a host from a host group
automatically disconnects the host from all volumes associated with the group.
Hosts can be removed from host groups at any time. The `group_names` and
`member_names` parameters are required and must be set together, and only one
host group can be specified at a time.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_hosts_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of host groups that are associated with hosts.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_hosts_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_host_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host to a host group. Adding a host to a host group automatically
connects the host to all volumes associated with the group. Multiple hosts can
be belong to a host group, but a host can only belong to one host group. Hosts
can be added to host groups at any time. The `group_names` and `member_names`
parameters are required and must be set together, and only one host group can be
specified at a time.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_hosts_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_host_groups(
self,
references=None, # type: List[models.ReferenceType]
host_group=None, # type: models.HostGroupPatch
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostGroupResponse
"""
Manages a host group. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
host_group (HostGroupPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
host_group=host_group,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_patch_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups_performance_by_array(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceNoIdByArrayGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O size data. The data returned is for each volume that is connected to
a host group on the current array and for each volume that is connected to a
host group on any remote arrays that are visible to the current array. The data
is displayed as a total across all host groups on each array and by individual
host group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_performance_by_array_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups_performance(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceNoIdGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O sizes across all volumes, displayed both by host group and as a
total across all host groups.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_performance_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_host_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostGroupResponse
"""
Creates a host group. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_host_groups_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host group member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the host group. The
`group_names` and `member_names` parameters are required and must be set
together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_protection_groups_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of host group members that belong to one or more protection
groups.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_protection_groups_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_host_groups_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host group member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the host group. The `group_names` and `member_names`
parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_protection_groups_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_host_groups_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceNoIdGetResponse
"""
Returns provisioned (virtual) size and physical storage consumption data for
each host group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._host_groups_api.api21_host_groups_space_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_hosts(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Deletes an existing host. All volumes that are connected to the host, either
through private or shared connections, must be disconnected from the host before
the host can be deleted. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostGetResponse
"""
Returns a list of hosts.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_hosts_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host from a host group. Removing a host from a host group
automatically disconnects the host from all volumes associated with the group.
Hosts can be removed from host groups at any time. The `group_names` and
`member_names` parameters are required and must be set together, and only one
host group can be specified at a time.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_host_groups_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of hosts that are associated with host groups.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_host_groups_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_hosts_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host to a host group. Adding a host to a host group automatically
connects the host to all volumes associated with the group. Multiple hosts can
be belong to a host group, but a host can only belong to one host group. Hosts
can be added to host groups at any time. The `group_names` and `member_names`
parameters are required and must be set together, and only one host group can be
specified at a time.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_host_groups_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_hosts(
self,
references=None, # type: List[models.ReferenceType]
host=None, # type: models.HostPatch
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostResponse
"""
Manages an existing host, including its storage network addresses, CHAP, host
personality, and preferred arrays, or associate a host to a host group. The
`names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
host (HostPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
host=host,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_patch_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts_performance_by_array(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceNoIdByArrayGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O size data. The data returned is for each volume that is connected to
a host on the current array and for each volume that is connected to a host on
any remote arrays that are visible to the current array. The data is displayed
as a total across all hosts on each array and by individual host.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_performance_by_array_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts_performance(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceNoIdGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O sizes across all volumes, displayed both by host and as a total
across all hosts.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_performance_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_hosts(
self,
references=None, # type: List[models.ReferenceType]
host=None, # type: models.HostPost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.HostResponse
"""
Creates a host. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
host (HostPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
host=host,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_hosts_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the host. The `group_names` and
`member_names` parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_protection_groups_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of host members that belong to one or more protection groups.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_protection_groups_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_hosts_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the host. The `group_names` and `member_names` parameters
are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_protection_groups_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_hosts_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceNoIdGetResponse
"""
Returns provisioned (virtual) size and physical storage consumption data for
each host.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._hosts_api.api21_hosts_space_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_offloads(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Disconnects the array from an offload target.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._offloads_api.api21_offloads_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_offloads(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
protocol=None, # type: str
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.OffloadGetResponse
"""
Returns a list of offload targets that are connected to the array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
protocol (str, optional):
Protocol type. Valid values are `nfs`, `s3`, and `azure`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
limit=limit,
names=names,
offset=offset,
protocol=protocol,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._offloads_api.api21_offloads_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_offloads(
self,
references=None, # type: List[models.ReferenceType]
offload=None, # type: models.OffloadPost
authorization=None, # type: str
x_request_id=None, # type: str
initialize=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.OffloadResponse
"""
Connects the array to an offload target. Before you can connect to, manage, and
replicate to an offload target, the respective Purity//FA app must be installed.
For more information about Purity//FA apps, refer to the Apps section of this
guide.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
offload (OffloadPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
initialize (bool, optional):
If set to `true`, initializes the Amazon S3 or Azure Blob container in
preparation for offloading. The parameter must be set to `true` if this is the
first time the array is connecting to the offload target.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
offload=offload,
authorization=authorization,
x_request_id=x_request_id,
initialize=initialize,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._offloads_api.api21_offloads_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_pods_arrays(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
group_ids=None, # type: List[str]
member_names=None, # type: List[str]
member_ids=None, # type: List[str]
with_unknown=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Unstretches a pod from an array, collapsing the pod to a single array. Unstretch
a pod from an array when the volumes within the stretched pod no longer need to
be synchronously replicated between the two arrays. After a pod has been
unstretched, synchronous replication stops. A destroyed version of the pod with
\"restretch\" appended to the pod name is created on the array that no longer
has the pod. The restretch pod represents a point-in-time snapshot of the pod,
just before it was unstretched. The restretch pod enters an eradication pending
period starting from the time that the pod was unstretched. A restretch can pod
can be cloned or destroyed, but it cannot be explicitly recovered. The
`group_names` parameter represents the name of the pod to be unstretched. The
`member_names` parameter represents the name of the array from which the pod is
to be unstretched. The `group_names` and `member_names` parameters are required
and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names and group_ids keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names and member_ids keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
group_ids (list[str], optional):
A list of group IDs.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
member_ids (list[str], optional):
Performs the operation on the unique member IDs specified. Enter multiple member
IDs in comma-separated format. The `member_ids` and `member_names` parameters
cannot be provided together.
with_unknown (bool, optional):
If set to `true`, unstretches the specified pod from the specified array by
force. Use the `with_unknown` parameter in the following rare event: the
local array goes offline while the pod is still stretched across two arrays, the
status of the remote array becomes unknown, and there is no guarantee that the
pod is online elsewhere.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
group_ids=group_ids,
member_names=member_names,
member_ids=member_ids,
with_unknown=with_unknown,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_arrays_delete_with_http_info
_process_references(groups, ['group_names', 'group_ids'], kwargs)
_process_references(members, ['member_names', 'member_ids'], kwargs)
return self._call_api(endpoint, kwargs)
def get_pods_arrays(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
group_ids=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
member_ids=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberGetResponse
"""
Returns a list of pods and the local and remote arrays over which the pods are
stretched. The optional `group_names` parameter represents the name of the pod.
The optional `member_names` parameter represents the name of the array over
which the pod is stretched.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names and group_ids keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names and member_ids keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
group_ids (list[str], optional):
A list of group IDs.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
member_ids (list[str], optional):
Performs the operation on the unique member IDs specified. Enter multiple member
IDs in comma-separated format. The `member_ids` and `member_names` parameters
cannot be provided together.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
group_names=group_names,
group_ids=group_ids,
limit=limit,
member_names=member_names,
member_ids=member_ids,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_arrays_get_with_http_info
_process_references(groups, ['group_names', 'group_ids'], kwargs)
_process_references(members, ['member_names', 'member_ids'], kwargs)
return self._call_api(endpoint, kwargs)
def post_pods_arrays(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
group_ids=None, # type: List[str]
member_names=None, # type: List[str]
member_ids=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberResponse
"""
Stretches a pod to an array. When a pod is stretched to an array, the data in
the arrays over which the pod is stretched is synchronously replicated. The
`group_names` parameter represents the name of the pod to be stretched. The
`member_names` parameter represents the name of the array over which the pod is
to be stretched. The `group_names` and `member_names` parameters are required
and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names and group_ids keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names and member_ids keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
group_ids (list[str], optional):
A list of group IDs.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
member_ids (list[str], optional):
Performs the operation on the unique member IDs specified. Enter multiple member
IDs in comma-separated format. The `member_ids` and `member_names` parameters
cannot be provided together.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
group_ids=group_ids,
member_names=member_names,
member_ids=member_ids,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_arrays_post_with_http_info
_process_references(groups, ['group_names', 'group_ids'], kwargs)
_process_references(members, ['member_names', 'member_ids'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_pods(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a pod that has been destroyed and is pending eradication. Eradicated
pods cannot be recovered. Pods are destroyed through the PATCH method. The `ids`
or `names` parameter is required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_pods(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.PodGetResponse
"""
Returns a list of pods that are stretched to this array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_pods(
self,
references=None, # type: List[models.ReferenceType]
pod=None, # type: models.PodPatch
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.PodResponse
"""
Manages the details of a pod.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
pod (PodPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
pod=pod,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_pods_performance_by_array(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceByArrayGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O size data. The data is displayed as a total across all pods on the
local array and by individual pod.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_performance_by_array_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_pods_performance(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O sizes across all pods, displayed both by pod and as a total across
all pods.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_performance_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_pods(
self,
references=None, # type: List[models.ReferenceType]
pod=None, # type: models.PodPost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.PodResponse
"""
Creates a pod on the local array. Each pod must be given a name that is unique
across the arrays to which they are stretched, so a pod cannot be stretched to
an array that already contains a pod with the same name. After a pod has been
created, add volumes and protection groups to the pod, and then stretch the pod
to another (connected) array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
pod (PodPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
pod=pod,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_pods_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceGetResponse
"""
Returns provisioned (virtual) size and physical storage consumption data for
each pod on the local array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._pods_api.api21_pods_space_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a protection group snapshot that has been destroyed and is pending
eradication. Eradicating a protection group snapshot eradicates all of its
protection group snapshots. Eradicated protection group snapshots cannot be
recovered. Protection group snapshots are destroyed through the `PATCH` method.
The `ids` or `names` parameter is required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_group_snapshots_api.api21_protection_group_snapshots_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupSnapshotGetResponse
"""
Returns a list of protection group snapshots, including those pending
eradication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_group_snapshots_api.api21_protection_group_snapshots_get_with_http_info
_process_references(references, ['names'], kwargs)
_process_references(sources, ['source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
protection_group_snapshot=None, # type: models.ProtectionGroupSnapshotPatch
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupSnapshotResponse
"""
Destroys a protection group snapshot. To destroy a volume, set `destroyed=true`.
To recover a volume that has been destroyed and is pending eradication, set
`destroyed=false`. The `names` parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
protection_group_snapshot (ProtectionGroupSnapshotPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
protection_group_snapshot=protection_group_snapshot,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_group_snapshots_api.api21_protection_group_snapshots_patch_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_group_snapshots(
self,
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
apply_retention=None, # type: bool
source_names=None, # type: List[str]
protection_group_snapshot=None, # type: models.ProtectionGroupSnapshotPost
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupSnapshotResponse
"""
Creates a point-in-time snapshot of the contents of a protection group. The
`source_ids` or `source_names` parameter is required, but cannot be set
together.
Args:
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
apply_retention (bool, optional):
If `true`, applies the local and remote retention policy to the snapshots.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
apply_retention=apply_retention,
source_names=source_names,
protection_group_snapshot=protection_group_snapshot,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_group_snapshots_api.api21_protection_group_snapshots_post_with_http_info
_process_references(sources, ['source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_group_snapshots_transfer(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupSnapshotTransferGetResponse
"""
Returns a list of protection group snapshots and their transfer statistics.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_group_snapshots_api.api21_protection_group_snapshots_transfer_get_with_http_info
_process_references(references, ['names'], kwargs)
_process_references(sources, ['source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a protection group that has been destroyed and is pending
eradication. Eradicated protection groups cannot be recovered. Protection groups
are destroyed through the PATCH method. The`ids` or `names` parameter is
required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupGetResponse
"""
Returns a list of protection groups, including their associated source arrays,
replication targets, hosts, host groups, and volumes. The list includes
protection groups that were created on the local array to replicate snapshot
data to other arrays or offload targets, created on a remote array and
replicated asynchronously to this array, or created inside a pod on a remote
array and stretched to the local array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_groups_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host group member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the host group. The
`group_names` and `member_names` parameters are required and must be set
together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_host_groups_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of protection groups that have host group members.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_host_groups_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_groups_host_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host group member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the host group. The `group_names` and `member_names`
parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_host_groups_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a host member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the host. The `group_names` and
`member_names` parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_hosts_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of protection groups that have host members.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_hosts_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_groups_hosts(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a host member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the host. The `group_names` and `member_names` parameters
are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_hosts_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
protection_group=None, # type: models.ProtectionGroup
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupResponse
"""
Configures the protection group schedules to generate and replicate snapshots to
another array or to an external storage system. Also renames or destroys a
protection group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
protection_group (ProtectionGroup, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
protection_group=protection_group,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_patch_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_performance_replication_by_array(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupPerformanceArrayResponse
"""
Returns the total number of bytes of replication data transmitted and received
per second. The data is grouped by protection group and includes the names of
the source array and targets for each protection group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
limit=limit,
offset=offset,
sort=sort,
total_item_count=total_item_count,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_performance_replication_by_array_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_performance_replication(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupPerformanceResponse
"""
Returns the total number of bytes of replication data transmitted and received
per second. The data is grouped by protection group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
limit=limit,
offset=offset,
sort=sort,
total_item_count=total_item_count,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_performance_replication_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
source_names=None, # type: List[str]
overwrite=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupResponse
"""
Creates a protection group on the local array for asynchronous replication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
source_names (list[str], optional):
The name of the protection group or protection group snapshot to be copied into
a new or existing protection group. If the destination protection group and all
of its volumes already exist, include the `overwrite` parameter to overwrite all
of the existing volumes with the snapshot contents. If including the `overwrite`
parameter, the names of the volumes that are being overwritten must match the
names of the volumes that are being restored. If the source is a protection
group, the latest snapshot of the protection group will be used as the source
during the copy operation.
overwrite (bool, optional):
If set to `true`, overwrites an existing volume during a volume copy operation.
If set to `false` or not set at all and the target name is an existing volume,
the volume copy operation fails. Required if the `source: id` or `source: name`
body parameter is set and the source overwrites an existing volume during the
volume copy operation.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
source_names=source_names,
overwrite=overwrite,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_post_with_http_info
_process_references(references, ['names'], kwargs)
_process_references(sources, ['source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceNoIdGetResponse
"""
Returns provisioned (virtual) size and physical storage consumption data for
each protection group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_space_get_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_groups_targets(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes an array or offload target from a protection group. The `group_names`
parameter represents the name of the protection group. The `member_names`
parameter represents the name of the array or offload target that is being
removed from the protection group. The `group_names` and `member_names`
parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_targets_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_targets(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupTargetGetResponse
"""
Returns a list of protection groups that have target arrays or offload targets.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_targets_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_protection_groups_targets(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
target=None, # type: models.TargetProtectionGroupPostPatch
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupTargetResponse
"""
Allows the source array to replicate protection group data to the target array,
or disallows the source array from replicating protection group data to the
target array. The `allowed` parameter must be set from the target array. The
`group_names` parameter represents the name of the protection group. The
`allowed` and `group_names` parameters are required and must be set together.
Offload targets do not support the `allowed` parameter.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
target (TargetProtectionGroupPostPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
target=target,
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_targets_patch_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_groups_targets(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ProtectionGroupTargetResponse
"""
Adds an array or offload target to a protection group. The `group_names`
parameter represents the name of the protection group. The `member_names`
parameter represents the name of the array or offload target that is being added
to the protection group. The `group_names` and `member_names` parameters are
required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_targets_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_protection_groups_volumes(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a volume member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the volume. The `group_names`
and `member_names` parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_volumes_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_protection_groups_volumes(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of protection groups that have volume members.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_volumes_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_protection_groups_volumes(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a volume member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the volume. The `group_names` and `member_names`
parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._protection_groups_api.api21_protection_groups_volumes_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_pods(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemotePodsResponse
"""
Returns a list of pods that that are on connected arrays but not stretched to
this array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
on=on,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_pods_api.api21_remote_pods_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_remote_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
on=None, # type: str
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a remote protection group snapshot that has been destroyed and is
pending eradication. Eradicated remote protection group snapshots cannot be
recovered. Remote protection group snapshots are destroyed through the `PATCH`
method. The `names` parameter represents the name of the protection group
snapshot. The `on` parameter represents the name of the offload target. The
`names` and `on` parameters are required and must be used together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
on (str, optional):
Performs the operation on the target name specified. For example,
`targetName01`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
names=names,
on=on,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_group_snapshots_api.api21_remote_protection_group_snapshots_delete_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteProtectionGroupSnapshotGetResponse
"""
Returns a list of remote protection group snapshots.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
limit=limit,
names=names,
offset=offset,
on=on,
sort=sort,
source_names=source_names,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_group_snapshots_api.api21_remote_protection_group_snapshots_get_with_http_info
_process_references(references, ['names'], kwargs)
_process_references(sources, ['source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_remote_protection_group_snapshots(
self,
references=None, # type: List[models.ReferenceType]
remote_protection_group_snapshot=None, # type: models.DestroyedPatchPost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
on=None, # type: str
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteProtectionGroupSnapshotResponse
"""
Destroys a remote protection group snapshot from the offload target. The `on`
parameter represents the name of the offload target. The `ids` or `names`
parameter and the `on` parameter are required and must be used together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
remote_protection_group_snapshot (DestroyedPatchPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
on (str, optional):
Performs the operation on the target name specified. For example,
`targetName01`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
remote_protection_group_snapshot=remote_protection_group_snapshot,
authorization=authorization,
x_request_id=x_request_id,
names=names,
on=on,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_group_snapshots_api.api21_remote_protection_group_snapshots_patch_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_protection_group_snapshots_transfer(
self,
sources=None, # type: List[models.ReferenceType]
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
limit=None, # type: int
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteProtectionGroupSnapshotTransferGetResponse
"""
Returns a list of remote protection groups and their transfer statistics.
Args:
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_names keyword arguments.
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
limit=limit,
offset=offset,
on=on,
sort=sort,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_group_snapshots_api.api21_remote_protection_group_snapshots_transfer_get_with_http_info
_process_references(sources, ['source_names'], kwargs)
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_remote_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
on=None, # type: str
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a remote protection group that has been destroyed and is pending
eradication. Eradicated remote protection groups cannot be recovered. Remote
protection groups are destroyed through the `PATCH` method. The `on` parameter
represents the name of the offload target. The `ids` or `names` parameter and
the `on` parameter are required and must be used together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
on (str, optional):
Performs the operation on the target name specified. For example,
`targetName01`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
on=on,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_groups_api.api21_remote_protection_groups_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteProtectionGroupGetResponse
"""
Returns a list of remote protection groups.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
on=on,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_groups_api.api21_remote_protection_groups_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_remote_protection_groups(
self,
references=None, # type: List[models.ReferenceType]
remote_protection_group=None, # type: models.RemoteProtectionGroup
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
on=None, # type: str
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteProtectionGroupResponse
"""
Configures the snapshot retention schedule of a remote protection group. Also
destroys a remote protection group from the offload target. Before the remote
protection group can be destroyed, the offload target must first be removed from
the protection group via the source array. The `on` parameter represents the
name of the offload target. The `ids` or `names` parameter and the `on`
parameter are required and must be used together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
remote_protection_group (RemoteProtectionGroup, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
on (str, optional):
Performs the operation on the target name specified. For example,
`targetName01`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
remote_protection_group=remote_protection_group,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
on=on,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_protection_groups_api.api21_remote_protection_groups_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_volume_snapshots(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
source_ids=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteVolumeSnapshotGetResponse
"""
Returns a list of remote volume snapshots.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_ids and source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_ids (list[str], optional):
Performs the operation on the source ID specified. Enter multiple source IDs in
comma-separated format.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
on=on,
sort=sort,
source_ids=source_ids,
source_names=source_names,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_volume_snapshots_api.api21_remote_volume_snapshots_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
_process_references(sources, ['source_ids', 'source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_remote_volume_snapshots_transfer(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
on=None, # type: List[str]
sort=None, # type: List[str]
source_ids=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.RemoteVolumeSnapshotTransferGetResponse
"""
Returns a list of remote volume snapshots and their transfer statistics.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_ids and source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
on (list[str], optional):
Performs the operation on the target name specified. Enter multiple target names
in comma-separated format. For example, `targetName01,targetName02`.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_ids (list[str], optional):
Performs the operation on the source ID specified. Enter multiple source IDs in
comma-separated format.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
offset=offset,
on=on,
sort=sort,
source_ids=source_ids,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._remote_volume_snapshots_api.api21_remote_volume_snapshots_transfer_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
_process_references(sources, ['source_ids', 'source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_volume_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a volume group that has been destroyed and is pending eradication.
Eradicated volume groups cannot be recovered. Volume groups are destroyed
through the `PATCH` method. The `ids` or `names` parameter is required, but
cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_groups(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeGroupGetResponse
"""
Returns a list of volume groups, including those pending eradication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_volume_groups(
self,
references=None, # type: List[models.ReferenceType]
volume_group=None, # type: models.VolumeGroup
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeGroupResponse
"""
Renames, destroys, or sets the QoS limits for the To rename a volume group, set
`name` to the new name. To destroy a volume group, set `destroyed=true`. To
recover a volume group that has been destroyed and is pending eradication, set
`destroyed=false`. Sets the bandwidth and IOPs limits of a volume group through
the respective `bandwidth_limit` and `iops_limit` parameter. The `ids` or
`names` parameter is required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
volume_group (VolumeGroup, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume_group=volume_group,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_groups_performance(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O sizes for each volume group and and as a total of all volume groups
across the entire array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_performance_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_volume_groups(
self,
references=None, # type: List[models.ReferenceType]
volume_group=None, # type: models.VolumeGroupPost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeGroupResponse
"""
Creates a volume group. The volume group itself does not contain any meaningful
content; instead, it acts as a container that is used to organize volumes. Once
a volume group has been created, volumes can be created inside the volume group
or moved into and out of the volume group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
volume_group (VolumeGroupPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume_group=volume_group,
authorization=authorization,
x_request_id=x_request_id,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_groups_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceGetResponse
"""
Returns the provisioned (virtual) size and physical storage consumption data for
each volume group.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_space_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_groups_volumes(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_ids=None, # type: List[str]
limit=None, # type: int
member_ids=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberGetResponse
"""
Returns a list of volume groups that contain volumes.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_ids and group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_ids and member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_ids (list[str], optional):
A list of group IDs.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_ids (list[str], optional):
Performs the operation on the unique member IDs specified. Enter multiple member
IDs in comma-separated format. The `member_ids` and `member_names` parameters
cannot be provided together.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_ids=group_ids,
limit=limit,
member_ids=member_ids,
offset=offset,
sort=sort,
total_item_count=total_item_count,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_groups_api.api21_volume_groups_volumes_get_with_http_info
_process_references(groups, ['group_ids', 'group_names'], kwargs)
_process_references(members, ['member_ids', 'member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_volume_snapshots(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicate a volume snapshot that has been destroyed and is pending eradication.
Eradicated volumes snapshots cannot be recovered. Volume snapshots are destroyed
through the `PATCH` method. The `ids` or `names` parameter is required, but
cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_snapshots_api.api21_volume_snapshots_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_snapshots(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
source_ids=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeSnapshotGetResponse
"""
Return a list of volume snapshots, including those pending eradication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_ids and source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_ids (list[str], optional):
Performs the operation on the source ID specified. Enter multiple source IDs in
comma-separated format.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
source_ids=source_ids,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_snapshots_api.api21_volume_snapshots_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
_process_references(sources, ['source_ids', 'source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_volume_snapshots(
self,
references=None, # type: List[models.ReferenceType]
volume_snapshot=None, # type: models.VolumeSnapshotPatch
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeSnapshotResponse
"""
Rename, destroy, or recover a volume snapshot. To rename the suffix of a volume
snapshot, set `name` to the new suffix name. To recover a volume snapshot that
has been destroyed and is pending eradication, set `destroyed=true`. The `ids`
or `names` parameter is required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
volume_snapshot (VolumeSnapshotPatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume_snapshot=volume_snapshot,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_snapshots_api.api21_volume_snapshots_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_volume_snapshots(
self,
sources=None, # type: List[models.ReferenceType]
volume_snapshot=None, # type: models.VolumeSnapshotPost
authorization=None, # type: str
x_request_id=None, # type: str
on=None, # type: str
source_ids=None, # type: List[str]
source_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeSnapshotResponse
"""
Create a point-in-time snapshot of the contents of a volume. The `source_ids` or
`source_names` parameter is required, but cannot be set together.
Args:
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_ids and source_names keyword arguments.
volume_snapshot (VolumeSnapshotPost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
on (str, optional):
Performs the operation on the target name specified. For example,
`targetName01`.
source_ids (list[str], optional):
Performs the operation on the source ID specified. Enter multiple source IDs in
comma-separated format.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume_snapshot=volume_snapshot,
authorization=authorization,
x_request_id=x_request_id,
on=on,
source_ids=source_ids,
source_names=source_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_snapshots_api.api21_volume_snapshots_post_with_http_info
_process_references(sources, ['source_ids', 'source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volume_snapshots_transfer(
self,
references=None, # type: List[models.ReferenceType]
sources=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
source_ids=None, # type: List[str]
source_names=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeSnapshotTransferGetResponse
"""
Returns a list of volume snapshots and their transfer statistics.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
sources (list[FixedReference], optional):
A list of sources to query for. Overrides source_ids and source_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
source_ids (list[str], optional):
Performs the operation on the source ID specified. Enter multiple source IDs in
comma-separated format.
source_names (list[str], optional):
Performs the operation on the source name specified. Enter multiple source names
in comma-separated format. For example, `name01,name02`.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
offset=offset,
sort=sort,
source_ids=source_ids,
source_names=source_names,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volume_snapshots_api.api21_volume_snapshots_transfer_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
_process_references(sources, ['source_ids', 'source_names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_volumes(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Eradicates a volume that has been destroyed and is pending eradication.
Eradicated volumes cannot be recovered. Volumes are destroyed through the
`PATCH` method. The `ids` or `names` parameter is required, but cannot be set
together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_delete_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeGetResponse
"""
Returns a list of volumes, including those pending eradication.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
destroyed=destroyed,
filter=filter,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def patch_volumes(
self,
references=None, # type: List[models.ReferenceType]
volume=None, # type: models.VolumePatch
authorization=None, # type: str
x_request_id=None, # type: str
ids=None, # type: List[str]
names=None, # type: List[str]
truncate=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeResponse
"""
Renames, destroys, or resizes a volume. To rename a volume, set `name` to the
new name. To destroy a volume, set `destroyed=true`. To recover a volume that
has been destroyed and is pending eradication, set `destroyed=false`. Sets the
bandwidth and IOPs limits of a volume through the respective `bandwidth_limit`
and `iops_limit` parameter. Moves the volume into a pod or volume group through
the respective `pod` or `volume_group` parameter. The `ids` or `names` parameter
is required, but cannot be set together.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
volume (VolumePatch, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
truncate (bool, optional):
If set to `true`, reduces the size of a volume during a volume resize operation.
When a volume is truncated, Purity automatically takes an undo snapshot,
providing a 24-hour window during which the previous contents can be retrieved.
After truncating a volume, its provisioned size can be subsequently increased,
but the data in truncated sectors cannot be retrieved. If set to `false` or not
set at all and the volume is being reduced in size, the volume copy operation
fails. Required if the `provisioned` parameter is set to a volume size that is
smaller than the original size.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume=volume,
authorization=authorization,
x_request_id=x_request_id,
ids=ids,
names=names,
truncate=truncate,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_patch_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes_performance_by_array(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceByArrayGetResponse
"""
Return real-time and historical performance data, real-time latency data, and
average I/O size data. The data returned is for each volume on the current array
and for each volume on any remote arrays that are visible to the current array.
The data is grouped by individual volumes and as a total across all volumes on
each array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_performance_by_array_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes_performance(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourcePerformanceGetResponse
"""
Returns real-time and historical performance data, real-time latency data, and
average I/O sizes for each volume and and as a total of all volumes across the
entire array.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
names=names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_performance_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_volumes(
self,
references=None, # type: List[models.ReferenceType]
volume=None, # type: models.VolumePost
authorization=None, # type: str
x_request_id=None, # type: str
names=None, # type: List[str]
overwrite=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.VolumeResponse
"""
Creates one or more virtual storage volumes of the specified size. If
`provisioned` is not specified, the size of the new volume defaults to 1 MB in
size. The `names` query parameter is required.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides names keyword arguments.
volume (VolumePost, required):
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
overwrite (bool, optional):
If set to `true`, overwrites an existing volume during a volume copy operation.
If set to `false` or not set at all and the target name is an existing volume,
the volume copy operation fails. Required if the `source: id` or `source: name`
body parameter is set and the source overwrites an existing volume during the
volume copy operation.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
volume=volume,
authorization=authorization,
x_request_id=x_request_id,
names=names,
overwrite=overwrite,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_post_with_http_info
_process_references(references, ['names'], kwargs)
return self._call_api(endpoint, kwargs)
def delete_volumes_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> None
"""
Removes a volume member from a protection group. After the member has been
removed, it is no longer protected by the group. Any protection group snapshots
that were taken before the member was removed will not be affected. Removing a
member from a protection group does not delete the member from the array, and
the member can be added back to the protection group at any time. The
`group_names` parameter represents the name of the protection group, and the
`member_names` parameter represents the name of the volume. The `group_names`
and `member_names` parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_protection_groups_delete_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_names=None, # type: List[str]
limit=None, # type: int
member_names=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllGetResponse
"""
Returns a list of volume members that belong to one or more protection groups.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_names=group_names,
limit=limit,
member_names=member_names,
offset=offset,
sort=sort,
total_item_count=total_item_count,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_protection_groups_get_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def post_volumes_protection_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberNoIdAllResponse
"""
Adds a volume member to a protection group. Members that are already in the
protection group are not affected. For asynchronous replication, only members of
the same type can belong to a protection group. The `group_names` parameter
represents the name of the protection group, and the `member_names` parameter
represents the name of the volume. The `group_names` and `member_names`
parameters are required and must be set together.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_protection_groups_post_with_http_info
_process_references(groups, ['group_names'], kwargs)
_process_references(members, ['member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes_space(
self,
references=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
destroyed=None, # type: bool
filter=None, # type: str
end_time=None, # type: int
resolution=None, # type: int
start_time=None, # type: int
ids=None, # type: List[str]
limit=None, # type: int
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
total_only=None, # type: bool
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.ResourceSpaceGetResponse
"""
Returns the provisioned (virtual) size and physical storage consumption data for
each volume.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
destroyed (bool, optional):
If set to `true`, lists only destroyed objects that are in the eradication
pending state. If set to `false`, lists only objects that are not destroyed. For
destroyed objects, the time remaining is displayed in milliseconds.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
end_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
resolution (int, optional):
The number of milliseconds between samples of historical data. For array-wide
performance metrics (`/arrays/performance` endpoint), valid values are `1000` (1
second), `30000` (30 seconds), `300000` (5 minutes), `1800000` (30 minutes),
`7200000` (2 hours), `28800000` (8 hours), and `86400000` (24 hours). For
performance metrics on storage objects (`<object name>/performance` endpoint),
such as volumes, valid values are `30000` (30 seconds), `300000` (5 minutes),
`1800000` (30 minutes), `7200000` (2 hours), `28800000` (8 hours), and
`86400000` (24 hours). For space metrics, (`<object name>/space` endpoint),
valid values are `300000` (5 minutes), `1800000` (30 minutes), `7200000` (2
hours), `28800000` (8 hours), and `86400000` (24 hours). Include the
`start_time` parameter to display the performance data starting at the specified
start time. If `start_time` is not specified, the start time will default to one
resolution before the end time, meaning that the most recent sample of
performance data will be displayed. Include the `end_time` parameter to display
the performance data until the specified end time. If `end_time`is not
specified, the end time will default to the current time. If the `resolution`
parameter is not specified but either the `start_time` or `end_time` parameter
is, then `resolution` will default to the lowest valid resolution.
start_time (int, optional):
Displays historical performance data for the specified time window, where
`start_time` is the beginning of the time window, and `end_time` is the end of
the time window. The `start_time` and `end_time` parameters are specified in
milliseconds since the UNIX epoch. If `start_time` is not specified, the start
time will default to one resolution before the end time, meaning that the most
recent sample of performance data will be displayed. If `end_time`is not
specified, the end time will default to the current time. Include the
`resolution` parameter to display the performance data at the specified
resolution. If not specified, `resolution` defaults to the lowest valid
resolution.
ids (list[str], optional):
Performs the operation on the unique resource IDs specified. Enter multiple
resource IDs in comma-separated format. The `ids` and `names` parameters cannot
be provided together.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
total_only (bool, optional):
If set to `true`, returns the aggregate value of all items after filtering.
Where it makes more sense, the average value is displayed instead. The values
are displayed for each name where meaningful. If `total_only=true`, the `items`
list will be empty.
names (list[str], optional):
Performs the operation on the unique name specified. Enter multiple names in
comma-separated format. For example, `name01,name02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
destroyed=destroyed,
filter=filter,
end_time=end_time,
resolution=resolution,
start_time=start_time,
ids=ids,
limit=limit,
offset=offset,
sort=sort,
total_item_count=total_item_count,
total_only=total_only,
names=names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_space_get_with_http_info
_process_references(references, ['ids', 'names'], kwargs)
return self._call_api(endpoint, kwargs)
def get_volumes_volume_groups(
self,
groups=None, # type: List[models.ReferenceType]
members=None, # type: List[models.ReferenceType]
authorization=None, # type: str
x_request_id=None, # type: str
continuation_token=None, # type: str
filter=None, # type: str
group_ids=None, # type: List[str]
limit=None, # type: int
member_ids=None, # type: List[str]
offset=None, # type: int
sort=None, # type: List[str]
total_item_count=None, # type: bool
group_names=None, # type: List[str]
member_names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
_request_timeout=None, # type: Optional[int]
):
# type: (...) -> models.MemberGetResponse
"""
Returns a list of volumes that are in a volume group.
Args:
groups (list[FixedReference], optional):
A list of groups to query for. Overrides group_ids and group_names keyword arguments.
members (list[FixedReference], optional):
A list of members to query for. Overrides member_ids and member_names keyword arguments.
x_request_id (str, optional):
A header to provide to track the API call. Generated by the server if not
provided.
continuation_token (str, optional):
An opaque token to iterate over a collection of resources.
filter (Filter, optional):
A filter to include only resources that match the specified criteria.
group_ids (list[str], optional):
A list of group IDs.
limit (int, optional):
Limit the number of resources in the response. If not specified, defaults to
1000.
member_ids (list[str], optional):
Performs the operation on the unique member IDs specified. Enter multiple member
IDs in comma-separated format. The `member_ids` and `member_names` parameters
cannot be provided together.
offset (int, optional):
The starting position based on the results of the query in relation to the full
set of response objects returned.
sort (list[Property], optional):
Sort the response by the specified Properties. Can also be a single element.
total_item_count (bool, optional):
If set to `true`, the `total_item_count` matching the specified query parameters
is calculated and returned in the response. If set to `false`, the
`total_item_count` is `null` in the response. This may speed up queries where
the `total_item_count` is large. If not specified, defaults to `false`.
group_names (list[str], optional):
Performs the operation on the unique group name specified. Examples of groups
include host groups, pods, protection groups, and volume groups. Enter multiple
names in comma-separated format. For example, `hgroup01,hgroup02`.
member_names (list[str], optional):
Performs the operation on the unique member name specified. Examples of members
include volumes, hosts, host groups, and directories. Enter multiple names in
comma-separated format. For example, `vol01,vol02`.
async_req (bool, optional):
Request runs in separate thread and method returns
multiprocessing.pool.ApplyResult.
_return_http_data_only (bool, optional):
Returns only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs = dict(
authorization=authorization,
x_request_id=x_request_id,
continuation_token=continuation_token,
filter=filter,
group_ids=group_ids,
limit=limit,
member_ids=member_ids,
offset=offset,
sort=sort,
total_item_count=total_item_count,
group_names=group_names,
member_names=member_names,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
endpoint = self._volumes_api.api21_volumes_volume_groups_get_with_http_info
_process_references(groups, ['group_ids', 'group_names'], kwargs)
_process_references(members, ['member_ids', 'member_names'], kwargs)
return self._call_api(endpoint, kwargs)
def _get_base_url(self, target):
return 'https://{}'.format(target)
def _get_api_token_endpoint(self, target):
return self._get_base_url(target) + '/api/2.1/login'
def _set_agent_header(self):
"""
Set the user-agent header of the internal client.
"""
self._api_client.set_default_header('User-Agent', self._api_client.user_agent)
def _set_auth_header(self, refresh=False):
"""
Set the authorization or x-auth-token header of the internal client with the access
token.
Args:
refresh (bool, optional): Whether to retrieve a new access token.
Defaults to False.
Raises:
PureError: If there was an error retrieving the access token.
"""
if isinstance(self._token_man, TokenManager):
self._api_client.set_default_header(Headers.authorization,
self._token_man.get_header(refresh=refresh))
else:
self._api_client.set_default_header(Headers.x_auth_token,
self._token_man.get_session_token(refresh=refresh))
def _call_api(self, api_function, kwargs):
"""
Call the API function and process the response. May call the API
repeatedly if the request failed for a reason that may not persist in
the next call.
Args:
api_function (function): Swagger-generated function to call.
kwargs (dict): kwargs to pass to the function.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueError: If a parameter is of an invalid type.
TypeError: If invalid or missing parameters are used.
"""
kwargs['_request_timeout'] = self._timeout
retries = self._retries
while True:
try:
response = api_function(**kwargs)
# Call was successful (200)
return self._create_valid_response(response, api_function, kwargs)
except ApiException as error:
# If no chance for retries, return the error
if retries == 0:
return self._create_error_response(error)
# If bad request or not found, return the error (it will never work)
elif error.status in [400, 404]:
return self._create_error_response(error)
# If authentication error, reset access token and retry
elif error.status in [401, 403]:
self._set_auth_header(refresh=True)
# If rate limit error, wait the proper time and try again
elif error.status == 429:
# If the the minute limit hit, wait that long
if (int(error.headers.get(Headers.x_ratelimit_remaining_min))
== int(error.headers.get(Headers.x_ratelimit_min))):
time.sleep(60)
# Otherwise it was the second limit and only wait a second
time.sleep(1)
# If some internal server error we know nothing about, return
elif error.status == 500:
return self._create_error_response(error)
# If internal server errors that has to do with timeouts, try again
elif error.status > 500:
pass
# If error with the swagger client, raise the error
else:
raise PureError(error)
retries = retries - 1
def _create_valid_response(self, response, endpoint, kwargs):
"""
Create a ValidResponse from a Swagger response.
Args:
response (tuple):
Body, status, header tuple as returned from Swagger client.
endpoint (function):
The function of the Swagger client that was called.
kwargs (dict):
The processed kwargs that were passed to the endpoint function.
Returns:
ValidResponse
"""
body, status, headers = response
continuation_token = getattr(body, "continuation_token", None)
total_item_count = getattr(body, "total_item_count", None)
total = getattr(body, "total", None)
more_items_remaining = getattr(body, "more_items_remaining", None)
items = None
if body is not None:
items = iter(ItemIterator(self, endpoint, kwargs,
continuation_token, total_item_count,
body.items,
headers.get(Headers.x_request_id, None),
more_items_remaining or False, None))
return ValidResponse(status, continuation_token, total_item_count,
items, headers, total, more_items_remaining)
def _create_error_response(self, error):
"""
Create an ErrorResponse from a Swagger error.
Args:
error (ApiException):
Error returned by Swagger client.
Returns:
ErrorResponse
"""
status = error.status
try:
body = json.loads(error.body)
except Exception:
body = {}
if status in [403, 429]:
# Parse differently if the error message came from kong
errors = [ApiError(None, body.get(Responses.message, None))]
else:
errors = [ApiError(err.get(Responses.context, None),
err.get(Responses.message, None))
for err in body.get(Responses.errors, {})]
return ErrorResponse(status, errors, headers=error.headers)
def _process_references(references, params, kwargs):
"""
Process reference objects into a list of ids or names.
Removes ids and names arguments.
Args:
references (list[FixedReference]):
The references from which to extract ids or names.
params (list[Parameter]):
The parameters to be overridden.
kwargs (dict):
The kwargs to process.
Raises:
PureError: If a reference does not have an id or name.
"""
if references is not None:
if not isinstance(references, list):
references = [references]
for param in params:
kwargs.pop(param, None)
all_have_id = all(getattr(ref, 'id', None) is not None for ref in references)
all_have_name = all(getattr(ref, 'name', None) is not None for ref in references)
id_param = [param for param in params if param.endswith("ids")]
name_param = [param for param in params if param.endswith("names")]
if all_have_id and len(id_param) > 0:
kwargs[id_param[0]] = [getattr(ref, 'id') for ref in references]
elif all_have_name and len(name_param) > 0:
kwargs[name_param[0]] = [getattr(ref, 'name') for ref in references]
else:
raise PureError('Invalid reference for {}'.format(", ".join(params)))
|
amatuni/multiformats | multiformats/multiformats.bzl | COPTS = [
"-std=c++1z",
"-stdlib=libc++",
"-Wall",
"-Wextra",
"-Wno-unused",
"-Wno-unused-parameter",
"-pedantic",
]
|
errbotio/err-ghstatus | ghstatus.py | <filename>ghstatus.py
# Copyright 2018 Argo AI, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from errbot import BotPlugin, botcmd, arg_botcmd
from github import Github
USERS = 'users'
class GHStatus(BotPlugin):
"""
This plugin allows you to query github for state on developers.
"""
def get_configuration_template(self):
"""
Get configuration template for this plugin.
It works by mapping users on chat to github users.
"""
return {'github-token': '<PASSWORD>', 'repo': 'argoai/av'}
def check_id(self, usr: str):
try:
self.build_identifier(usr)
except Exception as _:
return False
return True
def activate(self):
if not self.config:
return # do not activate if the plugin is not configured
super().activate()
self.gh = Github(self.config['github-token'], api_preview=True)
self.repo = self.gh.get_repo(self.config['repo'])
self.USERS = USERS # easier to use for external dependencies.
if USERS not in self:
self[USERS]={}
@botcmd
def gh_users(self, msg, _):
"""List currently configured users."""
response = '__Configured users__\n'
if not self[USERS]:
return ' -> no user configured yet, use !gh users add'
for chat_usr, gh_usr in self[USERS].items():
response += f'- {chat_usr} ▶ {gh_usr}\n'
return response
@arg_botcmd('gh_usr')
@arg_botcmd('chat_usr')
def gh_users_add(self, _, chat_usr, gh_usr):
"""Add a user mapping from chat user to github user."""
if not self.check_id(chat_usr):
return f'{chat_usr} is not a valid {self.mode} user.' # self.mode is for example 'Slack'
with self.mutable(USERS) as users:
users[chat_usr] = gh_usr
return f'{chat_usr} ▶ {gh_usr} configured.'
@arg_botcmd('chat_usr')
def gh_users_rm(self, _, chat_usr):
"""Removes a user mapping."""
with self.mutable(USERS) as users:
del users[chat_usr]
return f'{chat_usr} removed.'
@botcmd
def gh_prs(self, msg, chat_usr):
"""Lists PRs opened by your user or the one specified as an argument."""
if not chat_usr:
chat_usr = str(msg.frm.aclattr)
if not self.check_id(chat_usr):
return f'{chat_usr} is not a valid slack user.'
users = self[USERS]
if chat_usr not in users:
return f'{chat_usr} user is unknown. Use !gh users add.'
gh_user = users[chat_usr]
prs = [i for i in self.repo.get_issues(creator=gh_user) if i.pull_request]
if not prs:
return 'No PRs found.'
response = f'__PRs currently opened by {chat_usr}__\n\n'
for pr in prs:
response += f'- [{pr.number}]({pr.html_url}) {pr.title}\n'
return response
@botcmd
def gh_reviews(self, msg, chat_usr):
"""Lists the PRs you are specifically named as reviewer on or specify a chat user."""
if not chat_usr:
chat_usr = str(msg.frm.aclattr)
if not self.check_id(chat_usr):
return f'{chat_usr} is not a valid slack user.'
users = self[USERS]
if chat_usr not in users:
return f'{chat_usr} user is unknown. Use !gh users add.'
gh_user = users[chat_usr]
# adding review-requested AND involves is a trick to only get PRs you are explicitely asked to review.
# otherwise you will get any group you belong to.
prs = self.gh.search_issues(f'state:open type:pr review-requested:{gh_user} '
f'involves:{gh_user} repo:{self.repo.full_name}')
if not prs:
return 'No PRs found.'
response = f'__PRs open for review for {chat_usr}__\n\n'
for pr in prs:
response += f'- [{pr.number}]({pr.html_url}) {pr.title}\n'
return response
|
MeganWright3109/Human-Machine-Interaction | Robot-Maze-Supreme.py | <filename>Robot-Maze-Supreme.py
# !/usr/bin/env python3
'''COM2009-3009 EV3DEV TEST PROGRAM'''
# Connect left motor to Output C and right motor to Output B
# Connect an ultrasonic sensor to Input 3
import math
import matplotlib.pyplot as plt
from matplotlib import style
import time
import numpy as np
import random
import os
# Global Variables
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
integral_left = 0
integral_right = 0
last_error_left = 0
last_error_right = 0
derivative_left = 0
derivative_right = 0
start_time = time.time()
end_time = time.time()
class RunningStats:
# The following are to calculate the running stats
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
# @staticmethod
def push(self, x):
global m_n, m_oldM, m_newM, m_oldS, m_newS
m_n = m_n + 1
if (m_n == 1):
# Double check it
# TODO
m_newM = x
m_oldM = x
m_oldS = 0.0
else:
m_newM = m_oldM + (x - m_oldM)/m_n
m_newS = m_oldS + (x - m_oldM)*(x - m_newM)
# set up for next iteration
m_oldM = m_newM
m_oldS = m_newS
# Calculates the running variance
@staticmethod
def variance():
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will
# be different than 0
# When the variable is greater, returns the equation
if (m_n >= 1):
return (m_newS)/(m_n-1)
else:
return 0.0
# Calculates the running standard deviation
def standard_deviation(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
return math.sqrt(RunningStats.variance())
# Calculates the running mean
def mean(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will be
# different than 0
if (m_n >= 1):
return m_newM
else:
return 0.0
def create_file(light_sensor_left, light_sensor_right, offset):
global start_time, end_time
# Create the time variable
end_time = time.time()
# Calculate the necessary time to get the values from the light sensor
time_taken = end_time - start_time
l = open("robot_left.txt", "a+")
r = open("robot_right.txt", "a+")
d = open("offset.txt", "a+")
string_value_left = str("%.2f" % time_taken)+"," + str(light_sensor_left)+"\n"
l.write(string_value_left)
string_value_right = str("%.2f" % time_taken)+"," + str(light_sensor_right)+"\n"
r.write(string_value_right)
d.write(str(offset)+"\n")
r.close
l.close
d.close
def create_graphic():
x, y_right = np.loadtxt('robot_right.txt', delimiter=',', unpack=True)
x, y_left = np.loadtxt('robot_left.txt', delimiter=',', unpack=True)
d = np.loadtxt('offset.txt', unpack=True)
# Creats a graph on it
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
plt.xlabel("Time(s)")
plt.ylabel("Light Sensor Value")
ax1.plot(x, y_right, linestyle='', marker="o")
ax1.plot(x, y_left, linestyle='', marker="x")
ax1.plot(x, d)
plt.show()
def select_controller(mode):
# Using Ku to get a better integral
Ku = 6
Tu = 0.3
if mode == "P":
print("Running in P mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.6*100
# Proportional for the Integral
Ki = 0
# Proportional for the derivative
Kd = 0
return Kp, Ki, Kd
elif mode == "PI":
print("Running in PI mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.45*100*Ku
# Proportional for the Integral
Ki = (0.54*Ku)/Tu
# Proportional for the derivative
Kd = 0
return Kp, Ki, Kd
else:
print("Running in PID mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.6*100*Ku
# Proportional for the Integral
Ki = (1.2*Ku)/Tu
# Proportional for the derivative
Kd = (3*Ku*Tu)
return Kp, Ki, Kd
# Calculates the PID, sets Ki, Kd = 0 if you would like to use only P and so on
def calculate_pid(left_sensor, right_sensor, mode):
global integral_left, integral_right, last_error_left, last_error_right, derivative_left, derivative_right
Kp, Ki, Kd = select_controller(mode)
# In words our conversion is "for every 1
# unit change in the error we will increase the
# power of one motor by 10"
# The value that would be right
left_sensor = left_sensor/10
right_sensor = right_sensor/10
offset = (left_sensor + right_sensor)/2
# The target power, when the error is 0 the motors will run in this power
# The target point for when the value is == to the offset value can be
# higher
# Therefore, it would be good to have an if statement checking it
# If the line is pretty straight you can use a large Tp to get the
# robot running at high speed and a small Kp so the
# turns (corrections) are gentle.
Tp = 50
# Starting the loop>>>>>>
# This has to read from the robot's left sensor
error_left = left_sensor - offset
# This has to read from the robot's left sensor
error_right = right_sensor - offset
# It will increase or decrease the error conform the "size" of the integral
# variable, giving the controller a method to reduce errors over time
# Another way to don't make the integral to get too big is to do times
# 2/3, making the integral forget about long term errors
integral_left = ((2/3)*integral_left) + error_left
integral_right = ((2/3)*integral_right) + error_right
# The derivative that tries to see the future error
derivative_left = error_left - last_error_left
derivative_right = error_right - last_error_right
# This is the P, therefore, how much we want to change the velocity
# of the motor
# Divide velocity by 100 to decrease from the Kp from before
velocity_p_left = ((error_left*Kp)+(integral_left*Ki)+(derivative_left*Kd))/100
velocity_p_right = ((error_right*Kp)+(integral_right*Ki)+(derivative_right*Kd))/100
print(velocity_p_left)
print(velocity_p_right)
# Those are the powers that will be suplied to the motors
power_right = velocity_p_right + Tp
power_left = velocity_p_left + Tp
# Save the last error to be the next error
last_error_left = error_left
last_error_right = error_right
# Check the maximum and minimum power that can be sent to the robot
# Also check if the motor can receive a negative power
# Also double check by how far both motors go from a 100
# If it goes too far, better changing some Tune like Kp or Tp
if power_left > 100:
power_left = 100
elif power_left < -100:
power_left = -100
if power_right > 100:
power_right = 100
elif power_right < -100:
power_right = -100
# Sets the integral to zero when the error is zero
# That is to make sure that the integral does not get too big
# if error == 0:
# integral = 0
# debug_print(error)
# Return the powers of the robots
# if error >= 0.5 or error <= 0.5:
return power_left, power_right
# else:
# return 0, 0
# debug_print(error)
def test_no_robot():
value = 0
while value <= 100:
random_number_left = (random.randrange(400, 1000, 1)/10)
random_number_right = (random.randrange(400, 1000, 1)/10)
power = calculate_pid(45, 33, "P")
create_file(power[0], power[1], 50)
print("Power Left", power[0])
print("Power Right", power[1])
value = value + 1
# create_graphic()
# power = calculate_pid(10, 10, "PID")
# print("Power Left", power[0])
# print("Power Right", power[1])
# os.remove("offset.txt")
def main():
test_no_robot()
# rs=RunningStats()
#
# print(rs.mean())
# print(rs.variance())
# print(rs.standard_deviation())
main()
|
MeganWright3109/Human-Machine-Interaction | com2009-3009_ev3dev_test.py | <filename>com2009-3009_ev3dev_test.py
#!/usr/bin/env python3
'''COM2009-3009 EV3DEV TEST PROGRAM'''
# Connect left motor to Output C and right motor to Output B
# Connect an ultrasonic sensor to Input 3
import os
import sys
import time
import ev3dev.ev3 as ev3
import math
# import random
# import matplotlib.pyplot as plt
# from matplotlib import style
# import time
# import numpy as np
# Global Variables
ON = True
OFF = False
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
integral_left = 0
integral_right = 0
last_error_left = 0
last_error_right = 0
derivative_left = 0
derivative_right = 0
# start_time = time.time()
# end_time = time.time()
class RunningStats:
# The following are to calculate the running stats
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
# @staticmethod
def push(self, x):
global m_n, m_oldM, m_newM, m_oldS, m_newS
m_n = m_n + 1
if (m_n == 1):
# Double check it
# TODO
m_newM = x
m_oldM = x
m_oldS = 0.0
else:
m_newM = m_oldM + (x - m_oldM)/m_n
m_newS = m_oldS + (x - m_oldM)*(x - m_newM)
# set up for next iteration
m_oldM = m_newM
m_oldS = m_newS
# Calculates the running variance
@staticmethod
def variance():
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will
# be different than 0
# When the variable is greater, returns the equation
if (m_n >= 1):
return (m_newS)/(m_n-1)
else:
return 0.0
# Calculates the running standard deviation
def standard_deviation(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
return math.sqrt(RunningStats.variance())
# Calculates the running mean
def mean(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will be
# different than 0
if (m_n >= 1):
return m_newM
else:
return 0.0
# Professors Code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def debug_print(*args, **kwargs):
'''Print debug messages to stderr.
This shows up in the output panel in VS Code.
'''
print(*args, **kwargs, file=sys.stderr)
def reset_console():
'''Resets the console to the default state'''
print('\x1Bc', end='')
def set_cursor(state):
'''Turn the cursor on or off'''
if state:
print('\x1B[?25h', end='')
else:
print('\x1B[?25l', end='')
def set_font(name):
'''Sets the console font
A full list of fonts can be found with `ls /usr/share/consolefonts`
'''
os.system('setfont ' + name)
def select_controller(mode):
# Using Ku to get a better integral
Ku = 6
Tu = 0.3
if mode == "P":
print("Running in P mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.6*100*Ku
# Proportional for the Integral
Ki = 0
# Proportional for the derivative
Kd = 0
return Kp, Ki, Kd
elif mode == "PI":
print("Running in PI mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.45*100*Ku
# Proportional for the Integral
Ki = (0.54*Ku)/Tu
# Proportional for the derivative
Kd = 0
return Kp, Ki, Kd
elif mode == "PID":
print("Running in PID mode")
# Mulitply Kp by 100 to use decimal points
Kp = 0.6*100*Ku
# Proportional for the Integral
Ki = (1.2*Ku)/Tu
# Proportional for the derivative
Kd = (3*Ku*Tu)
return Kp, Ki, Kd
# Calculates the PID, sets Ki, Kd = 0 if you would like to use only P and so on
def calculate_pid(left_sensor, right_sensor, mode):
global integral_left, integral_right, last_error_left, last_error_right, derivative_left, derivative_right
Kp, Ki, Kd = select_controller(mode)
# In words our conversion is "for every 1
# unit change in the error we will increase the
# power of one motor by 10"
# The value that would be right
left_sensor = left_sensor/10
right_sensor = right_sensor/10
offset = (left_sensor + right_sensor)/2
# The target power, when the error is 0 the motors will run in this power
# The target point for when the value is == to the offset value can be
# higher
# Therefore, it would be good to have an if statement checking it
# If the line is pretty straight you can use a large Tp to get the
# robot running at high speed and a small Kp so the
# turns (corrections) are gentle.
Tp = 50
# This has to read from the robot's left sensor
error_left = left_sensor - offset
# This has to read from the robot's left sensor
error_right = right_sensor - offset
# It will increase or decrease the error conform the "size" of the integral
# variable, giving the controller a method to reduce errors over time
# Another way to don't make the integral to get too big is to do times
# 2/3, making the integral forget about long term errors
integral_left = (integral_left) + error_left
integral_right = (integral_right) + error_right
# The derivative that tries to see the future error
derivative_left = error_left - last_error_left
derivative_right = error_right - last_error_right
# This is the P, therefore, how much we want to change the velocity
# of the motor
# Divide velocity by 100 to decrease from the Kp from before
velocity_p_left = ((error_left*Kp)+(integral_left*Ki)+(derivative_left*Kd))/100
velocity_p_right = ((error_right*Kp)+(integral_right*Ki)+(derivative_right*Kd))/100
# Those are the powers that will be suplied to the motors
power_right = velocity_p_right + Tp
power_left = velocity_p_left + Tp
# Save the last error to be the next error
last_error_left = error_left
last_error_right = error_right
# Check the maximum and minimum power that can be sent to the robot
# Also check if the motor can receive a negative power
# Also double check by how far both motors go from a 100
# If it goes too far, better changing some Tune like Kp or Tp
if power_left > 100:
power_left = 100
elif power_left < -100:
power_left = -100
if power_right > 100:
power_right = 100
elif power_right < -100:
power_right = -100
# Sets the integral to zero when the error is zero
# That is to make sure that the integral does not get too big
# if error == 0:
# integral = 0
# debug_print(error)
# error =
# Return the powers of the robots
if (error_left <= 3 and error_left >= -3) and (error_right <= 3 and error_right >= -3):
debug_print("Full speed")
return 90, 90
else:
return power_left, power_right
def main():
'''The main function of our program'''
# set the console just how we want it
reset_console()
set_cursor(OFF)
set_font('Lat15-Terminus24x12')
# display something on the screen of the device
print('Best Robot 2019')
# print something to the output panel in VS Code
debug_print('Good evening')
# announce program start
ev3.Sound.speak('Program Starting').wait()
# set the motor variables
mb = ev3.LargeMotor('outB')
mc = ev3.LargeMotor('outD')
# set the ultrasonic sensor variable
left_sensor = ev3.UltrasonicSensor('in1')
right_sensor = ev3.UltrasonicSensor('in4')
while True:
time.sleep(0.005)
power_left, power_right = calculate_pid(left_sensor.value(), right_sensor.value(), "P")
# Give power to the motors
debug_print("Power Left="+str(power_left) + "Power Right="+str(power_right))
mb.run_direct(duty_cycle_sp=(power_left))
mc.run_direct(duty_cycle_sp=(power_right))
if __name__ == '__main__':
main()
|
MeganWright3109/Human-Machine-Interaction | Robot-Maze-B1.py | # !/usr/bin/env python3
'''COM2009-3009 EV3DEV TEST PROGRAM'''
# Connect left motor to Output C and right motor to Output B
# Connect an ultrasonic sensor to Input 3
import os
import sys
import time
import ev3dev.ev3 as ev3
import math
from time import sleep, time
# state constants
ON = True
OFF = False
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
# Calculation for standard deviation, variance and mean
def push(value):
global m_n
global m_oldM
global m_newM
global m_oldS
global m_newS
m_n = m_n + 1
if(m_n == 1):
m_oldM = m_newM
m_newM = value
m_oldS = 0.0
else:
m_newM = m_oldM + (value-m_oldM)/m_n
m_newS = m_oldS + (value-m_oldM)*(value-m_newM)
# Set up for next iteraction
m_oldM = m_newM
m_old = m_newS
def mean():
global m_n
if (m_n > 0):
return m_newM
else:
return 0.0
def variance():
global m_newS
global m_n
if (m_n > 1):
return m_newS/(m_n-1)
else:
return 0.00
def standard_deviation():
return math.sqrt(variance())
def debug_print(*args, **kwargs):
'''Print debug messages to stderr.
This shows up in the output panel in VS Code.
'''
print(*args, **kwargs, file=sys.stderr)
def reset_console():
'''Resets the console to the default state'''
print('\x1Bc', end='')
def set_cursor(state):
'''Turn the cursor on or off'''
if state:
print('\x1B[?25h', end='')
else:
print('\x1B[?25l', end='')
def set_font(name):
'''Sets the console font
A full list of fonts can be found with `ls /usr/share/consolefonts`
'''
os.system('setfont ' + name)
def main():
'''The main function of our program'''
# set the console just how we want it
reset_console()
set_cursor(OFF)
set_font('Lat15-Terminus24x12')
# display something on the screen of the device
# print('Hello World!')
# print something to the output panel in VS Code
debug_print('Hello VS Code!')
# announce program start
# ev3.Sound.speak('Test program starting!').wait()
# set the motor variables
mb = ev3.LargeMotor('outB')
mc = ev3.LargeMotor('outC')
sp = 30
delta = 30
# set the ultrasonic sensor variable
us3 = ev3.UltrasonicSensor('in3')
# # program loop
# for x in range (1, 5):
# display the distance on the screen of the device
# print('Distance =',ds)
# print the distance to the output panel in VS Code
# debug_print('Distance =',ds)
# ds = us3.value()
# announce the distance
# ev3.Sound.speak(ds).wait()
# move
# mb.run_direct(duty_cycle_sp=sp)
# mc.run_direct(duty_cycle_sp=sp)
# time.sleep(0.)
# for x in range(1, 1000):
# time.sleep(0.01)
# ds = us3.value()
# # debug_print('Distance =',ds)
# push(ds)
# mean_current = mean()
# variance_current = variance()
# stdev = standard_deviation()
# debug_print("Distance", ds)
# debug_print("Mean", mean_current)
# debug_print("Variance", variance_current)
# debug_print("Standar Deviation", stdev)
# mb.run_timed(time_sp=1, speed_sp=1000)
# mc.run_timed(time_sp=200000, speed_sp=1000)
# mb.run_direct(duty_cycle_sp=60)
# mc.run_direct(duty_cycle_sp=60)
# time.sleep(2.5)
# mb.run_direct(duty_cycle_sp=10)
# time.sleep(2)
# mb.run_direct(duty_cycle_sp=0)
# mc.run_direct(duty_cycle_sp=0)
# question 4 open loop
# for x in range(1,4):
# mb.run_direct(duty_cycle_sp=60)
# mc.run_direct(duty_cycle_sp=60)
# time.sleep(2.5)
# mb.run_direct(duty_cycle_sp=10)
# time.sleep(2)
# # stop
# mb.run_direct(duty_cycle_sp=0)
# mc.run_direct(duty_cycle_sp=0)
# # reverse direction
# sp = -sp
Kp = 50
Ki = 0
Kd = 0
r = 500
Tp = 25
integral = 0
lastError = 0
derivative = 0
b = ev3.UltrasonicSensor('in3')
rafa = 0
error = r - (b.value())
startTime = time()
while rafa == 0:
debug_print(round((time() - startTime) % 20))
if round((time() - startTime) % 20) == 0:
r = 500
elif round((time() - startTime) % 10) == 0:
r = 300
integral = integral + error
derivative = error - lastError
Turn = Kp*error + Ki*integral + Kd*derivative
Turn = Turn/100
powerB = Tp + Turn
powerC = Tp + Turn
error = r - (b.value())
debug_print(error)
debug_print("Value of b", b.value())
if error > 0:
mb.run_direct(duty_cycle_sp=-(powerB))
mc.run_direct(duty_cycle_sp=-(powerC))
else:
mb.run_direct(duty_cycle_sp=(powerB))
mc.run_direct(duty_cycle_sp=(powerC))
# integral = integral + error
# derivative = error - lastError
# Turn = Kp*error + Ki*integral + Kd*derivative
# Turn = Turn/100
# powerB = Tp + Turn
# powerC = Tp + Turn
# error = r - (b.value())
# debug_print (error)
# debug_print ("Value of b",b.value())
# if error > 0:
# mb.run_direct(duty_cycle_sp=-(powerB))
# mc.run_direct(duty_cycle_sp=-(powerC))
# else:
# mb.run_direct(duty_cycle_sp=(powerB))
# mc.run_direct(duty_cycle_sp=(powerC))
# if error == 0:
# mb.run_direct(duty_cycle_sp=0)
# mc.run_direct(duty_cycle_sp=0)
# else:
# mb.run_direct(duty_cycle_sp=powerB)
# mc.run_direct(duty_cycle_sp=powerC)
# debug_print("PowerB", powerB)
# debug_print("PowerB", powerC)
# time.sleep(10)
# lastError = error
# # announce program end
# ev3.Sound.speak('Test program ending').wait()
# push(17.0)
# push(18.0)
# push(5.0)
# mean_current = mean()
# variance_current = variance()
# stdev = standard_deviation()
# debug_print (mean_current)
# debug_print (variance_current)
# debug_print(stdev)
# debug_print(m_n)
if __name__ == '__main__':
main()
|
MeganWright3109/Human-Machine-Interaction | Robot-Maze-B1-Test-Rafa.py | <filename>Robot-Maze-B1-Test-Rafa.py
# !/usr/bin/env python3
'''COM2009-3009 EV3DEV TEST PROGRAM'''
# Connect left motor to Output C and right motor to Output B
# Connect an ultrasonic sensor to Input 3
import os
import sys
import time
import ev3dev.ev3 as ev3
import math
import random
import matplotlib.pyplot as plt
from matplotlib import style
import time
import numpy as np
# Global Variables
ON = True
OFF = False
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
integral = 0
last_error = 0
derivative = 0
start_time = time.time()
end_time = time.time()
class RunningStats:
# The following are to calculate the running stats
m_n = 0
m_oldM = 0
m_newM = 0
m_oldS = 0
m_newS = 0
# @staticmethod
def push(self, x):
global m_n, m_oldM, m_newM, m_oldS, m_newS
m_n = m_n + 1
if (m_n == 1):
# Double check it
# TODO
m_newM = x
m_oldM = x
m_oldS = 0.0
else:
m_newM = m_oldM + (x - m_oldM)/m_n
m_newS = m_oldS + (x - m_oldM)*(x - m_newM)
# set up for next iteration
m_oldM = m_newM
m_oldS = m_newS
# Calculates the running variance
@staticmethod
def variance():
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will
# be different than 0
# When the variable is greater, returns the equation
if (m_n >= 1):
return (m_newS)/(m_n-1)
else:
return 0.0
# Calculates the running standard deviation
def standard_deviation(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
return math.sqrt(RunningStats.variance())
# Calculates the running mean
def mean(self):
global m_n, m_oldM, m_newM, m_oldS, m_newS
# Changed to greater or equals to make sure that the value will be
# different than 0
if (m_n >= 1):
return m_newM
else:
return 0.0
# Professors Code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def debug_print(*args, **kwargs):
'''Print debug messages to stderr.
This shows up in the output panel in VS Code.
'''
print(*args, **kwargs, file=sys.stderr)
def reset_console():
'''Resets the console to the default state'''
print('\x1Bc', end='')
def set_cursor(state):
'''Turn the cursor on or off'''
if state:
print('\x1B[?25h', end='')
else:
print('\x1B[?25l', end='')
def set_font(name):
'''Sets the console font
A full list of fonts can be found with `ls /usr/share/consolefonts`
'''
os.system('setfont ' + name)
def create_file(light_sensor_value, offset):
global start_time, end_time
# Create the time variable
end_time = time.time()
# Calculate the necessary time to get the values from the light sensor
time_taken = end_time - start_time
f = open("robot.txt", "a+")
d = open("offset.txt", "a+")
string_value = str("%.2f" % time_taken)+"," + str(light_sensor_value)+"\n"
f.write(string_value)
d.write(str(offset)+"\n")
f.close
d.close
def create_graphic():
x, y = np.loadtxt('robot.txt', delimiter=',', unpack=True)
d = np.loadtxt('offset.txt', unpack=True)
print(d)
# Creats a graph on it
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
plt.xlabel("Time(s)")
plt.ylabel("Light Sensor Value")
ax1.plot(x, y)
print(d.shape)
print(y.shape)
ax1.plot(x, d)
plt.show()
def calculate_pid(left_sensor):
global integral, last_error, derivative
# In words our conversion is "for every 1
# unit change in the error we will increase the
# power of one motor by 10"
# Mulitply Kp by 100 to use decimal points
Kp = 3.5*100
# Proportional for the Integral
Ki = 0 * 100
# Proportional for the derivative
Kd = 0 * 100
# The value that would be right
offset = 90
# Creates a graphic for it
create_file(left_sensor, offset)
# The target power, when the error is 0 the motors will run in this power
# The target point for when the value is == to the offset value can be
# higher
# Therefore, it would be good to have an if statement checking it
# If the line is pretty straight you can use a large Tp to get the
# robot running at high speed and a small Kp so the
# turns (corrections) are gentle.
Tp = 15
# Starting the loop>>>>>>
# This has to read from the robot's right sensor
error = left_sensor - offset
# It will increase or decrease the error conform the "size" of the integral
# variable, giving the controller a method to reduce errors over time
# Another way to don't make the integral to get too big is to do times
# 2/3, making the integral forget about long term errors
integral = ((2/3)*integral) + error
# The derivative that tries to see the future error
derivative = error - last_error
# This is the P, therefore, how much we want to change the velocity
# of the motor
# Divide velocity by 100 to decrease from the Kp from before
velocity_p = (error*Kp)+(integral*Ki)+(derivative*Kd)
velocity_p = velocity_p/100
# Those are the powers that will be suplied to the motors
power_right = velocity_p + Tp
power_left = velocity_p + Tp
# Save the last error to be the next error
last_error = error
# Check the maximum and minimum power that can be sent to the robot
# Also check if the motor can receive a negative power
# Also double check by how far both motors go from a 100
# If it goes too far, better changing some Tune like Kp or Tp
if power_left > 100:
power_left = 100
elif power_left < -100:
power_left = -100
if power_right > 100:
power_right = 100
elif power_right < -100:
power_right = -100
# Sets the integral to zero when the error is zero
# That is to make sure that the integral does not get too big
# if error == 0:
# integral = 0
# Return the powers of the robots
if error != 0:
return power_left, power_right
else:
return 0, 0
def main():
'''The main function of our program'''
# set the console just how we want it
reset_console()
set_cursor(OFF)
set_font('Lat15-Terminus24x12')
# display something on the screen of the device
print('Best Robot 2019')
# print something to the output panel in VS Code
debug_print('Good evening')
# announce program start
ev3.Sound.speak('Program Starting').wait()
# set the motor variables
mb = ev3.LargeMotor('outB')
mc = ev3.LargeMotor('outC')
# set the ultrasonic sensor variable
us3 = ev3.UltrasonicSensor('in3')
# Get the ultrasonic sensors values
left_sensor = ev3.UltrasonicSensor('in3')
power_left, power_right = calculate_pid(left_sensor)
# Give power to the motors
mb.run_direct(duty_cycle_sp=-(power_left))
mc.run_direct(duty_cycle_sp=-(power_right))
if __name__ == '__main__':
main()
|
suyanzhou626/predict_sliding.py | predict_sliding.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
def tta_inference(inp, model, num_classes=8, scales=[1.0], flip=True):
b, _, h, w = inp.size()
preds = inp.new().resize_(b, num_classes, h, w).zero_().to(inp.device)
for scale in scales:
size = (int(scale*h), int(scale*w))
resized_img = F.interpolate(inp, size=size, mode='bilinear', align_corners=True,)
pred = model_inference(model, resized_img.to(inp.device), flip)
pred = F.interpolate(pred, size=(h, w), mode='bilinear', align_corners=True,)
preds += pred
return preds/(len(scales))
def model_inference(model, image, flip=True):
output = model(image)
if flip:
fimg = image.flip(2)
output += model(fimg).flip(2)
fimg = image.flip(3)
output += model(fimg).flip(3)
return output/3
return output
def slide(model, scale_image, num_classes=6, crop_size=512, overlap=1/2, scales=[1.0], flip=True):
N, C, H_, W_ = scale_image.shape
print(f"Height: {H_} Width: {W_}")
full_probs = torch.zeros((N, num_classes, H_, W_), device=scale_image.device) #
count_predictions = torch.zeros((N, num_classes, H_, W_), device=scale_image.device) #
h_overlap_length = int((1-overlap)*crop_size)
w_overlap_length = int((1-overlap)*crop_size)
h = 0
slide_finish = False
while not slide_finish:
if h + crop_size <= H_:
print(f"h: {h}")
# set row flag
slide_row = True
# initial row start
w = 0
while slide_row:
if w + crop_size <= W_:
print(f" h={h} w={w} -> h'={h+crop_size} w'={w+crop_size}")
patch_image = scale_image[:, :, h:h+crop_size, w:w+crop_size]
#
patch_pred_image = tta_inference(patch_image, model, num_classes=num_classes, scales=scales, flip=flip)
count_predictions[:,:,h:h+crop_size, w:w+crop_size] += 1
full_probs[:,:,h:h+crop_size, w:w+crop_size] += patch_pred_image
else:
print(f" h={h} w={W_-crop_size} -> h'={h+crop_size} w'={W_}")
patch_image = scale_image[:, :, h:h+crop_size, W_-crop_size:W_]
#
patch_pred_image = tta_inference(patch_image, model, num_classes=num_classes, scales=scales, flip=flip)
count_predictions[:,:,h:h+crop_size, W_-crop_size:W_] += 1
full_probs[:,:,h:h+crop_size, W_-crop_size:W_] += patch_pred_image
slide_row = False
w += w_overlap_length
else:
print(f"h: {h}")
# set last row flag
slide_last_row = True
# initial row start
w = 0
while slide_last_row:
if w + crop_size <= W_:
print(f"h={H_-crop_size} w={w} -> h'={H_} w'={w+crop_size}")
patch_image = scale_image[:,:,H_-crop_size:H_, w:w+crop_size]
#
patch_pred_image = tta_inference(patch_image, model, num_classes=num_classes, scales=scales, flip=flip)
count_predictions[:,:,H_-crop_size:H_, w:w+crop_size] += 1
full_probs[:,:,H_-crop_size:H_, w:w+crop_size] += patch_pred_image
else:
print(f"h={H_-crop_size} w={W_-crop_size} -> h'={H_} w'={W_}")
patch_image = scale_image[:,:,H_-crop_size:H_, W_-crop_size:W_]
#
patch_pred_image = tta_inference(patch_image, model, num_classes=num_classes, scales=scales, flip=flip)
count_predictions[:,:,H_-crop_size:H_, W_-crop_size:W_] += 1
full_probs[:,:,H_-crop_size:H_, W_-crop_size:W_] += patch_pred_image
slide_last_row = False
slide_finish = True
w += w_overlap_length
h += h_overlap_length
full_probs /= count_predictions
return full_probs
def test(testloader, model, savedir, device):
'''
args:
test_loaded for test dataset
model: model
return:
mean,Iou,IoU class
'''
if not os.path.exists(savedir):
os.mkdir(savedir)
model.eval()
total_batches = len(testloader)
with torch.no_grad():
for idx, batch in enumerate(testloader):
# load data
image, _, name = batch
image = image.to(device)
N, C, H, W = image.shape
# sliding eval
output = slide(
model=model,
scale_image=image,
num_classes=6,
crop_size=512,
overlap=1/2,
scales=[1.0],
flip=True)
_, output = torch.max(output, 1)
assert len(output.shape) == 3, f"Wrong shape!"
# convert torch to array
output = np.asarray(output.permute(1,2,0).data.cpu().numpy(), dtype=np.uint8)
# input: [H, W, 3]
imageout = decode_segmap(output.squeeze())
# std output
img_save_name = os.path.basename(name[0])
img_save_name = os.path.splitext(img_save_name)[0]
img_save_path = os.path.join(savedir, img_save_name+'_gt.png')
imageout = Image.fromarray(imageout)
imageout.save(img_save_path)
|
jonathonwpowell/alexaTwitchSkill | awsLambda/lambda_code.py | import requests
# --------------- Helpers that build all of the responses ----------------------
# These helpers are from amazon
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': clean_return_for_TTS(output)
},
'card': {
'type': 'Simple',
'title': title,
'content': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_login_card_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'LinkAccount',
'title': title,
'content': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
# ---------------------- Twitch Auth Helpers--------------------------------------
def get_twitch_auth(session):
if 'accessToken' in session['user']:
return session['user']['accessToken']
else:
return None
# ------------------------Twitch API Helpers -------------------------------------
def twitch_top_streamers(num_of_responses):
api_info = get_twitch_api_info()
url = api_info['base_api_url'] + api_info['top_streams']
headers = {"Accept": "application/json", "Client-ID": api_info['Client-ID']}
api_response = requests.get(url, headers=headers)
json = api_response.json()
streams = ""
for num in range(0, num_of_responses):
if streams != "":
streams = streams + ", "
streams = streams + json['streams'][num]['channel']['display_name']
return streams
def twitch_my_top_streamers(num_of_responses, auth_info):
api_info = get_twitch_api_info()
url = api_info['base_api_url'] + api_info['my_top_streams']
headers = {"Accept": "application/json",
"Client-ID": api_info['Client-ID'],
"Authorization": "OAuth " + auth_info}
api_response = requests.get(url, headers=headers)
json = api_response.json()
if 'streams' not in json:
return None
streams = ""
i = 0
while i < num_of_responses and i < len(json['streams']):
if streams != "":
streams = streams + ", "
streams = streams + json['streams'][i]['channel']['display_name']
i = i + 1
if not streams:
return 'no followed streams are live'
return streams
def twitch_game_top_streamers(num_of_responses, game):
api_info = get_twitch_api_info()
url = api_info['base_api_url'] + api_info['top_game_streams'].format(game)
headers = {"Accept": "application/json", "Client-ID": api_info['Client-ID']}
api_response = requests.get(url, headers=headers)
json = api_response.json()
streams = ""
for num in range(0, num_of_responses):
if num < len(json['streams']):
if streams != "":
streams = streams + ", "
streams = streams + json['streams'][num]['channel']['display_name']
if not streams:
return 'no streams are available'
return streams
def get_twitch_api_info():
api_info = {
"Client-ID": "fq5m7globoglp4zanbya8c4r5q8e1i",
"base_api_url": "https://api.twitch.tv/kraken/",
"top_streams": "streams",
"top_game_streams": "streams/?game={}",
"my_top_streams": "streams/followed"
}
return api_info
# --------------- Functions that modify behavior --------------------------------
def get_welcome_response(session):
if get_twitch_auth(session) is None:
return get_login_card()
session_attributes = {}
card_title = "Welcome to the My Twitch Streams Alexa Skill"
speech_output = "Welcome to the My Twitch streams skill. " \
"To get your available streams ask who is streaming. " \
"To get the top available streams ask what are the top streams. " \
"To get the top streams by game ask who is streaming League of Legends" \
.format(get_skill_invocation_name())
reprompt_text = None
should_end_session = False
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_end_response():
session_attributes = {}
card_title = None
speech_output = None
reprompt_text = None
should_end_session = True
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_top_streamers(session):
num_of_streams = 5
top_streamers = twitch_top_streamers(num_of_streams)
session_attributes = {}
card_title = "Top Twitch Streamers On Now"
speech_output = "Here are the top available streamers: {}".format(top_streamers)
reprompt_text = None
should_end_session = True
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_my_top_streamers(session):
num_of_streams = 5
auth_info = get_twitch_auth(session)
if auth_info is None:
return get_login_card()
my_top_streamers = twitch_my_top_streamers(num_of_streams, auth_info)
if my_top_streamers is None:
return get_login_card()
session_attributes = {}
card_title = "Your Twitch Streamers On Now"
speech_output = "Here are your top available streamers: {}".format(my_top_streamers)
reprompt_text = None
should_end_session = True
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_game_top_streamers(request, session):
num_of_streams = 5
game = get_twitch_game_name(request['intent']['slots']['Game']['value'])
if game is None:
return get_invalid_game_response()
streamers = twitch_game_top_streamers(num_of_streams, game)
session_attributes = {}
card_title = "Top Twitch Streamers On Now For {}".format(game)
speech_output = "Here are the top available streamers for {}: {}".format(game, streamers)
reprompt_text = None
should_end_session = True
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_invalid_game_response():
session_attributes = {}
card_title = "Unknown game"
speech_output = "Unknown game, please try again. Please note many games are not supported"
reprompt_text = None
should_end_session = False
return build_response(session_attributes,
build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))
def get_login_card():
session_attributes = {}
card_title = "Register With Twitch"
speech_output = "Thank you for using my twitch streams. " \
"Please register with your twitch account if you wish to get information about your followed streams. " \
"You can still get the top streams by asking what are the top streams, " \
"or get the top streams by game by asking who is streaming League of Legends" \
.format(get_skill_invocation_name())
reprompt_text = None
should_end_session = False
return build_response(session_attributes,
build_login_card_response(card_title, speech_output, reprompt_text, should_end_session))
def get_skill_invocation_name():
return "my twitch streams"
# ---------------------------- Events -------------------------------------------
def on_intent(request, session):
intent_name = request['intent']['name']
log_action("Intent ({})".format(intent_name), request, session)
if intent_name == "GetMyStreams":
return get_my_top_streamers(session)
elif intent_name == "GetTopStreams":
return get_top_streamers(session)
elif intent_name == "GetTopStreamsByGame":
return get_game_top_streamers(request, session)
elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
return get_end_response()
elif intent_name == "AMAZON.HelpIntent":
return get_welcome_response(session)
else:
print ("Invalid intent passed in: {}".format(intent_name))
raise ValueError("Invalid intent: " + intent_name)
def on_launch(request, session):
log_action("Launch", request, session)
return get_welcome_response(session)
def on_end(request, session):
log_action("End session", request, session)
return get_end_response()
# ---------------------------- Logging ------------------------------------------
def log_action(action, request, session):
print("{}: requestId={}, sessionId={}".format(action, request['requestId'], session['sessionId']))
# -------------------------- Main -----------------------------------------------
def lambda_handler(event, context):
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
# confirm the API call is from the expected skill
# if (event['session']['application']['applicationId'] !=
# "amzn1.ask.skill.d84e53f8-eec2-48fd-a22e-f31f16177f8c"):
# raise ValueError("Invalid Application ID")
if event['session']['new']:
log_action("New Session", event['request'], event['session'])
if event['request']['type'] == "LaunchRequest":
return on_launch(event['request'], event['session'])
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_end(event['request'], event['session'])
else:
raise ValueError("Invalid request: " + event['request']['type'])
# ------------------------- Game Name Conversion -----------------------
def get_twitch_game_name(game):
name_dict = {}
with open("twitchGameNameConversions.txt") as f:
for line in f:
(key, val) = line.split(",")
name_dict[key.lower().strip()] = val.strip()
if game.lower() in name_dict:
return name_dict[game.lower().strip()]
else:
return None
# -----------------------------------TTS Conversions-------------------------------------
def clean_return_for_TTS(toConvert):
if not toConvert:
return ''
temp = switch_names_for_TTS(toConvert)
toReturn = remove_underscore_for_TTS(temp)
return toReturn
def remove_underscore_for_TTS(toConvert):
return toConvert.replace("_"," ")
# This is to change the name of the streamer to a way that Alexa TTS will say it correctly
def switch_names_for_TTS(toConvert):
if toConvert is None:
return None
return_text = toConvert
conversion_dict = {}
with open("channelNameTTSConversion.txt") as f:
print 'reading in name conversion file'
for line in f:
(key, val) = line.split(",")
conversion_dict[key.strip()] = val.strip()
for display_name in conversion_dict:
if display_name in return_text:
return_text = return_text.replace(display_name, conversion_dict[display_name])
return return_text |
lianwutech/ws_plugin_xxx | devices/eq2008/eq2008.py | <gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
EQ2008库DLL的Ctypes封装
"""
from ctypes import *
from ctypes.wintypes import *
import win32con
import win32gui
from libs.winutils import RGB
# 定义结构
# 面板区域结构定义
class _StructPartInfo(Structure):
_fields_ = [('iX', c_int),
('iY', c_int),
('iWidth', c_int),
('iHeight', c_int),
('iFrameMode', c_int),
('FrameColor', COLORREF)]
def __str__(self):
return 'iX:%d, iY:%d, iWidth:%d, iHeight:%d, iFrameMode:%d, FrameColor:%d'.format(self.iX,
self.iY,
self.iWidth,
self.iHeight,
self.iFrameMode,
self.FrameColor)
# User_Bmp结构定义
class _StructUserBmp(Structure):
_fields_ =[('PartInfo', _StructPartInfo)]
def __str__(self):
return 'User_PartInfo:%s'.format(self.User_PartInfo)
# 节目控制
class _StructMoveSet(Structure):
_fields_ = [('iActionType', c_int),
('iActionSpeed', c_int),
('bClear', c_bool),
('iHoldTime', c_int),
('iClearSpeed', c_int),
('iClearActionType', c_int),
('iFrameTime', c_int)]
def __str__(self):
return """iActionType:%d, iActionSpeed:%d, bClear:%r, iHoldTime:%d, iClearSpeed:%d, iClearActionType:%d, iFrameTime:%d""".\
format(self.iActionType,
self.iActionSpeed,
self.bClear,
self.iHoldTime,
self.iClearSpeed,
self.iClearActionType,
self.iFrameTime)
# dll的配置文件
eq2008_ini = "devices/eq2008/EQ2008_Dll_Set.ini"
#加载API库
api = CDLL('devices/eq2008/EQ2008_Dll.dll')
#初始化函数的参数类型
# 添加节目
# DLL_API int __stdcall User_AddProgram(int CardNum,BOOL bWaitToEnd,int iPlayTime);
api.User_AddProgram.argtypes = [c_int, c_bool, c_int]
api.User_AddProgram.restype = c_int
# 添加图文区
# DLL_API int __stdcall User_AddBmpZone(int CardNum,User_Bmp *pBmp,int iProgramIndex);
api.User_AddBmpZone.argtypes = [c_ushort, _StructUserBmp, c_ushort]
api.User_AddBmpZone.restype = c_int
# DLL_API BOOL __stdcall User_AddBmp(int CardNum,int iBmpPartNum,HBITMAP hBitmap,User_MoveSet* pMoveSet,int iProgramIndex);
api.User_AddBmp.argtypes = [c_int, c_int, c_long, _StructMoveSet, c_int]
api.User_AddBmp.restype = c_bool
# DLL_API BOOL __stdcall User_AddBmpFile(int CardNum,int iBmpPartNum,char *strFileName,User_MoveSet* pMoveSet,int iProgramIndex);
api.User_AddBmpFile.argtypes = [c_int, c_int, c_char_p, _StructMoveSet, c_int]
api.User_AddBmpFile.restype = c_bool
# 删除节目
# DLL_API BOOL __stdcall User_DelProgram(int CardNum,int iProgramIndex);
api.User_DelProgram.argtypes = [c_int, c_int]
api.User_DelProgram.restype = c_bool
# 删除所有节目
# DLL_API BOOL __stdcall User_DelAllProgram(int CardNum);
api.User_DelAllProgram.argtypes = [c_int]
api.User_DelAllProgram.restype = c_bool
# 发送数据
# DLL_API BOOL __stdcall User_SendToScreen(int CardNum);
api.User_SendToScreen.argtypes = [c_int]
api.User_SendToScreen.restype = c_bool
# 发送节目文件和索引文件
# DLL_API BOOL __stdcall User_SendFileToScreen(int CardNum,char pSendPath[MAX_PATH],char pIndexPath[MAX_PATH]);
api.User_SendFileToScreen.argtypes = [c_int, c_char_p, c_char_p]
api.User_SendFileToScreen.restype = c_bool
# 开机
# DLL_API BOOL __stdcall User_OpenScreen(int CardNum);
api.User_OpenScreen.argtypes = [c_int]
api.User_OpenScreen.restype = c_bool
# 关机
# DLL_API BOOL __stdcall User_CloseScreen(int CardNum);
api.User_CloseScreen.argtypes = [c_int]
api.User_CloseScreen.restype = c_bool
# 校正板卡的时间
# DLL_API BOOL __stdcall User_AdjustTime(int CardNum);
api.User_AdjustTime.argtypes = [c_int]
api.User_AdjustTime.restype = c_bool
# 实时发送数据
# DLL_API BOOL __stdcall User_RealtimeConnect(int CardNum); //建立连接
api.User_RealtimeConnect.argtypes = [c_int]
api.User_RealtimeConnect.restype = c_bool
# 发送数据
# DLL_API BOOL __stdcall User_RealtimeSendData(int CardNum,int x,int y,int iWidth,int iHeight,HBITMAP hBitmap);
api.User_RealtimeSendData.argtypes = [c_int, c_int, c_int, c_int, HBITMAP]
api.User_RealtimeSendData.restype = c_bool
# 断开连接
# DLL_API BOOL __stdcall User_RealtimeDisConnect(int CardNum);
api.User_RealtimeDisConnect.argtypes = [c_int]
api.User_RealtimeDisConnect.restype = c_bool
def open_screan(card_num):
result = api.User_OpenScreen(c_int(card_num))
return result.value
# 直接发送BMP图片到LED
def send_bmp_to_led(card_num, height, weight, bmp_file):
c_card_num = c_int(card_num)
c_bmp_file = c_char_p(bmp_file)
c_program_index = api.User_AddProgram(c_card_num)
if c_program_index == 0:
return False
# 初始化区域
c_bmp_zone = _StructUserBmp()
c_bmp_zone.PartInfo.iX = c_int(0)
c_bmp_zone.PartInfo.iY = c_int(0)
c_bmp_zone.PartInfo.iWidth = c_int(weight)
c_bmp_zone.PartInfo.iHeight = c_int(height)
c_bmp_zone.PartInfo.iFrameMode = c_int(0xFF00)
c_bmp_zone.PartInfo.FrameColor = COLORREF(RGB(0x00, 0xFF, 0x00))
# 初始化图形移动设置
c_move_set = _StructMoveSet()
c_move_set.iActionType = c_int(0)
c_move_set.iActionSpeed = c_int(4)
c_move_set.bClear = c_bool(True)
c_move_set.iHoldTime = c_int(50)
c_move_set.iClearSpeed = c_int(4)
c_move_set.iClearActionType = c_int(4)
c_move_set.iFrameTime = c_int(20)
# iBMPZoneNum = User_AddBmpZone(g_iCardNum, ref BmpZone, g_iProgramIndex);
c_bmp_zone_num = api.User_AddBmpZone(c_card_num, byref(c_bmp_zone), c_program_index)
# if (false == User_AddBmpFile(g_iCardNum, iBMPZoneNum, strBmpFile, ref MoveSet, g_iProgramIndex))
if False == api.User_AddBmpFile(c_card_num, c_bmp_zone_num, c_bmp_file, byref(c_move_set), c_program_index):
return False
# Bitmap bmp = new Bitmap(pictureBox2.Image,BmpZone.PartInfo.iWidth ,BmpZone.PartInfo.iHeight);
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
h_bitmap = win32gui.LoadImage(0, c_bmp_file, win32con.IMAGE_BITMAP, 0, 0, icon_flags)
# if (false == User_AddBmp(g_iCardNum, iBMPZoneNum,bmp.GetHbitmap() ,ref MoveSet, g_iProgramIndex))
if -1 == api.User_AddBmp(c_card_num, c_bmp_zone_num, h_bitmap, byref(c_move_set), c_program_index):
return False
# 发送数据
# if(User_SendToScreen(m_iCardNum)==FALSE)
result = api.User_SendToScreen(c_card_num)
return result.value
|
lianwutech/ws_plugin_xxx | plugin.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
modbus网络的串口数据采集插件
1、device_id的组成方式为ip_port_slaveid
2、设备类型为0,协议类型为modbus
3、devices_info_dict需要持久化设备信息,启动时加载,变化时写入
4、device_cmd内容:json字符串
"""
import time
from setting import *
from libs.plugin import *
from libs.mqttclient import MQTTClient
# 全局变量
devices_file_name = "devices.txt"
config_file_name = "plugin.cfg"
# 日志对象
logger = logging.getLogger('plugin')
# 配置信息
config_info = load_config(config_file_name)
# 停止标记
run_flag = False
def plugin_stop():
"""
插件停止
:return:
"""
run_flag = False
def plugin_run():
"""
插件运行主函数
:return:
"""
# 连接mqtt
# 连接设备
#
run_flag = True
# 切换工作目录
os.chdir(cur_file_dir())
if "device_type" not in config_info \
or "mqtt" not in config_info \
or "device" not in config_info \
or "protocol" not in config_info:
logger.fatal("配置文件配置项不全,启动失败。")
return
device_type = config_info["device_type"]
network_name = config_info["network_name"]
# 获取Device类对象
device_class = load_device(device_type)
# 参数检查
if device_class.check_config(config_info["device"]) \
and MQTTClient.check_config(config_info["mqtt"]):
logger.debug("参数检查通过。")
else:
logger.fatal("device、protocol、mqtt参数配置项错误,请检查.")
return
# 此处需注意启动顺序,先创建mqtt对象,然后创建device对象,mqtt对象设置device属性,mqtt才能够链接服务器
# 1、初始化mqttclient对象
mqtt_client = MQTTClient(config_info["mqtt"], network_name)
result = mqtt_client.connect()
if not result:
logger.fatal("mqtt connect fail.")
return
# 3、初始化device对象
device = device_class(config_info["device"], devices_file_name, mqtt_client, network_name)
# 4、mqtt设置通道对象
mqtt_client.set_device(device)
while True:
if not device.isAlive():
logger.info("device进程停止,重新启动。")
device.start()
if not mqtt_client.isAlive():
logger.info("mqtt进程停止,重新启动。")
mqtt_client.start()
logger.debug("周期处理结束")
time.sleep(2)
|
lianwutech/ws_plugin_xxx | test/test_svg_to_bmp.py | <reponame>lianwutech/ws_plugin_xxx
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import time
import json
import cairo
import rsvg
from PIL import Image
def convert_svg_to_png(svg_file_name, png_file_name):
file_svg = open(svg_file_name)
svg_data = file_svg.read()
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
ctx = cairo.Context(img)
## handle = rsvg.Handle(<svg filename>)
# or, for in memory SVG data:
handle = rsvg.Handle(None, str(svg_data))
handle.render_cairo(ctx)
img.write_to_png(png_file_name)
def convert_png_to_bmp(png_file_name, bmp_file_name):
img_png = Image.open(png_file_name)
try:
# 使用白色来填充背景 from:www.sharejs.com
# (alpha band as paste mask).
length_x, length_y = img_png.size
img = Image.new('RGBA', img_png.size, (255, 255, 255))
img.paste(img_png, (0, 0, length_x, length_y), img_png)
img.save("new_test.png")
new_img = Image.open("new_test.png")
# 转换成RGBA格式
new_img.convert("RGBA")
# 分割成RGBA,然后重新组合
lenght = len(new_img.split())
if len(new_img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = new_img.split()
new_img = Image.merge("RGB", (r, g, b))
new_img.save(bmp_file_name)
else:
new_img.save(bmp_file_name)
print "convert success."
except Exception,e :
print "exception: %r" % e
svg_file_name = "test.svg"
png_file_name = "test.png"
bmp_file_name = "test.bmp"
convert_svg_to_png(svg_file_name, png_file_name)
convert_png_to_bmp(png_file_name, bmp_file_name)
|
lianwutech/ws_plugin_xxx | libs/winutils.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import json
def RGB(r, g, b):
"""
COLORREF 映射
COLORREF is a typedef to DWORD, not a structure.
All RGB macro does is some bitshifting to get 0x00bbggrr value.
:param r: red
:param g: green
:param b: blue
:return:
"""
r = r & 0xFF
g = g & 0xFF
b = b & 0xFF
return (b << 16) | (g << 8) | r
|
lianwutech/ws_plugin_xxx | devices/led_eq2008.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
LER EQ2008设备类
EQ2008设备协议。
参数配置说明:
device_id和cardnum的对应关系
如:
"device": {
“device_1”: 0,
"device_2": 1
}
"""
import os
import time
import json
import logging
from Jinja2 import Template
import cairo
import rsvg
from PIL import Image
from libs.base_device import BaseDevice
from devices.eq2008 import eq2008
logger = logging.getLogger('plugin')
class LEDQE2008Device(BaseDevice):
def __init__(self, device_params, devices_file_name, mqtt_client, network_name):
BaseDevice.__init__(self, device_params, devices_file_name, mqtt_client, network_name)
# 配置项
self.server = device_params.get("server", "")
self.port = device_params.get("port", 0)
self.card_num = device_params.get("card_num", 0)
self.height = device_params.get("height", 0)
self.weight = device_params.get("weigth", 0)
self.svg_file_template = device_params.get("svg_file_template", "")
self.mqtt_client = mqtt_client
# 打开屏幕
eq2008.api.User_OpenScreen(self.card_num)
@staticmethod
def check_config(device_params):
if "server" not in device_params or "port" not in device_params:
return False
return BaseDevice.check_config(device_params)
def run(self):
# 首先上报设备数据
for device_id in self.devices_info_dict:
device_info = self.devices_info_dict[device_id]
device_msg = {
"device_id": device_info["device_id"],
"device_type": device_info["device_type"],
"device_addr": device_info["device_addr"],
"device_port": device_info["device_port"],
"protocol": "",
"data": ""
}
self.mqtt_client.publish_data(device_msg)
# 后续没有任何处理
return
def process_cmd(self, device_cmd_msg):
device_id = device_cmd_msg.get("device_id", "")
device_cmd = device_cmd_msg["command"]
if device_id in self.devices_info_dict:
device_info = self.devices_info_dict[device_id]
else:
logger.error("不支持的modbus指令:%r" % device_cmd)
return
# device_cmd为字符串
output_data = json.loads(device_cmd)
# 判断文件是否存在
if not os.path.exists(self.svg_file_template):
logger.error("svg template file(%s) not exist." % "")
return
# 根据配置项打开svg模版文件并基于模版文件和数据生成svg文件
file_svg_template = open(self.svg_file_template)
template_content = file_svg_template.read()
svg_template = Template(template_content)
svg_content = svg_template.render(output_data)
svg_img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640, 480)
ctx = cairo.Context(svg_img)
handle = rsvg.Handle(None, str(svg_content))
# svg文件生成png
png_file_name = "%r.png" % device_id
handle.render_cairo(ctx)
svg_img.write_to_png(png_file_name)
# png文件增加白色背景
new_png_file_name = "new_%r.png" % device_id
png_img = Image.open(png_file_name)
length_x, length_y = png_img.size
white_bg_img = Image.new('RGBA', png_img.size, (255, 255, 255))
white_bg_img.paste(png_img, (0, 0, length_x, length_y), png_img)
white_bg_img.save(new_png_file_name)
# png文件生成bmp
bmp_file_name = "%r.bmp" % device_id
new_png_img = Image.open(new_png_file_name)
# 转换成RGBA格式
new_png_img.convert("RGBA")
# 分割成RGBA,然后重新组合
lenght = len(new_png_img.split())
if len(new_png_img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = new_png_img.split()
bmp_img = Image.merge("RGB", (r, g, b))
bmp_img.save(bmp_file_name)
else:
new_png_img.save(bmp_file_name)
# bmp文件输出到LED
try:
result = eq2008.send_bmp_to_led(self.card_num, self.height, self.weight, bmp_file_name)
if result:
logger.debug("outpu bmp %s success." % bmp_file_name)
else:
logger.debug("outpu bmp %s fail." % bmp_file_name)
except Exception, e:
logger.error("send_bmp_to_led exception: %r" % e)
def isAlive(self):
return True |
lianwutech/ws_plugin_xxx | PluginService.py | <gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import win32serviceutil
import win32service
import win32event
import os
import logging
import inspect
from setting import *
import plugin
class PluginService(win32serviceutil.ServiceFramework):
_svc_name_ = ""
_svc_display_name_ = "Jambu Plugin Service"
_svc_description_ = "This is a plugin service of Jambu, run as a windows service."
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.logger = self._getLogger()
def _getLogger(self):
logger = logging.getLogger('[PluginService]')
this_file = inspect.getfile(inspect.currentframe())
dirpath = os.path.abspath(os.path.dirname(this_file))
handler = logging.FileHandler(os.path.join(dirpath, "plugin_service.log"))
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
def SvcDoRun(self):
import time
self.logger.info("plugin service is run....")
plugin.plugin_run()
def SvcStop(self):
self.logger.info("plugin service is stop....")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
plugin.plugin_stop()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(PluginService)
|
lianwutech/ws_plugin_xxx | setting.py | <reponame>lianwutech/ws_plugin_xxx<gh_stars>0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import logging
import logging.config
from libs.utils import *
# 设置系统为utf-8 勿删除
reload(sys)
sys.setdefaultencoding('utf-8')
# 程序运行路径
# 工作目录切换为python脚本所在地址,后续成为守护进程后会被修改为'/'
procedure_path = cur_file_dir()
os.chdir(procedure_path)
# 通过工作目录获取当前插件名称
plugin_name = procedure_path.split("/")[-1]
# 创建日志目录
mkdir("logs")
# 加载logging.conf
logging.config.fileConfig('logging.conf')
|
HTGoldston/sweepstakes_starter | main.py | <gh_stars>0
from contestant import Contestant
if __name__ == "__main__":
print_contsatant_info(contestant): pass
contestants = {
} |
HTGoldston/sweepstakes_starter | sweepstakes_queue_manager.py | from sweepstake import Sweepstake
class Sweepstakes_Queue_Manager:
def __init__(self, queue):
self.sweepstakes_stack_manager = Sweepstakes_Queue_Manager
self.queue = queue
def insert_sweepstakes(sweepstakes): pass
def get_sweepstakes(): Sweepstake |
HTGoldston/sweepstakes_starter | marketing_firm_creator.py |
class Marketing_Firm_Creator:
def __init__(self, choose_manager_type):
self.marketing_firm_creator = Marketing_Firm_Creator
self.choose_manager_type = choose_manager_type
def choose_manager_type(marketing_firm):
pass |
HTGoldston/sweepstakes_starter | sweepstake.py | import random
class Sweepstake:
def __init__(self, contestants, name):
self.sweepstake = Sweepstake
self.contestants = contestants
#keypairs key and value Dictionary
def pick_winner(self): pass #.random
def register_contestant(self): pass
# register_contestant(contestant): pass
# .random with Tuple
def pick_winner(): pass
#print_contstant_info(contstant): pass see user_interface |
HTGoldston/sweepstakes_starter | contestant.py | <filename>contestant.py
from sweepstake import Sweepstake
class Contestant(Sweepstake):
def __init__(self):
self.contestant = Contestant
super(Contestant, self).__init__((self, self.first_name, self.last_name, self.email_address,
self.registration_number))
self.first_name = input("first_name")
self.last_name = input("last_name")
self.email_address = input("email_address")
self.registration_number = 1 <= 10
|
HTGoldston/sweepstakes_starter | sweepstakes_stack_manager.py | <reponame>HTGoldston/sweepstakes_starter
class Sweepstakes_Stack_Manager:
def __init__(self, stack):
self.sweepstakes_stack_manager = Sweepstakes_Stack_Manager
self.stack = stack
def insert_sweepstakes(sweepstakes): pass
def get_sweepstakes(): Sweepstake |
HTGoldston/sweepstakes_starter | marketing_firm.py | <filename>marketing_firm.py
class Marketing_Firm:
def __init__(self, manager):
self.marketing_firm = Marketing_Firm
self.manager = manager
def create_sweepstakes(self): pass
|
HTGoldston/sweepstakes_starter | user_interface.py | <reponame>HTGoldston/sweepstakes_starter
from contestant import Contestant
class User_Interface:
def __init__(self):
self.user_interface = User_Interface
def register(self=None):
self.register(self, Contestant)
def print_contestant_info ([Contestant]):
print_contstant_info(contstant): pass
|
Conight/Go-LibDucoHasher | client_sample.py | from ctypes import cdll, Structure, c_char_p, c_longlong, c_double
lib = cdll.LoadLibrary('/path/to/shared/main.so')
class GoString(Structure):
_fields_ = [('p', c_char_p), ('n', c_longlong)]
class Return(Structure):
_fields_ = [
('r0', c_longlong),
('r1', c_double),
]
# DUCOS1
lib.DUCOS1.argtypes = [GoString, GoString, c_longlong, c_double]
lib.DUCOS1.restype = Return
# DUCOS1Nonce
lib.DUCOS1Nonce.argtypes = [GoString, GoString, c_longlong, c_double]
lib.DUCOS1Nonce.restype = c_longlong
def DUCOS1Nonce(
last_h: str, exp_h: str, diff: int, eff: float,
):
last_h = GoString(last_h.encode(), 40)
exp_h = GoString(exp_h.encode(), 40)
r = lib.DUCOS1Nonce(
last_h,
exp_h,
diff,
eff,
)
return r
def DUCOS1(
last_h: str, exp_h: str, diff: int, eff: float,
):
last_h = GoString(last_h.encode(), 40)
exp_h = GoString(exp_h.encode(), 40)
r = lib.DUCOS1(
last_h,
exp_h,
diff,
eff,
)
return r.r0, r.r1
if __name__ == '__main__':
last_h: str = 'f316f4cd012371b15da767fa66c6c7478bf9593e'
exp_h: str = '98ce69810af441b69971eec6ba4d87b766bf0213'
diff: int = 500000
eff: float = 0.005
print(DUCOS1(last_h, exp_h, diff, eff))
print(DUCOS1Nonce(last_h, exp_h, diff, eff))
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/hbar/migrations/0001_initial.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['hbar'] |
RacingTadpole/cmsplugin-rt | cmsplugin_rt/self_calc_pagination/templatetags/descendant_selected.py | from django import template
register = template.Library()
@register.assignment_tag
def descendant_selected(node):
"""Returns true if this node or a descendant of it is selected.
Use as e.g.: {% if descendant_selected node %}
"""
if node.selected:
return True
for child in node.children:
if descendant_selected(child):
return True
return False
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/text_minimal_markup/cms_plugins.py | <reponame>RacingTadpole/cmsplugin-rt
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class TextMinimalMarkupPlugin(CMSPluginBase):
model = TextMinimalMarkupPluginModel
name = _("Text with some markup")
# module = generic_module_name
render_template = "text_minimal_markup_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
return context
plugin_pool.register_plugin(TextMinimalMarkupPlugin)
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/style_modifier/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class StyleModifierPlugin(CMSPluginBase):
model = StyleModifierPluginModel
name = _("Style Modifier")
module = layout_module_name
render_template = "style_modifier.html"
def render(self, context, instance, placeholder):
# we display three fields without escaping, so we can use ", ' and >
# but we try to ensure string cannot include any tags by removing <
# we also remove any refs to script or expression
# this is not a comprehensive solution!
instance.mod_class = instance.mod_class.replace(u'<',u'')
instance.freeform = instance.freeform.replace(u'<',u'')
instance.font_family = instance.font_family.replace(u'<',u'')
instance.mod_class = instance.mod_class.replace(u'script',u'x')
instance.freeform = instance.freeform.replace(u'script',u'x')
instance.font_family = instance.font_family.replace(u'script',u'x')
instance.mod_class = instance.mod_class.replace(u'expression',u'x')
instance.freeform = instance.freeform.replace(u'expression',u'x')
instance.font_family = instance.font_family.replace(u'expression',u'x')
context['instance'] = instance
return context
plugin_pool.register_plugin(StyleModifierPlugin)
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/resizeable_picture/cms_plugins.py | <reponame>RacingTadpole/cmsplugin-rt<filename>cmsplugin_rt/resizeable_picture/cms_plugins.py
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
from cms.plugins.picture.cms_plugins import PicturePlugin
class ResizeablePicturePlugin(PicturePlugin):
model = ResizeablePicturePluginModel
name = _("Resizable Picture")
#module = generic_module_name
render_template = "resizeable_picture_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
if instance.img_width.endswith("%"):
context["width_percent"] = instance.img_width
else:
context["width"] = instance.img_width
if instance.img_height.endswith("%"):
context["height_percent"] = instance.img_height
else:
context["height"] = instance.img_height
# to make the user's usage of max_width consistent with width,
# we add px to it if needed here
if instance.img_max_width.endswith("%"):
context["max_width"] = instance.img_max_width
elif instance.img_max_width:
context["max_width"] = instance.img_max_width+"px"
if instance.img_max_height.endswith("%"):
context["max_height"] = instance.img_max_height
elif instance.img_max_height:
context["max_height"] = instance.img_max_height+"px"
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(ResizeablePicturePlugin)
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/button/forms.py | <gh_stars>1-10
from django.forms.models import ModelForm
from django.utils.translation import ugettext_lazy as _
from .models import ButtonPluginModel
from django import forms
from cms.models import Page
class ButtonForm(ModelForm):
page_link = forms.ModelChoiceField(label=_("page"),
queryset=Page.objects.drafts(),
help_text=_("A link to a page overrides the above button link."),
required=False)
class Meta:
model = ButtonPluginModel
exclude = ('page', 'position', 'placeholder', 'language', 'plugin_type') |
RacingTadpole/cmsplugin-rt | cmsplugin_rt/button_appstore/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
class ButtonAppstorePlugin(CMSPluginBase):
model = ButtonAppstorePluginModel
name = _("App Store Button")
render_template = "button_appstore_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonAppstorePlugin)
|
RacingTadpole/cmsplugin-rt | cmsplugin_rt/mailchimp_form/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.models import CMSPlugin
from cms.plugin_pool import plugin_pool
from cmsplugin_mailchimp import models
from django.utils.translation import ugettext_lazy as _
class BasePlugin(CMSPluginBase):
name = None
module = _("Social Networking")
def render(self, context, instance, placeholder):
context.update({'instance': instance, 'name': self.name})
return context
class MailChimpPlugin(BasePlugin):
model = models.MailChimpPluginModel
name = "Mailchimp form"
render_template = 'mailchimp_form_plugin.html'
plugin_pool.register_plugin(MailChimpPlugin)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.