blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
1e07be35a858fc399900eb54d6cc0dcdfb0f3ccf
c7979f4f6435fe8d0d07fff7a430da55e3592aed
/test.py
0085787c62ee273653b9670e76a27096a30e9b1b
[]
no_license
banboooo044/AtCoder
cee87d40bb98abafde19017f4f4e2f984544b9f8
7541d521cf0da848ecb5eb10ffea7d75a44cbbb6
refs/heads/master
2020-04-14T11:35:24.977457
2019-09-17T03:20:27
2019-09-17T03:20:27
163,818,272
0
0
null
null
null
null
UTF-8
Python
false
false
619
py
def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) for i in combinations(range(5),3): print(i)
[ "touhoucrisis7@gmail.com" ]
touhoucrisis7@gmail.com
7185c8542f411f88a48c7e3f01fcf4055e55fab8
0d0bb746d73cff020d30a774dd59e7fd08537bee
/ProblemA.py
10b0f3011b49e3e82627cd7b6b236fb1d0299c1c
[]
no_license
stephypy/CS2302_LAB5
c629aa5c124b1124ffb89087e17ef6f1f46a75ff
a908256316826ee2fcd42ff8b923fec9dad3ebb7
refs/heads/master
2020-09-10T22:49:03.272304
2019-11-22T23:09:29
2019-11-22T23:09:29
221,856,608
0
0
null
null
null
null
UTF-8
Python
false
false
2,126
py
class Node: def __init__(self, val): self.val = val self.next = None self.prev = None class DLL: def __init__(self): self.head = None self.tail = None self.size = 0 # Wil always insert at the head def insert(self, val): if val is None: raise Exception('Invalid new value') new_node = Node(val) if self.head is None: self.head = self.tail = new_node else: self.head.prev = new_node new_node.next = self.head self.head = new_node self.size += 1 def delete_last(self): if self.size == 0: raise Exception('Doubly Linked List is empty') if self.size == 1: self.head = self.tail = None self.size = 0 return new_tail = self.tail.prev new_tail.next = None self.tail = new_tail self.size -= 1 class LRU: def __init__(self, maximum): self.cache_values = {} self.cache = DLL() self.maximum = maximum def get(self, key): if key not in self.cache_values: return -1 return self.cache_values[key] def put(self, key, value): if self.size() < self.max_capacity(): self.cache_values[key] = value self.cache.insert(key) else: lru = self.cache.tail.val self.cache.delete_last() self.cache_values.pop(lru) self.cache_values[key] = value self.cache.insert(key) def size(self): return self.cache.size def max_capacity(self): return self.maximum def print_lru(self): curr = self.cache.head while curr is not None: print('key: ', curr.val, 'val: ', self.get(curr.val)) curr = curr.next def main(): lru = LRU(5) for i in range(1, 5): lru.put(i, i*2) lru.print_lru() print('') lru.print_lru() lru.put(5, 10) print('') lru.print_lru() lru.put(6, 12) print('') lru.print_lru() main()
[ "noreply@github.com" ]
stephypy.noreply@github.com
44ffa1fa89ef37026f245298617c83abca0ad872
15dc2e69defdde688acc20467c7bfd65ff553cef
/代理.py
f2c97d418848621608c66fe9124512b11c201d2a
[]
no_license
Jizishuo/Spider-play
6bbd67aa706ef1c87f9dd9afa4e95fe32ddd5e46
262a30aa0b92e00d6639c3abb6790c948def2cd1
refs/heads/master
2020-04-07T05:12:07.941873
2018-11-18T13:36:00
2018-11-18T13:36:00
158,087,044
0
0
null
null
null
null
UTF-8
Python
false
false
1,466
py
import requests #无验证代理 prexir_dict = { 'http':'代理一', 'https':'代理2', 'https/wwww.7777':'代理3', } ret = requests.get(url='',proxies=prexir_dict) #验证代理 prexir_dict2 = { 'http':'代理一', 'https':'代理2', 'https/wwww.7777':'代理3', } from requests.auth import HTTPProxyAuth auth = HTTPProxyAuth('用户名','密码') ret2 = requests.get( url='', proxies=prexir_dict, auth=auth ) #文件上传 (定制文件名) file_dict = { 'f1':('text.txt', open('xxx', 'rb')), } requests.post(url='', files=file_dict) #无页面验证(类似路由器)(浏览器做的) 加密用户名密码放请求头 给后台 #请求头 'Authorization : 'basic base64(用户名:密码)' from requests.auth import HTTPBasicAuth, HTTPDigestAuth ret3 = requests.get(url='', auth=HTTPBasicAuth('用户名', '密码')) #超时 timeout #重定向 allow_redirects requests.get(url='', allow_redirects=False) #大文件下载 stream(一点一点取) from contextlib import closing with closing(requests.get(url='', stream=True)) as r: for i in r.iter_content(): print(i) i.write() #携带自定义正书 cert requests.get(url='', cert='xx/xxx/xx.pem') #证书加密 前边证书,后边秘钥 requests.get(url='', cert=('xx/xxx/xx.pem', 'xxx/xxx/xxx.key')) #证书确认 verify=False #request 的 session (自动保存cooikes)
[ "948369894@qq.com" ]
948369894@qq.com
23b1ca144ba941c268e996dae75bfb6915124788
e6dab5aa1754ff13755a1f74a28a201681ab7e1c
/.parts/lib/django-1.4/django/contrib/localflavor/mk/models.py
cf5659ffbc189b781726f7734eaf7bbe4ae7ddbd
[]
no_license
ronkagan/Euler_1
67679203a9510147320f7c6513eefd391630703e
022633cc298475c4f3fd0c6e2bde4f4728713995
refs/heads/master
2021-01-06T20:45:52.901025
2014-09-06T22:34:16
2014-09-06T22:34:16
23,744,842
0
1
null
null
null
null
UTF-8
Python
false
false
105
py
/home/action/.parts/packages/googleappengine/1.9.4/lib/django-1.4/django/contrib/localflavor/mk/models.py
[ "ron.y.kagan@gmail.com" ]
ron.y.kagan@gmail.com
5d889094c96bb0e4abfa38cb283c4e2bab8f5c03
72a4273e0e7ba0a50cbf1f113411266e4a4c8b82
/blog/functions.py
afd59dfbfb05a3ac4cbac1d8e60c711661159ed9
[]
no_license
Metajake/nicemurals
2e9ff201c681056bdc040cc929bab2cea9c6b6f6
4a70911ff264ebde4fe9f0b5e5bc4b9521a3ed7f
refs/heads/master
2022-12-10T12:43:12.426804
2020-01-29T14:10:14
2020-01-29T14:10:14
195,178,506
0
0
null
2022-12-08T03:30:45
2019-07-04T06:04:01
CSS
UTF-8
Python
false
false
2,685
py
from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.conf import settings import random import tweepy, requests, inspect from blog.models import Entry, Config blogOptions = { 'homeAnchorIcons' : [ ('fas', 'fa-car-side'), ('fas', 'fa-blind'), ('fas', 'fa-car-crash'), ('fas', 'fa-baby-carriage'), ('fas', 'fa-people-carry'), ('fas', 'fa-truck-pickup'), ('fas', 'fa-dolly'), ('fab', 'fa-accessible-icon'), ], 'favIcons' : ['cone', 'cube', 'elipse', 'diamond', 'trapezoid', 'trapezoid2', 'star', 'star2', 'star3',], } def getBlogBaseProperties(): config = Config.objects.get(pk=1) toReturn = { 'entry_sort_type' : 'columns' if config.entry_sorting == 'columns' else 'tile', 'home_icon': random.choice(blogOptions['homeAnchorIcons']), 'favicon': random.choice(blogOptions['favIcons']), 'language':random.choice(['ja','en']), 'config': config, } return toReturn #THIS GETS FIRED WHETHER YOU SAVE AN ENTRY FROM THE ADMIN OR FROM THIS FILE LINE 28 (HITTING THE TEMPLATE TWEET BUTTON) @receiver(pre_save, sender=Entry) def incrementTweetVersion(sender, instance, **kwargs): instance.tweet_version = instance.tweet_version + 1 @receiver(post_save, sender=Entry) def tweetEntryLink(sender, instance, **kwargs): auth = tweepy.OAuthHandler('wqZDVmeQ0LRjIPblT5N8ZxAQ6', 'SPrk2ifNUZ5SGK6EV04MW41hmKp5yxjDw58In3oAJ4zHEZydoV') auth.set_access_token('995766360-5x2RE1NhbEfmzM2hbAuV4vyet4fAqQ1m0FVpQCgY', '8xLHNA40eDYK7vP6SZXqleAPCwNUNcQLN8Jdpxcdrul8L') api = tweepy.API(auth) #Hack: Check if Instance has title property (in other words, check if it's a Real Django Database Class instance (not an ajax object)) try: myStatusText = instance.title + " v" + str(instance.tweet_version) + ' http://firststudio.co/entry/'+instance.slug except AttributeError: e = Entry.objects.get(title=instance['title']) e.save( update_fields=['tweet_version'] ) myStatusText = instance['title'] + " v" + str(instance['tweet_version']) + ' http://firststudio.co/entry/'+instance['slug'] try: if settings.DEBUG == False: if instance.fire_laser: api.update_status(status=myStatusText) except: print("ERROR TWEETING") pass def getEmptyRowCount(totalEntries, rowTotalCount): if totalEntries < rowTotalCount: emptyCards = rowTotalCount - totalEntries #to fill in template row else: emptyCards = rowTotalCount - (totalEntries % rowTotalCount) #to fill in template row return emptyCards
[ "jaynoco@gmail.com" ]
jaynoco@gmail.com
7e0abbfbb0cd97126cfbd2b4d8a25b41051f0740
cb9ae0bd4c93de3f5f3a40c3917129c788a61373
/153Q13.py
e28d5bd4a9a70f7a58552f1b65b9f5eaea6a7dc6
[]
no_license
ParulProgrammingHub/assignment-1-Trushti
80065fea651efa8c6076fcc2afd0701b0d77804d
17397a3a4d5ebf63e36cda4eaabacd1fc827d7b3
refs/heads/master
2021-01-22T05:58:01.000344
2017-02-13T15:52:37
2017-02-13T15:52:37
81,725,055
0
0
null
null
null
null
UTF-8
Python
false
false
78
py
n=input("Enter n") if(n%2==0):print("%s is even"%n) else:print("%s is odd"%n)
[ "noreply@github.com" ]
ParulProgrammingHub.noreply@github.com
3c56ed2e2f07c7a457406633dd157748174e5323
a21b40dc7c5c7b77e63b8b035a10b10eee52ccf9
/databaseConnection.py
52bdb64de096e5070f4f897d1f4077a80431aaaa
[]
no_license
pecey/shortify
ef6785012593580cfd136bd4c2d0c6bdb647b78b
1e1578c8eb0605ea4efc1c65ab46dd8bb1ce2e8c
refs/heads/master
2021-07-12T15:32:45.976148
2018-10-26T01:42:29
2018-10-26T01:42:29
46,062,129
0
0
null
2021-03-19T21:54:00
2015-11-12T15:30:52
Python
UTF-8
Python
false
false
1,122
py
import redis def connect(server="127.0.0.1", port=6379, db=0, password=None): connection = {} connection['Status'] = None connection['Data'] = None try: connectionString = redis.StrictRedis(host=server, port=port, db=db, password=password, charset="utf-8") connection['Status'] = True connection['Data'] = connectionString except: connection['Status'] = False connection['Data'] = "There was an error in connecting to the Redis server." finally: return connection def insert(connectionString, key, value): response = {} response['Status'] = None response['Data'] = None if connectionString.exists(key): response['Status'] = False response['Data'] = "Key is already set." else: connectionString.set(key,value) response['Status'] = True response['Data'] = "Data inserted." return response def query(connectionString, key): response = {} response['Status'] = None response['Data'] = None if connectionString.exists(key): response['Status'] = True response['Data'] = connectionString.get(key) else: response['status'] = False response['Data'] = "Key not set." return response
[ "palash@protonmail.ch" ]
palash@protonmail.ch
76068c5dd2a452b6c43aa8f71c3d870c39ac7b40
be08b95d4c381a99299be9686daf613f0ac78fdf
/part1_3th_list/practice3_2.py
36023a4ad0b1d00d4192c48d1191d28dc77c6c82
[]
no_license
LHB6540/Python_programming_from_entry_to_practice_code_demo
433dca09707a473fa908a419b7da4452e206441f
9ed6167a94301ab5d9ddc8b7446da2ac18dafdd8
refs/heads/master
2023-02-17T09:53:13.766324
2021-01-20T05:51:45
2021-01-20T05:51:45
293,476,027
0
0
null
null
null
null
UTF-8
Python
false
false
381
py
# 继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名 names = ["bai", "zhu", "ye", "zhang"] print("Hello,my good friend "+names[0]) print("Hello,my good friend "+names[1]) print("Hello,my good friend "+names[2]) print("Hello,my good friend "+names[3])
[ "lhb@lhbdeMacBook-Pro.local" ]
lhb@lhbdeMacBook-Pro.local
16632db9c0a34de250399322e67794aff341e3c9
479cfc7426246570cc9eb70da291bd8461943f2f
/DSUM/apps.py
eacfbfa94506dfa5627a2ae5695cbd4851d9875f
[]
no_license
john9803/Excurri_Web_Project
54f180874f8da6dd91862fd2082c34a615fa1858
bfe4b6f82c40280a1dcfabfb898d7769018e9234
refs/heads/master
2023-06-09T19:39:12.517790
2021-06-25T07:05:01
2021-06-25T07:05:01
299,186,241
0
0
null
null
null
null
UTF-8
Python
false
false
83
py
from django.apps import AppConfig class DsumConfig(AppConfig): name = 'DSUM'
[ "john9803@likelion.org" ]
john9803@likelion.org
c3c63b6f512a3edb63e011f7bcce142b2873a78d
efb8721ea4d05894216f8b62929a22cd53bb6388
/day18/p2.py
523ce7f91fefa0fa7575f36fb8429487f96ca772
[]
no_license
dangor/advent-of-code-2020
1c8f5fe5f3fa792cc56aaa2c266c135bf2cb1631
1860b6fefbb7e8bd6dc96a846070d4959b8d4ce4
refs/heads/master
2023-02-05T01:51:02.104591
2020-12-25T22:10:24
2020-12-25T22:10:24
317,695,742
0
0
null
null
null
null
UTF-8
Python
false
false
1,176
py
def run(inputfile): file = open(inputfile) equations = list(x.strip('\n').replace(' ', '') for x in file.readlines()) file.close() sum = 0 for equation in equations: result = evaluate(equation) sum += result print(f"Answer: {sum}") def evaluate(equation): terms = [] operators = [] # parse and collapse groups for char in equation: if char == '(': operators.insert(0, char) elif char == ')': first = operators.index('(') op_group = operators[:first] operators = operators[first + 1:] term_group = terms[:first + 1] terms = terms[first + 1:] group_result = evaluate_group(term_group, op_group) terms.insert(0, group_result) elif char in ['+', '*']: operators.insert(0, char) else: terms.insert(0, int(char)) return evaluate_group(terms, operators) def evaluate_group(terms, operators): terms.reverse() operators.reverse() while '+' in operators: first = operators.index('+') operators.pop(first) sum = terms.pop(first) + terms.pop(first) terms.insert(first, sum) product = 1 for factor in terms: product *= factor return product
[ "briancdang@gmail.com" ]
briancdang@gmail.com
e6a5c355fbd23be4ca147b5780846a516b5731d5
c77d8957f5cbf182ad987b546ebc851b4288d6f6
/plotting-normal-distribution.py
4dc97cb324d2edeb74be9f1a244ce2cd791802ac
[]
no_license
Goku-kun/statistics-with-numpy
b1db23d537888f80f36c7f1a055c5919bfd0e20b
5d6683415654567708c7d6cef41d84a8ca4cb648
refs/heads/main
2023-01-13T04:36:39.773197
2020-11-10T18:39:30
2020-11-10T18:39:30
310,846,087
0
0
null
null
null
null
UTF-8
Python
false
false
301
py
# Plotting a normal distribution curve using Histogram # It will be a unimodal symmetric histogram with center=0 and std=1 as mentioned in np.random.normal method as arguments import numpy as np from matplotlib import pyplot as plt data = np.random.normal(0, 1, size=10000) plt.hist(data) plt.show()
[ "jethvadharmarajsinh@gmail.com" ]
jethvadharmarajsinh@gmail.com
37bc9e5dc34b6df333a626882f5b695237bf0911
4c0328c7fa7805cdd196cf890695ec1a8a438a5f
/devel/lib/python2.7/dist-packages/humanoid_nav_msgs/msg/_ExecFootstepsGoal.py
7060f4f7755727f3a1eb70d162baf59f11ee98b0
[]
no_license
SebsBarbas/iRob_KTH
d98dfce8692bdd4d32ce3a4d72daa8d022976c0a
c164c9d12efcab56b4871fc5bb5538df5849a42e
refs/heads/main
2023-01-23T10:49:59.073113
2020-12-04T18:49:53
2020-12-04T18:49:53
318,595,723
0
0
null
null
null
null
UTF-8
Python
false
false
7,302
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from humanoid_nav_msgs/ExecFootstepsGoal.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg import humanoid_nav_msgs.msg class ExecFootstepsGoal(genpy.Message): _md5sum = "40a3f8092ef3bb49c3253baa6eb94932" _type = "humanoid_nav_msgs/ExecFootstepsGoal" _has_header = False #flag to mark the presence of a Header object _full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== # Define the goal humanoid_nav_msgs/StepTarget[] footsteps float64 feedback_frequency ================================================================================ MSG: humanoid_nav_msgs/StepTarget # Target for a single stepping motion of a humanoid's leg geometry_msgs/Pose2D pose # step pose as relative offset to last leg uint8 leg # which leg to use (left/right, see below) uint8 right=0 # right leg constant uint8 left=1 # left leg constant ================================================================================ MSG: geometry_msgs/Pose2D # Deprecated # Please use the full 3D pose. # In general our recommendation is to use a full 3D representation of everything and for 2D specific applications make the appropriate projections into the plane for their calculations but optimally will preserve the 3D information during processing. # If we have parallel copies of 2D datatypes every UI and other pipeline will end up needing to have dual interfaces to plot everything. And you will end up with not being able to use 3D tools for 2D use cases even if they're completely valid, as you'd have to reimplement it with different inputs and outputs. It's not particularly hard to plot the 2D pose or compute the yaw error for the Pose message and there are already tools and libraries that can do this for you. # This expresses a position and orientation on a 2D manifold. float64 x float64 y float64 theta """ __slots__ = ['footsteps','feedback_frequency'] _slot_types = ['humanoid_nav_msgs/StepTarget[]','float64'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: footsteps,feedback_frequency :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(ExecFootstepsGoal, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.footsteps is None: self.footsteps = [] if self.feedback_frequency is None: self.feedback_frequency = 0. else: self.footsteps = [] self.feedback_frequency = 0. def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: length = len(self.footsteps) buff.write(_struct_I.pack(length)) for val1 in self.footsteps: _v1 = val1.pose _x = _v1 buff.write(_get_struct_3d().pack(_x.x, _x.y, _x.theta)) buff.write(_get_struct_B().pack(val1.leg)) buff.write(_get_struct_d().pack(self.feedback_frequency)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: if self.footsteps is None: self.footsteps = None end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.footsteps = [] for i in range(0, length): val1 = humanoid_nav_msgs.msg.StepTarget() _v2 = val1.pose _x = _v2 start = end end += 24 (_x.x, _x.y, _x.theta,) = _get_struct_3d().unpack(str[start:end]) start = end end += 1 (val1.leg,) = _get_struct_B().unpack(str[start:end]) self.footsteps.append(val1) start = end end += 8 (self.feedback_frequency,) = _get_struct_d().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: length = len(self.footsteps) buff.write(_struct_I.pack(length)) for val1 in self.footsteps: _v3 = val1.pose _x = _v3 buff.write(_get_struct_3d().pack(_x.x, _x.y, _x.theta)) buff.write(_get_struct_B().pack(val1.leg)) buff.write(_get_struct_d().pack(self.feedback_frequency)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: if self.footsteps is None: self.footsteps = None end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.footsteps = [] for i in range(0, length): val1 = humanoid_nav_msgs.msg.StepTarget() _v4 = val1.pose _x = _v4 start = end end += 24 (_x.x, _x.y, _x.theta,) = _get_struct_3d().unpack(str[start:end]) start = end end += 1 (val1.leg,) = _get_struct_B().unpack(str[start:end]) self.footsteps.append(val1) start = end end += 8 (self.feedback_frequency,) = _get_struct_d().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_B = None def _get_struct_B(): global _struct_B if _struct_B is None: _struct_B = struct.Struct("<B") return _struct_B _struct_d = None def _get_struct_d(): global _struct_d if _struct_d is None: _struct_d = struct.Struct("<d") return _struct_d _struct_3d = None def _get_struct_3d(): global _struct_3d if _struct_3d is None: _struct_3d = struct.Struct("<3d") return _struct_3d
[ "ssbl@kth.se" ]
ssbl@kth.se
5b23fd2da439c4d23eae958b44db0085550b3016
d9bb656bd11f85e6419ebd786aec6fe3f917cb73
/python/biograph/coverage/covanno_test.py
a70d2353548e31bb21d41005797a826ccb909eae
[ "BSD-2-Clause" ]
permissive
spiralgenetics/biograph
55a91703a70429568107209ce20e71f6b96577df
5f40198e95b0626ae143e021ec97884de634e61d
refs/heads/main
2023-08-30T18:04:55.636103
2021-10-31T00:50:48
2021-10-31T00:51:08
386,059,959
21
10
NOASSERTION
2021-07-22T23:28:45
2021-07-14T19:52:15
HTML
UTF-8
Python
false
false
5,439
py
# pylint: disable=missing-docstring import unittest import biograph from biograph.coverage import CovAnno, VcfEntryInfo import biograph.variants as bgexvar class CovAnnoTestCases(unittest.TestCase): @classmethod def setUpClass(cls): cls.bg = biograph.BioGraph("datasets/lambdaToyData/benchmark/proband_lambda.bg") cls.seqset = cls.bg.seqset cls.rm = cls.bg.open_readmap() cls.ref = biograph.Reference("datasets/lambdaToyData/benchmark/ref_lambda") cls.vcf_file = "datasets/lambdaToyData/benchmark/family.vcf.gz" cls.asms = VcfEntryInfo.parse_region(cls.vcf_file, 'lambda', 0, cls.ref.scaffold_lens["lambda"], sample_index=None) # terribly verbose answer checking cls.answer_vcf = [] cls.answer_fmt = [] cls.answer_vcf.append(['lambda', '2191', '.', 'TCTACGGAAAGCCGGTGGCCAGCATGCCACGTAAGCGAAACAAAAACGGGGTTTACCTTACCGAAATCGGTACGGATACCGCGAAAGAGCAGATTTATAAC', 'T', '100', 'PASS', 'NS=1;END=2291;SVLEN=100;SVTYPE=DEL', 'GT:PG:GQ:PI:OV:DP:AD:PDP:PAD', '1/1:1|1:100:54842:144:126:0,126:97:0,97', '.', '1/1:1|1:100:57915:145:143:0,143:115:0,115']) cls.answer_fmt.append({'US': '2,74', 'DS': '0,74', 'UC': '2,127', 'DC': '0,126', 'UDC': '1,57', 'UCC': '1,70', 'DDC': '0,56', 'DCC': '0,70', 'UMO': '149,141', 'DMO': '0,141', 'UXO': '149,150', 'DXO': '0,150', 'NR': '2,127', 'MO': '0,141', 'XO': '0,150', 'XC': '0,127', 'AC': '0,126', 'EC': '0,126', 'MC': '0,126', 'MP': '2,2'}) cls.answer_vcf.append(['lambda', '2667', '.', 'C', 'CA', '100', 'PASS', 'NS=1', 'GT:PG:GQ:PI:OV:DP:AD:PDP:PAD', '1/1:1|1:100:54495:146:153:0,153:115:0,115', '.', '1/1:1|1:100:2062:145:152:0,152:119:0,119']) cls.answer_fmt.append({'US': '1,75', 'DS': '0,74', 'UC': '2,155', 'DC': '0,155', 'UDC': '0,88', 'UCC': '2,67', 'DDC': '0,88', 'DCC': '0,67', 'UMO': '150,146', 'DMO': '0,146', 'UXO': '150,150', 'DXO': '0,150', 'NR': '2,157', 'MO': '0,146', 'XO': '0,150', 'XC': '0,155', 'AC': '0,154', 'EC': '0,155', 'MC': '0,153', 'MP': '2,2'}) cls.answer_vcf.append(['lambda', '5897', '.', 'G', 'A', '100', 'PASS', 'NS=1', 'GT:PG:GQ:PI:OV:DP:AD:PDP:PAD', '1/1:1|1:100:6698:145:160:0,160:118:0,118', '.', '1/1:1|1:100:53723:146:153:0,153:105:0,105']) cls.answer_fmt.append({'US': '0,74', 'DS': '0,75', 'UC': '0,160', 'DC': '0,161', 'UDC': '0,76', 'UCC': '0,84', 'DDC': '0,76', 'DCC': '0,85', 'UMO': '0,145', 'DMO': '0,145', 'UXO': '0,150', 'DXO': '0,150', 'NR': '0,161', 'MO': '0,145', 'XO': '0,150', 'XC': '0,161', 'AC': '0,160', 'EC': '0,160', 'MC': '0,160', 'MP': '2,2'}) cls.answer_vcf.append(['lambda', '7146', '.', 'G', 'GTA', '100', 'PASS', 'NS=1', 'GT:PG:GQ:PI:OV:DP:AD:PDP:PAD', '1/1:1|1:100:49155:144:144:0,144:110:0,110', '.', '1/1:1|1:100:52298:144:138:0,138:99:0,99']) cls.answer_fmt.append({'US': '2,75', 'DS': '1,72', 'UC': '4,144', 'DC': '2,148', 'UDC': '1,71', 'UCC': '3,73', 'DDC': '0,73', 'DCC': '2,75', 'UMO': '149,140', 'DMO': '150,140', 'UXO': '150,150', 'DXO': '150,150', 'NR': '6,152', 'MO': '150,140', 'XO': '150,150', 'XC': '2,148', 'AC': '2,146', 'EC': '2,145', 'MC': '2,144', 'MP': '2,2'}) cls.answer_vcf.append(['lambda', '8493', '.', 'C', 'CT', '100', 'PASS', 'NS=1', 'GT:PG:GQ:PI:OV:DP:AD:PDP:PAD', '1/1:1|1:100:47631:146:171:0,171:135:0,135', '1/1:1|1:100:48926:145:139:0,139:106:0,106', '.']) cls.answer_fmt.append({'US': '1,75', 'DS': '0,73', 'UC': '2,172', 'DC': '0,171', 'UDC': '1,88', 'UCC': '1,84', 'DDC': '0,89', 'DCC': '0,82', 'UMO': '150,145', 'DMO': '0,145', 'UXO': '150,150', 'DXO': '0,150', 'NR': '2,174', 'MO': '0,145', 'XO': '0,150', 'XC': '0,172', 'AC': '0,171', 'EC': '0,171', 'MC': '0,171', 'MP': '2,2'}) def test_lambda(self): self.maxDiff = 10000 anno = CovAnno(True) asms = bgexvar.add_ref_assemblies(self.ref, 'lambda', self.asms, 250) data = anno.parse(self.rm, asms) found = 0 expecteds, actuals = [], [] trimmed_answer = [fields[:9] for fields in self.answer_vcf] for i in data: if i.matches_reference: continue if i.vcf_entry_info.vcf_entry in trimmed_answer: idx = trimmed_answer.index(i.vcf_entry_info.vcf_entry) expecteds.append(self.answer_fmt[idx]) actuals.append(i.vcf_entry_info.new_fmt) print(self.answer_fmt[idx]) found += 1 self.assertEqual(expecteds, actuals) self.assertEqual(found, len(self.answer_vcf)) if __name__ == '__main__': unittest.main(verbosity=2)
[ "rob@spiralgenetics.com" ]
rob@spiralgenetics.com
a1f83ec58251bd75d452c487b955aebddd806f8f
94b75a7213223f64455d5ec1790f4e306e0d1c37
/webqcm/associate/urls.py
f7b4ad17ba3753e3f8b4938d54f17b59a6a16f54
[]
no_license
mike38/webqcm
d0c53d5454e9616065230769a5219bac4e483f91
742c2dc0dc32a78f220168f92ef61f0659de3c7a
refs/heads/master
2021-01-01T18:29:59.154378
2012-07-20T21:52:27
2012-07-20T21:52:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
266
py
from django.conf.urls import patterns, include, url urlpatterns = patterns('associate.views', url(r'^$', 'index'), url(r'^(?P<copie_id>\d+)/$', 'copie'), # url(r'^(?P<poll_id>\d+)/results/$', 'results'), # url(r'^(?P<poll_id>\d+)/vote/$', 'vote'), )
[ "mike@alezan" ]
mike@alezan
32046ec62e3909e6bcee725e3f0ddee8dd62870e
5d810201c5dd42c93d5fc0e827af09b240f345bf
/chapter_6/mclip.py
a57e74e5e65b8abe46c4702d24ff81c2b024b388
[]
no_license
thebluetoob/automateTheBoringStuff
3d2acbdc75c81351a5f7014df969aa5cafcce7c3
af2924c057d0269397f5b978991f591d9c8ce49d
refs/heads/master
2022-09-16T16:40:00.816000
2020-05-30T03:18:41
2020-05-30T03:18:41
265,687,675
0
0
null
null
null
null
UTF-8
Python
false
false
639
py
#!/usr/bin/env python3 # mclip.py - A multi-clipboard program. import sys, pyperclip TEXT = {'agree' : """Yes, I agree. That sounds fine to me""", 'busy' : """Sorry, can we do this later this week or next week?""", 'upsell' : """Would you consider making this a monthly donation?"""} if len(sys.argv) < 2: print('Usage: python mclip.py [keyphrase] - copy phrase text') sys.exit() keyphrase = sys.argv[1] # first command line arg is the keyphrase if keyphrase in TEXT: pyperclip.copy(TEXT[keyphrase]) print('Text for ' + keyphrase + ' copied to clipboard.') else: print('There is no text for ' + keyphrase)
[ "github@benjaminellett.com" ]
github@benjaminellett.com
b222f61b6de0d092cbd584db1fb54e9f8ceea4e7
7af3de2633036ac03bc3164821b1cf75f30fc840
/nltktest.py
6544be814045ecbe6251db43b0a6bf20a198491e
[]
no_license
feweje/ES96-Dictation-Device
257943c9bf2f2a780dc0d762316a41bed7729f7d
16a9e01861d59d1f5d5d07f8bec1bfefed6bb7c3
refs/heads/master
2021-05-08T02:13:52.532226
2017-10-23T09:08:06
2017-10-23T09:08:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
891
py
from nltk.tokenize import sent_tokenize, word_tokenize #EXAMPLE_TEXT = "heart rate 78 bpm, temperature 98 F. pediatric cancer in low-income countries. I love ES96. Drug administration is accordingly riskier. A unicorn is a fictional animal." #print file.readline() import itertools words = [] with open('exampletext.txt','r') as f: for line in f: for word in line.split(): words.append(str(word)) # Store the numbers in a set, and use the set to check if the number already exists length = len(words) for k in range(length-2): keyword1 = words[k] keyword2 = words[k+1] num = words[k+2] if(keyword1 == 'heart' and keyword2 == 'rate'): print "Heart Rate:", num for k in range (length-1): keyword1 = words[k] num = words[k+1] if(keyword1 == 'temperature'): print "Temperature:", num #break
[ "32832145+bhu01@users.noreply.github.com" ]
32832145+bhu01@users.noreply.github.com
9300b8490aae6ab681657dc63e16317b41d7645c
1bfb5b8fd4f452c704a609ca2a310057e88fd4be
/main/tests.py
01868e6d24e3997e31a345e4b9dbe82ed96c5cbd
[]
no_license
JungleTryne/mshp_project
58f208cfc4a474a3bdae9e3bf38afc7ae04fad93
15669d181811f65997e66e1900deec42220e6dda
refs/heads/master
2023-04-06T21:42:12.438412
2021-03-25T15:42:50
2021-03-25T15:42:50
314,556,519
0
0
null
null
null
null
UTF-8
Python
false
false
2,371
py
import os from django.contrib.auth.models import User from django.test import TestCase, Client from django.urls import reverse from main.models import Snippet class TestIndexPage(TestCase): fixtures = ['test_db.json'] def setUp(self): self.c = Client() user = User.objects.get(username='vasya') self.c.force_login(user) self.response = self.c.get(reverse('index')) def test_simple(self): self.assertEqual(self.response.context['pagename'], 'PythonBin v2.0') self.assertEqual(self.response.context['user'].username, 'vasya') self.assertTemplateUsed(self.response, 'pages/index.html') class TestAddSnippetPage(TestCase): fixtures = ['test_db.json'] def setUp(self): self.c = Client() user = User.objects.get(username='vasya') self.c.force_login(user) self.response = self.c.get(reverse('add_snippet')) def test_simple_get(self): self.assertEqual(self.response.context['pagename'], 'Добавление нового сниппета') self.assertTemplateUsed(self.response, 'pages/add_snippet.html') def test_simple_post(self): response = self.c.post(reverse('add_snippet'), { 'name': '123', 'code': 'import this' }) record = Snippet.objects.filter(name='123') self.assertEqual(len(record), 1) class TestPep8SnippetPage(TestCase): fixtures = ['test_db.json'] def setUp(self): self.c = Client() user = User.objects.get(username='vasya') self.c.force_login(user) self.c.post(reverse('add_snippet'), {'name': '123', 'code': ' a = b + c '}) self.record = Snippet.objects.filter(name='123').last() def test_get(self): response = self.c.get(reverse('view_format', kwargs={'snippet_id': self.record.id, 'utility': 'pep8'})) self.c.post(reverse('add_snippet'), {'name': '123', 'code': ' a = b + c '}) self.record = Snippet.objects.filter(name='123').last() self.assertEqual(response.context['code'], 'a = b + c\n') self.assertTrue(os.path.exists(self.record.get_filename('autopep8'))) def test_invalid_get(self): response = self.c.get(reverse('view_format', kwargs={'snippet_id': 100, 'utility': 'pep8'})) self.assertEqual(response.status_code, 404)
[ "danila.mishin.2001@gmail.com" ]
danila.mishin.2001@gmail.com
e70139106c1e2181cbb578a5feafe790f6ef511a
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02709/s006433127.py
8e891819bfe8e5250a41e5dd8b8b921a1409cc08
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
698
py
from sys import stdin def get_result(data): N = data[0][0] A = data[1] dp = [[0]*(N+1) for _ in range(N+1)] B = [[A[i], i] for i in range(N)] B = sorted(B, reverse=True) for i in range(N): for j in range(N-i): dp[i+1][j] = max(dp[i+1][j], dp[i][j] + B[i+j][0] * (B[i+j][1] - i)) dp[i][j+1] = max(dp[i][j+1], dp[i][j] + B[i+j][0] * ((N-1-j) - B[i+j][1])) res = 0 for i in range(N): res = max(res, dp[i][N-i]) return res if __name__ == '__main__': raw_data = [val.rstrip() for val in stdin.readlines()] data = [list(map(int, val.split(' '))) for val in raw_data] result = get_result(data) print(result)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
0eafece1102e1dbcb09b8dd1bafc8ddf971fbd94
0ff378b747db1a00d2366fcdaabcb9a24e5180e8
/venv/bin/explode.py
8a9e12cb2efade1f854c5914336ac9e49be7af41
[]
no_license
lmreyes/-django-initiation
8e971e21fc1f42fb6dde0fc7017af6ecaffbeb1b
5b929051c06cc8bb638ad97f0cb46dd4e3244fe3
refs/heads/master
2020-06-12T15:20:40.798206
2016-12-07T07:37:23
2016-12-07T07:37:23
75,811,028
0
0
null
null
null
null
UTF-8
Python
false
false
2,469
py
#!/home/lmreyes/workspace-Django/venv/bin/python3 # # The Python Imaging Library # $Id$ # # split an animation into a number of frame files # from __future__ import print_function from PIL import Image import os import sys class Interval(object): def __init__(self, interval="0"): self.setinterval(interval) def setinterval(self, interval): self.hilo = [] for s in interval.split(","): if not s.strip(): continue try: v = int(s) if v < 0: lo, hi = 0, -v else: lo = hi = v except ValueError: i = s.find("-") lo, hi = int(s[:i]), int(s[i+1:]) self.hilo.append((hi, lo)) if not self.hilo: self.hilo = [(sys.maxsize, 0)] def __getitem__(self, index): for hi, lo in self.hilo: if hi >= index >= lo: return 1 return 0 # -------------------------------------------------------------------- # main program html = 0 if sys.argv[1:2] == ["-h"]: html = 1 del sys.argv[1] if not sys.argv[2:]: print() print("Syntax: python explode.py infile template [range]") print() print("The template argument is used to construct the names of the") print("individual frame files. The frames are numbered file001.ext,") print("file002.ext, etc. You can insert %d to control the placement") print("and syntax of the frame number.") print() print("The optional range argument specifies which frames to extract.") print("You can give one or more ranges like 1-10, 5, -15 etc. If") print("omitted, all frames are extracted.") sys.exit(1) infile = sys.argv[1] outfile = sys.argv[2] frames = Interval(",".join(sys.argv[3:])) try: # check if outfile contains a placeholder outfile % 1 except TypeError: file, ext = os.path.splitext(outfile) outfile = file + "%03d" + ext ix = 1 im = Image.open(infile) if html: file, ext = os.path.splitext(outfile) html = open(file+".html", "w") html.write("<html>\n<body>\n") while True: if frames[ix]: im.save(outfile % ix) print(outfile % ix) if html: html.write("<img src='%s'><br>\n" % outfile % ix) try: im.seek(ix) except EOFError: break ix += 1 if html: html.write("</body>\n</html>\n")
[ "lmreyes@emergya.com" ]
lmreyes@emergya.com
7f14657e7b918876a0fe9942e960644e89ddc2ba
41d95ff0ba21fa388755744fc01af03f80cbd5c6
/gallery_mukamisha/urls.py
dc4c3f6e3ad5671df0e167c030294ecfdc116024
[]
no_license
mukamisha/Gallery
49a71affefe1aaa0a764e13bd7d06dd208600240
6d5cb25b117b798e5d2b83ce76aef5c16b18058f
refs/heads/master
2021-09-08T04:09:32.379594
2019-10-15T09:25:49
2019-10-15T09:25:49
214,124,864
0
0
null
2021-09-08T01:22:10
2019-10-10T08:11:51
Python
UTF-8
Python
false
false
508
py
from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from . import views urlpatterns=[ url(r'^$',views.images,name = 'pictures'), url(r'^search/', views.search_results, name='search_results'), url(r'^image/(\d+)',views.get_image,name ='photo'), url(r'^locations/(\d+)', views.filter_by_location, name = 'filter_by_location'), ] if settings.DEBUG: urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
[ "mukamishajacky97@gmail.com" ]
mukamishajacky97@gmail.com
596bf66bc030390c1d4bd47394cce4f3ee11c470
bf68a46803318531af0c06816a9269d6f44a0f7c
/4_3_listOfDepths.py
6a9e479cc76dac4b04ecec01c600e5463e7601a0
[]
no_license
pghanem/Data-Structures-Algorithms
09b03cea4a374a6328865f029a27a8414b4d34ad
cf9900d9ef5634f879625ddf89cf35c11c652c0d
refs/heads/master
2020-05-04T03:47:15.881326
2019-04-01T21:57:22
2019-04-01T21:57:22
178,953,136
0
0
null
null
null
null
UTF-8
Python
false
false
2,169
py
class LinkedListNode: next_node = None val = None def __init__(self, val): self.val = val def add(self, val): while self.next_node: self = self.next_node self.next_node = LinkedListNode(val) def print(self): while self: print(self.val) self = self.next_node class BT: val = None left = None right = None def __init__(self, val): self.val = val def insert(self, val): if self.val == val: return if val > self.val and not self.right: self.right = BT(val) elif val < self.val and not self.left: self.left = BT(val) elif val > self.val and self.right: self.right.insert(val) else: self.left.insert(val) def depth(tree): if tree == None: return 0 if tree.left == None and tree.right == None: return 1 else: depthL = 1 + depth(tree.left) depthR = 1 + depth(tree.right) if depthL > depthR: return depthL else: return depthR def listOfDepths(root): if root is None: return q1 = [] q2 = [] llists = [] q1.append(root) while not q1 == [] or not q2 == []: llist = LinkedListNode(None) while not q1 == []: root = q1.pop(0) llist.add(root.val) if root.left is not None: q2.append(root.left) if root.right is not None: q2.append(root.right) llists.append(llist) llist = LinkedListNode(None) while not q2 == []: root = q2.pop(0) llist.add(root.val) if root.left is not None: q1.append(root.left) if root.right is not None: q1.append(root.right) llists.append(llist) return llists def printAll(lst): for x in lst: x.print() def CBT(): bt = BT(6) bt.insert(3) bt.insert(7) bt.insert(1) bt.insert(13) bt.insert(44) bt.insert(22) bt.insert(2) bt.insert(8) bt.insert(9) bt.insert(12) bt.insert(10) bt.insert(4) bt.insert(5) return bt
[ "noreply@github.com" ]
pghanem.noreply@github.com
4b95fef90b2dca9cddd020a2a0d313454473685d
c2b8fe6e03e6572a628c03d7c9804631da55af2c
/Algorithmic Questions/Queue.py
7aaf2b3025c236110c4727c9b5a7b1e247c500cc
[]
no_license
Anthonymcqueen21/Python-Interview-Questions
0f49f72b483f5f5b0549f0cdf4856e92d073e994
de4657a96a48c86897b952f77666a1180fe9360a
refs/heads/master
2020-04-02T01:18:06.826564
2019-05-11T03:55:05
2019-05-11T03:55:05
153,848,489
2
0
null
null
null
null
UTF-8
Python
false
false
710
py
# Queue is a linear data structure with a sequential collection process. # Python implementation from collections import deque class Queue: def __init__(self): self._queue = deque([]) def add(self.name): """ Add element as the last item in Queue """ self._queue.append(value) def remove(self): """ Remove elements from the front """ return self._queue.popleft() def is_empty(self): """ Returns a boolean indication """ return not len(self._queue) def size(self): """ Return size of the Queue """ return len(self._queue)
[ "noreply@github.com" ]
Anthonymcqueen21.noreply@github.com
4b88b4d4cf117c940218f430967cca96ba168a15
79371c17517f3d2d61659feceb6ad0c206f8a5f5
/run.py
dffb5490c8bdd4828a42aebd9b56c6f01ead7196
[]
no_license
kenuxi/EVA
f238582602669314172fb75fb56e161e7efb15fc
00c9985df9951b25cd2fc8a4d0670ed14d7e54e3
refs/heads/master
2022-11-29T23:53:49.135472
2020-08-19T13:43:49
2020-08-19T13:43:49
261,166,488
0
0
null
null
null
null
UTF-8
Python
false
false
240
py
from werkzeug.serving import run_simple from eva import application if __name__ == "__main__": run_simple(hostname='localhost', port=5000, application=application, use_reloader=True, use_debugger=True, use_evalex=True)
[ "kennethjlroos@gmail.com" ]
kennethjlroos@gmail.com
beeaa9a3badc321697bf696bfbad8e80950b20ba
2a986763160be52499303f974784fb0833935bf2
/regex.py
3d6fc97e0b04bb713c5b3a64d3e096ce4b6bb0cd
[]
no_license
mdav2/optavc
6195e85c1eb05815d00cf5335edac85730a76f9b
cb43ba0bd4f3d8d50d3357bce52056a9a669410e
refs/heads/master
2021-04-09T20:49:21.111634
2020-03-21T00:32:47
2020-03-21T00:32:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,630
py
# fundamental components character = r'[a-zA-Z]' unsigned_integer = r'\d+' signed_double = r'-?\d+\.\d+' whitespace = r'\s' endline = r'\n' # fundamental functions def capture(string): return r'({:s})'.format(string) def maybe(string): return r'(?:{:s})?'.format(string) def zero_or_more(string): return r'(?:{:s})*'.format(string) def one_or_more(string): return r'(?:{:s})+'.format(string) def two_or_more(string): return r'(?:{:s}){{2,}}'.format(string) # some commonly used strings -- lsp indicates "zero or more *l*eading *sp*aces" lsp_endline = zero_or_more(whitespace) + endline lsp_word = zero_or_more(whitespace) + two_or_more(character) lsp_signed_double = zero_or_more(whitespace) + signed_double lsp_atomic_symbol = zero_or_more(whitespace) + character + maybe(character) class BagelRegex: """ Regular expression library for Bagel outputs Includes samples of the output for comparisson """ """ 9 -75.02529220 0.00000001 0.00 o DIIS 0.00 o Diag 0.00 o Post process 0.00 o Fock build 0.00 10 -75.02529220 0.00000000 0.00 * SCF iteration converged. * Permanent dipole moment: """ hf = r"\d+\s+(-?\d+\.\d+)\s+0\.\d+\s+\d+\.\d+\n\s*\n \* SCF iteration converged\." """ === Relativistic FCI iteration === * sigma vector 4.17e-03 * davidson 2.77e-04 * error 1.13e-05 * denominator 4.83e-06 0 0 * -99.37091199 5.56e-16 0.00 0 1 * -99.37091199 1.62e-15 0.00 0 2 * -99.37091199 1.54e-15 0.00 0 3 * -99.37091199 4.07e-15 0.00 0 4 * -99.36906267 2.29e-15 0.00 0 5 * -99.36906267 1.84e-15 0.00 * ci vector, state 0 b22 (0.0403514045,-0.0394344882) """ casscf = r"\* denominator\s+\d+\.\d+e-\d+\n\s+\d+\s+\d+\s+\*\s+(-\d+\.\d+)\s+\d+\.\d+e-\d+\s+\d+\.\d+" """ - MRCI energy evaluation 5839.09 0 0 -190.78090477 0.00000000 0.00 - MRCI+Q energy evaluation 0.00 """ mrci = r"- MRCI energy evaluation\s+\d+\.\d+\n\n\s+0 0\s+(-\d+\.\d+)\s+\d+\.\d+\s+\d+\.\d+"
[ "matthew.mcallister.davis@gmail.com" ]
matthew.mcallister.davis@gmail.com
c99381c88d34efa19d7aecee9a4ec148ee6586ae
81882d9b2e7eb535e204406d6bfe3eec6e61425d
/libAFP/add_songs/input.py
1404ea82699c5714f893218fd173ab284527663e
[]
no_license
happyyang/audio_fingerprint
ca63ef5f45cc7e679353087d6e4b1a3c1c9a6501
6a5fd3ac1308e255bc1f130b964970ff901c51f8
refs/heads/master
2021-01-15T08:35:35.081181
2011-11-16T07:46:58
2011-11-16T07:46:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
600
py
#!/usr/bin/python import sys import base64 import binascii import gmpy import string c=sys.argv[1] #c=base64.encodestring(p) def b1(n): return "01"[n%2] def b2(n): return b1(n>>1)+b1(n) def b3(n): return b2(n>>2)+b2(n) def b4(n): return b3(n>>4)+b3(n) bytes = [ b4(n) for n in range(256)] def binstring(s): return ''.join(bytes[ord(c)] for c in s) #p=base64.decodestring(c) ##a=binascii.a2b_base64(c) b=binstring(c) print b c=string.atoi(b, 2) print c #bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in "aa"), 0)) #for c in b: # print gmpy.digits(ord(c), 2)
[ "khanna.vikesh@gmail.com" ]
khanna.vikesh@gmail.com
9869e254728f68b4d2a518791c63dc07e2a42ae6
6d7e44292e34bbc5e8cbc0eb9e9b264c0b498c5d
/test/unit/modules/test_sfp_stevenblack_hosts.py
712857037dea53cb3a71165cf2ff4556e6a96ae6
[ "Python-2.0", "MIT" ]
permissive
smicallef/spiderfoot
69585266dad860d3230d3ce7b801e34eeb359f90
6e8e6a8277ea251fdd62a0946268f5dfe9162817
refs/heads/master
2023-08-28T09:40:10.136780
2023-08-18T05:47:39
2023-08-18T05:47:39
4,165,675
10,620
2,130
MIT
2023-09-13T08:18:31
2012-04-28T07:10:13
Python
UTF-8
Python
false
false
795
py
import pytest import unittest from modules.sfp_stevenblack_hosts import sfp_stevenblack_hosts from sflib import SpiderFoot @pytest.mark.usefixtures class TestModuleStevenblackHosts(unittest.TestCase): def test_opts(self): module = sfp_stevenblack_hosts() self.assertEqual(len(module.opts), len(module.optdescs)) def test_setup(self): sf = SpiderFoot(self.default_options) module = sfp_stevenblack_hosts() module.setup(sf, dict()) def test_watchedEvents_should_return_list(self): module = sfp_stevenblack_hosts() self.assertIsInstance(module.watchedEvents(), list) def test_producedEvents_should_return_list(self): module = sfp_stevenblack_hosts() self.assertIsInstance(module.producedEvents(), list)
[ "noreply@github.com" ]
smicallef.noreply@github.com
38debb1f5fa4785b91bf6b4dedd6dc28fe0193ab
483bfa7d1ded5563659e93daa9ce9e6157e67bf0
/configuracion.py
a673e40865d914b9f0eb68b0d48975ee69554a16
[]
no_license
marioguzzzman/LPC---BOT
5400faffed4172c289dd6d480b45294f6ec133e7
71e4cca8a9a1a8cb88cb5573fdbe69f0588eff48
refs/heads/master
2022-12-24T02:14:43.924841
2020-10-01T20:44:00
2020-10-01T20:44:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
778
py
class Configuracion: def __init__(self): # Tokens de Twitter self.api_key = '8uwasd9eVvEutiExvCCtFr2SVE' self.secret_api_key = 'J4N5VoHasdasd7Z4aFZ49q9dwud4jSoMhtT8mevNBjI4aItmMM6' self.access_token = '126467jkghj67jghjdfgdfAyKJMwb3iy7bHjlQ2wioy' self.secret_access_token = 'jV456dfhdfhebyWFQwW3ygQ3zip8u6vj7KGE4g' # Aca van las palabras que mirara el bot para saber si responde o no a un tweet self.palabras_para_responder = [' ','pregunta'] # El tiempo de espera entre publicaciones y respuestas, esta en segundos self.tiempo_entre_publicaciones = 300 # Aca se designa el nombre del archivo donde se guardaran los IDs de los Tweets ya respondidos self.archivo_texto = 'ids_reply.txt'
[ "jc.luque10@uniandes.edu.co" ]
jc.luque10@uniandes.edu.co
81abca48c200b3db8d321878e030c42ff732c1af
6e5ac4591a78657311ec16f05f310b769192caf5
/translator_ui/source/utils.py
a4a0f5cb36e0cb622e69a47efc7ba427ad667ea4
[]
no_license
md-experiments/translator_ui
527781991f32de75d32588536f57986ea3c747b4
fd34df0a60f3eaf789d506b46593b4786811f93f
refs/heads/master
2023-07-27T14:28:42.293523
2021-09-09T11:23:57
2021-09-09T11:23:57
404,384,640
0
0
null
null
null
null
UTF-8
Python
false
false
965
py
import json import requests def transliterate(text, reverse=False): symbols = (u"абвгдежзийклмнопрстуфхцчшщъыьюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", u"abvgdejzijklmnoprstufhzcss_y_uaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA") if reverse==True: tr = {ord(b):ord(a) for a, b in zip(*symbols)} else: tr = {ord(a):ord(b) for a, b in zip(*symbols)} return text.translate(tr) def call_fast_api(data, endpoint, port=4990, action='GET', host = '127.0.0.1'): if not isinstance(data, str): data=json.dumps(data) api_url = f'http://{host}:{port}/{endpoint}' if action=='GET': response = requests.get(api_url, data=data) elif action=='POST': response = requests.post(api_url, data=data) if response.status_code == 200: return json.loads(response.content.decode('utf-8')) else: return response
[ "eggs@countingchickens.co.uk" ]
eggs@countingchickens.co.uk
5d4e75981ff37df6ecfef8505474e4adc1816e4f
0f07cc65a0a233c4ea66562f7730a78ecd0254b5
/Models/Ensemble/Ensemble_30lgb.py
02576cf27ff90f62baabd662c94ddbda524f6a10
[]
no_license
Lihit/HomeCreditDefaultRisk
777cd92988444083b18e449f11cad9b2716ab9de
029b41b4c0f67eb0b21e993adb63fa6c4c5de70e
refs/heads/master
2020-03-27T17:10:53.596149
2018-08-31T03:10:55
2018-08-31T03:10:55
146,833,520
2
0
null
null
null
null
UTF-8
Python
false
false
11,559
py
import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score from sklearn.preprocessing import LabelEncoder from skopt.space import Real, Categorical, Integer import xgboost as xgb from xgboost import XGBClassifier import os import gc import time from matplotlib import pyplot as plt from sklearn.model_selection import GridSearchCV from skopt import BayesSearchCV import lightgbm as lgb from sklearn.svm import LinearSVC, SVC import seaborn as sns from sklearn.model_selection import train_test_split, KFold, StratifiedKFold from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.feature_selection import VarianceThreshold from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, MinMaxScaler import random import warnings warnings.simplefilter('ignore') TrainDataDir = 'data' ResultSaveDir = 'result_ensemble' # 设置的超参数 LgbmNum = 20 TrainDataName_withCate = 'train_mini5.csv' TrainDataName_withoutCate = 'train_mini5.csv' # 设置lgbm的参数,有两种,一种是有category特征,一种是没有的 model_config_withCate = { #'random_search_runs': 0, 'device': 'cpu', # gpu cpu 'num_threads':-1, 'boosting_type': 'gbdt', 'objective': 'binary', 'metric': 'auc', 'learning_rate': 0.015, 'max_bin': 300, 'max_depth': -1, 'num_leaves': 30, 'min_child_samples': 40, 'subsample': 1, 'subsample_freq': 1, 'colsample_bytree': 0.03, 'min_gain_to_split': 2, 'reg_lambda': 110, 'reg_alpha': 0.0, 'scale_pos_weight': 1, 'is_unbalance': False} model_config_withoutCate = { #'random_search_runs': 0, 'device': 'cpu', # gpu cpu 'num_threads':-1, 'boosting_type': 'gbdt', 'objective': 'binary', 'metric': 'auc', 'learning_rate': 0.015, 'max_bin': 300, 'max_depth': -1, 'num_leaves': 30, 'min_child_samples': 40, 'subsample': 1, 'subsample_freq': 1, 'colsample_bytree': 0.03, 'min_gain_to_split': 2, 'reg_lambda': 110, 'reg_alpha': 0.0, 'scale_pos_weight': 1, 'is_unbalance': False} # 获取特征重要度的函数 def get_importances(feature_importance_df_): importances = feature_importance_df_[["feature", "importance"]].groupby( "feature").mean().sort_values(by="importance", ascending=False) return importances def loadData(Dir, DataName, index_col_flag=False): DataPath = os.path.join(Dir, DataName) if not os.path.exists(DataPath): print('%s does not exist!' % DataPath) return if index_col_flag: OriginData = pd.read_csv(DataPath, index_col=0) else: OriginData = pd.read_csv(DataPath) # OriginData = OriginData.sample(frac=1) # 打乱顺序后返回 return OriginData def RandomDisturbance(model_config): model_config_random = { 'learning_rate': model_config['learning_rate'] + random.uniform(-0.001, 0.001), 'num_leaves': model_config['num_leaves'] + random.randint(-1, 1), 'subsample': model_config['subsample'] - random.uniform(0, 0.01), 'colsample_bytree': model_config['colsample_bytree'] + random.uniform(-0.001, 0.001), 'reg_lambda': model_config['reg_lambda'] + random.randint(-1, 1), } return model_config_random def saveData(IsCategory, NumofModel, importance, submission, oof_train): if IsCategory: ResultSaveSubDir = os.path.join(ResultSaveDir, 'WithCategory') if not os.path.exists(ResultSaveSubDir): os.mkdir(ResultSaveSubDir) else: ResultSaveSubDir = os.path.join(ResultSaveDir, 'WithoutCategory') if not os.path.exists(ResultSaveSubDir): os.mkdir(ResultSaveSubDir) # 保存数据 SaveDirPath = os.path.join(ResultSaveSubDir, 'lgbmodel%d' % NumofModel) if not os.path.exists(SaveDirPath): os.mkdir(SaveDirPath) importance.to_csv(os.path.join(SaveDirPath, "importance.csv")) submission.to_csv(os.path.join(SaveDirPath, "submission.csv")) oof_train.to_csv(os.path.join(SaveDirPath, "oof_train.csv")) def train(TrainDataName, IsCategory): gc.enable() print('loading data:%s'%TrainDataName) TrainData = loadData(TrainDataDir, TrainDataName, True) if IsCategory: model_config = model_config_withCate.copy() features = [x for x in TrainData.columns if x != 'TARGET' and x != 'SK_ID_CURR'] ObjColList = TrainData.select_dtypes(include='object').columns.tolist() for objcol in ObjColList: TrainData[objcol] = TrainData[objcol].astype('category') else: model_config = model_config_withoutCate.copy() features = [x for x in TrainData.columns if x != 'TARGET' and x != 'SK_ID_CURR'] ObjColList = TrainData.select_dtypes(include='object').columns.tolist() for objcol in ObjColList: if objcol in features: features.remove(objcol) df_test = TrainData[TrainData.TARGET.isnull()] df_test.reset_index(drop=True, inplace=True) df_train = TrainData[~TrainData.TARGET.isnull()] df_train.reset_index(drop=True, inplace=True) del TrainData gc.collect() for i in range(LgbmNum): t0 = time.time() print('------>Using Category:%s' % ('True' if IsCategory else 'False')) print('------>This is the %dth model...' % (i+1)) print("------>Starting LGBM. Train shape: {}, test shape: {}".format( df_train.shape, df_test.shape)) print("------>Num of Feature:", len(features)) # Cross validation model num_folds = random.choice([5, 7]) stratified = random.choice([0, 1]) # 随机扰动参数 model_config_in = model_config_withCate.copy( ) if IsCategory else model_config_withoutCate.copy() model_config.update(RandomDisturbance(model_config_in)) print(model_config) if stratified: print('------>StratifiedKFold:%d...' % num_folds) folds = StratifiedKFold( n_splits=num_folds, shuffle=True, random_state=random.randint(0, 100000)) else: print('------>KFold%d...' % num_folds) folds = KFold(n_splits=num_folds, shuffle=True, random_state=random.randint(0, 100000)) # Create arrays and dataframes to store results oof_preds = np.zeros(df_train.shape[0]) sub_preds = np.zeros(df_test.shape[0]) roc_score_list = [] feature_importance_df = pd.DataFrame() for n_fold, (train_idx, valid_idx) in enumerate(folds.split(df_train[features], df_train['TARGET'])): train_x, train_y = df_train[features].iloc[train_idx], df_train['TARGET'].iloc[train_idx] valid_x, valid_y = df_train[features].iloc[valid_idx], df_train['TARGET'].iloc[valid_idx] data_train = lgb.Dataset( data=train_x, label=train_y, feature_name='auto', categorical_feature='auto') data_valid = lgb.Dataset( data=valid_x, label=valid_y, feature_name='auto', categorical_feature='auto') clf = lgb.train(model_config, data_train, valid_sets=[data_train, data_valid], valid_names=['data_train', 'data_valid'], num_boost_round=10000, early_stopping_rounds=200, verbose_eval=200, feature_name='auto', categorical_feature='auto') oof_preds[valid_idx] = clf.predict( valid_x, num_iteration=clf.best_iteration) sub_preds += clf.predict(df_test[features], num_iteration=clf.best_iteration)/num_folds roc_curr = roc_auc_score(valid_y, oof_preds[valid_idx]) roc_score_list.append(roc_curr) print('Fold %d AUC : %.6f' % (n_fold + 1, roc_curr)) fold_importance_df = pd.DataFrame() fold_importance_df["feature"] = features fold_importance_df["importance"] = clf.feature_importance() fold_importance_df["fold"] = n_fold + 1 feature_importance_df = pd.concat( [feature_importance_df, fold_importance_df], axis=0) del clf, train_x, train_y, valid_x, valid_y gc.collect() print('------>The %dth model uses %f s' % (i+1, time.time()-t0)) print('------>mean of model:%f' % np.mean(roc_score_list)) print('------>std of model:%f' % np.std(roc_score_list)) # 保存数据 submission = pd.DataFrame( {'SK_ID_CURR': df_test['SK_ID_CURR'], 'TARGET': sub_preds}) oof_train = pd.DataFrame( {'SK_ID_CURR': df_train['SK_ID_CURR'], 'pred': oof_preds}) importance = get_importances(fold_importance_df) print('------>Save Data...') saveData(IsCategory, i, importance, submission, oof_train) def getMeanSub(): ModelCount = 0 submission_ensemble = pd.DataFrame() ResultSaveSubDirWithCategory = os.path.join(ResultSaveDir, 'WithCategory') ResultSaveSubDirWithoutCategory = os.path.join( ResultSaveDir, 'WithoutCategory') if os.path.exists(ResultSaveSubDirWithCategory): print('reading WithCategory') for SubDir in os.listdir(ResultSaveSubDirWithCategory): print(SubDir) submission = pd.read_csv(os.path.join( ResultSaveSubDirWithCategory, SubDir, 'submission.csv'), index_col=0) if len(submission_ensemble): submission_ensemble['TARGET'] += submission['TARGET'] else: submission_ensemble = submission.copy() ModelCount += 1 if os.path.exists(ResultSaveSubDirWithoutCategory): print('reading WithoutCategory') for SubDir in os.listdir(ResultSaveSubDirWithoutCategory): print(SubDir) submission = pd.read_csv(os.path.join( ResultSaveSubDirWithoutCategory, SubDir, 'submission.csv'), index_col=0) if len(submission_ensemble): submission_ensemble['TARGET'] += submission['TARGET'] else: submission_ensemble = submission.copy() ModelCount += 1 submission_ensemble['TARGET'] /= ModelCount return submission_ensemble def main(): print('------>Start train lgb model with category...') train(TrainDataName_withCate, 1) #print('------>Start train lgb model without category...') #train('train_mini3.csv', 0) # 将预测的30个结果做一个均值 #submission_ensemble = getMeanSub() #submission_ensemble.to_csv(os.path.join( #ResultSaveDir, 'submission_ensemble.csv'), index=False) if __name__ == '__main__': main()
[ "wenshaoguo0611@163.com" ]
wenshaoguo0611@163.com
1483cd24cc2bdb62d35c8307505d0e2a9adbd2c7
3bf86722e58af76093eac07a5bf0dbbb7a1f6f98
/application/utils/mail.py
4449c47a127c8be3022b54b4004496a6e2bd1033
[]
no_license
trigladon/forest
348e2dc057c619caa5dba24eec591aed01719f4d
f64e987b2b53ac1720e321494bbdd6c6a4d6b0a0
refs/heads/master
2022-12-15T18:22:21.042210
2019-03-29T07:34:50
2019-03-29T07:34:50
178,353,192
0
0
null
2022-12-08T01:46:08
2019-03-29T07:17:29
Python
UTF-8
Python
false
false
1,059
py
import smtplib, ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from configuration import ( settings, logger as setting_logger ) logger = setting_logger.get_logger(__name__) def send(email_from, email_to, subject, template, variables={}): msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = email_from msg['To'] = email_to template = settings.jinja_env.get_template(template) html = template.render(variables) text = "Пожалуйста используйте html версию письма." mime_text = MIMEText(text, 'plain') html_text = MIMEText(html, 'html') msg.attach(mime_text) msg.attach(html_text) logger.info(f'Send email to {email_to}') with smtplib.SMTP_SSL(settings.EMAIL_URL, settings.EMAIL_PORT) as server: server.ehlo() server.login(settings.EMAIL_USERNAME, settings.EMAIL_PASSWORD) server.sendmail(email_from, email_to, msg.as_string()) logger.info(f'Email to {email_to} sent')
[ "trigladon@gmail.com" ]
trigladon@gmail.com
641034933abd1960b6154c7f2ba6d00c5602d12c
8b1f8ec972406ede68d2664c0a53c6ac307b0dc6
/horizon/horizon/dashboards/nova/overview/urls.py
fc372d5ae87a4299afd544fd05b2720f114fdfe5
[ "Apache-2.0" ]
permissive
artofwar/stack
23a61ffee1e57442b82e00048e9a2793e2a5005a
fc0bef9bf5ad2f0325ea2e4bbc4f37cfa5d56738
refs/heads/master
2021-01-17T05:27:26.181569
2013-02-05T04:55:18
2013-02-05T04:55:18
8,145,813
0
1
null
2020-07-24T08:43:29
2013-02-11T20:24:20
Python
UTF-8
Python
false
false
1,098
py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # 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 django.conf.urls.defaults import url, patterns from .views import ProjectOverview, WarningView urlpatterns = patterns('horizon.dashboards.nova.overview.views', url(r'^$', ProjectOverview.as_view(), name='index'), url(r'^warning$', WarningView.as_view(), name='warning'), )
[ "weiyuanke123@gmail.com" ]
weiyuanke123@gmail.com
85092789baf54e9d15f22e67e6a723793350b160
9d0a6302159217ee4e8b7f1ab987d412862525c2
/Vehicle Detection & Tracking/detector.py
d3c768730394ab01376935cfde8618098a270ffc
[]
no_license
raajprakash/APOLLO_Autonomous_Car
e292d34837dbf0c6d12d70306c1abfe7e743af90
01f1da0b1524849c27bfc614f71e3c5dac66e657
refs/heads/master
2020-06-06T19:22:55.281624
2020-03-09T17:20:22
2020-03-09T17:20:22
192,833,279
0
0
null
null
null
null
UTF-8
Python
false
false
13,882
py
import imageProcessing as ip import numpy as np from Line import Line from LaneFinding import LineSpace import cv2 import helper as aux from moviepy.editor import ImageSequenceClip, VideoFileClip import os.path from tqdm import tqdm from scanner import VehicleScanner class Detector: def __init__(self, imgMarginWidth=320, historyDepth=5, margin=100, windowSplit=2, winCount=9, searchPortion=1., veHiDepth=30, pointSize=64, groupThrd=10, groupDiff=.1, confidenceThrd=.7): self.imgProcessor = ip.Processing() self.warper = ip.Warping() self.imgMarginWidth = imgMarginWidth self.lineLeft = Line(lineSpace=LineSpace.LEFT, historyDepth=historyDepth, margin=margin, windowSplit=windowSplit, winCount=winCount, searchPortion=searchPortion) self.lineRight = Line(lineSpace=LineSpace.RIGHT, historyDepth=historyDepth, margin=margin, windowSplit=windowSplit, winCount=winCount, searchPortion=searchPortion) self.fitHistory = [] # ====| PROJECT 5 - VEHICLE DETECTION |==== # Adding Vehicle scanner self.scanner = VehicleScanner(pointSize=pointSize, veHiDepth=veHiDepth, groupThrd=groupThrd, groupDiff=groupDiff, confidenceThrd=confidenceThrd) def preProcess(self, src): """ Creates binary with combined threshold and applies perspective transform for bird-eye view :param src: source color image (assuming it's been previously undistorted) :return: bird-eye view binary """ imgHeight = src.shape[0] binary = ip.Thresholding.combiThreshold(src=src) filler = np.zeros((imgHeight, self.imgMarginWidth), dtype=np.uint8) binary = np.hstack((filler, binary, filler)) binaryWarp = self.warper.birdEye(img=binary, leftShift=self.imgMarginWidth) return binaryWarp @staticmethod def sanityCheckPass(fitL, fitR): """ Checking for left and right curvatures similarity and lane width to be within a given range :param fitL: left curve polynomial parameters :param fitR: right curve polynomial parameters :return: True or False """ tolerance = 1.2 maxCurvDelta = 0.006 # 0.000666 * tolerance laneWidthRange = (800 / tolerance, 1000 * tolerance) imgBottom = 719 if fitR is None or fitL is None: return False al = fitL[0] ar = fitR[0] curvDelta = abs(ar - al) if curvDelta > maxCurvDelta: return False else: bl = fitL[1] br = fitR[1] cl = fitL[2] cr = fitR[2] leftBottomX = al * (imgBottom ** 2) + bl * imgBottom + cl rightBottomX = ar * (imgBottom ** 2) + br * imgBottom + cr laneWidth = rightBottomX - leftBottomX return (rightBottomX > leftBottomX) & ( laneWidthRange[1] >= laneWidth >= int(laneWidthRange[0])) def addLanePoly(self, srcShape, dst, fitLeft, fitRight): """ Adding lane polygon to an empty image with the shape of bird-eye view with subsequent perspective projection to destination image (clipping previously added left and right fillers) :param srcShape: shape of bird-eye view (may be wider than original image) :param dst: original color (assumed previously undistorted) image :param fitLeft: left curve polynomial parameters :param fitRight: right curve polynomial parameters :return: color image with projected lane """ lanePolyImg, leftOutstand, _ = ip.Drawing.addPolygon(srcShape=srcShape, lFit=fitLeft, rFit=fitRight, stepCount=10, color=(0, 255, 0)) imgH = dst.shape[1] lShift = self.imgMarginWidth + leftOutstand perspective = self.warper.perspective(lanePolyImg, leftShift=lShift)[:, lShift:lShift + imgH, :] return cv2.addWeighted(dst, 1, perspective, 0.5, 0) def addPip(self, pipImage, dstImage, pipAlpha=0.5, pipResizeRatio=0.3, origin=(20, 20)): """ Adding small Picture-in-picture binary bird-eye projection with search areas and found lines embedded :param pipImage: original binary bird-eye projection with search areas and found lines embedded :param dstImage: destination color image (assumed undistorted) :param pipAlpha: pip alpha :param pipResizeRatio: pip scale :param origin: coordinates of upper-left corner of small picture :return: color image with P-i-P embedded """ smallPip = self.imgProcessor.resize(src=pipImage, ratio=pipResizeRatio) pipHeight = smallPip.shape[0] pipWidth = smallPip.shape[1] backGround = dstImage[origin[1]:origin[1] + pipHeight, origin[0]:origin[0] + pipWidth] blend = np.round(backGround * (1 - pipAlpha), 0) + np.round(smallPip * pipAlpha, 0) blend = np.minimum(blend, 255) dstImage[origin[1]:origin[1] + pipHeight, origin[0]:origin[0] + pipWidth] = blend # return dstImage def addOffsetStamp(self, leftFit, rightFit, image, origin, color=(255, 255, 255), fontScale=1.0, thickness=1): """ Evaluating camera offset and adding it to a given image :param thickness: line thickness :param leftFit: left curve polynomial parameters :param rightFit: right curve polynomial parameters :param image: image where data being added :param origin: upper-left corner of the offset stamp :param color: stamp color :param fontScale: font scale :return: void (adds text to passed image) """ imgW = image.shape[1] imgH = image.shape[0] yBottom = imgH - 1 cameraCenter = imgW / 2 lBottomX = aux.funcSpace(argSpace=yBottom, fitParams=leftFit) - self.imgMarginWidth rBottomX = aux.funcSpace(argSpace=yBottom, fitParams=rightFit) - self.imgMarginWidth laneWidth = rBottomX - lBottomX scaleX = 3.7 / laneWidth laneCenter = (lBottomX + rBottomX) / 2 offSet = (cameraCenter - laneCenter) * scaleX aux.putText(img=image, text='Estimated Vehicle Offset: {:.2f} m'.format(offSet), origin=origin, color=color, scale=fontScale, thickness=thickness) @staticmethod def addCurvatureStamp(leftFit, rightFit, image, origin, color=(255, 255, 255), fontScale=1.0, thickness=1): """ Evaluating lane curvature and adding it to a given image :param thickness: text thickness :param leftFit: left curve polynomial parameters :param rightFit: right curve polynomial parameters :param image: image where data being added :param origin: upper-left corner of the offset stamp :param color: stamp color :param fontScale: font scale :return: void (adds text to passed image) """ imgH = image.shape[0] yBottom = imgH - 1 scaleY = 27 / imgH # meters per pixel leftCurvature = aux.curvature(fitParams=leftFit, variable=yBottom, scale=scaleY) rightCurvature = aux.curvature(fitParams=rightFit, variable=yBottom, scale=scaleY) curvature = (leftCurvature + rightCurvature) / 2 aux.putText(img=image, text='Estimated Lane Curvature: {:.1f} m'.format(round(curvature / 100, 1) * 100), origin=origin, color=color, scale=fontScale, thickness=thickness) def embedDetections(self, src, pipParams=None): """ Main 'pipeline' for adding Lane polygon AND detected vehicles to the original image :param src: original image :param pipParams: alpha and scale ratios :return: undistorted color image with the Lane embedded. """ # 1. Undistortion img = self.imgProcessor.undistort(src=src) """ 1a. ====| PROJECT 5 - VEHICLE DETECTION |==== Getting vehicle boxes """ vBoxes, heatMap = self.scanner.relevantBoxes(src=img) # 2. Binary (bird-eye projection) binary = self.preProcess(src=img) # 3. Getting fits currFitLeft, leftFitType, leftBin = self.lineLeft.getFit(src=binary) currFitRight, rightFitType, rightBin = self.lineRight.getFit(src=binary) # 4. Evaluation sanityPass = self.sanityCheckPass(currFitLeft, currFitRight) if sanityPass: # Adding Lane polygon if sanity check passed img = self.addLanePoly(srcShape=binary.shape, dst=img, fitLeft=currFitLeft, fitRight=currFitRight) else: # Evaluation if box-search re-scan justified without resetting history of previous fits if self.lineLeft.reScanJustified(): currFitLeft, leftFitType, leftBin = self.lineLeft.reScanWithPrimary(src=binary) else: # Resetting fits and starting from scratch with box-search self.lineLeft.resetFits() currFitLeft, leftFitType, leftBin = self.lineLeft.getFit(src=binary) # Same for right fit. if self.lineRight.reScanJustified(): currFitRight, rightFitType, rightBin = self.lineRight.reScanWithPrimary(src=binary) else: self.lineRight.resetFits() currFitRight, rightFitType, rightBin = self.lineRight.getFit(src=binary) # Evaluation after second search attempt # sanityPass, laneWidth = self.sanityCheckPass(currFitLeft, currFitRight) sanityPass = self.sanityCheckPass(currFitLeft, currFitRight) # Adding Lane polygon if sanity check passed. Otherwise, simply no poly added if sanityPass: img = self.addLanePoly(srcShape=binary.shape, dst=img, fitLeft=currFitLeft, fitRight=currFitRight) # ====| PROJECT 5 - VEHICLE DETECTION |==== # Drawing vehicle boxes aux.drawBoxes(img=img, bBoxes=vBoxes) # Upper left corner where starting to add pip and telemetry origin = (20, 20) # Adding PIP if pipParams is not None: alpha = pipParams['alpha'] ratio = pipParams['scaleRatio'] # Combining bins from left and right fit searches commonBin = cv2.addWeighted(src1=leftBin, alpha=0.5, src2=rightBin, beta=0.5, gamma=1.0) # To keep for subsequent telemetry stamps pipHeight = int(commonBin.shape[0] * ratio) heatWidth = int(heatMap.shape[1] * ratio) # Lane Detection Picture-in-Picture self.addPip(pipImage=commonBin, dstImage=img, pipAlpha=alpha, pipResizeRatio=ratio, origin=origin) # ====| PROJECT 5 - VEHICLE DETECTION |==== # Vehicle Detection Picture-in-Picture self.addPip(pipImage=heatMap, dstImage=img, pipAlpha=alpha, pipResizeRatio=ratio, origin=(img.shape[1] - heatWidth - 20, 20)) if currFitLeft is not None and currFitRight is not None: self.addCurvatureStamp(leftFit=currFitLeft, rightFit=currFitRight, image=img, origin=(20, pipHeight + 40), fontScale=0.66, thickness=2, color=(0, 255, 0)) self.addOffsetStamp(leftFit=currFitLeft, rightFit=currFitRight, image=img, origin=(20, pipHeight + 70), fontScale=0.66, thickness=2, color=(0, 255, 0)) return img def main(): """ Runs when invoking directly from command line :return: """ resultFrames = [] clipFileName = input('Enter video file name: ') if not os.path.isfile(clipFileName): print('No such file. Exiting.') return clip = VideoFileClip(clipFileName) # depth = aux.promptForInt(message='Enter history depth in frames: ') # detectionPointSize = aux.promptForInt(message='Enter Search Margin: ') # fillerWidth = aux.promptForInt(message='Enter filler width: ') # windowSplit = aux.promptForInt(message='Enter Window Split: ') # winCount = aux.promptForInt(message='Enter Window Count for Box Search: ') # searchPortion = aux.promptForFloat(message='Enter the Search portion (0.0 - 1.0): ') # pipAlpha = aux.promptForFloat(message='Enter Picture-in-picture alpha: (0.0 - 1.0): ') # pipScaleRatio = aux.promptForFloat(message='Enter Picture-in-picture scale (0.0 - 1.0): ') depth = 5 margin = 100 fillerWidth = 320 windowSplit = 2 winCount = 18 searchPortion = 1. pipAlpha = .7 pipScaleRatio = .35 pipParams = {'alpha': pipAlpha, 'scaleRatio': pipScaleRatio} print('Total frames: {}'.format(clip.duration * clip.fps)) ld = Detector(imgMarginWidth=fillerWidth, historyDepth=depth, margin=margin, windowSplit=windowSplit, winCount=winCount, searchPortion=searchPortion, veHiDepth=45, pointSize=64, groupThrd=10, groupDiff=.1, confidenceThrd=.5) for frame in tqdm(clip.iter_frames()): dst = ld.embedDetections(src=frame, pipParams=pipParams) resultFrames.append(dst) resultClip = ImageSequenceClip(resultFrames, fps=25, with_mask=False) resultFileName = clipFileName.split('.')[0] resultFileName = '{}_out_{}.mp4'.format(resultFileName, aux.timeStamp()) resultClip.write_videofile(resultFileName) if __name__ == '__main__': main()
[ "noreply@github.com" ]
raajprakash.noreply@github.com
db2402bfb01caf374619bb7219c1b47b2f0fff35
c4c50697f59d3abcfcd1aee52f1dea452387e9b7
/milestone_2/save_load.py
2d1aabe9829bfbb7a55684f26b8642aa2ef4bbfd
[]
no_license
Stringz/toolkits-architectures
0bbc55ddf0f1cd4210557eaa35117dfc54dd462a
639b8413406f71a836e5e0022d2e2ba9c8e6bd32
refs/heads/master
2023-01-14T14:34:48.627115
2020-11-02T20:34:59
2020-11-02T20:34:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
520
py
from __future__ import print_function from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import Embedding from keras.layers import Conv1D, GlobalMaxPooling1D from keras.datasets import imdb from keras.models import load_model # Save fitted model as .h5-file def saveModel(model,filename): model.save(str(filename)) # Load the model as .h5-file def loadModel(filename): model = load_model(str(filename)) return model
[ "noreply@github.com" ]
Stringz.noreply@github.com
f157f00b6f13e54d55bd5cd0c1cdfb96d9528a7c
7177d2a83895a1ee820487877c0f0176631323b5
/Cross_Checker_OpenCV_Threshold_Vary.py
a7b14d62e0bc32d8d14f863499586e96e4824423
[]
no_license
FTi130/CrossChecker
21c8b4da3d43e7e1d5f5775aac8552fc3a32e8a6
cd3afe7d1d2c0fd7ae722743191ee452ed0fb774
refs/heads/master
2022-04-28T04:43:43.036436
2020-05-02T02:11:31
2020-05-02T02:11:31
260,596,715
0
0
null
null
null
null
UTF-8
Python
false
false
20,100
py
# -*- coding: utf-8 -*- import sys import os from PySide import QtGui, QtCore import numpy as np import cv2 import subprocess import matplotlib.pyplot as plt #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa global info info = [] sys.setrecursionlimit(900) class TestListView(QtGui.QListWidget): fileDropped = QtCore.Signal(list) def __init__(self, type, parent=None): super(TestListView, self).__init__(parent) self.setAcceptDrops(True) # self.setIconSize(QtCore.QSize(300, 300)) def dragEnterEvent(self, event): self.setStyleSheet("background-color: rgb(60, 73, 76);") if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): #self.setStyleSheet("background-color: rgb(100, 63, 66);") if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): self.setStyleSheet("background-color: rgb(35, 40, 45);")##################### rgb(50, 51, 53) if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() links = [] for url in event.mimeData().urls(): try: links.append(str(url.toLocalFile())) except UnicodeEncodeError: msg = QtGui.QMessageBox() msg.setIcon(QtGui.QMessageBox.Critical) msg.setText("Don't feed me with some weird files") msg.setInformativeText('Check if there is a Russian name in {}'.format(str(url).split('///')[1])) msg.setWindowTitle("Wait a second") msg.exec_() self.fileDropped.emit(links) else: event.ignore() def mouseDoubleClickEvent(self, event): self.clearSelection() ################# ################# class MainForm(QtGui.QMainWindow): fileChoosen = QtCore.Signal() resized = QtCore.Signal() global ii ii = 0 def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.view = TestListView(self) self.view.fileDropped.connect(self.ffprobe) # connection to the main function ffprobe self.setCentralWidget(self.view) #self.move(QtGui.QApplication.desktop().screen().rect().center() - self.rect().center()) ### lastchange centre # Title self.setWindowTitle("SILA SVETA OpenCV Checker") # logo self.setWindowIcon(QtGui.QIcon('output_checker_icon.ico')) # Resize Main Window self.resize(1400, 1020) # 1400, 1020 # Enabling of Multiselection goes here self.view.setSelectionMode(self.view.SingleSelection) self.view.setSelectionBehavior(self.view.SelectRows) #self.view.setSelectionMode(self.view.A) #### WTF self.view.setEditTriggers(self.view.NoEditTriggers) self.view.setFocusPolicy(QtCore.Qt.NoFocus) self.setStyleSheet("background-color: rgb(55, 60, 65);\n" # (100,100,100) "border-radius: 2px;\n" "color: rgb(255, 255, 255);\n" "selection-background-color: rgb(120, 160, 230);") #self.view.setStyleSheet("background-color: rgb(35, 40, 45); alternate-background-color: rgb(90,255, 90); color: rgb(255, 255, 255);") ####### color font changes here #('font: bold 8px;') background-color: rgb(100, 100, 100) self.view.setStyleSheet(""" QTableWidget:hover { background-color: rgb(60, 73, 76); alternate-background-color: rgb(90,255, 90); color: rgb(255, 255, 255) } QTableWidget:!hover { background-color: rgb(35, 40, 45); alternate-background-color: rgb(90,255, 90); color: rgb(255, 255, 255)) } """) self.view.setMouseTracking(True) # ComboBoxes self.menu = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.menu.sizePolicy().hasHeightForWidth()) spacerItem = QtGui.QSpacerItem(10, 100, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.menu.setSizePolicy(sizePolicy) self.menu.setMinimumSize(QtCore.QSize(300, 100)) self.menu.setObjectName("menu") self.listwidget = QtGui.QListWidget(self) #raw. #self.listwidget.setStyleSheet('background-color: rgb(35, 75, 45);font: 14px;') #raw. ############################################# self.menu.textDrop = QtGui.QLabel() self.menu.textDrop.setText("You can drop folder on the right") # Buttons self.menu.buttonex = QtGui.QPushButton('Browse', self) #Former Exit self.menu.buttonclear = QtGui.QPushButton('Clear All', self) self.menu.buttonex.setMinimumSize(QtCore.QSize(0, 30)) self.menu.buttonclear.setMinimumSize(QtCore.QSize(0, 30)) # Layouts self.menu.h2Box = QtGui.QVBoxLayout() self.menu.vbox = QtGui.QVBoxLayout() self.menu.hbox = QtGui.QVBoxLayout() self.menu.mybox = QtGui.QHBoxLayout() self.menu.vbox.setContentsMargins(15, 15, -1, 20) #-1 0 -1 -1 self.menu.vbox.addWidget(self.menu.textDrop) # GroupBox self.groupBox_Properties = QtGui.QGroupBox(self.menu) self.groupBox_Properties.setObjectName("groupBox_Properties") font = QtGui.QFont() font.setPointSize(8) self.groupBox_Properties.setFont(font) #self.groupBox_Properties.setStyleSheet("background: red;") self.formLayout = QtGui.QFormLayout(self.groupBox_Properties) self.formLayout.setContentsMargins(0, 26, 0, 16) self.formLayout.setSpacing(10) self.menu.vbox.addWidget(self.groupBox_Properties) #self.menu.vbox.addItem(spacerItem) ############################## add smth indications buttons self.menu.vbox.addWidget(self.menu.buttonex) #vbox self.menu.vbox.addWidget(self.menu.buttonclear) #vbox #self.menu.vbox.addWidget(self.menu.buttonsortname) #### Adding spacer self.menu.vbox.addItem(spacerItem) #self.menu.vbox.addLayout(self.menu.mybox, stretch=True) self.menu.vbox.addLayout(self.menu.h2Box, stretch=True) self.menu.vbox.addLayout(self.menu.hbox, stretch=True) #self.menu.vbox.addLayout(self.menu.mybox, stretch=True) #self.menu.hbox.addLayout(self.menu.vbox) self.menu.setLayout(self.menu.vbox) self.setLayout(self.menu.h2Box) self.setMenuWidget(self.menu) # Here menu Widget becomes Menu on top of the window______________________________ #self.menu.move(0, 500) self.dockMenu = QtGui.QDockWidget(str(""), self) self.dockMenu.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea) self.dockMenu.setWidget(self.menu) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockMenu) self.dockMenu.setFeatures(QtGui.QDockWidget.DockWidgetMovable == False) #QtGui.QDockWidget.DockWidgetFloatable)# | QtGui.QDockWidget.DockWidgetMovable) self.dockMenu.setTitleBarWidget(QtGui.QWidget(None)) ############################################################ ############################################################ # GroupBox ######################################################### ########## ########## # Setting a style for comboboxes and buttons using CSS self.menu.buttonex.setStyleSheet(""" QPushButton:hover { background-color: rgb(105, 110, 115) } QPushButton:!hover { background-color: rgb( 95, 100, 105) } QPushButton:pressed { background-color: rgb(125, 130, 135); } """) self.menu.buttonclear.setStyleSheet(""" QPushButton:hover { background-color: rgb(105, 110, 115) } QPushButton:!hover { background-color: rgb( 95, 100, 105) } QPushButton:pressed { background-color: rgb(125, 130, 135); } """) self.menu.textDrop.setStyleSheet('font: 12px;color:white;') # MS Shell Dlg 2 20px self.menu.buttonclear.clicked.connect(self.cleartable) self.menu.buttonex.clicked.connect(self.openFileDialog) # Exit button openFileDialog ButtonEx def resizeEvent(self, event): self.resized.emit() return super(MainForm, self).resizeEvent(event) # Resize columns after resizing MainWindow def keyPressEvent(self,event): if event.key()==QtCore.Qt.Key_Delete: self._del_item() def _del_item(self): self.view.clear() # Clear the table function def cleartable(self): self.view.clear() def openFileDialog(self): """ Opens a file dialog """ import os path, _ = QtGui.QFileDialog.getOpenFileName(self, "Open File", os.getcwd()) #self.label.setText(path) f=[] f.append(path) self.ffprobe(f) ############################## HERE adding def openDirectoryDialog(self): """ Opens a dialog to allow user to choose a directory """ flags = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly d = directory = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", os.getcwd(),flags) #self.label.setText(d) #Following functions together with their buttons are created because when SetSortingEnabled is True and you sort items in the column pressing on the ColumnHeader # after adding a next batch of urls your rows will mess up. Idk where is the reason, probably, due to adding an empty row affter execution of all ffprobe() actions # Exit function def ButtonEx(self): app.exit() # Main function. It is working with FFprobe and add data to the table def ffprobe(self, f): neededFiles = [] for url in f: # case if dropped item is a file # starting a pathfinder and get all the sequence from its folder if os.path.isfile(url): # print url file_without_path = url.split('/')[-1] path = url.split('/')[:-1] path = '/'.join(path) print path print file_without_path base_name, ext = os.path.splitext(file_without_path) print base_name # print ext everyname = base_name.split('_')[:-1] counter = base_name.split('_')[-1] os.chdir(path) for i in os.listdir(path): i_without_path = i.split('/')[-1] base_name_i, ext_i = os.path.splitext(i_without_path) everyname_i = base_name_i.split('_')[:-1] counter_i = base_name_i.split('_')[-1] if everyname == everyname_i and counter != counter_i: neededFiles.append(i) print neededFiles FirstFileName = neededFiles[1] def GetSequenceName( FirstFileName): # GetSequenceName processes file name and converts it to sequence name, adding pattern like %05d start = '_' end = '.' symbols = list(FirstFileName) i = 0 pos1 = 0 pos2 = 0 for symbol in symbols: if symbol == start: pos1 = i elif symbol == end: pos2 = i i += 1 result = FirstFileName[pos1 + 1:pos2] count = len(result) return (FirstFileName[:pos1] + '_%0' + str(count) + 'd' + FirstFileName[pos2:]) name = str(GetSequenceName(FirstFileName)) ###### # lists = os.listdir(url) # dir is your directory path numberfiles = len(neededFiles) neededFiles.sort() for pics in neededFiles: # print pics img = cv2.imread(pics, cv2.IMREAD_COLOR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) graycenter = gray[int(gray.shape[0] / 2), int(gray.shape[1] / 2)] grayleftUpper = gray[int(gray.shape[0] / 4), int(gray.shape[1] / 4)] threefour = 4 thresh = cv2.threshold(gray, 5, 255, cv2.THRESH_BINARY)[1] fourthree = 4 / 3 thrcenter = thresh[int(thresh.shape[0] / 2), int(thresh.shape[1] / (2))] thrleftUpper = thresh[int(thresh.shape[0] / (4)), int(thresh.shape[1] / 4)] thrrightUpper = thresh[int(thresh.shape[0] / (1.33333333)), int(thresh.shape[1] / 4)] thrrightLower = thresh[int(thresh.shape[0] / (1.33333333)), int(thresh.shape[1] / (1.33333333))] thrleftLower = thresh[int(thresh.shape[0] / 4), int(thresh.shape[1] / (1.33333333))] randompoint1 = thresh[int(thresh.shape[0] / 4), int(thresh.shape[1] / 2.5)] randompoint2 = thresh[int(thresh.shape[0] / 3.7), int(thresh.shape[1] / (1.8))] try: colorCenter = img[int(img.shape[0] / 2), int(img.shape[1] / 2)] except AttributeError: message = str(pics) + " looks like some shit" item = QtGui.QListWidgetItem(message, self.view) #if thrleftLower == thrrightLower == thrrightUpper == thrleftUpper == thrcenter: if (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint1) \ and (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint2): # print "Picture is probably with the cross" try: message = str(pics) + " is probably with cross" item = QtGui.QListWidgetItem(message, self.view) except AttributeError: message = str(pics) + " looks like some shit" item = QtGui.QListWidgetItem(message, self.view) app.processEvents() else: # case if dropped item is a folder with a sequence inside # print url if os.path.exists(url): os.chdir(url) for pics in os.listdir(url): # print pics img = cv2.imread(pics, cv2.IMREAD_COLOR) # #### Start changing try: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) except AttributeError: message = str(pics) + " looks like some shit" item = QtGui.QListWidgetItem(message, self.view) #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) graycenter = gray[int(gray.shape[0] / 2), int(gray.shape[1] / 2)] grayleftUpper = gray[int(gray.shape[0] / 4), int(gray.shape[1] / 4)] threefour = 4 thresh = cv2.threshold(gray, 5, 255, cv2.THRESH_BINARY)[1] fourthree = 4 / 3 thrcenter = thresh[int(thresh.shape[0] / 2), int(thresh.shape[1] / (2))] thrleftUpper = thresh[int(thresh.shape[0] / (4)), int(thresh.shape[1] / 4)] thrrightUpper = thresh[int(thresh.shape[0] / (1.33333333)), int(thresh.shape[1] / 4)] thrrightLower = thresh[int(thresh.shape[0] / (1.33333333)), int(thresh.shape[1] / (1.33333333))] thrleftLower = thresh[int(thresh.shape[0] / 4), int(thresh.shape[1] / (1.33333333))] randompoint1 = thresh[int(thresh.shape[0] / 4), int(thresh.shape[1] / 2.5)] randompoint2 = thresh[int(thresh.shape[0] / 3.7), int(thresh.shape[1] / (1.8))] randompoint3 = thresh[int(thresh.shape[0] / 2), int(thresh.shape[1] / (1.33333333))] randompoint4 = thresh[int(thresh.shape[0] / 1.33333333), int(thresh.shape[1] / 2)] try: colorCenter = img[int(img.shape[0] / 2), int(img.shape[1] / 2)] except AttributeError: message = str(pics) + " looks like some shit" item = QtGui.QListWidgetItem(message, self.view) #if thrleftLower == thrrightLower == thrrightUpper == thrleftUpper ==thrcenter: if (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint1) \ and (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint2) \ and (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint3) \ and (thrleftLower == thrrightLower == thrrightUpper == thrleftUpper != randompoint4): try: icon = QtGui.QIcon(pics) pixmap = icon.pixmap(800, 800) icon = QtGui.QIcon(pixmap) message = str(pics) + " is probably with cross" + "\n" +\ str(thrleftLower) + "__" +\ str(thrrightLower) + "__" +\ str(thrrightUpper) + "__" +\ str(thrleftUpper) + ", Center: " +\ str(thrcenter) + " Random1: " +\ str(randompoint1) + " Random2: " + \ str(randompoint2) item = QtGui.QListWidgetItem(message, self.view) item.setIcon(icon) except AttributeError: message = str(pics) + " looks like some shit" icon = QtGui.QIcon(pics) pixmap = icon.pixmap(800, 800) icon = QtGui.QIcon(pixmap) item = QtGui.QListWidgetItem(message, self.view) item.setIcon(icon) app.processEvents() def main(): global app app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() if __name__ == '__main__': main()
[ "noreply@github.com" ]
FTi130.noreply@github.com
5907690d15733e45c2756e5f9287c4ae14232bbc
cd5b4ccd1d328d236b1d375e35b2dea91259f0e2
/api/migrations/0003_auto_20210213_1601.py
826530665010d175a9243d75d7ce5e4bb331f52c
[]
no_license
Ayan9074/CourseLookUp
68026d81cdd1d6d88d8c9e8174b12b61431c95c3
2e293144204b91693356b775b59b3ca27978ad44
refs/heads/master
2023-03-05T19:18:31.949154
2021-02-14T17:44:02
2021-02-14T17:44:02
338,860,816
0
0
null
null
null
null
UTF-8
Python
false
false
358
py
# Generated by Django 3.1.6 on 2021-02-13 12:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_course_img'), ] operations = [ migrations.AlterField( model_name='course', name='img', field=models.TextField(), ), ]
[ "Ayan9074@yahoo.com" ]
Ayan9074@yahoo.com
60851afd037bbd2705035aa7f44d394c711243a1
5c3196734ee503de910a94a19f61ee4fd8b13dde
/tests/test_tree.py
409cc2cd6fd469dd24ae2b4cbf5df600aed54008
[]
no_license
B3QL/pyheart
3b7b503dc97aa62a1378428f3e1cfb7e2179cac2
8f51f2fc0dec5cfb1cffe0321dc534a24d3eef6f
refs/heads/master
2020-03-17T14:16:13.741098
2018-05-09T09:55:09
2018-05-09T13:03:15
133,665,628
1
0
null
null
null
null
UTF-8
Python
false
false
1,866
py
from pyheart.tree import GameTree, Node, ActionGenerator class UniqueNode(Node): def __hash__(self): return hash(self.__class__) ^ hash(id(self)) def test_create_tree(): tree = GameTree() assert tree.nodes == 1 assert tree.height == 0 tree.root.add_children(UniqueNode() for _ in range(10)) assert tree.nodes == 11 assert tree.height == 1 list(tree.root.children)[0].add_children(UniqueNode() for _ in range(5)) assert tree.nodes == 16 assert tree.height == 2 def test_tree_policy(): tree = GameTree() assert tree.tree_policy() != tree.root assert tree.nodes == 2 assert tree.tree_policy() assert tree.nodes == 3 def test_node_path(): tree = GameTree() root = tree.root root.add_children(Node() for _ in range(10)) first_level = list(root.children)[0] first_level.add_children(Node() for _ in range(5)) leaf = list(first_level.children)[0] assert leaf.is_leaf assert list(leaf.path) == [leaf, first_level, root] def test_node_expand_abilities(): tree = GameTree() root = tree.root tree.game.start() actions = list(ActionGenerator(tree.game)) assert root.is_expandable for _ in actions: assert root.is_expandable tree.expand(root) assert len(root.children) == len(actions) tree.expand(root) assert len(root.children) == len(actions) assert not root.is_expandable def test_node_wins_propagation(): tree = GameTree() tree.run() assert tree.root.wins == tree.root.children[0].wins def test_root_wins_losses_propagation(): tree = GameTree() tree.run(10) wins = sum(tree.root.children.wins) losses = sum(tree.root.children.losses) assert wins == tree.root.wins or wins + 1 == tree.root.wins assert losses == tree.root.losses or losses + 1 == tree.root.losses
[ "bartlomiej+gitlab@kurzeja.it" ]
bartlomiej+gitlab@kurzeja.it
39bbcccfab2796a7203fddb6692ffe0121f7b164
aa86d0078742695a8489bb3d7fed6edc56b926d1
/Problem009.py
4f219092391f377d8291c19cb39ccffca531eb63
[]
no_license
Hyeongseock/EulerProject
fd40793a0bb0f92f65be5f7dde7eb5eeac0d68c6
a63a9ddfd26cf98af8c8927842ff08dbf4d40faf
refs/heads/master
2020-03-21T11:50:29.615519
2018-11-20T11:19:41
2018-11-20T11:19:41
138,524,206
1
0
null
null
null
null
UTF-8
Python
false
false
2,048
py
''' Special Pythagorean triplet Problem 9 ''' ''' English version A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' a = 0 b = 0 c = 0 #i == a and i is the smallest number among 3 numbers. #So, i's max number is 332.(a < b < c ==> 332 < 333 < 335) for i in range(1,333): a = i b = 1000 - a for j in range(2, b) : #j == b and j is the secondary biggest number among 3 number. So, j's min number is 2 because j is bigger than i c = 1000 - i - j # c number depends on a and b(i and j) square_a = a*a square_b = j*j square_c = c*c if square_a + square_b == square_c : #check Pythagorean triplet print(a, j, c) print(a * j * c) #answer break #time spent : 0.069 seconds ''' Korean version 세 자연수 a, b, c 가 피타고라스 정리 a2 + b2 = c2 를 만족하면 피타고라스 수라고 부릅니다 (여기서 a < b < c ). 예를 들면 32 + 42 = 9 + 16 = 25 = 52이므로 3, 4, 5는 피타고라스 수입니다. a + b + c = 1000 인 피타고라스 수 a, b, c는 한 가지 뿐입니다. 이 때, a × b × c 는 얼마입니까? ''' a = 0 b = 0 c = 0 #i는 a이고 i는 a,b,c중에 가장 작은 값이다. #그러므로 i의 최대값은 332이다.(a<b<c이며 최대값은 332<333<335의 경우를 따른다.) for i in range(1,333): a = i b = 1000 - a for j in range(2, b) : #j는 b이며 a,b,c중에 두번째로 크다. 그러므로 j의 최소값은 i보다 커야하므로 2이다. c = 1000 - i - j # c 숫자는 a와 b에 따라 달라진다. square_a = a*a square_b = j*j square_c = c*c if square_a + square_b == square_c : #피타고라스 함수인지 확인하기 print(a, j, c) print(a * j * c) # break #걸린 시간 : 0.069 seconds
[ "noreply@github.com" ]
Hyeongseock.noreply@github.com
dc79bf4d4658c6c6f2bb3784f50b2dcc487dd371
48a90fbcd45aae3d8da7c9564cbefb1bb99b5f47
/HelloScrap.py
820ce74d8a78a27317e3e763c4650a885115e880
[ "BSD-2-Clause" ]
permissive
claw0ed/HelloScrap
2d10fe96caf5aca0ad157d1b97e38fda9df74e80
0f11fe7c887780430cd86f77f60e31613a95a66c
refs/heads/master
2021-05-04T17:35:19.493596
2018-02-13T07:16:00
2018-02-13T07:16:00
120,274,512
0
0
null
null
null
null
UTF-8
Python
false
false
994
py
#-*- coding: utf-8 -*- # 설치 필수 패키지 # requests # BeautifulSoup # 파이썬 패키지 설치 방법 # 1 미리 설치하고 작업 : pip 패키지ㅣ 관리자 # 2 작업 중 설치 : alt + enter import requests from bs4 import BeautifulSoup #py3에서는 bs4로 설치 #py2에서는 BeautifulSoup로 설치 # 지정한 URL로부터 HTML 소스를 가져옴 # source_code = requests.get('http://finance.naver.com') # source_code.encoding = 'euc-kr' source_code = requests.get('http://naver.com') # 웹 사이트에서 HTML 소스를 출력함 - 보기 불편 # print (source_code.text) # 지정한 웹페이지 소스를 변수에 저장 plain_text = source_code.text soup = BeautifulSoup(plain_text, 'lxml') print(soup) # soup = BeautifulSoup(plain_text, 'html.parser') # print(soup) for title in soup.select('title'): print(title.text) for title in soup.select('h3'): print(title.text) for title in soup.select("h3['class=tit']"): print(">>>" + title.text)
[ "claw0ed@gmail.com" ]
claw0ed@gmail.com
545d9076bec7e6604b7c13c8b4747780594480db
f5812c5cc411780c98a26179b105d6e35e9e5dbc
/ast_functions_scope_return/mypy/cases/relational_operators.py
a04f0b9c9fd8fa94fdd6adb34676e7a8d09b906a
[]
no_license
simeonbabatunde/python2-interpreter
157751aa18e5106f0e11b8cbf65fa2202a5c82b9
8f70ce8860b55cbd209c7a6f77ccbdb3abf1a5b7
refs/heads/master
2020-04-08T02:53:49.120509
2019-07-21T22:54:31
2019-07-21T22:54:31
158,952,902
1
0
null
null
null
null
UTF-8
Python
false
false
215
py
x=3 y=2 x+=y**(.5+1*2) def g(): y = 5 if y%-2 == -1: print -2 def k(): x = 8 if y*x+(5%3)**y < 99: print y*x+(5%3)**y else: print 99 k() g()
[ "babatunde.simeon@gmail.com" ]
babatunde.simeon@gmail.com
e023032ed0087cf95d92c25d9409129a98a2ad7c
425f8b4cb3f4bedcc42a35c7a1fc883b28b54711
/model/modules/components/unit_wise_GRU.py
85601efbb0b22707c14c0c3aa143d30f68de3ade
[]
no_license
TobbysGitHub/Brain-like-integrated-network
70aeec9cc85e4788c3728ca31521547020921023
29bf570edc32a55a49c878e25de0220b3b2571c5
refs/heads/master
2021-01-07T23:23:02.832456
2020-05-02T12:24:22
2020-05-02T12:24:22
241,848,766
0
0
null
null
null
null
UTF-8
Python
false
false
2,055
py
import numpy as np import torch from torch import nn from model.modules.components.unit_wise_linear import UnitWiseLinear class UnitWiseGRU(nn.Module): def __init__(self, num_units, in_features, out_features, max_bptt=np.inf): super().__init__() self.num_units = num_units self.in_features = in_features self.out_features = out_features self.max_bptt = max_bptt self.counter = 0 self.ir = UnitWiseLinear(num_units, in_features, out_features, init=False) self.iz = UnitWiseLinear(num_units, in_features, out_features, init=False) self.in_ = UnitWiseLinear(num_units, in_features, out_features, init=False) self.hr = UnitWiseLinear(num_units, out_features, out_features, init=False) self.hz = UnitWiseLinear(num_units, out_features, out_features, init=False) self.hn = UnitWiseLinear(num_units, out_features, out_features, init=False) self.hidden_init = nn.Parameter(torch.empty(1, num_units, self.out_features)) self.hidden = None bound = np.sqrt(1 / out_features) for p in self.parameters(): nn.init.uniform_(p, -bound, bound) def forward(self, x): """ :param x: s_b * num_units * d_input """ if self.hidden is None: self.hidden = self.hidden_init.expand(x.shape[0], -1, -1) r = torch.sigmoid(self.ir(x) + self.hr(self.hidden)) z = torch.sigmoid(self.iz(x) + self.hz(self.hidden)) n = torch.tanh(self.in_(x) + r * self.hn(self.hidden)) x = (1 - z) * n + z * self.hidden self.counter += 1 if self.counter % self.max_bptt == 0: self.hidden = x.detach() else: self.hidden = x return x def reset(self): self.hidden = None def extra_repr(self) -> str: return 'num_units={num_units}, in_features={in_features}, ' \ 'out_features={out_features}, max_bptt={max_bptt}'.format(**self.__dict__) if __name__ == '__main__': pass
[ "15652969420@163.com" ]
15652969420@163.com
6af47eb3ef096ca55c61f98b997fbe4372f50239
077e837f753a62e894da3e44342dbca0e48b520e
/scatterGraph.py
d2b19f917ebab92a2fb79eb2c56744f50662a964
[]
no_license
CzarKunder/C-103
97600f7d6e055bce552137c3c0f616eb20f7f0f4
2d54d948a729f35f4c7c53e4a31b2cffdd44764f
refs/heads/main
2023-07-14T10:14:49.446196
2021-08-27T11:14:26
2021-08-27T11:14:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
139
py
import pandas as pd import plotly_express as px df=pd.read_csv("data.csv") fig=px.scatter(df,x="date",y="cases",color="country") fig.show()
[ "noreply@github.com" ]
CzarKunder.noreply@github.com
7f18d11dddb539bf444bf341f2475c2791d74926
ce529b23367320ac89f964e99f2340d1356602b6
/FNN_try1.py
4182ba6f318d440d48747bd75a78014e2e7e2fb4
[]
no_license
Ian8797/March_Madness-
08d9947b22f17c1e312cfd865c34dcf3e07da207
71f2927552edda6ef45dd84b2b03f77e660c481d
refs/heads/master
2020-07-24T23:47:37.672420
2019-09-12T15:59:43
2019-09-12T15:59:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,533
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 2 14:19:52 2019 @author: ianvaimberg Pretty good accuracy toping out at around 73% """ import pandas as pd import pyodbc import numpy as np from sklearn.preprocessing import StandardScaler import random import tensorflow as tf a=pyodbc.connect('DRIVER=/Library/simba/sqlserverodbc/lib/libsqlserverodbc_sbu.dylib;' 'SERVER=localhost;' 'DATABASE=march_madness;' 'UID=sa;' 'PWD=Ivaim1997%') cursor = a.cursor() cursor.execute(""" SELECT r.Season, r.WTeamID, CAST(SUBSTRING(s1.Seed,2,2) AS INT) AS Win_Seed, r.LTeamID, CAST(SUBSTRING(s2.Seed,2,2) AS INT) AS Lose_Seed, m2.Centered_SOS-m1.Centered_SOS AS SOS_diff, m2.Rank_day_129-m1.Rank_day_129 AS Rank_diff, m1.Off_eff-m2.Off_eff AS Off_eff_diff, m1.Off_speed-m2.Off_speed AS Off_speed_diff, m2.Def_eff-m1.Def_eff AS Def_eff_diff, m1.Def_speed-m2.Def_speed AS Def_speed_diff, m1.Winslast10 - m2.Winslast10 AS Winslast10_diff, m1.Plus_Minus_last10 - m2.Plus_Minus_last10 AS Plus_Minus_last10_diff, m1.FGPct - m2.FGPct AS FGPct_diff, m1.FG3Pct - m2.FG3Pct AS FG3Pct_diff, m1.FTPct - m2.FTPct AS FTPct_diff, m1.PFPG - m2.PFPG AS PFPG_diff, m2.PAPG - m1.PAPG AS PAPG_diff, m1.Plus_Minus - m2.Plus_Minus AS Plus_Minus_diff, m1.wins - m2.wins AS wins_diff, m2.Losses - m1.Losses AS Losses_diff FROM NCAATourneyCompactResults_ r JOIN NCAATourneySeeds s1 ON s1.Season = r.Season AND s1.TeamID = r.WTeamID JOIN NCAATourneySeeds s2 ON s2.Season = r.Season AND s2.TeamID = r.LTeamID /*WHERE r.Season >=2003 ORDER BY CAST(SUBSTRING(s2.Seed,2,2) AS INT) - CAST(SUBSTRING(s1.Seed,2,2) AS INT) DESC*/ JOIN Master_Table m1 ON r.Season = m1.Season AND r.WTeamID = m1.TeamID JOIN Master_Table m2 ON r.Season = m2.Season AND r.LTeamID = m2.TeamID;""") cols = ['Season','WTeamID','Win_Seed','LTeamID','Lose_Seed','SOS_diff','Rank_diff','Off_eff_diff', 'Off_speed_diff','Def_eff_diff','Def_speed_diff','Winslast10_diff', 'Plus_Minus_last10_diff','FGPct_diff','FG3Pct_diff', 'FTPct_diff', 'PFPG_diff', 'PAPG_diff','Plus_Minus_diff', 'Wins_diff','Losses_diff'] results = pd.DataFrame(np.array(cursor.fetchall()),columns=cols) drop_cols = ['Season','WTeamID','Win_Seed','LTeamID','Lose_Seed'] imp_data = results.drop(columns=drop_cols) #print(imp_data['SOS_diff']) target = np.zeros((imp_data.shape[0],2)) for x in range(target.shape[0]): #all target vectors are [1,0] (winner-loser) or [0,1] (loser-winner) target[x,0] = random.choice([1,0]) # will really need to play attention to order when inserting 2019 data target[x,1] = 1-target[x,0] for x,i in zip(range(imp_data.shape[0]), target[:,0]): if i == 0: imp_data.iloc[x] = imp_data.iloc[x]*-1 #multipled some by -1 to show (loser-winner) data_std = StandardScaler().fit_transform(imp_data) data_std = pd.DataFrame(data_std) data_std["T1"] = target[:,0] data_std["T2"] = target[:,1] shuffled = tf.random.shuffle(data_std.values) k = 5 # the k in k_fold ind = [int(int(shuffled.shape[0])/k)*x for x in range(k)] ind.append(shuffled.shape[0]) full_index = np.arange(0,1048) results = [] data_std = tf.slice(shuffled,[0,0],[-1,16]) #data slice target = tf.slice(shuffled,[0,16],[-1,2]) # target slice #print(target) for x in range(k): model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(8, input_dim=imp_data.shape[1], activation='relu')) model.add(tf.keras.layers.Dense(2,activation='sigmoid')) model.compile(loss='mean_squared_error',optimizer='adam',metrics=['binary_accuracy']) # working on k - fold cross validation, 5 fold train_indices = np.delete(full_index,np.s_[ind[x]:ind[x+1]]) test_indices = np.delete(full_index,train_indices) #print(train_indices,test_indices) history = model.fit(tf.gather(data_std,tf.constant(train_indices)), tf.gather(target,tf.constant(train_indices)), epochs=200, steps_per_epoch=1, verbose=1) test_data = np.array(tf.gather(data_std,tf.constant(test_indices))) prediction = model.predict(test_data) b = np.zeros_like(prediction) b[np.arange(len(prediction)), prediction.argmax(1)] = 1 length = len(test_indices) compare = tf.gather(target,test_indices).numpy() #print(b,type(b),compare,type(compare)) #break results.append((sum(b == compare/length)[0])) print(results)
[ "noreply@github.com" ]
Ian8797.noreply@github.com
d775b455901b007d04aabe84cc1f0977ab3515c0
a5bec8821233c1dfac266de331b810a44bbe0d1c
/insta_uploader.py
84a24459d2cc7b7cf8d4fc82aa83c256cc10604d
[]
no_license
Anitej/plp_bot
e341d96b94fa3472b9e4cb4e84669c291b505022
a31e3b7774140e1ce0909c67226270a20041a3d2
refs/heads/master
2020-08-23T00:59:59.774294
2019-10-21T08:19:22
2019-10-21T08:19:22
216,054,760
0
0
null
null
null
null
UTF-8
Python
false
false
236
py
from InstagramAPI import InstagramAPI from os import getcwd api = InstagramAPI('USERNAME','PASSWORD') api.login() image_path = getcwd()+'/image.jpg' caption = 'test' api.uploadPhoto(image_path,caption=caption) print('my upload done')
[ "noreply@github.com" ]
Anitej.noreply@github.com
bb79ec35e80fe9a5ce0d1864a9defd91f9079e1e
fb4a589b87fde22d43fe4345794c00bbc3785085
/resources/oci-lib/lib/python3.6/site-packages/services/core/src/oci_cli_virtual_network/generated/virtualnetwork_cli.py
2755a5bb958688d7f2e52e3318996e5cab4b333f
[]
no_license
dickiesanders/oci-cli-action
a29ccf353a09cb110a38dc9c7f9ea76260c62a48
ef409321a0b9bdbce37e0e39cfe0e6499ccffe1f
refs/heads/master
2022-12-18T02:52:07.786446
2020-09-19T09:44:02
2020-09-19T09:44:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
682,685
py
# coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from __future__ import print_function import click import oci # noqa: F401 import six # noqa: F401 import sys # noqa: F401 from oci_cli import cli_constants # noqa: F401 from oci_cli import cli_util from oci_cli import json_skeleton_utils from oci_cli import custom_types # noqa: F401 from oci_cli.aliasing import CommandGroupWithAlias from services.core.src.oci_cli_core.generated import core_service_cli @click.command(cli_util.override('virtual_network.virtual_network_root_group.command_name', 'virtual-network'), cls=CommandGroupWithAlias, help=cli_util.override('virtual_network.virtual_network_root_group.help', """API covering the [Networking], [Compute], and [Block Volume] services. Use this API to manage resources such as virtual cloud networks (VCNs), compute instances, and block storage volumes."""), short_help=cli_util.override('virtual_network.virtual_network_root_group.short_help', """Core Services API""")) @cli_util.help_option_group def virtual_network_root_group(): pass @click.command(cli_util.override('virtual_network.remote_peering_connection_group.command_name', 'remote-peering-connection'), cls=CommandGroupWithAlias, help="""A remote peering connection (RPC) is an object on a DRG that lets the VCN that is attached to the DRG peer with a VCN in a different region. *Peering* means that the two VCNs can communicate using private IP addresses, but without the traffic traversing the internet or routing through your on-premises network. For more information, see [VCN Peering]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def remote_peering_connection_group(): pass @click.command(cli_util.override('virtual_network.subnet_group.command_name', 'subnet'), cls=CommandGroupWithAlias, help="""A logical subdivision of a VCN. Each subnet consists of a contiguous range of IP addresses that do not overlap with other subnets in the VCN. Example: 172.16.1.0/24. For more information, see [Overview of the Networking Service] and [VCNs and Subnets]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def subnet_group(): pass @click.command(cli_util.override('virtual_network.nat_gateway_group.command_name', 'nat-gateway'), cls=CommandGroupWithAlias, help="""A NAT (Network Address Translation) gateway, which represents a router that lets instances without public IPs contact the public internet without exposing the instance to inbound internet traffic. For more information, see [NAT Gateway]. To use any of the API operations, you must be authorized in an IAM policy. If you are not authorized, talk to an administrator. If you are an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def nat_gateway_group(): pass @click.command(cli_util.override('virtual_network.drg_attachment_group.command_name', 'drg-attachment'), cls=CommandGroupWithAlias, help="""A link between a DRG and VCN. For more information, see [Overview of the Networking Service]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def drg_attachment_group(): pass @click.command(cli_util.override('virtual_network.public_ip_group.command_name', 'public-ip'), cls=CommandGroupWithAlias, help="""A *public IP* is a conceptual term that refers to a public IP address and related properties. The `publicIp` object is the API representation of a public IP. There are two types of public IPs: 1. Ephemeral 2. Reserved For more information and comparison of the two types, see [Public IP Addresses]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def public_ip_group(): pass @click.command(cli_util.override('virtual_network.ip_sec_connection_device_config_group.command_name', 'ip-sec-connection-device-config'), cls=CommandGroupWithAlias, help="""Deprecated. For tunnel information, instead see: * [IPSecConnectionTunnel] * [IPSecConnectionTunnelSharedSecret]""") @cli_util.help_option_group def ip_sec_connection_device_config_group(): pass @click.command(cli_util.override('virtual_network.ip_sec_connection_tunnel_group.command_name', 'ip-sec-connection-tunnel'), cls=CommandGroupWithAlias, help="""Information about a single tunnel in an IPSec connection. This object does not include the tunnel's shared secret (pre-shared key). That is in the [IPSecConnectionTunnelSharedSecret] object.""") @cli_util.help_option_group def ip_sec_connection_tunnel_group(): pass @click.command(cli_util.override('virtual_network.fast_connect_provider_service_group.command_name', 'fast-connect-provider-service'), cls=CommandGroupWithAlias, help="""A service offering from a supported provider. For more information, see [FastConnect Overview].""") @cli_util.help_option_group def fast_connect_provider_service_group(): pass @click.command(cli_util.override('virtual_network.cross_connect_location_group.command_name', 'cross-connect-location'), cls=CommandGroupWithAlias, help="""An individual FastConnect location.""") @cli_util.help_option_group def cross_connect_location_group(): pass @click.command(cli_util.override('virtual_network.virtual_circuit_public_prefix_group.command_name', 'virtual-circuit-public-prefix'), cls=CommandGroupWithAlias, help="""A public IP prefix and its details. With a public virtual circuit, the customer specifies the customer-owned public IP prefixes to advertise across the connection. For more information, see [FastConnect Overview].""") @cli_util.help_option_group def virtual_circuit_public_prefix_group(): pass @click.command(cli_util.override('virtual_network.private_ip_group.command_name', 'private-ip'), cls=CommandGroupWithAlias, help="""A *private IP* is a conceptual term that refers to an IPv4 private IP address and related properties. The `privateIp` object is the API representation of a private IP. **Note:** For information about IPv6 addresses, see [Ipv6]. Each instance has a *primary private IP* that is automatically created and assigned to the primary VNIC during instance launch. If you add a secondary VNIC to the instance, it also automatically gets a primary private IP. You can't remove a primary private IP from its VNIC. The primary private IP is automatically deleted when the VNIC is terminated. You can add *secondary private IPs* to a VNIC after it's created. For more information, see the `privateIp` operations and also [IP Addresses]. **Note:** Only [ListPrivateIps] and [GetPrivateIp] work with *primary* private IPs. To create and update primary private IPs, you instead work with instance and VNIC operations. For example, a primary private IP's properties come from the values you specify in [CreateVnicDetails] when calling either [LaunchInstance] or [AttachVnic]. To update the hostname for a primary private IP, you use [UpdateVnic]. `PrivateIp` objects that are created for use with the Oracle Cloud VMware Solution are assigned to a VLAN and not a VNIC in a subnet. See the descriptions of the relevant attributes in the `PrivateIp` object. Also see [Vlan]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def private_ip_group(): pass @click.command(cli_util.override('virtual_network.ip_sec_connection_tunnel_shared_secret_group.command_name', 'ip-sec-connection-tunnel-shared-secret'), cls=CommandGroupWithAlias, help="""The tunnel's shared secret (pre-shared key).""") @cli_util.help_option_group def ip_sec_connection_tunnel_shared_secret_group(): pass @click.command(cli_util.override('virtual_network.virtual_circuit_group.command_name', 'virtual-circuit'), cls=CommandGroupWithAlias, help="""For use with Oracle Cloud Infrastructure FastConnect. A virtual circuit is an isolated network path that runs over one or more physical network connections to provide a single, logical connection between the edge router on the customer's existing network and Oracle Cloud Infrastructure. *Private* virtual circuits support private peering, and *public* virtual circuits support public peering. For more information, see [FastConnect Overview]. Each virtual circuit is made up of information shared between a customer, Oracle, and a provider (if the customer is using FastConnect via a provider). Who fills in a given property of a virtual circuit depends on whether the BGP session related to that virtual circuit goes from the customer's edge router to Oracle, or from the provider's edge router to Oracle. Also, in the case where the customer is using a provider, values for some of the properties may not be present immediately, but may get filled in as the provider and Oracle each do their part to provision the virtual circuit. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def virtual_circuit_group(): pass @click.command(cli_util.override('virtual_network.local_peering_gateway_group.command_name', 'local-peering-gateway'), cls=CommandGroupWithAlias, help="""A local peering gateway (LPG) is an object on a VCN that lets that VCN peer with another VCN in the same region. *Peering* means that the two VCNs can communicate using private IP addresses, but without the traffic traversing the internet or routing through your on-premises network. For more information, see [VCN Peering]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def local_peering_gateway_group(): pass @click.command(cli_util.override('virtual_network.tunnel_cpe_device_config_group.command_name', 'tunnel-cpe-device-config'), cls=CommandGroupWithAlias, help="""The set of CPE configuration answers for the tunnel, which the customer provides in [UpdateTunnelCpeDeviceConfig]. The answers correlate to the questions that are specific to the CPE device type (see the `parameters` attribute of [CpeDeviceShapeDetail]). See these related operations: * [GetTunnelCpeDeviceConfig] * [GetTunnelCpeDeviceConfigContent] * [GetIpsecCpeDeviceConfigContent] * [GetCpeDeviceConfigContent]""") @cli_util.help_option_group def tunnel_cpe_device_config_group(): pass @click.command(cli_util.override('virtual_network.vlan_group.command_name', 'vlan'), cls=CommandGroupWithAlias, help="""A resource to be used only with the Oracle Cloud VMware Solution. Conceptually, a virtual LAN (VLAN) is a broadcast domain that is created by partitioning and isolating a network at the data link layer (a *layer 2 network*). VLANs work by using IEEE 802.1Q VLAN tags. Layer 2 traffic is forwarded within the VLAN based on MAC learning. In the Networking service, a VLAN is an object within a VCN. You use VLANs to partition the VCN at the data link layer (layer 2). A VLAN is analagous to a subnet, which is an object for partitioning the VCN at the IP layer (layer 3).""") @cli_util.help_option_group def vlan_group(): pass @click.command(cli_util.override('virtual_network.ipv6_group.command_name', 'ipv6'), cls=CommandGroupWithAlias, help="""An *IPv6* is a conceptual term that refers to an IPv6 address and related properties. The `IPv6` object is the API representation of an IPv6. You can create and assign an IPv6 to any VNIC that is in an IPv6-enabled subnet in an IPv6-enabled VCN. **Note:** IPv6 addressing is currently supported only in certain regions. For important details about IPv6 addressing in a VCN, see [IPv6 Addresses].""") @cli_util.help_option_group def ipv6_group(): pass @click.command(cli_util.override('virtual_network.cross_connect_port_speed_shape_group.command_name', 'cross-connect-port-speed-shape'), cls=CommandGroupWithAlias, help="""An individual port speed level for cross-connects.""") @cli_util.help_option_group def cross_connect_port_speed_shape_group(): pass @click.command(cli_util.override('virtual_network.drg_group.command_name', 'drg'), cls=CommandGroupWithAlias, help="""A dynamic routing gateway (DRG), which is a virtual router that provides a path for private network traffic between your VCN and your existing network. You use it with other Networking Service components to create an IPSec VPN or a connection that uses Oracle Cloud Infrastructure FastConnect. For more information, see [Overview of the Networking Service]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def drg_group(): pass @click.command(cli_util.override('virtual_network.route_table_group.command_name', 'route-table'), cls=CommandGroupWithAlias, help="""A collection of `RouteRule` objects, which are used to route packets based on destination IP to a particular network entity. For more information, see [Overview of the Networking Service]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def route_table_group(): pass @click.command(cli_util.override('virtual_network.cpe_group.command_name', 'cpe'), cls=CommandGroupWithAlias, help="""An object you create when setting up an IPSec VPN between your on-premises network and VCN. The `Cpe` is a virtual representation of your customer-premises equipment, which is the actual router on-premises at your site at your end of the IPSec VPN connection. For more information, see [Overview of the Networking Service]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def cpe_group(): pass @click.command(cli_util.override('virtual_network.cross_connect_group.command_name', 'cross-connect'), cls=CommandGroupWithAlias, help="""For use with Oracle Cloud Infrastructure FastConnect. A cross-connect represents a physical connection between an existing network and Oracle. Customers who are colocated with Oracle in a FastConnect location create and use cross-connects. For more information, see [FastConnect Overview]. Oracle recommends you create each cross-connect in a [CrossConnectGroup] so you can use link aggregation with the connection. **Note:** If you're a provider who is setting up a physical connection to Oracle so customers can use FastConnect over the connection, be aware that your connection is modeled the same way as a colocated customer's (with `CrossConnect` and `CrossConnectGroup` objects, and so on). To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def cross_connect_group(): pass @click.command(cli_util.override('virtual_network.letter_of_authority_group.command_name', 'letter-of-authority'), cls=CommandGroupWithAlias, help="""The Letter of Authority for the cross-connect. You must submit this letter when requesting cabling for the cross-connect at the FastConnect location.""") @cli_util.help_option_group def letter_of_authority_group(): pass @click.command(cli_util.override('virtual_network.cross_connect_status_group.command_name', 'cross-connect-status'), cls=CommandGroupWithAlias, help="""The status of the cross-connect.""") @cli_util.help_option_group def cross_connect_status_group(): pass @click.command(cli_util.override('virtual_network.security_rule_group.command_name', 'security-rule'), cls=CommandGroupWithAlias, help="""A security rule is one of the items in a [NetworkSecurityGroup]. It is a virtual firewall rule for the VNICs in the network security group. A rule can be for either inbound (`direction`= INGRESS) or outbound (`direction`= EGRESS) IP packets.""") @cli_util.help_option_group def security_rule_group(): pass @click.command(cli_util.override('virtual_network.vcn_group.command_name', 'vcn'), cls=CommandGroupWithAlias, help="""A virtual cloud network (VCN). For more information, see [Overview of the Networking Service]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def vcn_group(): pass @click.command(cli_util.override('virtual_network.cpe_device_shape_group.command_name', 'cpe-device-shape'), cls=CommandGroupWithAlias, help="""A summary of information about a particular CPE device type. Compare with [CpeDeviceShapeDetail].""") @cli_util.help_option_group def cpe_device_shape_group(): pass @click.command(cli_util.override('virtual_network.ip_sec_connection_device_status_group.command_name', 'ip-sec-connection-device-status'), cls=CommandGroupWithAlias, help="""Deprecated. For tunnel information, instead see [IPSecConnectionTunnel].""") @cli_util.help_option_group def ip_sec_connection_device_status_group(): pass @click.command(cli_util.override('virtual_network.network_security_group_vnic_group.command_name', 'network-security-group-vnic'), cls=CommandGroupWithAlias, help="""Information about a VNIC that belongs to a network security group.""") @cli_util.help_option_group def network_security_group_vnic_group(): pass @click.command(cli_util.override('virtual_network.vnic_group.command_name', 'vnic'), cls=CommandGroupWithAlias, help="""A virtual network interface card. Each VNIC resides in a subnet in a VCN. An instance attaches to a VNIC to obtain a network connection into the VCN through that subnet. Each instance has a *primary VNIC* that is automatically created and attached during launch. You can add *secondary VNICs* to an instance after it's launched. For more information, see [Virtual Network Interface Cards (VNICs)]. Each VNIC has a *primary private IP* that is automatically assigned during launch. You can add *secondary private IPs* to a VNIC after it's created. For more information, see [CreatePrivateIp] and [IP Addresses]. If you are an Oracle Cloud VMware Solution customer, you will have secondary VNICs that reside in a VLAN instead of a subnet. These VNICs have other differences, which are called out in the descriptions of the relevant attributes in the `Vnic` object. Also see [Vlan]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def vnic_group(): pass @click.command(cli_util.override('virtual_network.cpe_device_shape_detail_group.command_name', 'cpe-device-shape-detail'), cls=CommandGroupWithAlias, help="""The detailed information about a particular CPE device type. Compare with [CpeDeviceShapeSummary].""") @cli_util.help_option_group def cpe_device_shape_detail_group(): pass @click.command(cli_util.override('virtual_network.fast_connect_provider_service_key_group.command_name', 'fast-connect-provider-service-key'), cls=CommandGroupWithAlias, help="""A provider service key and its details. A provider service key is an identifier for a provider's virtual circuit.""") @cli_util.help_option_group def fast_connect_provider_service_key_group(): pass @click.command(cli_util.override('virtual_network.dhcp_options_group.command_name', 'dhcp-options'), cls=CommandGroupWithAlias, help="""A set of DHCP options. Used by the VCN to automatically provide configuration information to the instances when they boot up. There are two options you can set: - [DhcpDnsOption]: Lets you specify how DNS (hostname resolution) is handled in the subnets in your VCN. - [DhcpSearchDomainOption]: Lets you specify a search domain name to use for DNS queries. For more information, see [DNS in Your Virtual Cloud Network] and [DHCP Options]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def dhcp_options_group(): pass @click.command(cli_util.override('virtual_network.virtual_circuit_bandwidth_shape_group.command_name', 'virtual-circuit-bandwidth-shape'), cls=CommandGroupWithAlias, help="""An individual bandwidth level for virtual circuits.""") @cli_util.help_option_group def virtual_circuit_bandwidth_shape_group(): pass @click.command(cli_util.override('virtual_network.peer_region_for_remote_peering_group.command_name', 'peer-region-for-remote-peering'), cls=CommandGroupWithAlias, help="""Details about a region that supports remote VCN peering. For more information, see [VCN Peering].""") @cli_util.help_option_group def peer_region_for_remote_peering_group(): pass @click.command(cli_util.override('virtual_network.service_gateway_group.command_name', 'service-gateway'), cls=CommandGroupWithAlias, help="""Represents a router that lets your VCN privately access specific Oracle services such as Object Storage without exposing the VCN to the public internet. Traffic leaving the VCN and destined for a supported Oracle service (see [ListServices]) is routed through the service gateway and does not traverse the internet. The instances in the VCN do not need to have public IP addresses nor be in a public subnet. The VCN does not need an internet gateway for this traffic. For more information, see [Access to Oracle Services: Service Gateway]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def service_gateway_group(): pass @click.command(cli_util.override('virtual_network.internet_gateway_group.command_name', 'internet-gateway'), cls=CommandGroupWithAlias, help="""Represents a router that connects the edge of a VCN with the Internet. For an example scenario that uses an internet gateway, see [Typical Networking Service Scenarios]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def internet_gateway_group(): pass @click.command(cli_util.override('virtual_network.ip_sec_connection_group.command_name', 'ip-sec-connection'), cls=CommandGroupWithAlias, help="""A connection between a DRG and CPE. This connection consists of multiple IPSec tunnels. Creating this connection is one of the steps required when setting up an IPSec VPN. **Important:** Each tunnel in an IPSec connection can use either static routing or BGP dynamic routing (see the [IPSecConnectionTunnel] object's `routing` attribute). Originally only static routing was supported and every IPSec connection was required to have at least one static route configured. To maintain backward compatibility in the API when support for BPG dynamic routing was introduced, the API accepts an empty list of static routes if you configure both of the IPSec tunnels to use BGP dynamic routing. If you switch a tunnel's routing from `BGP` to `STATIC`, you must first ensure that the IPSec connection is configured with at least one valid CIDR block static route. Oracle uses the IPSec connection's static routes when routing a tunnel's traffic *only* if that tunnel's `routing` attribute = `STATIC`. Otherwise the static routes are ignored. For more information about the workflow for setting up an IPSec connection, see [IPSec VPN]. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def ip_sec_connection_group(): pass @click.command(cli_util.override('virtual_network.service_group.command_name', 'service'), cls=CommandGroupWithAlias, help="""An object that represents one or multiple Oracle services that you can enable for a [ServiceGateway]. In the User Guide topic [Access to Oracle Services: Service Gateway], the term *service CIDR label* is used to refer to the string that represents the regional public IP address ranges of the Oracle service or services covered by a given `Service` object. That unique string is the value of the `Service` object's `cidrBlock` attribute.""") @cli_util.help_option_group def service_group(): pass @click.command(cli_util.override('virtual_network.network_security_group_group.command_name', 'network-security-group'), cls=CommandGroupWithAlias, help="""A *network security group* (NSG) provides virtual firewall rules for a specific set of [VNICs] in a VCN. Compare NSGs with [SecurityLists], which provide virtual firewall rules to all the VNICs in a *subnet*. A network security group consists of two items: * The set of [VNICs] that all have the same security rule needs (for example, a group of Compute instances all running the same application) * A set of NSG [SecurityRules] that apply to the VNICs in the group After creating an NSG, you can add VNICs and security rules to it. For example, when you create an instance, you can specify one or more NSGs to add the instance to (see [CreateVnicDetails]). Or you can add an existing instance to an NSG with [UpdateVnic]. To add security rules to an NSG, see [AddNetworkSecurityGroupSecurityRules]. To list the VNICs in an NSG, see [ListNetworkSecurityGroupVnics]. To list the security rules in an NSG, see [ListNetworkSecurityGroupSecurityRules]. For more information about network security groups, see [Network Security Groups]. **Important:** Oracle Cloud Infrastructure Compute service images automatically include firewall rules (for example, Linux iptables, Windows firewall). If there are issues with some type of access to an instance, make sure all of the following are set correctly: * Any security rules in any NSGs the instance's VNIC belongs to * Any [SecurityLists] associated with the instance's subnet * The instance's OS firewall rules To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def network_security_group_group(): pass @click.command(cli_util.override('virtual_network.cross_connect_group_group.command_name', 'cross-connect-group'), cls=CommandGroupWithAlias, help="""For use with Oracle Cloud Infrastructure FastConnect. A cross-connect group is a link aggregation group (LAG), which can contain one or more [CrossConnects]. Customers who are colocated with Oracle in a FastConnect location create and use cross-connect groups. For more information, see [FastConnect Overview]. **Note:** If you're a provider who is setting up a physical connection to Oracle so customers can use FastConnect over the connection, be aware that your connection is modeled the same way as a colocated customer's (with `CrossConnect` and `CrossConnectGroup` objects, and so on). To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def cross_connect_group_group(): pass @click.command(cli_util.override('virtual_network.drg_redundancy_status_group.command_name', 'drg-redundancy-status'), cls=CommandGroupWithAlias, help="""The redundancy status of the DRG. For more information, see [Redundancy Remedies].""") @cli_util.help_option_group def drg_redundancy_status_group(): pass @click.command(cli_util.override('virtual_network.security_list_group.command_name', 'security-list'), cls=CommandGroupWithAlias, help="""A set of virtual firewall rules for your VCN. Security lists are configured at the subnet level, but the rules are applied to the ingress and egress traffic for the individual instances in the subnet. The rules can be stateful or stateless. For more information, see [Security Lists]. **Note:** Compare security lists to [NetworkSecurityGroup]s, which let you apply a set of security rules to a *specific set of VNICs* instead of an entire subnet. Oracle recommends using network security groups instead of security lists, although you can use either or both together. **Important:** Oracle Cloud Infrastructure Compute service images automatically include firewall rules (for example, Linux iptables, Windows firewall). If there are issues with some type of access to an instance, make sure both the security lists associated with the instance's subnet and the instance's firewall rules are set correctly. To use any of the API operations, you must be authorized in an IAM policy. If you're not authorized, talk to an administrator. If you're an administrator who needs to write policies to give users access, see [Getting Started with Policies]. **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.""") @cli_util.help_option_group def security_list_group(): pass core_service_cli.core_service_group.add_command(virtual_network_root_group) virtual_network_root_group.add_command(remote_peering_connection_group) virtual_network_root_group.add_command(subnet_group) virtual_network_root_group.add_command(nat_gateway_group) virtual_network_root_group.add_command(drg_attachment_group) virtual_network_root_group.add_command(public_ip_group) virtual_network_root_group.add_command(ip_sec_connection_device_config_group) virtual_network_root_group.add_command(ip_sec_connection_tunnel_group) virtual_network_root_group.add_command(fast_connect_provider_service_group) virtual_network_root_group.add_command(cross_connect_location_group) virtual_network_root_group.add_command(virtual_circuit_public_prefix_group) virtual_network_root_group.add_command(private_ip_group) virtual_network_root_group.add_command(ip_sec_connection_tunnel_shared_secret_group) virtual_network_root_group.add_command(virtual_circuit_group) virtual_network_root_group.add_command(local_peering_gateway_group) virtual_network_root_group.add_command(tunnel_cpe_device_config_group) virtual_network_root_group.add_command(vlan_group) virtual_network_root_group.add_command(ipv6_group) virtual_network_root_group.add_command(cross_connect_port_speed_shape_group) virtual_network_root_group.add_command(drg_group) virtual_network_root_group.add_command(route_table_group) virtual_network_root_group.add_command(cpe_group) virtual_network_root_group.add_command(cross_connect_group) virtual_network_root_group.add_command(letter_of_authority_group) virtual_network_root_group.add_command(cross_connect_status_group) virtual_network_root_group.add_command(security_rule_group) virtual_network_root_group.add_command(vcn_group) virtual_network_root_group.add_command(cpe_device_shape_group) virtual_network_root_group.add_command(ip_sec_connection_device_status_group) virtual_network_root_group.add_command(network_security_group_vnic_group) virtual_network_root_group.add_command(vnic_group) virtual_network_root_group.add_command(cpe_device_shape_detail_group) virtual_network_root_group.add_command(fast_connect_provider_service_key_group) virtual_network_root_group.add_command(dhcp_options_group) virtual_network_root_group.add_command(virtual_circuit_bandwidth_shape_group) virtual_network_root_group.add_command(peer_region_for_remote_peering_group) virtual_network_root_group.add_command(service_gateway_group) virtual_network_root_group.add_command(internet_gateway_group) virtual_network_root_group.add_command(ip_sec_connection_group) virtual_network_root_group.add_command(service_group) virtual_network_root_group.add_command(network_security_group_group) virtual_network_root_group.add_command(cross_connect_group_group) virtual_network_root_group.add_command(drg_redundancy_status_group) virtual_network_root_group.add_command(security_list_group) @security_rule_group.command(name=cli_util.override('virtual_network.add_network_security_group_security_rules.command_name', 'add'), help=u"""Adds one or more security rules to the specified network security group.""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--security-rules', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The NSG security rules to add. This option is a JSON list with items of type AddSecurityRuleDetails. For documentation on AddSecurityRuleDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/AddSecurityRuleDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @json_skeleton_utils.get_cli_json_input_option({'security-rules': {'module': 'core', 'class': 'list[AddSecurityRuleDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'security-rules': {'module': 'core', 'class': 'list[AddSecurityRuleDetails]'}}, output_type={'module': 'core', 'class': 'AddedNetworkSecurityGroupSecurityRules'}) @cli_util.wrap_exceptions def add_network_security_group_security_rules(ctx, from_json, network_security_group_id, security_rules): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} _details = {} if security_rules is not None: _details['securityRules'] = cli_util.parse_json_parameter("security_rules", security_rules) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.add_network_security_group_security_rules( network_security_group_id=network_security_group_id, add_network_security_group_security_rules_details=_details, **kwargs ) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.attach_service_id.command_name', 'attach'), help=u"""Adds the specified [Service] to the list of enabled `Service` objects for the specified gateway. You must also set up a route rule with the `cidrBlock` of the `Service` as the rule's destination and the service gateway as the rule's target. See [Route Table]. **Note:** The `AttachServiceId` operation is an easy way to add an individual `Service` to the service gateway. Compare it with [UpdateServiceGateway], which replaces the entire existing list of enabled `Service` objects with the list that you provide in the `Update` call.""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @cli_util.option('--service-id', required=True, help=u"""The [OCID] of the [Service].""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'ServiceGateway'}) @cli_util.wrap_exceptions def attach_service_id(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, service_gateway_id, service_id, if_match): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} _details['serviceId'] = service_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.attach_service_id( service_gateway_id=service_gateway_id, attach_service_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_service_gateway') and callable(getattr(client, 'get_service_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_service_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @virtual_circuit_public_prefix_group.command(name=cli_util.override('virtual_network.bulk_add_virtual_circuit_public_prefixes.command_name', 'bulk-add'), help=u"""Adds one or more customer public IP prefixes to the specified public virtual circuit. Use this operation (and not [UpdateVirtualCircuit]) to add prefixes to the virtual circuit. Oracle must verify the customer's ownership of each prefix before traffic for that prefix will flow across the virtual circuit.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--public-prefixes', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The public IP prefixes (CIDRs) to add to the public virtual circuit.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @json_skeleton_utils.get_cli_json_input_option({'public-prefixes': {'module': 'core', 'class': 'list[CreateVirtualCircuitPublicPrefixDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'public-prefixes': {'module': 'core', 'class': 'list[CreateVirtualCircuitPublicPrefixDetails]'}}) @cli_util.wrap_exceptions def bulk_add_virtual_circuit_public_prefixes(ctx, from_json, virtual_circuit_id, public_prefixes): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} _details = {} _details['publicPrefixes'] = cli_util.parse_json_parameter("public_prefixes", public_prefixes) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.bulk_add_virtual_circuit_public_prefixes( virtual_circuit_id=virtual_circuit_id, bulk_add_virtual_circuit_public_prefixes_details=_details, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_public_prefix_group.command(name=cli_util.override('virtual_network.bulk_delete_virtual_circuit_public_prefixes.command_name', 'bulk-delete'), help=u"""Removes one or more customer public IP prefixes from the specified public virtual circuit. Use this operation (and not [UpdateVirtualCircuit]) to remove prefixes from the virtual circuit. When the virtual circuit's state switches back to PROVISIONED, Oracle stops advertising the specified prefixes across the connection.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--public-prefixes', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The public IP prefixes (CIDRs) to remove from the public virtual circuit.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @json_skeleton_utils.get_cli_json_input_option({'public-prefixes': {'module': 'core', 'class': 'list[DeleteVirtualCircuitPublicPrefixDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'public-prefixes': {'module': 'core', 'class': 'list[DeleteVirtualCircuitPublicPrefixDetails]'}}) @cli_util.wrap_exceptions def bulk_delete_virtual_circuit_public_prefixes(ctx, from_json, virtual_circuit_id, public_prefixes): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} _details = {} _details['publicPrefixes'] = cli_util.parse_json_parameter("public_prefixes", public_prefixes) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.bulk_delete_virtual_circuit_public_prefixes( virtual_circuit_id=virtual_circuit_id, bulk_delete_virtual_circuit_public_prefixes_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.change_cpe_compartment.command_name', 'change-compartment'), help=u"""Moves a CPE object into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the CPE.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the CPE object to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_cpe_compartment(ctx, from_json, cpe_id, compartment_id): if isinstance(cpe_id, six.string_types) and len(cpe_id.strip()) == 0: raise click.UsageError('Parameter --cpe-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_cpe_compartment( cpe_id=cpe_id, change_cpe_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.change_cross_connect_compartment.command_name', 'change-compartment'), help=u"""Moves a cross-connect into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the cross-connect to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_cross_connect_compartment(ctx, from_json, cross_connect_id, compartment_id): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_cross_connect_compartment( cross_connect_id=cross_connect_id, change_cross_connect_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.change_cross_connect_group_compartment.command_name', 'change-compartment'), help=u"""Moves a cross-connect group into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--cross-connect-group-id', required=True, help=u"""The OCID of the cross-connect group.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the cross-connect group to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_cross_connect_group_compartment(ctx, from_json, cross_connect_group_id, compartment_id): if isinstance(cross_connect_group_id, six.string_types) and len(cross_connect_group_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-group-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_cross_connect_group_compartment( cross_connect_group_id=cross_connect_group_id, change_cross_connect_group_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.change_dhcp_options_compartment.command_name', 'change-compartment'), help=u"""Moves a set of DHCP options into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--dhcp-id', required=True, help=u"""The OCID for the set of DHCP options.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the set of DHCP options to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_dhcp_options_compartment(ctx, from_json, dhcp_id, compartment_id): if isinstance(dhcp_id, six.string_types) and len(dhcp_id.strip()) == 0: raise click.UsageError('Parameter --dhcp-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_dhcp_options_compartment( dhcp_id=dhcp_id, change_dhcp_options_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.change_drg_compartment.command_name', 'change-compartment'), help=u"""Moves a DRG into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the DRG to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_drg_compartment(ctx, from_json, drg_id, compartment_id): if isinstance(drg_id, six.string_types) and len(drg_id.strip()) == 0: raise click.UsageError('Parameter --drg-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_drg_compartment( drg_id=drg_id, change_drg_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.change_internet_gateway_compartment.command_name', 'change-compartment'), help=u"""Moves an internet gateway into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--ig-id', required=True, help=u"""The OCID of the internet gateway.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the internet gateway to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_internet_gateway_compartment(ctx, from_json, ig_id, compartment_id): if isinstance(ig_id, six.string_types) and len(ig_id.strip()) == 0: raise click.UsageError('Parameter --ig-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_internet_gateway_compartment( ig_id=ig_id, change_internet_gateway_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.change_ip_sec_connection_compartment.command_name', 'change-compartment'), help=u"""Moves an IPSec connection into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the IPSec connection to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_ip_sec_connection_compartment(ctx, from_json, ipsc_id, compartment_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_ip_sec_connection_compartment( ipsc_id=ipsc_id, change_ip_sec_connection_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.change_local_peering_gateway_compartment.command_name', 'change-compartment'), help=u"""Moves a local peering gateway into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--local-peering-gateway-id', required=True, help=u"""The OCID of the local peering gateway.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the local peering gateway to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_local_peering_gateway_compartment(ctx, from_json, local_peering_gateway_id, compartment_id): if isinstance(local_peering_gateway_id, six.string_types) and len(local_peering_gateway_id.strip()) == 0: raise click.UsageError('Parameter --local-peering-gateway-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_local_peering_gateway_compartment( local_peering_gateway_id=local_peering_gateway_id, change_local_peering_gateway_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.change_nat_gateway_compartment.command_name', 'change-compartment'), help=u"""Moves a NAT gateway into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--nat-gateway-id', required=True, help=u"""The NAT gateway's [OCID].""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the NAT gateway to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_nat_gateway_compartment(ctx, from_json, nat_gateway_id, compartment_id): if isinstance(nat_gateway_id, six.string_types) and len(nat_gateway_id.strip()) == 0: raise click.UsageError('Parameter --nat-gateway-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_nat_gateway_compartment( nat_gateway_id=nat_gateway_id, change_nat_gateway_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.change_network_security_group_compartment.command_name', 'change-compartment'), help=u"""Moves a network security group into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the network security group to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_network_security_group_compartment(ctx, from_json, network_security_group_id, compartment_id): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_network_security_group_compartment( network_security_group_id=network_security_group_id, change_network_security_group_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.change_public_ip_compartment.command_name', 'change-compartment'), help=u"""Moves a public IP into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment]. This operation applies only to reserved public IPs. Ephemeral public IPs always belong to the same compartment as their VNIC and move accordingly.""") @cli_util.option('--public-ip-id', required=True, help=u"""The OCID of the public IP.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the public IP to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_public_ip_compartment(ctx, from_json, public_ip_id, compartment_id): if isinstance(public_ip_id, six.string_types) and len(public_ip_id.strip()) == 0: raise click.UsageError('Parameter --public-ip-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_public_ip_compartment( public_ip_id=public_ip_id, change_public_ip_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.change_remote_peering_connection_compartment.command_name', 'change-compartment'), help=u"""Moves a remote peering connection (RPC) into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--remote-peering-connection-id', required=True, help=u"""The OCID of the remote peering connection (RPC).""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the remote peering connection to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_remote_peering_connection_compartment(ctx, from_json, remote_peering_connection_id, compartment_id): if isinstance(remote_peering_connection_id, six.string_types) and len(remote_peering_connection_id.strip()) == 0: raise click.UsageError('Parameter --remote-peering-connection-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_remote_peering_connection_compartment( remote_peering_connection_id=remote_peering_connection_id, change_remote_peering_connection_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.change_route_table_compartment.command_name', 'change-compartment'), help=u"""Moves a route table into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--rt-id', required=True, help=u"""The OCID of the route table.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the route table to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_route_table_compartment(ctx, from_json, rt_id, compartment_id): if isinstance(rt_id, six.string_types) and len(rt_id.strip()) == 0: raise click.UsageError('Parameter --rt-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_route_table_compartment( rt_id=rt_id, change_route_table_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.change_security_list_compartment.command_name', 'change-compartment'), help=u"""Moves a security list into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--security-list-id', required=True, help=u"""The OCID of the security list.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the security list to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_security_list_compartment(ctx, from_json, security_list_id, compartment_id): if isinstance(security_list_id, six.string_types) and len(security_list_id.strip()) == 0: raise click.UsageError('Parameter --security-list-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_security_list_compartment( security_list_id=security_list_id, change_security_list_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.change_service_gateway_compartment.command_name', 'change-compartment'), help=u"""Moves a service gateway into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the service gateway to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_service_gateway_compartment(ctx, from_json, service_gateway_id, compartment_id): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_service_gateway_compartment( service_gateway_id=service_gateway_id, change_service_gateway_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.change_subnet_compartment.command_name', 'change-compartment'), help=u"""Moves a subnet into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--subnet-id', required=True, help=u"""The OCID of the subnet.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the subnet to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_subnet_compartment(ctx, from_json, subnet_id, compartment_id): if isinstance(subnet_id, six.string_types) and len(subnet_id.strip()) == 0: raise click.UsageError('Parameter --subnet-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_subnet_compartment( subnet_id=subnet_id, change_subnet_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @vcn_group.command(name=cli_util.override('virtual_network.change_vcn_compartment.command_name', 'change-compartment'), help=u"""Moves a VCN into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the VCN to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_vcn_compartment(ctx, from_json, vcn_id, compartment_id): if isinstance(vcn_id, six.string_types) and len(vcn_id.strip()) == 0: raise click.UsageError('Parameter --vcn-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_vcn_compartment( vcn_id=vcn_id, change_vcn_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.change_virtual_circuit_compartment.command_name', 'change-compartment'), help=u"""Moves a virtual circuit into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the virtual circuit to.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_virtual_circuit_compartment(ctx, from_json, virtual_circuit_id, compartment_id): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_virtual_circuit_compartment( virtual_circuit_id=virtual_circuit_id, change_virtual_circuit_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.change_vlan_compartment.command_name', 'change-compartment'), help=u"""Moves a VLAN into a different compartment within the same tenancy. For information about moving resources between compartments, see [Moving Resources to a Different Compartment].""") @cli_util.option('--vlan-id', required=True, help=u"""The [OCID] of the VLAN.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to move the VLAN to.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def change_vlan_compartment(ctx, from_json, vlan_id, compartment_id, if_match): if isinstance(vlan_id, six.string_types) and len(vlan_id.strip()) == 0: raise click.UsageError('Parameter --vlan-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['compartmentId'] = compartment_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.change_vlan_compartment( vlan_id=vlan_id, change_vlan_compartment_details=_details, **kwargs ) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.connect_local_peering_gateways.command_name', 'connect'), help=u"""Connects this local peering gateway (LPG) to another one in the same region. This operation must be called by the VCN administrator who is designated as the *requestor* in the peering relationship. The *acceptor* must implement an Identity and Access Management (IAM) policy that gives the requestor permission to connect to LPGs in the acceptor's compartment. Without that permission, this operation will fail. For more information, see [VCN Peering].""") @cli_util.option('--local-peering-gateway-id', required=True, help=u"""The OCID of the local peering gateway.""") @cli_util.option('--peer-id', required=True, help=u"""The OCID of the LPG you want to peer with.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def connect_local_peering_gateways(ctx, from_json, local_peering_gateway_id, peer_id): if isinstance(local_peering_gateway_id, six.string_types) and len(local_peering_gateway_id.strip()) == 0: raise click.UsageError('Parameter --local-peering-gateway-id cannot be whitespace or empty string') kwargs = {} _details = {} _details['peerId'] = peer_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.connect_local_peering_gateways( local_peering_gateway_id=local_peering_gateway_id, connect_local_peering_gateways_details=_details, **kwargs ) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.connect_remote_peering_connections.command_name', 'connect'), help=u"""Connects this RPC to another one in a different region. This operation must be called by the VCN administrator who is designated as the *requestor* in the peering relationship. The *acceptor* must implement an Identity and Access Management (IAM) policy that gives the requestor permission to connect to RPCs in the acceptor's compartment. Without that permission, this operation will fail. For more information, see [VCN Peering].""") @cli_util.option('--remote-peering-connection-id', required=True, help=u"""The OCID of the remote peering connection (RPC).""") @cli_util.option('--peer-id', required=True, help=u"""The OCID of the RPC you want to peer with.""") @cli_util.option('--peer-region-name', required=True, help=u"""The name of the region that contains the RPC you want to peer with. Example: `us-ashburn-1`""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def connect_remote_peering_connections(ctx, from_json, remote_peering_connection_id, peer_id, peer_region_name): if isinstance(remote_peering_connection_id, six.string_types) and len(remote_peering_connection_id.strip()) == 0: raise click.UsageError('Parameter --remote-peering-connection-id cannot be whitespace or empty string') kwargs = {} _details = {} _details['peerId'] = peer_id _details['peerRegionName'] = peer_region_name client = cli_util.build_client('core', 'virtual_network', ctx) result = client.connect_remote_peering_connections( remote_peering_connection_id=remote_peering_connection_id, connect_remote_peering_connections_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.create_cpe.command_name', 'create'), help=u"""Creates a new virtual customer-premises equipment (CPE) object in the specified compartment. For more information, see [IPSec VPNs]. For the purposes of access control, you must provide the OCID of the compartment where you want the CPE to reside. Notice that the CPE doesn't have to be in the same compartment as the IPSec connection or other Networking Service components. If you're not sure which compartment to use, put the CPE in the same compartment as the DRG. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You must provide the public IP address of your on-premises router. See [Configuring Your On-Premises Router for an IPSec VPN]. You may optionally specify a *display name* for the CPE, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the CPE.""") @cli_util.option('--ip-address', required=True, help=u"""The public IP address of the on-premises router. Example: `203.0.113.2`""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--cpe-device-shape-id', help=u"""The [OCID] of the CPE device type. You can provide a value if you want to later generate CPE device configuration content for IPSec connections that use this CPE. You can also call [UpdateCpe] later to provide a value. For a list of possible values, see [ListCpeDeviceShapes]. For more information about generating CPE device configuration content, see: * [GetCpeDeviceConfigContent] * [GetIpsecCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfig]""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Cpe'}) @cli_util.wrap_exceptions def create_cpe(ctx, from_json, compartment_id, ip_address, defined_tags, display_name, freeform_tags, cpe_device_shape_id): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['ipAddress'] = ip_address if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if cpe_device_shape_id is not None: _details['cpeDeviceShapeId'] = cpe_device_shape_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_cpe( create_cpe_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.create_cross_connect.command_name', 'create'), help=u"""Creates a new cross-connect. Oracle recommends you create each cross-connect in a [CrossConnectGroup] so you can use link aggregation with the connection. After creating the `CrossConnect` object, you need to go the FastConnect location and request to have the physical cable installed. For more information, see [FastConnect Overview]. For the purposes of access control, you must provide the OCID of the compartment where you want the cross-connect to reside. If you're not sure which compartment to use, put the cross-connect in the same compartment with your VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the cross-connect. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the cross-connect.""") @cli_util.option('--location-name', required=True, help=u"""The name of the FastConnect location where this cross-connect will be installed. To get a list of the available locations, see [ListCrossConnectLocations]. Example: `CyrusOne, Chandler, AZ`""") @cli_util.option('--port-speed-shape-name', required=True, help=u"""The port speed for this cross-connect. To get a list of the available port speeds, see [ListCrossConnectPortSpeedShapes]. Example: `10 Gbps`""") @cli_util.option('--cross-connect-group-id', help=u"""The OCID of the cross-connect group to put this cross-connect in.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--far-cross-connect-or-cross-connect-group-id', help=u"""If you already have an existing cross-connect or cross-connect group at this FastConnect location, and you want this new cross-connect to be on a different router (for the purposes of redundancy), provide the OCID of that existing cross-connect or cross-connect group.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--near-cross-connect-or-cross-connect-group-id', help=u"""If you already have an existing cross-connect or cross-connect group at this FastConnect location, and you want this new cross-connect to be on the same router, provide the OCID of that existing cross-connect or cross-connect group.""") @cli_util.option('--customer-reference-name', help=u"""A reference name or identifier for the physical fiber connection that this cross-connect uses.""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_CUSTOMER", "PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'CrossConnect'}) @cli_util.wrap_exceptions def create_cross_connect(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, location_name, port_speed_shape_name, cross_connect_group_id, defined_tags, display_name, far_cross_connect_or_cross_connect_group_id, freeform_tags, near_cross_connect_or_cross_connect_group_id, customer_reference_name): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['locationName'] = location_name _details['portSpeedShapeName'] = port_speed_shape_name if cross_connect_group_id is not None: _details['crossConnectGroupId'] = cross_connect_group_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if far_cross_connect_or_cross_connect_group_id is not None: _details['farCrossConnectOrCrossConnectGroupId'] = far_cross_connect_or_cross_connect_group_id if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if near_cross_connect_or_cross_connect_group_id is not None: _details['nearCrossConnectOrCrossConnectGroupId'] = near_cross_connect_or_cross_connect_group_id if customer_reference_name is not None: _details['customerReferenceName'] = customer_reference_name client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_cross_connect( create_cross_connect_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect') and callable(getattr(client, 'get_cross_connect')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_cross_connect(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.create_cross_connect_group.command_name', 'create'), help=u"""Creates a new cross-connect group to use with Oracle Cloud Infrastructure FastConnect. For more information, see [FastConnect Overview]. For the purposes of access control, you must provide the OCID of the compartment where you want the cross-connect group to reside. If you're not sure which compartment to use, put the cross-connect group in the same compartment with your VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the cross-connect group. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the cross-connect group.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--customer-reference-name', help=u"""A reference name or identifier for the physical fiber connection that this cross-connect group uses.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'CrossConnectGroup'}) @cli_util.wrap_exceptions def create_cross_connect_group(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, defined_tags, display_name, customer_reference_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if customer_reference_name is not None: _details['customerReferenceName'] = customer_reference_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_cross_connect_group( create_cross_connect_group_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect_group') and callable(getattr(client, 'get_cross_connect_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_cross_connect_group(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.create_dhcp_options.command_name', 'create'), help=u"""Creates a new set of DHCP options for the specified VCN. For more information, see [DhcpOptions]. For the purposes of access control, you must provide the OCID of the compartment where you want the set of DHCP options to reside. Notice that the set of options doesn't have to be in the same compartment as the VCN, subnets, or other Networking Service components. If you're not sure which compartment to use, put the set of DHCP options in the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the set of DHCP options, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the set of DHCP options.""") @cli_util.option('--options', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""A set of DHCP options.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN the set of DHCP options belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'options': {'module': 'core', 'class': 'list[DhcpOption]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'options': {'module': 'core', 'class': 'list[DhcpOption]'}}, output_type={'module': 'core', 'class': 'DhcpOptions'}) @cli_util.wrap_exceptions def create_dhcp_options(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, options, vcn_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['options'] = cli_util.parse_json_parameter("options", options) _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_dhcp_options( create_dhcp_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_dhcp_options') and callable(getattr(client, 'get_dhcp_options')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_dhcp_options(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.create_drg.command_name', 'create'), help=u"""Creates a new dynamic routing gateway (DRG) in the specified compartment. For more information, see [Dynamic Routing Gateways (DRGs)]. For the purposes of access control, you must provide the OCID of the compartment where you want the DRG to reside. Notice that the DRG doesn't have to be in the same compartment as the VCN, the DRG attachment, or other Networking Service components. If you're not sure which compartment to use, put the DRG in the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the DRG, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the DRG.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Drg'}) @cli_util.wrap_exceptions def create_drg(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_drg( create_drg_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg') and callable(getattr(client, 'get_drg')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_drg(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_attachment_group.command(name=cli_util.override('virtual_network.create_drg_attachment.command_name', 'create'), help=u"""Attaches the specified DRG to the specified VCN. A VCN can be attached to only one DRG at a time, and vice versa. The response includes a `DrgAttachment` object with its own OCID. For more information about DRGs, see [Dynamic Routing Gateways (DRGs)]. You may optionally specify a *display name* for the attachment, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information. For the purposes of access control, the DRG attachment is automatically placed into the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service].""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN.""") @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique. Avoid entering confidential information.""") @cli_util.option('--route-table-id', help=u"""The OCID of the route table the DRG attachment will use. If you don't specify a route table here, the DRG attachment is created without an associated route table. The Networking service does NOT automatically associate the attached VCN's default route table with the DRG attachment. For information about why you would associate a route table with a DRG attachment, see: * [Transit Routing: Access to Multiple VCNs in Same Region] * [Transit Routing: Private Access to Oracle Services]""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ATTACHING", "ATTACHED", "DETACHING", "DETACHED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'DrgAttachment'}) @cli_util.wrap_exceptions def create_drg_attachment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, drg_id, vcn_id, display_name, route_table_id): kwargs = {} _details = {} _details['drgId'] = drg_id _details['vcnId'] = vcn_id if display_name is not None: _details['displayName'] = display_name if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_drg_attachment( create_drg_attachment_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg_attachment') and callable(getattr(client, 'get_drg_attachment')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_drg_attachment(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.create_internet_gateway.command_name', 'create'), help=u"""Creates a new internet gateway for the specified VCN. For more information, see [Access to the Internet]. For the purposes of access control, you must provide the OCID of the compartment where you want the Internet Gateway to reside. Notice that the internet gateway doesn't have to be in the same compartment as the VCN or other Networking Service components. If you're not sure which compartment to use, put the Internet Gateway in the same compartment with the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the internet gateway, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information. For traffic to flow between a subnet and an internet gateway, you must create a route rule accordingly in the subnet's route table (for example, 0.0.0.0/0 > internet gateway). See [UpdateRouteTable]. You must specify whether the internet gateway is enabled when you create it. If it's disabled, that means no traffic will flow to/from the internet even if there's a route rule that enables that traffic. You can later use [UpdateInternetGateway] to easily disable/enable the gateway without changing the route rule.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the internet gateway.""") @cli_util.option('--is-enabled', required=True, type=click.BOOL, help=u"""Whether the gateway is enabled upon creation.""") @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN the internet gateway is attached to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'InternetGateway'}) @cli_util.wrap_exceptions def create_internet_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, is_enabled, vcn_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['isEnabled'] = is_enabled _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_internet_gateway( create_internet_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_internet_gateway') and callable(getattr(client, 'get_internet_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_internet_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.create_ip_sec_connection.command_name', 'create'), help=u"""Creates a new IPSec connection between the specified DRG and CPE. For more information, see [IPSec VPNs]. If you configure at least one tunnel to use static routing, then in the request you must provide at least one valid static route (you're allowed a maximum of 10). For example: 10.0.0.0/16. If you configure both tunnels to use BGP dynamic routing, you can provide an empty list for the static routes. For more information, see the important note in [IPSecConnection]. For the purposes of access control, you must provide the OCID of the compartment where you want the IPSec connection to reside. Notice that the IPSec connection doesn't have to be in the same compartment as the DRG, CPE, or other Networking Service components. If you're not sure which compartment to use, put the IPSec connection in the same compartment as the DRG. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the IPSec connection, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information. After creating the IPSec connection, you need to configure your on-premises router with tunnel-specific information. For tunnel status and the required configuration information, see: * [IPSecConnectionTunnel] * [IPSecConnectionTunnelSharedSecret] For each tunnel, you need the IP address of Oracle's VPN headend and the shared secret (that is, the pre-shared key). For more information, see [Configuring Your On-Premises Router for an IPSec VPN].""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the IPSec connection.""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the [Cpe] object.""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @cli_util.option('--static-routes', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Static routes to the CPE. A static route's CIDR must not be a multicast address or class E address. Used for routing a given IPSec tunnel's traffic only if the tunnel is using static routing. If you configure at least one tunnel to use static routing, then you must provide at least one valid static route. If you configure both tunnels to use BGP dynamic routing, you can provide an empty list for the static routes. For more information, see the important note in [IPSecConnection]. The CIDR can be either IPv4 or IPv6. Note that IPv6 addressing is currently supported only in certain regions. See [IPv6 Addresses]. Example: `10.0.1.0/24` Example: `2001:db8::/32`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--cpe-local-identifier', help=u"""Your identifier for your CPE device. Can be either an IP address or a hostname (specifically, the fully qualified domain name (FQDN)). The type of identifier you provide here must correspond to the value for `cpeLocalIdentifierType`. If you don't provide a value, the `ipAddress` attribute for the [Cpe] object specified by `cpeId` is used as the `cpeLocalIdentifier`. For information about why you'd provide this value, see [If Your CPE Is Behind a NAT Device]. Example IP address: `10.0.3.3` Example hostname: `cpe.example.com`""") @cli_util.option('--cpe-local-identifier-type', type=custom_types.CliCaseInsensitiveChoice(["IP_ADDRESS", "HOSTNAME"]), help=u"""The type of identifier for your CPE device. The value you provide here must correspond to the value for `cpeLocalIdentifier`.""") @cli_util.option('--tunnel-configuration', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Information for creating the individual tunnels in the IPSec connection. You can provide a maximum of 2 `tunnelConfiguration` objects in the array (one for each of the two tunnels). This option is a JSON list with items of type CreateIPSecConnectionTunnelDetails. For documentation on CreateIPSecConnectionTunnelDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/CreateIPSecConnectionTunnelDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'static-routes': {'module': 'core', 'class': 'list[string]'}, 'tunnel-configuration': {'module': 'core', 'class': 'list[CreateIPSecConnectionTunnelDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'static-routes': {'module': 'core', 'class': 'list[string]'}, 'tunnel-configuration': {'module': 'core', 'class': 'list[CreateIPSecConnectionTunnelDetails]'}}, output_type={'module': 'core', 'class': 'IPSecConnection'}) @cli_util.wrap_exceptions def create_ip_sec_connection(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, cpe_id, drg_id, static_routes, defined_tags, display_name, freeform_tags, cpe_local_identifier, cpe_local_identifier_type, tunnel_configuration): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['cpeId'] = cpe_id _details['drgId'] = drg_id _details['staticRoutes'] = cli_util.parse_json_parameter("static_routes", static_routes) if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if cpe_local_identifier is not None: _details['cpeLocalIdentifier'] = cpe_local_identifier if cpe_local_identifier_type is not None: _details['cpeLocalIdentifierType'] = cpe_local_identifier_type if tunnel_configuration is not None: _details['tunnelConfiguration'] = cli_util.parse_json_parameter("tunnel_configuration", tunnel_configuration) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_ip_sec_connection( create_ip_sec_connection_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_ip_sec_connection') and callable(getattr(client, 'get_ip_sec_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_ip_sec_connection(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ipv6_group.command(name=cli_util.override('virtual_network.create_ipv6.command_name', 'create'), help=u"""Creates an IPv6 for the specified VNIC.""") @cli_util.option('--vnic-id', required=True, help=u"""The [OCID] of the VNIC to assign the IPv6 to. The IPv6 will be in the VNIC's subnet.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--ip-address', help=u"""An IPv6 address of your choice. Must be an available IP address within the subnet's CIDR. If you don't specify a value, Oracle automatically assigns an IPv6 address from the subnet. The subnet is the one that contains the VNIC you specify in `vnicId`. Example: `2001:DB8::`""") @cli_util.option('--is-internet-access-allowed', type=click.BOOL, help=u"""Whether the IPv6 can be used for internet communication. Allowed by default for an IPv6 in a public subnet. Never allowed for an IPv6 in a private subnet. If the value is `true`, the IPv6 uses its public IP address for internet communication. If `isInternetAccessAllowed` is set to `false`, the resulting `publicIpAddress` attribute for the Ipv6 is null. Example: `true`""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Ipv6'}) @cli_util.wrap_exceptions def create_ipv6(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, vnic_id, defined_tags, display_name, freeform_tags, ip_address, is_internet_access_allowed): kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['vnicId'] = vnic_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if ip_address is not None: _details['ipAddress'] = ip_address if is_internet_access_allowed is not None: _details['isInternetAccessAllowed'] = is_internet_access_allowed client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_ipv6( create_ipv6_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_ipv6') and callable(getattr(client, 'get_ipv6')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_ipv6(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.create_local_peering_gateway.command_name', 'create'), help=u"""Creates a new local peering gateway (LPG) for the specified VCN.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment containing the local peering gateway (LPG).""") @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN the LPG belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the LPG will use. If you don't specify a route table here, the LPG is created without an associated route table. The Networking service does NOT automatically associate the attached VCN's default route table with the LPG. For information about why you would associate a route table with an LPG, see [Transit Routing: Access to Multiple VCNs in Same Region].""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'LocalPeeringGateway'}) @cli_util.wrap_exceptions def create_local_peering_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, vcn_id, defined_tags, display_name, freeform_tags, route_table_id): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_local_peering_gateway( create_local_peering_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_local_peering_gateway') and callable(getattr(client, 'get_local_peering_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_local_peering_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.create_nat_gateway.command_name', 'create'), help=u"""Creates a new NAT gateway for the specified VCN. You must also set up a route rule with the NAT gateway as the rule's target. See [Route Table].""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to contain the NAT gateway.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN the gateway belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--block-traffic', type=click.BOOL, help=u"""Whether the NAT gateway blocks traffic through it. The default is `false`. Example: `true`""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'NatGateway'}) @cli_util.wrap_exceptions def create_nat_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, vcn_id, defined_tags, display_name, freeform_tags, block_traffic): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if block_traffic is not None: _details['blockTraffic'] = block_traffic client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_nat_gateway( create_nat_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_nat_gateway') and callable(getattr(client, 'get_nat_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_nat_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.create_network_security_group.command_name', 'create'), help=u"""Creates a new network security group for the specified VCN.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to contain the network security group.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN to create the network security group in.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name for the network security group. Does not have to be unique. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'NetworkSecurityGroup'}) @cli_util.wrap_exceptions def create_network_security_group(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, vcn_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_network_security_group( create_network_security_group_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_network_security_group') and callable(getattr(client, 'get_network_security_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_network_security_group(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @private_ip_group.command(name=cli_util.override('virtual_network.create_private_ip.command_name', 'create'), help=u"""Creates a secondary private IP for the specified VNIC. For more information about secondary private IPs, see [IP Addresses].""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--hostname-label', help=u"""The hostname for the private IP. Used for DNS. The value is the hostname portion of the private IP's fully qualified domain name (FQDN) (for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`). Must be unique across all VNICs in the subnet and comply with [RFC 952] and [RFC 1123]. For more information, see [DNS in Your Virtual Cloud Network]. Example: `bminstance-1`""") @cli_util.option('--ip-address', help=u"""A private IP address of your choice. Must be an available IP address within the subnet's CIDR. If you don't specify a value, Oracle automatically assigns a private IP address from the subnet. Example: `10.0.3.3`""") @cli_util.option('--vnic-id', help=u"""The OCID of the VNIC to assign the private IP to. The VNIC and private IP must be in the same subnet.""") @cli_util.option('--vlan-id', help=u"""Use this attribute only with the Oracle Cloud VMware Solution. The OCID of the VLAN from which the private IP is to be drawn. The IP address, *if supplied*, must be valid for the given VLAN. See [Vlan].""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'PrivateIp'}) @cli_util.wrap_exceptions def create_private_ip(ctx, from_json, defined_tags, display_name, freeform_tags, hostname_label, ip_address, vnic_id, vlan_id): kwargs = {} _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if hostname_label is not None: _details['hostnameLabel'] = hostname_label if ip_address is not None: _details['ipAddress'] = ip_address if vnic_id is not None: _details['vnicId'] = vnic_id if vlan_id is not None: _details['vlanId'] = vlan_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_private_ip( create_private_ip_details=_details, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.create_public_ip.command_name', 'create'), help=u"""Creates a public IP. Use the `lifetime` property to specify whether it's an ephemeral or reserved public IP. For information about limits on how many you can create, see [Public IP Addresses]. * **For an ephemeral public IP assigned to a private IP:** You must also specify a `privateIpId` with the OCID of the primary private IP you want to assign the public IP to. The public IP is created in the same availability domain as the private IP. An ephemeral public IP must always be assigned to a private IP, and only to the *primary* private IP on a VNIC, not a secondary private IP. Exception: If you create a [NatGateway], Oracle automatically assigns the NAT gateway a regional ephemeral public IP that you cannot remove. * **For a reserved public IP:** You may also optionally assign the public IP to a private IP by specifying `privateIpId`. Or you can later assign the public IP with [UpdatePublicIp]. **Note:** When assigning a public IP to a private IP, the private IP must not already have a public IP with `lifecycleState` = ASSIGNING or ASSIGNED. If it does, an error is returned. Also, for reserved public IPs, the optional assignment part of this operation is asynchronous. Poll the public IP's `lifecycleState` to determine if the assignment succeeded.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the public IP. For ephemeral public IPs, you must set this to the private IP's compartment OCID.""") @cli_util.option('--lifetime', required=True, type=custom_types.CliCaseInsensitiveChoice(["EPHEMERAL", "RESERVED"]), help=u"""Defines when the public IP is deleted and released back to the Oracle Cloud Infrastructure public IP pool. For more information, see [Public IP Addresses].""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--private-ip-id', help=u"""The OCID of the private IP to assign the public IP to. Required for an ephemeral public IP because it must always be assigned to a private IP (specifically a *primary* private IP). Optional for a reserved public IP. If you don't provide it, the public IP is created but not assigned to a private IP. You can later assign the public IP with [UpdatePublicIp].""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "ASSIGNING", "ASSIGNED", "UNASSIGNING", "UNASSIGNED", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'PublicIp'}) @cli_util.wrap_exceptions def create_public_ip(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, lifetime, defined_tags, display_name, freeform_tags, private_ip_id): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['lifetime'] = lifetime if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if private_ip_id is not None: _details['privateIpId'] = private_ip_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_public_ip( create_public_ip_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_public_ip') and callable(getattr(client, 'get_public_ip')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_public_ip(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.create_remote_peering_connection.command_name', 'create'), help=u"""Creates a new remote peering connection (RPC) for the specified DRG.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the RPC.""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG the RPC belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["AVAILABLE", "PROVISIONING", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'RemotePeeringConnection'}) @cli_util.wrap_exceptions def create_remote_peering_connection(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, drg_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['drgId'] = drg_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_remote_peering_connection( create_remote_peering_connection_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_remote_peering_connection') and callable(getattr(client, 'get_remote_peering_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_remote_peering_connection(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.create_route_table.command_name', 'create'), help=u"""Creates a new route table for the specified VCN. In the request you must also include at least one route rule for the new route table. For information on the number of rules you can have in a route table, see [Service Limits]. For general information about route tables in your VCN and the types of targets you can use in route rules, see [Route Tables]. For the purposes of access control, you must provide the OCID of the compartment where you want the route table to reside. Notice that the route table doesn't have to be in the same compartment as the VCN, subnets, or other Networking Service components. If you're not sure which compartment to use, put the route table in the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the route table, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the route table.""") @cli_util.option('--route-rules', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""The collection of rules used for routing destination IPs to network devices.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN the route table belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'route-rules': {'module': 'core', 'class': 'list[RouteRule]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'route-rules': {'module': 'core', 'class': 'list[RouteRule]'}}, output_type={'module': 'core', 'class': 'RouteTable'}) @cli_util.wrap_exceptions def create_route_table(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, route_rules, vcn_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['routeRules'] = cli_util.parse_json_parameter("route_rules", route_rules) _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_route_table( create_route_table_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_route_table') and callable(getattr(client, 'get_route_table')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_route_table(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.create_security_list.command_name', 'create'), help=u"""Creates a new security list for the specified VCN. For more information about security lists, see [Security Lists]. For information on the number of rules you can have in a security list, see [Service Limits]. For the purposes of access control, you must provide the OCID of the compartment where you want the security list to reside. Notice that the security list doesn't have to be in the same compartment as the VCN, subnets, or other Networking Service components. If you're not sure which compartment to use, put the security list in the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the security list, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the security list.""") @cli_util.option('--egress-security-rules', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Rules for allowing egress IP packets.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--ingress-security-rules', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Rules for allowing ingress IP packets.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN the security list belongs to.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'egress-security-rules': {'module': 'core', 'class': 'list[EgressSecurityRule]'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'ingress-security-rules': {'module': 'core', 'class': 'list[IngressSecurityRule]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'egress-security-rules': {'module': 'core', 'class': 'list[EgressSecurityRule]'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'ingress-security-rules': {'module': 'core', 'class': 'list[IngressSecurityRule]'}}, output_type={'module': 'core', 'class': 'SecurityList'}) @cli_util.wrap_exceptions def create_security_list(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, egress_security_rules, ingress_security_rules, vcn_id, defined_tags, display_name, freeform_tags): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['egressSecurityRules'] = cli_util.parse_json_parameter("egress_security_rules", egress_security_rules) _details['ingressSecurityRules'] = cli_util.parse_json_parameter("ingress_security_rules", ingress_security_rules) _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_security_list( create_security_list_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_security_list') and callable(getattr(client, 'get_security_list')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_security_list(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.create_service_gateway.command_name', 'create'), help=u"""Creates a new service gateway in the specified compartment. For the purposes of access control, you must provide the OCID of the compartment where you want the service gateway to reside. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the service gateway, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment to contain the service gateway.""") @cli_util.option('--services', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""List of the OCIDs of the [Service] objects to enable for the service gateway. This list can be empty if you don't want to enable any `Service` objects when you create the gateway. You can enable a `Service` object later by using either [AttachServiceId] or [UpdateServiceGateway]. For each enabled `Service`, make sure there's a route rule with the `Service` object's `cidrBlock` as the rule's destination and the service gateway as the rule's target. See [Route Table].""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the service gateway will use. If you don't specify a route table here, the service gateway is created without an associated route table. The Networking service does NOT automatically associate the attached VCN's default route table with the service gateway. For information about why you would associate a route table with a service gateway, see [Transit Routing: Private Access to Oracle Services].""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'services': {'module': 'core', 'class': 'list[ServiceIdRequestDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'services': {'module': 'core', 'class': 'list[ServiceIdRequestDetails]'}}, output_type={'module': 'core', 'class': 'ServiceGateway'}) @cli_util.wrap_exceptions def create_service_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, services, vcn_id, defined_tags, display_name, freeform_tags, route_table_id): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['services'] = cli_util.parse_json_parameter("services", services) _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_service_gateway( create_service_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_service_gateway') and callable(getattr(client, 'get_service_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_service_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.create_subnet.command_name', 'create'), help=u"""Creates a new subnet in the specified VCN. You can't change the size of the subnet after creation, so it's important to think about the size of subnets you need before creating them. For more information, see [VCNs and Subnets]. For information on the number of subnets you can have in a VCN, see [Service Limits]. For the purposes of access control, you must provide the OCID of the compartment where you want the subnet to reside. Notice that the subnet doesn't have to be in the same compartment as the VCN, route tables, or other Networking Service components. If you're not sure which compartment to use, put the subnet in the same compartment as the VCN. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally associate a route table with the subnet. If you don't, the subnet will use the VCN's default route table. For more information about route tables, see [Route Tables]. You may optionally associate a security list with the subnet. If you don't, the subnet will use the VCN's default security list. For more information about security lists, see [Security Lists]. You may optionally associate a set of DHCP options with the subnet. If you don't, the subnet will use the VCN's default set. For more information about DHCP options, see [DHCP Options]. You may optionally specify a *display name* for the subnet, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information. You can also add a DNS label for the subnet, which is required if you want the Internet and VCN Resolver to resolve hostnames for instances in the subnet. For more information, see [DNS in Your Virtual Cloud Network].""") @cli_util.option('--cidr-block', required=True, help=u"""The CIDR IP address range of the subnet. The CIDR must maintain the following rules - a. The CIDR block is valid and correctly formatted. b. The new range is within one of the parent VCN ranges. Example: `10.0.1.0/24`""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the subnet.""") @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN to contain the subnet.""") @cli_util.option('--availability-domain', help=u"""Controls whether the subnet is regional or specific to an availability domain. Oracle recommends creating regional subnets because they're more flexible and make it easier to implement failover across availability domains. Originally, AD-specific subnets were the only kind available to use. To create a regional subnet, omit this attribute. Then any resources later created in this subnet (such as a Compute instance) can be created in any availability domain in the region. To instead create an AD-specific subnet, set this attribute to the availability domain you want this subnet to be in. Then any resources later created in this subnet can only be created in that availability domain. Example: `Uocm:PHX-AD-1`""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--dhcp-options-id', help=u"""The OCID of the set of DHCP options the subnet will use. If you don't provide a value, the subnet uses the VCN's default set of DHCP options.""") @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--dns-label', help=u"""A DNS label for the subnet, used in conjunction with the VNIC's hostname and VCN's DNS label to form a fully qualified domain name (FQDN) for each VNIC within this subnet (for example, `bminstance-1.subnet123.vcn1.oraclevcn.com`). Must be an alphanumeric string that begins with a letter and is unique within the VCN. The value cannot be changed. This value must be set if you want to use the Internet and VCN Resolver to resolve the hostnames of instances in the subnet. It can only be set if the VCN itself was created with a DNS label. For more information, see [DNS in Your Virtual Cloud Network]. Example: `subnet123`""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--ipv6-cidr-block', help=u"""Use this to enable IPv6 addressing for this subnet. The VCN must be enabled for IPv6. You can't change this subnet characteristic later. All subnets are /64 in size. The subnet portion of the IPv6 address is the fourth hextet from the left (1111 in the following example). For important details about IPv6 addressing in a VCN, see [IPv6 Addresses]. Example: `2001:0db8:0123:1111::/64`""") @cli_util.option('--prohibit-public-ip-on-vnic', type=click.BOOL, help=u"""Whether VNICs within this subnet can have public IP addresses. Defaults to false, which means VNICs created in this subnet will automatically be assigned public IP addresses unless specified otherwise during instance launch or VNIC creation (with the `assignPublicIp` flag in [CreateVnicDetails]). If `prohibitPublicIpOnVnic` is set to true, VNICs created in this subnet cannot have public IP addresses (that is, it's a private subnet). For IPv6, if `prohibitPublicIpOnVnic` is set to `true`, internet access is not allowed for any IPv6s assigned to VNICs in the subnet. Example: `true`""") @cli_util.option('--route-table-id', help=u"""The OCID of the route table the subnet will use. If you don't provide a value, the subnet uses the VCN's default route table.""") @cli_util.option('--security-list-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The OCIDs of the security list or lists the subnet will use. If you don't provide a value, the subnet uses the VCN's default security list. Remember that security lists are associated *with the subnet*, but the rules are applied to the individual VNICs in the subnet.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'security-list-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'security-list-ids': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'Subnet'}) @cli_util.wrap_exceptions def create_subnet(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, cidr_block, compartment_id, vcn_id, availability_domain, defined_tags, dhcp_options_id, display_name, dns_label, freeform_tags, ipv6_cidr_block, prohibit_public_ip_on_vnic, route_table_id, security_list_ids): kwargs = {} _details = {} _details['cidrBlock'] = cidr_block _details['compartmentId'] = compartment_id _details['vcnId'] = vcn_id if availability_domain is not None: _details['availabilityDomain'] = availability_domain if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if dhcp_options_id is not None: _details['dhcpOptionsId'] = dhcp_options_id if display_name is not None: _details['displayName'] = display_name if dns_label is not None: _details['dnsLabel'] = dns_label if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if ipv6_cidr_block is not None: _details['ipv6CidrBlock'] = ipv6_cidr_block if prohibit_public_ip_on_vnic is not None: _details['prohibitPublicIpOnVnic'] = prohibit_public_ip_on_vnic if route_table_id is not None: _details['routeTableId'] = route_table_id if security_list_ids is not None: _details['securityListIds'] = cli_util.parse_json_parameter("security_list_ids", security_list_ids) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_subnet( create_subnet_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_subnet') and callable(getattr(client, 'get_subnet')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_subnet(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vcn_group.command(name=cli_util.override('virtual_network.create_vcn.command_name', 'create'), help=u"""Creates a new virtual cloud network (VCN). For more information, see [VCNs and Subnets]. For the VCN you must specify a single, contiguous IPv4 CIDR block. Oracle recommends using one of the private IP address ranges specified in [RFC 1918] (10.0.0.0/8, 172.16/12, and 192.168/16). Example: 172.16.0.0/16. The CIDR block can range from /16 to /30, and it must not overlap with your on-premises network. You can't change the size of the VCN after creation. For the purposes of access control, you must provide the OCID of the compartment where you want the VCN to reside. Consult an Oracle Cloud Infrastructure administrator in your organization if you're not sure which compartment to use. Notice that the VCN doesn't have to be in the same compartment as the subnets or other Networking Service components. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the VCN, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information. You can also add a DNS label for the VCN, which is required if you want the instances to use the Interent and VCN Resolver option for DNS in the VCN. For more information, see [DNS in Your Virtual Cloud Network]. The VCN automatically comes with a default route table, default security list, and default set of DHCP options. The OCID for each is returned in the response. You can't delete these default objects, but you can change their contents (that is, change the route rules, security list rules, and so on). The VCN and subnets you create are not accessible until you attach an internet gateway or set up an IPSec VPN or FastConnect. For more information, see [Overview of the Networking Service].""") @cli_util.option('--cidr-block', required=True, help=u"""The CIDR IP address block of the VCN. Example: `10.0.0.0/16`""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the VCN.""") @cli_util.option('--ipv6-cidr-block', help=u"""If you enable IPv6 for the VCN (see `isIpv6Enabled`), you may optionally provide an IPv6 /48 CIDR block from the supported ranges (see [IPv6 Addresses]. The addresses in this block will be considered private and cannot be accessed from the internet. The documentation refers to this as a *custom CIDR* for the VCN. If you don't provide a custom CIDR for the VCN, Oracle assigns the VCN's IPv6 /48 CIDR block. Regardless of whether you or Oracle assigns the `ipv6CidrBlock`, Oracle *also* assigns the VCN an IPv6 CIDR block for the VCN's public IP address space (see the `ipv6PublicCidrBlock` of the [Vcn] object). If you do not assign a custom CIDR, Oracle uses the *same* Oracle-assigned CIDR for both the private IP address space (`ipv6CidrBlock` in the `Vcn` object) and the public IP addreses space (`ipv6PublicCidrBlock` in the `Vcn` object). This means that a given VNIC might use the same IPv6 IP address for both private and public (internet) communication. You control whether an IPv6 address can be used for internet communication by using the `isInternetAccessAllowed` attribute in the [Ipv6] object. For important details about IPv6 addressing in a VCN, see [IPv6 Addresses]. Example: `2001:0db8:0123::/48`""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--dns-label', help=u"""A DNS label for the VCN, used in conjunction with the VNIC's hostname and subnet's DNS label to form a fully qualified domain name (FQDN) for each VNIC within this subnet (for example, `bminstance-1.subnet123.vcn1.oraclevcn.com`). Not required to be unique, but it's a best practice to set unique DNS labels for VCNs in your tenancy. Must be an alphanumeric string that begins with a letter. The value cannot be changed. You must set this value if you want instances to be able to use hostnames to resolve other instances in the VCN. Otherwise the Internet and VCN Resolver will not work. For more information, see [DNS in Your Virtual Cloud Network]. Example: `vcn1`""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--is-ipv6-enabled', type=click.BOOL, help=u"""Whether IPv6 is enabled for the VCN. Default is `false`. You cannot change this later. For important details about IPv6 addressing in a VCN, see [IPv6 Addresses]. Example: `true`""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Vcn'}) @cli_util.wrap_exceptions def create_vcn(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, cidr_block, compartment_id, ipv6_cidr_block, defined_tags, display_name, dns_label, freeform_tags, is_ipv6_enabled): kwargs = {} _details = {} _details['cidrBlock'] = cidr_block _details['compartmentId'] = compartment_id if ipv6_cidr_block is not None: _details['ipv6CidrBlock'] = ipv6_cidr_block if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if dns_label is not None: _details['dnsLabel'] = dns_label if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if is_ipv6_enabled is not None: _details['isIpv6Enabled'] = is_ipv6_enabled client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_vcn( create_vcn_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_vcn') and callable(getattr(client, 'get_vcn')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_vcn(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.create_virtual_circuit.command_name', 'create'), help=u"""Creates a new virtual circuit to use with Oracle Cloud Infrastructure FastConnect. For more information, see [FastConnect Overview]. For the purposes of access control, you must provide the OCID of the compartment where you want the virtual circuit to reside. If you're not sure which compartment to use, put the virtual circuit in the same compartment with the DRG it's using. For more information about compartments and access control, see [Overview of the IAM Service]. For information about OCIDs, see [Resource Identifiers]. You may optionally specify a *display name* for the virtual circuit. It does not have to be unique, and you can change it. Avoid entering confidential information. **Important:** When creating a virtual circuit, you specify a DRG for the traffic to flow through. Make sure you attach the DRG to your VCN and confirm the VCN's routing sends traffic to the DRG. Otherwise traffic will not flow. For more information, see [Route Tables].""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the virtual circuit.""") @cli_util.option('--type', required=True, type=custom_types.CliCaseInsensitiveChoice(["PUBLIC", "PRIVATE"]), help=u"""The type of IP addresses used in this virtual circuit. PRIVATE means [RFC 1918] addresses (10.0.0.0/8, 172.16/12, and 192.168/16).""") @cli_util.option('--bandwidth-shape-name', help=u"""The provisioned data rate of the connection. To get a list of the available bandwidth levels (that is, shapes), see [ListFastConnectProviderServiceVirtualCircuitBandwidthShapes]. Example: `10 Gbps`""") @cli_util.option('--cross-connect-mappings', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Create a `CrossConnectMapping` for each cross-connect or cross-connect group this virtual circuit will run on. This option is a JSON list with items of type CrossConnectMapping. For documentation on CrossConnectMapping please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/CrossConnectMapping.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--customer-bgp-asn', type=click.INT, help=u"""Deprecated. Instead use `customerAsn`. If you specify values for both, the request will be rejected.""") @cli_util.option('--customer-asn', type=click.INT, help=u"""Your BGP ASN (either public or private). Provide this value only if there's a BGP session that goes from your edge router to Oracle. Otherwise, leave this empty or null. Can be a 2-byte or 4-byte ASN. Uses \"asplain\" format. Example: `12345` (2-byte) or `1587232876` (4-byte)""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--gateway-id', help=u"""For private virtual circuits only. The OCID of the [dynamic routing gateway (DRG)] that this virtual circuit uses.""") @cli_util.option('--provider-name', help=u"""Deprecated. Instead use `providerServiceId`. To get a list of the provider names, see [ListFastConnectProviderServices].""") @cli_util.option('--provider-service-id', help=u"""The OCID of the service offered by the provider (if you're connecting via a provider). To get a list of the available service offerings, see [ListFastConnectProviderServices].""") @cli_util.option('--provider-service-key-name', help=u"""The service key name offered by the provider (if the customer is connecting via a provider).""") @cli_util.option('--provider-service-name', help=u"""Deprecated. Instead use `providerServiceId`. To get a list of the provider names, see [ListFastConnectProviderServices].""") @cli_util.option('--public-prefixes', type=custom_types.CLI_COMPLEX_TYPE, help=u"""For a public virtual circuit. The public IP prefixes (CIDRs) the customer wants to advertise across the connection. This option is a JSON list with items of type CreateVirtualCircuitPublicPrefixDetails. For documentation on CreateVirtualCircuitPublicPrefixDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/CreateVirtualCircuitPublicPrefixDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--region-parameterconflict', help=u"""The Oracle Cloud Infrastructure region where this virtual circuit is located. Example: `phx`""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_PROVIDER", "VERIFYING", "PROVISIONING", "PROVISIONED", "FAILED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'cross-connect-mappings': {'module': 'core', 'class': 'list[CrossConnectMapping]'}, 'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'public-prefixes': {'module': 'core', 'class': 'list[CreateVirtualCircuitPublicPrefixDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'cross-connect-mappings': {'module': 'core', 'class': 'list[CrossConnectMapping]'}, 'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'public-prefixes': {'module': 'core', 'class': 'list[CreateVirtualCircuitPublicPrefixDetails]'}}, output_type={'module': 'core', 'class': 'VirtualCircuit'}) @cli_util.wrap_exceptions def create_virtual_circuit(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, type, bandwidth_shape_name, cross_connect_mappings, customer_bgp_asn, customer_asn, defined_tags, display_name, freeform_tags, gateway_id, provider_name, provider_service_id, provider_service_key_name, provider_service_name, public_prefixes, region_parameterconflict): kwargs = {} _details = {} _details['compartmentId'] = compartment_id _details['type'] = type if bandwidth_shape_name is not None: _details['bandwidthShapeName'] = bandwidth_shape_name if cross_connect_mappings is not None: _details['crossConnectMappings'] = cli_util.parse_json_parameter("cross_connect_mappings", cross_connect_mappings) if customer_bgp_asn is not None: _details['customerBgpAsn'] = customer_bgp_asn if customer_asn is not None: _details['customerAsn'] = customer_asn if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if gateway_id is not None: _details['gatewayId'] = gateway_id if provider_name is not None: _details['providerName'] = provider_name if provider_service_id is not None: _details['providerServiceId'] = provider_service_id if provider_service_key_name is not None: _details['providerServiceKeyName'] = provider_service_key_name if provider_service_name is not None: _details['providerServiceName'] = provider_service_name if public_prefixes is not None: _details['publicPrefixes'] = cli_util.parse_json_parameter("public_prefixes", public_prefixes) if region_parameterconflict is not None: _details['region'] = region_parameterconflict client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_virtual_circuit( create_virtual_circuit_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_virtual_circuit') and callable(getattr(client, 'get_virtual_circuit')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_virtual_circuit(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.create_vlan.command_name', 'create'), help=u"""Creates a VLAN in the specified VCN and the specified compartment.""") @cli_util.option('--availability-domain', required=True, help=u"""The availability domain of the VLAN. Example: `Uocm:PHX-AD-1`""") @cli_util.option('--cidr-block', required=True, help=u"""The range of IPv4 addresses that will be used for layer 3 communication with hosts outside the VLAN. The CIDR must maintain the following rules - a. The CIDR block is valid and correctly formatted. Example: `192.0.2.0/24`""") @cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment to contain the VLAN.""") @cli_util.option('--vcn-id', required=True, help=u"""The OCID of the VCN to contain the VLAN.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A descriptive name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--nsg-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""A list of the OCIDs of the network security groups (NSGs) to add all VNICs in the VLAN to. For more information about NSGs, see [NetworkSecurityGroup].""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the VLAN will use. If you don't provide a value, the VLAN uses the VCN's default route table.""") @cli_util.option('--vlan-tag', type=click.INT, help=u"""The IEEE 802.1Q VLAN tag for this VLAN. The value must be unique across all VLANs in the VCN. If you don't provide a value, Oracle assigns one. You cannot change the value later. VLAN tag 0 is reserved for use by Oracle.""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED", "UPDATING"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'Vlan'}) @cli_util.wrap_exceptions def create_vlan(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, availability_domain, cidr_block, compartment_id, vcn_id, defined_tags, display_name, freeform_tags, nsg_ids, route_table_id, vlan_tag): kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} _details['availabilityDomain'] = availability_domain _details['cidrBlock'] = cidr_block _details['compartmentId'] = compartment_id _details['vcnId'] = vcn_id if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if nsg_ids is not None: _details['nsgIds'] = cli_util.parse_json_parameter("nsg_ids", nsg_ids) if route_table_id is not None: _details['routeTableId'] = route_table_id if vlan_tag is not None: _details['vlanTag'] = vlan_tag client = cli_util.build_client('core', 'virtual_network', ctx) result = client.create_vlan( create_vlan_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_vlan') and callable(getattr(client, 'get_vlan')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_vlan(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.delete_cpe.command_name', 'delete'), help=u"""Deletes the specified CPE object. The CPE must not be connected to a DRG. This is an asynchronous operation. The CPE's `lifecycleState` will change to TERMINATING temporarily until the CPE is completely removed.""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the CPE.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_cpe(ctx, from_json, cpe_id, if_match): if isinstance(cpe_id, six.string_types) and len(cpe_id.strip()) == 0: raise click.UsageError('Parameter --cpe-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_cpe( cpe_id=cpe_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.delete_cross_connect.command_name', 'delete'), help=u"""Deletes the specified cross-connect. It must not be mapped to a [VirtualCircuit].""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_CUSTOMER", "PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_cross_connect(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, cross_connect_id, if_match): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_cross_connect( cross_connect_id=cross_connect_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect') and callable(getattr(client, 'get_cross_connect')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_cross_connect(cross_connect_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.delete_cross_connect_group.command_name', 'delete'), help=u"""Deletes the specified cross-connect group. It must not contain any cross-connects, and it cannot be mapped to a [VirtualCircuit].""") @cli_util.option('--cross-connect-group-id', required=True, help=u"""The OCID of the cross-connect group.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_cross_connect_group(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, cross_connect_group_id, if_match): if isinstance(cross_connect_group_id, six.string_types) and len(cross_connect_group_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-group-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_cross_connect_group( cross_connect_group_id=cross_connect_group_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect_group') and callable(getattr(client, 'get_cross_connect_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_cross_connect_group(cross_connect_group_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.delete_dhcp_options.command_name', 'delete'), help=u"""Deletes the specified set of DHCP options, but only if it's not associated with a subnet. You can't delete a VCN's default set of DHCP options. This is an asynchronous operation. The state of the set of options will switch to TERMINATING temporarily until the set is completely removed.""") @cli_util.option('--dhcp-id', required=True, help=u"""The OCID for the set of DHCP options.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_dhcp_options(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, dhcp_id, if_match): if isinstance(dhcp_id, six.string_types) and len(dhcp_id.strip()) == 0: raise click.UsageError('Parameter --dhcp-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_dhcp_options( dhcp_id=dhcp_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_dhcp_options') and callable(getattr(client, 'get_dhcp_options')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_dhcp_options(dhcp_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.delete_drg.command_name', 'delete'), help=u"""Deletes the specified DRG. The DRG must not be attached to a VCN or be connected to your on-premise network. Also, there must not be a route table that lists the DRG as a target. This is an asynchronous operation. The DRG's `lifecycleState` will change to TERMINATING temporarily until the DRG is completely removed.""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_drg(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, drg_id, if_match): if isinstance(drg_id, six.string_types) and len(drg_id.strip()) == 0: raise click.UsageError('Parameter --drg-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_drg( drg_id=drg_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg') and callable(getattr(client, 'get_drg')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_drg(drg_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_attachment_group.command(name=cli_util.override('virtual_network.delete_drg_attachment.command_name', 'delete'), help=u"""Detaches a DRG from a VCN by deleting the corresponding `DrgAttachment`. This is an asynchronous operation. The attachment's `lifecycleState` will change to DETACHING temporarily until the attachment is completely removed.""") @cli_util.option('--drg-attachment-id', required=True, help=u"""The OCID of the DRG attachment.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ATTACHING", "ATTACHED", "DETACHING", "DETACHED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_drg_attachment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, drg_attachment_id, if_match): if isinstance(drg_attachment_id, six.string_types) and len(drg_attachment_id.strip()) == 0: raise click.UsageError('Parameter --drg-attachment-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_drg_attachment( drg_attachment_id=drg_attachment_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg_attachment') and callable(getattr(client, 'get_drg_attachment')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_drg_attachment(drg_attachment_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.delete_internet_gateway.command_name', 'delete'), help=u"""Deletes the specified internet gateway. The internet gateway does not have to be disabled, but there must not be a route table that lists it as a target. This is an asynchronous operation. The gateway's `lifecycleState` will change to TERMINATING temporarily until the gateway is completely removed.""") @cli_util.option('--ig-id', required=True, help=u"""The OCID of the internet gateway.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_internet_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, ig_id, if_match): if isinstance(ig_id, six.string_types) and len(ig_id.strip()) == 0: raise click.UsageError('Parameter --ig-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_internet_gateway( ig_id=ig_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_internet_gateway') and callable(getattr(client, 'get_internet_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_internet_gateway(ig_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.delete_ip_sec_connection.command_name', 'delete'), help=u"""Deletes the specified IPSec connection. If your goal is to disable the IPSec VPN between your VCN and on-premises network, it's easiest to simply detach the DRG but keep all the IPSec VPN components intact. If you were to delete all the components and then later need to create an IPSec VPN again, you would need to configure your on-premises router again with the new information returned from [CreateIPSecConnection]. This is an asynchronous operation. The connection's `lifecycleState` will change to TERMINATING temporarily until the connection is completely removed.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_ip_sec_connection(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, ipsc_id, if_match): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_ip_sec_connection( ipsc_id=ipsc_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_ip_sec_connection') and callable(getattr(client, 'get_ip_sec_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_ip_sec_connection(ipsc_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ipv6_group.command(name=cli_util.override('virtual_network.delete_ipv6.command_name', 'delete'), help=u"""Unassigns and deletes the specified IPv6. You must specify the object's OCID. The IPv6 address is returned to the subnet's pool of available addresses.""") @cli_util.option('--ipv6-id', required=True, help=u"""The [OCID] of the IPv6.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_ipv6(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, ipv6_id, if_match): if isinstance(ipv6_id, six.string_types) and len(ipv6_id.strip()) == 0: raise click.UsageError('Parameter --ipv6-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_ipv6( ipv6_id=ipv6_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_ipv6') and callable(getattr(client, 'get_ipv6')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_ipv6(ipv6_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.delete_local_peering_gateway.command_name', 'delete'), help=u"""Deletes the specified local peering gateway (LPG). This is an asynchronous operation; the local peering gateway's `lifecycleState` changes to TERMINATING temporarily until the local peering gateway is completely removed.""") @cli_util.option('--local-peering-gateway-id', required=True, help=u"""The OCID of the local peering gateway.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_local_peering_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, local_peering_gateway_id, if_match): if isinstance(local_peering_gateway_id, six.string_types) and len(local_peering_gateway_id.strip()) == 0: raise click.UsageError('Parameter --local-peering-gateway-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_local_peering_gateway( local_peering_gateway_id=local_peering_gateway_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_local_peering_gateway') and callable(getattr(client, 'get_local_peering_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_local_peering_gateway(local_peering_gateway_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.delete_nat_gateway.command_name', 'delete'), help=u"""Deletes the specified NAT gateway. The NAT gateway does not have to be disabled, but there must not be a route rule that lists the NAT gateway as a target. This is an asynchronous operation. The NAT gateway's `lifecycleState` will change to TERMINATING temporarily until the NAT gateway is completely removed.""") @cli_util.option('--nat-gateway-id', required=True, help=u"""The NAT gateway's [OCID].""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_nat_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, nat_gateway_id, if_match): if isinstance(nat_gateway_id, six.string_types) and len(nat_gateway_id.strip()) == 0: raise click.UsageError('Parameter --nat-gateway-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_nat_gateway( nat_gateway_id=nat_gateway_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_nat_gateway') and callable(getattr(client, 'get_nat_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_nat_gateway(nat_gateway_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.delete_network_security_group.command_name', 'delete'), help=u"""Deletes the specified network security group. The group must not contain any VNICs. To get a list of the VNICs in a network security group, use [ListNetworkSecurityGroupVnics]. Each returned [NetworkSecurityGroupVnic] object contains both the OCID of the VNIC and the OCID of the VNIC's parent resource (for example, the Compute instance that the VNIC is attached to).""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_network_security_group(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, network_security_group_id, if_match): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_network_security_group( network_security_group_id=network_security_group_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_network_security_group') and callable(getattr(client, 'get_network_security_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_network_security_group(network_security_group_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @private_ip_group.command(name=cli_util.override('virtual_network.delete_private_ip.command_name', 'delete'), help=u"""Unassigns and deletes the specified private IP. You must specify the object's OCID. The private IP address is returned to the subnet's pool of available addresses. This operation cannot be used with primary private IPs, which are automatically unassigned and deleted when the VNIC is terminated. **Important:** If a secondary private IP is the [target of a route rule], unassigning it from the VNIC causes that route rule to blackhole and the traffic will be dropped.""") @cli_util.option('--private-ip-id', required=True, help=u"""The OCID of the private IP.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_private_ip(ctx, from_json, private_ip_id, if_match): if isinstance(private_ip_id, six.string_types) and len(private_ip_id.strip()) == 0: raise click.UsageError('Parameter --private-ip-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_private_ip( private_ip_id=private_ip_id, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.delete_public_ip.command_name', 'delete'), help=u"""Unassigns and deletes the specified public IP (either ephemeral or reserved). You must specify the object's OCID. The public IP address is returned to the Oracle Cloud Infrastructure public IP pool. **Note:** You cannot update, unassign, or delete the public IP that Oracle automatically assigned to an entity for you (such as a load balancer or NAT gateway). The public IP is automatically deleted if the assigned entity is terminated. For an assigned reserved public IP, the initial unassignment portion of this operation is asynchronous. Poll the public IP's `lifecycleState` to determine if the operation succeeded. If you want to simply unassign a reserved public IP and return it to your pool of reserved public IPs, instead use [UpdatePublicIp].""") @cli_util.option('--public-ip-id', required=True, help=u"""The OCID of the public IP.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "ASSIGNING", "ASSIGNED", "UNASSIGNING", "UNASSIGNED", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_public_ip(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, public_ip_id, if_match): if isinstance(public_ip_id, six.string_types) and len(public_ip_id.strip()) == 0: raise click.UsageError('Parameter --public-ip-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_public_ip( public_ip_id=public_ip_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_public_ip') and callable(getattr(client, 'get_public_ip')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_public_ip(public_ip_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.delete_remote_peering_connection.command_name', 'delete'), help=u"""Deletes the remote peering connection (RPC). This is an asynchronous operation; the RPC's `lifecycleState` changes to TERMINATING temporarily until the RPC is completely removed.""") @cli_util.option('--remote-peering-connection-id', required=True, help=u"""The OCID of the remote peering connection (RPC).""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["AVAILABLE", "PROVISIONING", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_remote_peering_connection(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, remote_peering_connection_id, if_match): if isinstance(remote_peering_connection_id, six.string_types) and len(remote_peering_connection_id.strip()) == 0: raise click.UsageError('Parameter --remote-peering-connection-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_remote_peering_connection( remote_peering_connection_id=remote_peering_connection_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_remote_peering_connection') and callable(getattr(client, 'get_remote_peering_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_remote_peering_connection(remote_peering_connection_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.delete_route_table.command_name', 'delete'), help=u"""Deletes the specified route table, but only if it's not associated with a subnet. You can't delete a VCN's default route table. This is an asynchronous operation. The route table's `lifecycleState` will change to TERMINATING temporarily until the route table is completely removed.""") @cli_util.option('--rt-id', required=True, help=u"""The OCID of the route table.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_route_table(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, rt_id, if_match): if isinstance(rt_id, six.string_types) and len(rt_id.strip()) == 0: raise click.UsageError('Parameter --rt-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_route_table( rt_id=rt_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_route_table') and callable(getattr(client, 'get_route_table')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_route_table(rt_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.delete_security_list.command_name', 'delete'), help=u"""Deletes the specified security list, but only if it's not associated with a subnet. You can't delete a VCN's default security list. This is an asynchronous operation. The security list's `lifecycleState` will change to TERMINATING temporarily until the security list is completely removed.""") @cli_util.option('--security-list-id', required=True, help=u"""The OCID of the security list.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_security_list(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, security_list_id, if_match): if isinstance(security_list_id, six.string_types) and len(security_list_id.strip()) == 0: raise click.UsageError('Parameter --security-list-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_security_list( security_list_id=security_list_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_security_list') and callable(getattr(client, 'get_security_list')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_security_list(security_list_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.delete_service_gateway.command_name', 'delete'), help=u"""Deletes the specified service gateway. There must not be a route table that lists the service gateway as a target.""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_service_gateway(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, service_gateway_id, if_match): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_service_gateway( service_gateway_id=service_gateway_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_service_gateway') and callable(getattr(client, 'get_service_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_service_gateway(service_gateway_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.delete_subnet.command_name', 'delete'), help=u"""Deletes the specified subnet, but only if there are no instances in the subnet. This is an asynchronous operation. The subnet's `lifecycleState` will change to TERMINATING temporarily. If there are any instances in the subnet, the state will instead change back to AVAILABLE.""") @cli_util.option('--subnet-id', required=True, help=u"""The OCID of the subnet.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_subnet(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, subnet_id, if_match): if isinstance(subnet_id, six.string_types) and len(subnet_id.strip()) == 0: raise click.UsageError('Parameter --subnet-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_subnet( subnet_id=subnet_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_subnet') and callable(getattr(client, 'get_subnet')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_subnet(subnet_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vcn_group.command(name=cli_util.override('virtual_network.delete_vcn.command_name', 'delete'), help=u"""Deletes the specified VCN. The VCN must be empty and have no attached gateways. This is an asynchronous operation. The VCN's `lifecycleState` will change to TERMINATING temporarily until the VCN is completely removed.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_vcn(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, vcn_id, if_match): if isinstance(vcn_id, six.string_types) and len(vcn_id.strip()) == 0: raise click.UsageError('Parameter --vcn-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_vcn( vcn_id=vcn_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_vcn') and callable(getattr(client, 'get_vcn')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_vcn(vcn_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.delete_virtual_circuit.command_name', 'delete'), help=u"""Deletes the specified virtual circuit. **Important:** If you're using FastConnect via a provider, make sure to also terminate the connection with the provider, or else the provider may continue to bill you.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_PROVIDER", "VERIFYING", "PROVISIONING", "PROVISIONED", "FAILED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_virtual_circuit(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, virtual_circuit_id, if_match): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_virtual_circuit( virtual_circuit_id=virtual_circuit_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_virtual_circuit') and callable(getattr(client, 'get_virtual_circuit')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_virtual_circuit(virtual_circuit_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.delete_vlan.command_name', 'delete'), help=u"""Deletes the specified VLAN, but only if there are no VNICs in the VLAN.""") @cli_util.option('--vlan-id', required=True, help=u"""The [OCID] of the VLAN.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.confirm_delete_option @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED", "UPDATING"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def delete_vlan(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, vlan_id, if_match): if isinstance(vlan_id, six.string_types) and len(vlan_id.strip()) == 0: raise click.UsageError('Parameter --vlan-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.delete_vlan( vlan_id=vlan_id, **kwargs ) if wait_for_state: if hasattr(client, 'get_vlan') and callable(getattr(client, 'get_vlan')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) oci.wait_until(client, client.get_vlan(vlan_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs) except oci.exceptions.ServiceError as e: # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the # outcome of a delete operation it is possible that the resource is already gone and so the initial service call # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument # succeed_on_not_found=True to the waiter). # # Any non-404 should still result in the exception being thrown. if e.status == 404: pass else: raise except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.detach_service_id.command_name', 'detach'), help=u"""Removes the specified [Service] from the list of enabled `Service` objects for the specified gateway. You do not need to remove any route rules that specify this `Service` object's `cidrBlock` as the destination CIDR. However, consider removing the rules if your intent is to permanently disable use of the `Service` through this service gateway. **Note:** The `DetachServiceId` operation is an easy way to remove an individual `Service` from the service gateway. Compare it with [UpdateServiceGateway], which replaces the entire existing list of enabled `Service` objects with the list that you provide in the `Update` call. `UpdateServiceGateway` also lets you block all traffic through the service gateway without having to remove each of the individual `Service` objects.""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @cli_util.option('--service-id', required=True, help=u"""The [OCID] of the [Service].""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'ServiceGateway'}) @cli_util.wrap_exceptions def detach_service_id(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, service_gateway_id, service_id, if_match): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} _details['serviceId'] = service_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.detach_service_id( service_gateway_id=service_gateway_id, detach_service_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_service_gateway') and callable(getattr(client, 'get_service_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_service_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.get_cpe.command_name', 'get'), help=u"""Gets the specified CPE's information.""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the CPE.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Cpe'}) @cli_util.wrap_exceptions def get_cpe(ctx, from_json, cpe_id): if isinstance(cpe_id, six.string_types) and len(cpe_id.strip()) == 0: raise click.UsageError('Parameter --cpe-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cpe( cpe_id=cpe_id, **kwargs ) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.get_cpe_device_config_content.command_name', 'get-cpe-device-config-content'), help=u"""Renders a set of CPE configuration content that can help a network engineer configure the actual CPE device (for example, a hardware router) represented by the specified [Cpe] object. The rendered content is specific to the type of CPE device (for example, Cisco ASA). Therefore the [Cpe] must have the CPE's device type specified by the `cpeDeviceShapeId` attribute. The content optionally includes answers that the customer provides (see [UpdateTunnelCpeDeviceConfig]), merged with a template of other information specific to the CPE device type. The operation returns configuration information for *all* of the [IPSecConnection] objects that use the specified CPE. Here are similar operations: * [GetIpsecCpeDeviceConfigContent] returns CPE configuration content for all tunnels in a single IPSec connection. * [GetTunnelCpeDeviceConfigContent] returns CPE configuration content for a specific tunnel within an IPSec connection.""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the CPE.""") @cli_util.option('--file', type=click.File(mode='wb'), required=True, help="The name of the file that will receive the response data, or '-' to write to STDOUT.") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def get_cpe_device_config_content(ctx, from_json, file, cpe_id): if isinstance(cpe_id, six.string_types) and len(cpe_id.strip()) == 0: raise click.UsageError('Parameter --cpe-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cpe_device_config_content( cpe_id=cpe_id, **kwargs ) # If outputting to stdout we don't want to print a progress bar because it will get mixed up with the output # Also we need a non-zero Content-Length in order to display a meaningful progress bar bar = None if hasattr(file, 'name') and file.name != '<stdout>' and 'Content-Length' in result.headers: content_length = int(result.headers['Content-Length']) if content_length > 0: bar = click.progressbar(length=content_length, label='Downloading file') try: if bar: bar.__enter__() # TODO: Make the download size a configurable option # use decode_content=True to automatically unzip service responses (this should be overridden for object storage) for chunk in result.data.raw.stream(cli_constants.MEBIBYTE, decode_content=True): if bar: bar.update(len(chunk)) file.write(chunk) finally: if bar: bar.render_finish() file.close() @cpe_device_shape_detail_group.command(name=cli_util.override('virtual_network.get_cpe_device_shape.command_name', 'get-cpe-device-shape'), help=u"""Gets the detailed information about the specified CPE device type. This might include a set of questions that are specific to the particular CPE device type. The customer must supply answers to those questions (see [UpdateTunnelCpeDeviceConfig]). The service merges the answers with a template of other information for the CPE device type. The following operations return the merged content: * [GetCpeDeviceConfigContent] * [GetIpsecCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfigContent]""") @cli_util.option('--cpe-device-shape-id', required=True, help=u"""The [OCID] of the CPE device shape.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'CpeDeviceShapeDetail'}) @cli_util.wrap_exceptions def get_cpe_device_shape(ctx, from_json, cpe_device_shape_id): if isinstance(cpe_device_shape_id, six.string_types) and len(cpe_device_shape_id.strip()) == 0: raise click.UsageError('Parameter --cpe-device-shape-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cpe_device_shape( cpe_device_shape_id=cpe_device_shape_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.get_cross_connect.command_name', 'get'), help=u"""Gets the specified cross-connect's information.""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'CrossConnect'}) @cli_util.wrap_exceptions def get_cross_connect(ctx, from_json, cross_connect_id): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cross_connect( cross_connect_id=cross_connect_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.get_cross_connect_group.command_name', 'get'), help=u"""Gets the specified cross-connect group's information.""") @cli_util.option('--cross-connect-group-id', required=True, help=u"""The OCID of the cross-connect group.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'CrossConnectGroup'}) @cli_util.wrap_exceptions def get_cross_connect_group(ctx, from_json, cross_connect_group_id): if isinstance(cross_connect_group_id, six.string_types) and len(cross_connect_group_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-group-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cross_connect_group( cross_connect_group_id=cross_connect_group_id, **kwargs ) cli_util.render_response(result, ctx) @letter_of_authority_group.command(name=cli_util.override('virtual_network.get_cross_connect_letter_of_authority.command_name', 'get-cross-connect'), help=u"""Gets the Letter of Authority for the specified cross-connect.""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'LetterOfAuthority'}) @cli_util.wrap_exceptions def get_cross_connect_letter_of_authority(ctx, from_json, cross_connect_id): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cross_connect_letter_of_authority( cross_connect_id=cross_connect_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_status_group.command(name=cli_util.override('virtual_network.get_cross_connect_status.command_name', 'get'), help=u"""Gets the status of the specified cross-connect.""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'CrossConnectStatus'}) @cli_util.wrap_exceptions def get_cross_connect_status(ctx, from_json, cross_connect_id): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_cross_connect_status( cross_connect_id=cross_connect_id, **kwargs ) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.get_dhcp_options.command_name', 'get'), help=u"""Gets the specified set of DHCP options.""") @cli_util.option('--dhcp-id', required=True, help=u"""The OCID for the set of DHCP options.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'DhcpOptions'}) @cli_util.wrap_exceptions def get_dhcp_options(ctx, from_json, dhcp_id): if isinstance(dhcp_id, six.string_types) and len(dhcp_id.strip()) == 0: raise click.UsageError('Parameter --dhcp-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_dhcp_options( dhcp_id=dhcp_id, **kwargs ) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.get_drg.command_name', 'get'), help=u"""Gets the specified DRG's information.""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Drg'}) @cli_util.wrap_exceptions def get_drg(ctx, from_json, drg_id): if isinstance(drg_id, six.string_types) and len(drg_id.strip()) == 0: raise click.UsageError('Parameter --drg-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_drg( drg_id=drg_id, **kwargs ) cli_util.render_response(result, ctx) @drg_attachment_group.command(name=cli_util.override('virtual_network.get_drg_attachment.command_name', 'get'), help=u"""Gets the information for the specified `DrgAttachment`.""") @cli_util.option('--drg-attachment-id', required=True, help=u"""The OCID of the DRG attachment.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'DrgAttachment'}) @cli_util.wrap_exceptions def get_drg_attachment(ctx, from_json, drg_attachment_id): if isinstance(drg_attachment_id, six.string_types) and len(drg_attachment_id.strip()) == 0: raise click.UsageError('Parameter --drg-attachment-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_drg_attachment( drg_attachment_id=drg_attachment_id, **kwargs ) cli_util.render_response(result, ctx) @drg_redundancy_status_group.command(name=cli_util.override('virtual_network.get_drg_redundancy_status.command_name', 'get'), help=u"""Gets the redundancy status for the specified DRG. For more information, see [Redundancy Remedies].""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'DrgRedundancyStatus'}) @cli_util.wrap_exceptions def get_drg_redundancy_status(ctx, from_json, drg_id): if isinstance(drg_id, six.string_types) and len(drg_id.strip()) == 0: raise click.UsageError('Parameter --drg-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_drg_redundancy_status( drg_id=drg_id, **kwargs ) cli_util.render_response(result, ctx) @fast_connect_provider_service_group.command(name=cli_util.override('virtual_network.get_fast_connect_provider_service.command_name', 'get'), help=u"""Gets the specified provider service. For more information, see [FastConnect Overview].""") @cli_util.option('--provider-service-id', required=True, help=u"""The OCID of the provider service.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'FastConnectProviderService'}) @cli_util.wrap_exceptions def get_fast_connect_provider_service(ctx, from_json, provider_service_id): if isinstance(provider_service_id, six.string_types) and len(provider_service_id.strip()) == 0: raise click.UsageError('Parameter --provider-service-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_fast_connect_provider_service( provider_service_id=provider_service_id, **kwargs ) cli_util.render_response(result, ctx) @fast_connect_provider_service_key_group.command(name=cli_util.override('virtual_network.get_fast_connect_provider_service_key.command_name', 'get'), help=u"""Gets the specified provider service key's information. Use this operation to validate a provider service key. An invalid key returns a 404 error.""") @cli_util.option('--provider-service-id', required=True, help=u"""The OCID of the provider service.""") @cli_util.option('--provider-service-key-name', required=True, help=u"""The provider service key that the provider gives you when you set up a virtual circuit connection from the provider to Oracle Cloud Infrastructure. You can set up that connection and get your provider service key at the provider's website or portal. For the portal location, see the `description` attribute of the [FastConnectProviderService].""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'FastConnectProviderServiceKey'}) @cli_util.wrap_exceptions def get_fast_connect_provider_service_key(ctx, from_json, provider_service_id, provider_service_key_name): if isinstance(provider_service_id, six.string_types) and len(provider_service_id.strip()) == 0: raise click.UsageError('Parameter --provider-service-id cannot be whitespace or empty string') if isinstance(provider_service_key_name, six.string_types) and len(provider_service_key_name.strip()) == 0: raise click.UsageError('Parameter --provider-service-key-name cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_fast_connect_provider_service_key( provider_service_id=provider_service_id, provider_service_key_name=provider_service_key_name, **kwargs ) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.get_internet_gateway.command_name', 'get'), help=u"""Gets the specified internet gateway's information.""") @cli_util.option('--ig-id', required=True, help=u"""The OCID of the internet gateway.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'InternetGateway'}) @cli_util.wrap_exceptions def get_internet_gateway(ctx, from_json, ig_id): if isinstance(ig_id, six.string_types) and len(ig_id.strip()) == 0: raise click.UsageError('Parameter --ig-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_internet_gateway( ig_id=ig_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.get_ip_sec_connection.command_name', 'get'), help=u"""Gets the specified IPSec connection's basic information, including the static routes for the on-premises router. If you want the status of the connection (whether it's up or down), use [GetIPSecConnectionTunnel].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnection'}) @cli_util.wrap_exceptions def get_ip_sec_connection(ctx, from_json, ipsc_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ip_sec_connection( ipsc_id=ipsc_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_device_config_group.command(name=cli_util.override('virtual_network.get_ip_sec_connection_device_config.command_name', 'get'), help=u"""Deprecated. To get tunnel information, instead use: * [GetIPSecConnectionTunnel] * [GetIPSecConnectionTunnelSharedSecret]""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnectionDeviceConfig'}) @cli_util.wrap_exceptions def get_ip_sec_connection_device_config(ctx, from_json, ipsc_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ip_sec_connection_device_config( ipsc_id=ipsc_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_device_status_group.command(name=cli_util.override('virtual_network.get_ip_sec_connection_device_status.command_name', 'get'), help=u"""Deprecated. To get the tunnel status, instead use [GetIPSecConnectionTunnel].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnectionDeviceStatus'}) @cli_util.wrap_exceptions def get_ip_sec_connection_device_status(ctx, from_json, ipsc_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ip_sec_connection_device_status( ipsc_id=ipsc_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_tunnel_group.command(name=cli_util.override('virtual_network.get_ip_sec_connection_tunnel.command_name', 'get'), help=u"""Gets the specified tunnel's information. The resulting object does not include the tunnel's shared secret (pre-shared key). To retrieve that, use [GetIPSecConnectionTunnelSharedSecret].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnectionTunnel'}) @cli_util.wrap_exceptions def get_ip_sec_connection_tunnel(ctx, from_json, ipsc_id, tunnel_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ip_sec_connection_tunnel( ipsc_id=ipsc_id, tunnel_id=tunnel_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_tunnel_shared_secret_group.command(name=cli_util.override('virtual_network.get_ip_sec_connection_tunnel_shared_secret.command_name', 'get'), help=u"""Gets the specified tunnel's shared secret (pre-shared key). To get other information about the tunnel, use [GetIPSecConnectionTunnel].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnectionTunnelSharedSecret'}) @cli_util.wrap_exceptions def get_ip_sec_connection_tunnel_shared_secret(ctx, from_json, ipsc_id, tunnel_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ip_sec_connection_tunnel_shared_secret( ipsc_id=ipsc_id, tunnel_id=tunnel_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.get_ipsec_cpe_device_config_content.command_name', 'get-ipsec-cpe-device-config-content'), help=u"""Renders a set of CPE configuration content for the specified IPSec connection (for all the tunnels in the connection). The content helps a network engineer configure the actual CPE device (for example, a hardware router) that the specified IPSec connection terminates on. The rendered content is specific to the type of CPE device (for example, Cisco ASA). Therefore the [Cpe] used by the specified [IPSecConnection] must have the CPE's device type specified by the `cpeDeviceShapeId` attribute. The content optionally includes answers that the customer provides (see [UpdateTunnelCpeDeviceConfig]), merged with a template of other information specific to the CPE device type. The operation returns configuration information for all tunnels in the single specified [IPSecConnection] object. Here are other similar operations: * [GetTunnelCpeDeviceConfigContent] returns CPE configuration content for a specific tunnel within an IPSec connection. * [GetCpeDeviceConfigContent] returns CPE configuration content for *all* IPSec connections that use a specific CPE.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--file', type=click.File(mode='wb'), required=True, help="The name of the file that will receive the response data, or '-' to write to STDOUT.") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def get_ipsec_cpe_device_config_content(ctx, from_json, file, ipsc_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ipsec_cpe_device_config_content( ipsc_id=ipsc_id, **kwargs ) # If outputting to stdout we don't want to print a progress bar because it will get mixed up with the output # Also we need a non-zero Content-Length in order to display a meaningful progress bar bar = None if hasattr(file, 'name') and file.name != '<stdout>' and 'Content-Length' in result.headers: content_length = int(result.headers['Content-Length']) if content_length > 0: bar = click.progressbar(length=content_length, label='Downloading file') try: if bar: bar.__enter__() # TODO: Make the download size a configurable option # use decode_content=True to automatically unzip service responses (this should be overridden for object storage) for chunk in result.data.raw.stream(cli_constants.MEBIBYTE, decode_content=True): if bar: bar.update(len(chunk)) file.write(chunk) finally: if bar: bar.render_finish() file.close() @ipv6_group.command(name=cli_util.override('virtual_network.get_ipv6.command_name', 'get'), help=u"""Gets the specified IPv6. You must specify the object's OCID. Alternatively, you can get the object by using [ListIpv6s] with the IPv6 address (for example, 2001:0db8:0123:1111:98fe:dcba:9876:4321) and subnet OCID.""") @cli_util.option('--ipv6-id', required=True, help=u"""The [OCID] of the IPv6.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Ipv6'}) @cli_util.wrap_exceptions def get_ipv6(ctx, from_json, ipv6_id): if isinstance(ipv6_id, six.string_types) and len(ipv6_id.strip()) == 0: raise click.UsageError('Parameter --ipv6-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_ipv6( ipv6_id=ipv6_id, **kwargs ) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.get_local_peering_gateway.command_name', 'get'), help=u"""Gets the specified local peering gateway's information.""") @cli_util.option('--local-peering-gateway-id', required=True, help=u"""The OCID of the local peering gateway.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'LocalPeeringGateway'}) @cli_util.wrap_exceptions def get_local_peering_gateway(ctx, from_json, local_peering_gateway_id): if isinstance(local_peering_gateway_id, six.string_types) and len(local_peering_gateway_id.strip()) == 0: raise click.UsageError('Parameter --local-peering-gateway-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_local_peering_gateway( local_peering_gateway_id=local_peering_gateway_id, **kwargs ) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.get_nat_gateway.command_name', 'get'), help=u"""Gets the specified NAT gateway's information.""") @cli_util.option('--nat-gateway-id', required=True, help=u"""The NAT gateway's [OCID].""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'NatGateway'}) @cli_util.wrap_exceptions def get_nat_gateway(ctx, from_json, nat_gateway_id): if isinstance(nat_gateway_id, six.string_types) and len(nat_gateway_id.strip()) == 0: raise click.UsageError('Parameter --nat-gateway-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_nat_gateway( nat_gateway_id=nat_gateway_id, **kwargs ) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.get_network_security_group.command_name', 'get'), help=u"""Gets the specified network security group's information. To list the VNICs in an NSG, see [ListNetworkSecurityGroupVnics]. To list the security rules in an NSG, see [ListNetworkSecurityGroupSecurityRules].""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'NetworkSecurityGroup'}) @cli_util.wrap_exceptions def get_network_security_group(ctx, from_json, network_security_group_id): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_network_security_group( network_security_group_id=network_security_group_id, **kwargs ) cli_util.render_response(result, ctx) @private_ip_group.command(name=cli_util.override('virtual_network.get_private_ip.command_name', 'get'), help=u"""Gets the specified private IP. You must specify the object's OCID. Alternatively, you can get the object by using [ListPrivateIps] with the private IP address (for example, 10.0.3.3) and subnet OCID.""") @cli_util.option('--private-ip-id', required=True, help=u"""The OCID of the private IP.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'PrivateIp'}) @cli_util.wrap_exceptions def get_private_ip(ctx, from_json, private_ip_id): if isinstance(private_ip_id, six.string_types) and len(private_ip_id.strip()) == 0: raise click.UsageError('Parameter --private-ip-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_private_ip( private_ip_id=private_ip_id, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.get_public_ip.command_name', 'get'), help=u"""Gets the specified public IP. You must specify the object's OCID. Alternatively, you can get the object by using [GetPublicIpByIpAddress] with the public IP address (for example, 203.0.113.2). Or you can use [GetPublicIpByPrivateIpId] with the OCID of the private IP that the public IP is assigned to. **Note:** If you're fetching a reserved public IP that is in the process of being moved to a different private IP, the service returns the public IP object with `lifecycleState` = ASSIGNING and `assignedEntityId` = OCID of the target private IP.""") @cli_util.option('--public-ip-id', required=True, help=u"""The OCID of the public IP.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'PublicIp'}) @cli_util.wrap_exceptions def get_public_ip(ctx, from_json, public_ip_id): if isinstance(public_ip_id, six.string_types) and len(public_ip_id.strip()) == 0: raise click.UsageError('Parameter --public-ip-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_public_ip( public_ip_id=public_ip_id, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.get_public_ip_by_ip_address.command_name', 'get-public-ip-by-ip-address'), help=u"""Gets the public IP based on the public IP address (for example, 203.0.113.2). **Note:** If you're fetching a reserved public IP that is in the process of being moved to a different private IP, the service returns the public IP object with `lifecycleState` = ASSIGNING and `assignedEntityId` = OCID of the target private IP.""") @cli_util.option('--ip-address', required=True, help=u"""The public IP address. Example: 203.0.113.2""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'PublicIp'}) @cli_util.wrap_exceptions def get_public_ip_by_ip_address(ctx, from_json, ip_address): kwargs = {} _details = {} _details['ipAddress'] = ip_address client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_public_ip_by_ip_address( get_public_ip_by_ip_address_details=_details, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.get_public_ip_by_private_ip_id.command_name', 'get-public-ip-by-private-ip-id'), help=u"""Gets the public IP assigned to the specified private IP. You must specify the OCID of the private IP. If no public IP is assigned, a 404 is returned. **Note:** If you're fetching a reserved public IP that is in the process of being moved to a different private IP, and you provide the OCID of the original private IP, this operation returns a 404. If you instead provide the OCID of the target private IP, or if you instead call [GetPublicIp] or [GetPublicIpByIpAddress], the service returns the public IP object with `lifecycleState` = ASSIGNING and `assignedEntityId` = OCID of the target private IP.""") @cli_util.option('--private-ip-id', required=True, help=u"""OCID of the private IP.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'PublicIp'}) @cli_util.wrap_exceptions def get_public_ip_by_private_ip_id(ctx, from_json, private_ip_id): kwargs = {} _details = {} _details['privateIpId'] = private_ip_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_public_ip_by_private_ip_id( get_public_ip_by_private_ip_id_details=_details, **kwargs ) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.get_remote_peering_connection.command_name', 'get'), help=u"""Get the specified remote peering connection's information.""") @cli_util.option('--remote-peering-connection-id', required=True, help=u"""The OCID of the remote peering connection (RPC).""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'RemotePeeringConnection'}) @cli_util.wrap_exceptions def get_remote_peering_connection(ctx, from_json, remote_peering_connection_id): if isinstance(remote_peering_connection_id, six.string_types) and len(remote_peering_connection_id.strip()) == 0: raise click.UsageError('Parameter --remote-peering-connection-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_remote_peering_connection( remote_peering_connection_id=remote_peering_connection_id, **kwargs ) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.get_route_table.command_name', 'get'), help=u"""Gets the specified route table's information.""") @cli_util.option('--rt-id', required=True, help=u"""The OCID of the route table.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'RouteTable'}) @cli_util.wrap_exceptions def get_route_table(ctx, from_json, rt_id): if isinstance(rt_id, six.string_types) and len(rt_id.strip()) == 0: raise click.UsageError('Parameter --rt-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_route_table( rt_id=rt_id, **kwargs ) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.get_security_list.command_name', 'get'), help=u"""Gets the specified security list's information.""") @cli_util.option('--security-list-id', required=True, help=u"""The OCID of the security list.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'SecurityList'}) @cli_util.wrap_exceptions def get_security_list(ctx, from_json, security_list_id): if isinstance(security_list_id, six.string_types) and len(security_list_id.strip()) == 0: raise click.UsageError('Parameter --security-list-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_security_list( security_list_id=security_list_id, **kwargs ) cli_util.render_response(result, ctx) @service_group.command(name=cli_util.override('virtual_network.get_service.command_name', 'get'), help=u"""Gets the specified [Service] object.""") @cli_util.option('--service-id', required=True, help=u"""The service's [OCID].""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Service'}) @cli_util.wrap_exceptions def get_service(ctx, from_json, service_id): if isinstance(service_id, six.string_types) and len(service_id.strip()) == 0: raise click.UsageError('Parameter --service-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_service( service_id=service_id, **kwargs ) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.get_service_gateway.command_name', 'get'), help=u"""Gets the specified service gateway's information.""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'ServiceGateway'}) @cli_util.wrap_exceptions def get_service_gateway(ctx, from_json, service_gateway_id): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_service_gateway( service_gateway_id=service_gateway_id, **kwargs ) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.get_subnet.command_name', 'get'), help=u"""Gets the specified subnet's information.""") @cli_util.option('--subnet-id', required=True, help=u"""The OCID of the subnet.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Subnet'}) @cli_util.wrap_exceptions def get_subnet(ctx, from_json, subnet_id): if isinstance(subnet_id, six.string_types) and len(subnet_id.strip()) == 0: raise click.UsageError('Parameter --subnet-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_subnet( subnet_id=subnet_id, **kwargs ) cli_util.render_response(result, ctx) @tunnel_cpe_device_config_group.command(name=cli_util.override('virtual_network.get_tunnel_cpe_device_config.command_name', 'get'), help=u"""Gets the set of CPE configuration answers for the tunnel, which the customer provided in [UpdateTunnelCpeDeviceConfig]. To get the full set of content for the tunnel (any answers merged with the template of other information specific to the CPE device type), use [GetTunnelCpeDeviceConfigContent].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'TunnelCpeDeviceConfig'}) @cli_util.wrap_exceptions def get_tunnel_cpe_device_config(ctx, from_json, ipsc_id, tunnel_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_tunnel_cpe_device_config( ipsc_id=ipsc_id, tunnel_id=tunnel_id, **kwargs ) cli_util.render_response(result, ctx) @tunnel_cpe_device_config_group.command(name=cli_util.override('virtual_network.get_tunnel_cpe_device_config_content.command_name', 'get-tunnel-cpe-device-config-content'), help=u"""Renders a set of CPE configuration content for the specified IPSec tunnel. The content helps a network engineer configure the actual CPE device (for example, a hardware router) that the specified IPSec tunnel terminates on. The rendered content is specific to the type of CPE device (for example, Cisco ASA). Therefore the [Cpe] used by the specified [IPSecConnection] must have the CPE's device type specified by the `cpeDeviceShapeId` attribute. The content optionally includes answers that the customer provides (see [UpdateTunnelCpeDeviceConfig]), merged with a template of other information specific to the CPE device type. The operation returns configuration information for only the specified IPSec tunnel. Here are other similar operations: * [GetIpsecCpeDeviceConfigContent] returns CPE configuration content for all tunnels in a single IPSec connection. * [GetCpeDeviceConfigContent] returns CPE configuration content for *all* IPSec connections that use a specific CPE.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @cli_util.option('--file', type=click.File(mode='wb'), required=True, help="The name of the file that will receive the response data, or '-' to write to STDOUT.") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}) @cli_util.wrap_exceptions def get_tunnel_cpe_device_config_content(ctx, from_json, file, ipsc_id, tunnel_id): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_tunnel_cpe_device_config_content( ipsc_id=ipsc_id, tunnel_id=tunnel_id, **kwargs ) # If outputting to stdout we don't want to print a progress bar because it will get mixed up with the output # Also we need a non-zero Content-Length in order to display a meaningful progress bar bar = None if hasattr(file, 'name') and file.name != '<stdout>' and 'Content-Length' in result.headers: content_length = int(result.headers['Content-Length']) if content_length > 0: bar = click.progressbar(length=content_length, label='Downloading file') try: if bar: bar.__enter__() # TODO: Make the download size a configurable option # use decode_content=True to automatically unzip service responses (this should be overridden for object storage) for chunk in result.data.raw.stream(cli_constants.MEBIBYTE, decode_content=True): if bar: bar.update(len(chunk)) file.write(chunk) finally: if bar: bar.render_finish() file.close() @vcn_group.command(name=cli_util.override('virtual_network.get_vcn.command_name', 'get'), help=u"""Gets the specified VCN's information.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Vcn'}) @cli_util.wrap_exceptions def get_vcn(ctx, from_json, vcn_id): if isinstance(vcn_id, six.string_types) and len(vcn_id.strip()) == 0: raise click.UsageError('Parameter --vcn-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_vcn( vcn_id=vcn_id, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.get_virtual_circuit.command_name', 'get'), help=u"""Gets the specified virtual circuit's information.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'VirtualCircuit'}) @cli_util.wrap_exceptions def get_virtual_circuit(ctx, from_json, virtual_circuit_id): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_virtual_circuit( virtual_circuit_id=virtual_circuit_id, **kwargs ) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.get_vlan.command_name', 'get'), help=u"""Gets the specified VLAN's information.""") @cli_util.option('--vlan-id', required=True, help=u"""The [OCID] of the VLAN.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Vlan'}) @cli_util.wrap_exceptions def get_vlan(ctx, from_json, vlan_id): if isinstance(vlan_id, six.string_types) and len(vlan_id.strip()) == 0: raise click.UsageError('Parameter --vlan-id cannot be whitespace or empty string') kwargs = {} kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_vlan( vlan_id=vlan_id, **kwargs ) cli_util.render_response(result, ctx) @vnic_group.command(name=cli_util.override('virtual_network.get_vnic.command_name', 'get'), help=u"""Gets the information for the specified virtual network interface card (VNIC). You can get the VNIC OCID from the [ListVnicAttachments] operation.""") @cli_util.option('--vnic-id', required=True, help=u"""The OCID of the VNIC.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'Vnic'}) @cli_util.wrap_exceptions def get_vnic(ctx, from_json, vnic_id): if isinstance(vnic_id, six.string_types) and len(vnic_id.strip()) == 0: raise click.UsageError('Parameter --vnic-id cannot be whitespace or empty string') kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.get_vnic( vnic_id=vnic_id, **kwargs ) cli_util.render_response(result, ctx) @peer_region_for_remote_peering_group.command(name=cli_util.override('virtual_network.list_allowed_peer_regions_for_remote_peering.command_name', 'list-allowed-peer-regions-for-remote-peering'), help=u"""Lists the regions that support remote VCN peering (which is peering across regions). For more information, see [VCN Peering].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[PeerRegionForRemotePeering]'}) @cli_util.wrap_exceptions def list_allowed_peer_regions_for_remote_peering(ctx, from_json, all_pages, ): kwargs = {} client = cli_util.build_client('core', 'virtual_network', ctx) result = client.list_allowed_peer_regions_for_remote_peering( **kwargs ) cli_util.render_response(result, ctx) @cpe_device_shape_group.command(name=cli_util.override('virtual_network.list_cpe_device_shapes.command_name', 'list'), help=u"""Lists the CPE device types that the Networking service provides CPE configuration content for (example: Cisco ASA). The content helps a network engineer configure the actual CPE device represented by a [Cpe] object. If you want to generate CPE configuration content for one of the returned CPE device types, ensure that the [Cpe] object's `cpeDeviceShapeId` attribute is set to the CPE device type's OCID (returned by this operation). For information about generating CPE configuration content, see these operations: * [GetCpeDeviceConfigContent] * [GetIpsecCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfigContent]""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[CpeDeviceShapeSummary]'}) @cli_util.wrap_exceptions def list_cpe_device_shapes(ctx, from_json, all_pages, page_size, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_cpe_device_shapes, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_cpe_device_shapes, limit, page_size, **kwargs ) else: result = client.list_cpe_device_shapes( **kwargs ) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.list_cpes.command_name', 'list'), help=u"""Lists the customer-premises equipment objects (CPEs) in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Cpe]'}) @cli_util.wrap_exceptions def list_cpes(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_cpes, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_cpes, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_cpes( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.list_cross_connect_groups.command_name', 'list'), help=u"""Lists the cross-connect groups in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the specified lifecycle state. The value is case insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[CrossConnectGroup]'}) @cli_util.wrap_exceptions def list_cross_connect_groups(ctx, from_json, all_pages, page_size, compartment_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_cross_connect_groups, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_cross_connect_groups, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_cross_connect_groups( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_location_group.command(name=cli_util.override('virtual_network.list_cross_connect_locations.command_name', 'list'), help=u"""Lists the available FastConnect locations for cross-connect installation. You need this information so you can specify your desired location when you create a cross-connect.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[CrossConnectLocation]'}) @cli_util.wrap_exceptions def list_cross_connect_locations(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_cross_connect_locations, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_cross_connect_locations, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_cross_connect_locations( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.list_cross_connects.command_name', 'list'), help=u"""Lists the cross-connects in the specified compartment. You can filter the list by specifying the OCID of a cross-connect group.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--cross-connect-group-id', help=u"""The OCID of the cross-connect group.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_CUSTOMER", "PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the specified lifecycle state. The value is case insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[CrossConnect]'}) @cli_util.wrap_exceptions def list_cross_connects(ctx, from_json, all_pages, page_size, compartment_id, cross_connect_group_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if cross_connect_group_id is not None: kwargs['cross_connect_group_id'] = cross_connect_group_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_cross_connects, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_cross_connects, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_cross_connects( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_port_speed_shape_group.command(name=cli_util.override('virtual_network.list_crossconnect_port_speed_shapes.command_name', 'list-crossconnect-port-speed-shapes'), help=u"""Lists the available port speeds for cross-connects. You need this information so you can specify your desired port speed (that is, shape) when you create a cross-connect.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[CrossConnectPortSpeedShape]'}) @cli_util.wrap_exceptions def list_crossconnect_port_speed_shapes(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_crossconnect_port_speed_shapes, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_crossconnect_port_speed_shapes, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_crossconnect_port_speed_shapes( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.list_dhcp_options.command_name', 'list'), help=u"""Lists the sets of DHCP options in the specified VCN and specified compartment. If the VCN ID is not provided, then the list includes the sets of DHCP options from all VCNs in the specified compartment. The response includes the default set of options that automatically comes with each VCN, plus any other sets you've created.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[DhcpOptions]'}) @cli_util.wrap_exceptions def list_dhcp_options(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_dhcp_options, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_dhcp_options, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_dhcp_options( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @drg_attachment_group.command(name=cli_util.override('virtual_network.list_drg_attachments.command_name', 'list'), help=u"""Lists the `DrgAttachment` objects for the specified compartment. You can filter the results by VCN or DRG.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--drg-id', help=u"""The OCID of the DRG.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[DrgAttachment]'}) @cli_util.wrap_exceptions def list_drg_attachments(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, drg_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if drg_id is not None: kwargs['drg_id'] = drg_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_drg_attachments, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_drg_attachments, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_drg_attachments( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.list_drgs.command_name', 'list'), help=u"""Lists the DRGs in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Drg]'}) @cli_util.wrap_exceptions def list_drgs(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_drgs, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_drgs, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_drgs( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @fast_connect_provider_service_group.command(name=cli_util.override('virtual_network.list_fast_connect_provider_services.command_name', 'list'), help=u"""Lists the service offerings from supported providers. You need this information so you can specify your desired provider and service offering when you create a virtual circuit. For the compartment ID, provide the OCID of your tenancy (the root compartment). For more information, see [FastConnect Overview].""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[FastConnectProviderService]'}) @cli_util.wrap_exceptions def list_fast_connect_provider_services(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_fast_connect_provider_services, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_fast_connect_provider_services, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_fast_connect_provider_services( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @fast_connect_provider_service_group.command(name=cli_util.override('virtual_network.list_fast_connect_provider_virtual_circuit_bandwidth_shapes.command_name', 'list-fast-connect-provider-virtual-circuit-bandwidth-shapes'), help=u"""Gets the list of available virtual circuit bandwidth levels for a provider. You need this information so you can specify your desired bandwidth level (shape) when you create a virtual circuit. For more information about virtual circuits, see [FastConnect Overview].""") @cli_util.option('--provider-service-id', required=True, help=u"""The OCID of the provider service.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[VirtualCircuitBandwidthShape]'}) @cli_util.wrap_exceptions def list_fast_connect_provider_virtual_circuit_bandwidth_shapes(ctx, from_json, all_pages, page_size, provider_service_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') if isinstance(provider_service_id, six.string_types) and len(provider_service_id.strip()) == 0: raise click.UsageError('Parameter --provider-service-id cannot be whitespace or empty string') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_fast_connect_provider_virtual_circuit_bandwidth_shapes, provider_service_id=provider_service_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_fast_connect_provider_virtual_circuit_bandwidth_shapes, limit, page_size, provider_service_id=provider_service_id, **kwargs ) else: result = client.list_fast_connect_provider_virtual_circuit_bandwidth_shapes( provider_service_id=provider_service_id, **kwargs ) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.list_internet_gateways.command_name', 'list'), help=u"""Lists the internet gateways in the specified VCN and the specified compartment. If the VCN ID is not provided, then the list includes the internet gateways from all VCNs in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[InternetGateway]'}) @cli_util.wrap_exceptions def list_internet_gateways(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_internet_gateways, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_internet_gateways, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_internet_gateways( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_tunnel_group.command(name=cli_util.override('virtual_network.list_ip_sec_connection_tunnels.command_name', 'list'), help=u"""Lists the tunnel information for the specified IPSec connection.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[IPSecConnectionTunnel]'}) @cli_util.wrap_exceptions def list_ip_sec_connection_tunnels(ctx, from_json, all_pages, page_size, ipsc_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_ip_sec_connection_tunnels, ipsc_id=ipsc_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_ip_sec_connection_tunnels, limit, page_size, ipsc_id=ipsc_id, **kwargs ) else: result = client.list_ip_sec_connection_tunnels( ipsc_id=ipsc_id, **kwargs ) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.list_ip_sec_connections.command_name', 'list'), help=u"""Lists the IPSec connections for the specified compartment. You can filter the results by DRG or CPE.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--drg-id', help=u"""The OCID of the DRG.""") @cli_util.option('--cpe-id', help=u"""The OCID of the CPE.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[IPSecConnection]'}) @cli_util.wrap_exceptions def list_ip_sec_connections(ctx, from_json, all_pages, page_size, compartment_id, drg_id, cpe_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if drg_id is not None: kwargs['drg_id'] = drg_id if cpe_id is not None: kwargs['cpe_id'] = cpe_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_ip_sec_connections, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_ip_sec_connections, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_ip_sec_connections( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @ipv6_group.command(name=cli_util.override('virtual_network.list_ipv6s.command_name', 'list'), help=u"""Lists the [IPv6] objects based on one of these filters: * Subnet OCID. * VNIC OCID. * Both IPv6 address and subnet OCID: This lets you get an `Ipv6` object based on its private IPv6 address (for example, 2001:0db8:0123:1111:abcd:ef01:2345:6789) and not its OCID. For comparison, [GetIpv6] requires the OCID.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--ip-address', help=u"""An IP address. This could be either IPv4 or IPv6, depending on the resource. Example: `10.0.3.3`""") @cli_util.option('--subnet-id', help=u"""The OCID of the subnet.""") @cli_util.option('--vnic-id', help=u"""The OCID of the VNIC.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Ipv6]'}) @cli_util.wrap_exceptions def list_ipv6s(ctx, from_json, all_pages, page_size, limit, page, ip_address, subnet_id, vnic_id): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if ip_address is not None: kwargs['ip_address'] = ip_address if subnet_id is not None: kwargs['subnet_id'] = subnet_id if vnic_id is not None: kwargs['vnic_id'] = vnic_id kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_ipv6s, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_ipv6s, limit, page_size, **kwargs ) else: result = client.list_ipv6s( **kwargs ) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.list_local_peering_gateways.command_name', 'list'), help=u"""Lists the local peering gateways (LPGs) for the specified VCN and specified compartment. If the VCN ID is not provided, then the list includes the LPGs from all VCNs in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[LocalPeeringGateway]'}) @cli_util.wrap_exceptions def list_local_peering_gateways(ctx, from_json, all_pages, page_size, compartment_id, limit, page, vcn_id): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if vcn_id is not None: kwargs['vcn_id'] = vcn_id client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_local_peering_gateways, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_local_peering_gateways, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_local_peering_gateways( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.list_nat_gateways.command_name', 'list'), help=u"""Lists the NAT gateways in the specified compartment. You may optionally specify a VCN OCID to filter the results by VCN.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the specified lifecycle state. The value is case insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[NatGateway]'}) @cli_util.wrap_exceptions def list_nat_gateways(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_nat_gateways, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_nat_gateways, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_nat_gateways( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @security_rule_group.command(name=cli_util.override('virtual_network.list_network_security_group_security_rules.command_name', 'list-network-security-group'), help=u"""Lists the security rules in the specified network security group.""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--direction', type=custom_types.CliCaseInsensitiveChoice(["EGRESS", "INGRESS"]), help=u"""Direction of the security rule. Set to `EGRESS` for rules that allow outbound IP packets, or `INGRESS` for rules that allow inbound IP packets.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED"]), help=u"""The field to sort by.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[SecurityRule]'}) @cli_util.wrap_exceptions def list_network_security_group_security_rules(ctx, from_json, all_pages, page_size, network_security_group_id, direction, limit, page, sort_by, sort_order): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} if direction is not None: kwargs['direction'] = direction if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_network_security_group_security_rules, network_security_group_id=network_security_group_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_network_security_group_security_rules, limit, page_size, network_security_group_id=network_security_group_id, **kwargs ) else: result = client.list_network_security_group_security_rules( network_security_group_id=network_security_group_id, **kwargs ) cli_util.render_response(result, ctx) @network_security_group_vnic_group.command(name=cli_util.override('virtual_network.list_network_security_group_vnics.command_name', 'list'), help=u"""Lists the VNICs in the specified network security group.""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMEASSOCIATED"]), help=u"""The field to sort by.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[NetworkSecurityGroupVnic]'}) @cli_util.wrap_exceptions def list_network_security_group_vnics(ctx, from_json, all_pages, page_size, network_security_group_id, limit, page, sort_by, sort_order): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_network_security_group_vnics, network_security_group_id=network_security_group_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_network_security_group_vnics, limit, page_size, network_security_group_id=network_security_group_id, **kwargs ) else: result = client.list_network_security_group_vnics( network_security_group_id=network_security_group_id, **kwargs ) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.list_network_security_groups.command_name', 'list'), help=u"""Lists the network security groups in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the specified lifecycle state. The value is case insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[NetworkSecurityGroup]'}) @cli_util.wrap_exceptions def list_network_security_groups(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_network_security_groups, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_network_security_groups, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_network_security_groups( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @private_ip_group.command(name=cli_util.override('virtual_network.list_private_ips.command_name', 'list'), help=u"""Lists the [PrivateIp] objects based on one of these filters: - Subnet OCID. - VNIC OCID. - Both private IP address and subnet OCID: This lets you get a `privateIP` object based on its private IP address (for example, 10.0.3.3) and not its OCID. For comparison, [GetPrivateIp] requires the OCID. If you're listing all the private IPs associated with a given subnet or VNIC, the response includes both primary and secondary private IPs. If you are an Oracle Cloud VMware Solution customer and have VLANs in your VCN, you can filter the list by VLAN OCID. See [Vlan].""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--ip-address', help=u"""An IP address. This could be either IPv4 or IPv6, depending on the resource. Example: `10.0.3.3`""") @cli_util.option('--subnet-id', help=u"""The OCID of the subnet.""") @cli_util.option('--vnic-id', help=u"""The OCID of the VNIC.""") @cli_util.option('--vlan-id', help=u"""The [OCID] of the VLAN.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[PrivateIp]'}) @cli_util.wrap_exceptions def list_private_ips(ctx, from_json, all_pages, page_size, limit, page, ip_address, subnet_id, vnic_id, vlan_id): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if ip_address is not None: kwargs['ip_address'] = ip_address if subnet_id is not None: kwargs['subnet_id'] = subnet_id if vnic_id is not None: kwargs['vnic_id'] = vnic_id if vlan_id is not None: kwargs['vlan_id'] = vlan_id client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_private_ips, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_private_ips, limit, page_size, **kwargs ) else: result = client.list_private_ips( **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.list_public_ips.command_name', 'list'), help=u"""Lists the [PublicIp] objects in the specified compartment. You can filter the list by using query parameters. To list your reserved public IPs: * Set `scope` = `REGION` (required) * Leave the `availabilityDomain` parameter empty * Set `lifetime` = `RESERVED` To list the ephemeral public IPs assigned to a regional entity such as a NAT gateway: * Set `scope` = `REGION` (required) * Leave the `availabilityDomain` parameter empty * Set `lifetime` = `EPHEMERAL` To list the ephemeral public IPs assigned to private IPs: * Set `scope` = `AVAILABILITY_DOMAIN` (required) * Set the `availabilityDomain` parameter to the desired availability domain (required) * Set `lifetime` = `EPHEMERAL` **Note:** An ephemeral public IP assigned to a private IP is always in the same availability domain and compartment as the private IP.""") @cli_util.option('--scope', required=True, type=custom_types.CliCaseInsensitiveChoice(["REGION", "AVAILABILITY_DOMAIN"]), help=u"""Whether the public IP is regional or specific to a particular availability domain. * `REGION`: The public IP exists within a region and is assigned to a regional entity (such as a [NatGateway]), or can be assigned to a private IP in any availability domain in the region. Reserved public IPs have `scope` = `REGION`, as do ephemeral public IPs assigned to a regional entity. * `AVAILABILITY_DOMAIN`: The public IP exists within the availability domain of the entity it's assigned to, which is specified by the `availabilityDomain` property of the public IP object. Ephemeral public IPs that are assigned to private IPs have `scope` = `AVAILABILITY_DOMAIN`.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--availability-domain', help=u"""The name of the availability domain. Example: `Uocm:PHX-AD-1`""") @cli_util.option('--lifetime', type=custom_types.CliCaseInsensitiveChoice(["EPHEMERAL", "RESERVED"]), help=u"""A filter to return only public IPs that match given lifetime.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[PublicIp]'}) @cli_util.wrap_exceptions def list_public_ips(ctx, from_json, all_pages, page_size, scope, compartment_id, limit, page, availability_domain, lifetime): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if availability_domain is not None: kwargs['availability_domain'] = availability_domain if lifetime is not None: kwargs['lifetime'] = lifetime client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_public_ips, scope=scope, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_public_ips, limit, page_size, scope=scope, compartment_id=compartment_id, **kwargs ) else: result = client.list_public_ips( scope=scope, compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.list_remote_peering_connections.command_name', 'list'), help=u"""Lists the remote peering connections (RPCs) for the specified DRG and compartment (the RPC's compartment).""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--drg-id', help=u"""The OCID of the DRG.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[RemotePeeringConnection]'}) @cli_util.wrap_exceptions def list_remote_peering_connections(ctx, from_json, all_pages, page_size, compartment_id, drg_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if drg_id is not None: kwargs['drg_id'] = drg_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_remote_peering_connections, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_remote_peering_connections, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_remote_peering_connections( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.list_route_tables.command_name', 'list'), help=u"""Lists the route tables in the specified VCN and specified compartment. If the VCN ID is not provided, then the list includes the route tables from all VCNs in the specified compartment. The response includes the default route table that automatically comes with each VCN in the specified compartment, plus any route tables you've created.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[RouteTable]'}) @cli_util.wrap_exceptions def list_route_tables(ctx, from_json, all_pages, page_size, compartment_id, limit, page, vcn_id, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if vcn_id is not None: kwargs['vcn_id'] = vcn_id if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_route_tables, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_route_tables, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_route_tables( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.list_security_lists.command_name', 'list'), help=u"""Lists the security lists in the specified VCN and compartment. If the VCN ID is not provided, then the list includes the security lists from all VCNs in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[SecurityList]'}) @cli_util.wrap_exceptions def list_security_lists(ctx, from_json, all_pages, page_size, compartment_id, limit, page, vcn_id, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if vcn_id is not None: kwargs['vcn_id'] = vcn_id if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_security_lists, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_security_lists, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_security_lists( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.list_service_gateways.command_name', 'list'), help=u"""Lists the service gateways in the specified compartment. You may optionally specify a VCN OCID to filter the results by VCN.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[ServiceGateway]'}) @cli_util.wrap_exceptions def list_service_gateways(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if vcn_id is not None: kwargs['vcn_id'] = vcn_id if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_service_gateways, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_service_gateways, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_service_gateways( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @service_group.command(name=cli_util.override('virtual_network.list_services.command_name', 'list'), help=u"""Lists the available [Service] objects that you can enable for a service gateway in this region.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Service]'}) @cli_util.wrap_exceptions def list_services(ctx, from_json, all_pages, page_size, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_services, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_services, limit, page_size, **kwargs ) else: result = client.list_services( **kwargs ) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.list_subnets.command_name', 'list'), help=u"""Lists the subnets in the specified VCN and the specified compartment. If the VCN ID is not provided, then the list includes the subnets from all VCNs in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--vcn-id', help=u"""The [OCID] of the VCN.""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Subnet]'}) @cli_util.wrap_exceptions def list_subnets(ctx, from_json, all_pages, page_size, compartment_id, limit, page, vcn_id, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if vcn_id is not None: kwargs['vcn_id'] = vcn_id if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_subnets, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_subnets, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_subnets( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @vcn_group.command(name=cli_util.override('virtual_network.list_vcns.command_name', 'list'), help=u"""Lists the virtual cloud networks (VCNs) in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Vcn]'}) @cli_util.wrap_exceptions def list_vcns(ctx, from_json, all_pages, page_size, compartment_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_vcns, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_vcns, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_vcns( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_bandwidth_shape_group.command(name=cli_util.override('virtual_network.list_virtual_circuit_bandwidth_shapes.command_name', 'list'), help=u"""The deprecated operation lists available bandwidth levels for virtual circuits. For the compartment ID, provide the OCID of your tenancy (the root compartment).""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[VirtualCircuitBandwidthShape]'}) @cli_util.wrap_exceptions def list_virtual_circuit_bandwidth_shapes(ctx, from_json, all_pages, page_size, compartment_id, limit, page): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_virtual_circuit_bandwidth_shapes, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_virtual_circuit_bandwidth_shapes, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_virtual_circuit_bandwidth_shapes( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_public_prefix_group.command(name=cli_util.override('virtual_network.list_virtual_circuit_public_prefixes.command_name', 'list'), help=u"""Lists the public IP prefixes and their details for the specified public virtual circuit.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--verification-state', type=custom_types.CliCaseInsensitiveChoice(["IN_PROGRESS", "COMPLETED", "FAILED"]), help=u"""A filter to only return resources that match the given verification state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[VirtualCircuitPublicPrefix]'}) @cli_util.wrap_exceptions def list_virtual_circuit_public_prefixes(ctx, from_json, all_pages, virtual_circuit_id, verification_state): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') kwargs = {} if verification_state is not None: kwargs['verification_state'] = verification_state client = cli_util.build_client('core', 'virtual_network', ctx) result = client.list_virtual_circuit_public_prefixes( virtual_circuit_id=virtual_circuit_id, **kwargs ) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.list_virtual_circuits.command_name', 'list'), help=u"""Lists the virtual circuits in the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_PROVIDER", "VERIFYING", "PROVISIONING", "PROVISIONED", "FAILED", "INACTIVE", "TERMINATING", "TERMINATED"]), help=u"""A filter to return only resources that match the specified lifecycle state. The value is case insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[VirtualCircuit]'}) @cli_util.wrap_exceptions def list_virtual_circuits(ctx, from_json, all_pages, page_size, compartment_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_virtual_circuits, compartment_id=compartment_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_virtual_circuits, limit, page_size, compartment_id=compartment_id, **kwargs ) else: result = client.list_virtual_circuits( compartment_id=compartment_id, **kwargs ) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.list_vlans.command_name', 'list'), help=u"""Lists the VLANs in the specified VCN and the specified compartment.""") @cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @cli_util.option('--limit', type=click.INT, help=u"""For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see [List Pagination]. Example: `50`""") @cli_util.option('--page', help=u"""For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see [List Pagination].""") @cli_util.option('--display-name', help=u"""A filter to return only resources that match the given display name exactly.""") @cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted.""") @cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive.""") @cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED", "UPDATING"]), help=u"""A filter to only return resources that match the given lifecycle state. The state value is case-insensitive.""") @cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""") @cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'list[Vlan]'}) @cli_util.wrap_exceptions def list_vlans(ctx, from_json, all_pages, page_size, compartment_id, vcn_id, limit, page, display_name, sort_by, sort_order, lifecycle_state): if all_pages and limit: raise click.UsageError('If you provide the --all option you cannot provide the --limit option') kwargs = {} if limit is not None: kwargs['limit'] = limit if page is not None: kwargs['page'] = page if display_name is not None: kwargs['display_name'] = display_name if sort_by is not None: kwargs['sort_by'] = sort_by if sort_order is not None: kwargs['sort_order'] = sort_order if lifecycle_state is not None: kwargs['lifecycle_state'] = lifecycle_state kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) client = cli_util.build_client('core', 'virtual_network', ctx) if all_pages: if page_size: kwargs['limit'] = page_size result = cli_util.list_call_get_all_results( client.list_vlans, compartment_id=compartment_id, vcn_id=vcn_id, **kwargs ) elif limit is not None: result = cli_util.list_call_get_up_to_limit( client.list_vlans, limit, page_size, compartment_id=compartment_id, vcn_id=vcn_id, **kwargs ) else: result = client.list_vlans( compartment_id=compartment_id, vcn_id=vcn_id, **kwargs ) cli_util.render_response(result, ctx) @security_rule_group.command(name=cli_util.override('virtual_network.remove_network_security_group_security_rules.command_name', 'remove'), help=u"""Removes one or more security rules from the specified network security group.""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--security-rule-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The Oracle-assigned ID of each [SecurityRule] to be deleted.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @json_skeleton_utils.get_cli_json_input_option({'security-rule-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'security-rule-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.wrap_exceptions def remove_network_security_group_security_rules(ctx, from_json, network_security_group_id, security_rule_ids): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} _details = {} if security_rule_ids is not None: _details['securityRuleIds'] = cli_util.parse_json_parameter("security_rule_ids", security_rule_ids) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.remove_network_security_group_security_rules( network_security_group_id=network_security_group_id, remove_network_security_group_security_rules_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cpe_group.command(name=cli_util.override('virtual_network.update_cpe.command_name', 'update'), help=u"""Updates the specified CPE's display name or tags. Avoid entering confidential information.""") @cli_util.option('--cpe-id', required=True, help=u"""The OCID of the CPE.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--cpe-device-shape-id', help=u"""The [OCID] of the CPE device type. You can provide a value if you want to generate CPE device configuration content for IPSec connections that use this CPE. For a list of possible values, see [ListCpeDeviceShapes]. For more information about generating CPE device configuration content, see: * [GetCpeDeviceConfigContent] * [GetIpsecCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfigContent] * [GetTunnelCpeDeviceConfig]""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Cpe'}) @cli_util.wrap_exceptions def update_cpe(ctx, from_json, force, cpe_id, defined_tags, display_name, freeform_tags, cpe_device_shape_id, if_match): if isinstance(cpe_id, six.string_types) and len(cpe_id.strip()) == 0: raise click.UsageError('Parameter --cpe-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if cpe_device_shape_id is not None: _details['cpeDeviceShapeId'] = cpe_device_shape_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_cpe( cpe_id=cpe_id, update_cpe_details=_details, **kwargs ) cli_util.render_response(result, ctx) @cross_connect_group.command(name=cli_util.override('virtual_network.update_cross_connect.command_name', 'update'), help=u"""Updates the specified cross-connect.""") @cli_util.option('--cross-connect-id', required=True, help=u"""The OCID of the cross-connect.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--is-active', type=click.BOOL, help=u"""Set to true to activate the cross-connect. You activate it after the physical cabling is complete, and you've confirmed the cross-connect's light levels are good and your side of the interface is up. Activation indicates to Oracle that the physical connection is ready. Example: `true`""") @cli_util.option('--customer-reference-name', help=u"""A reference name or identifier for the physical fiber connection that this cross-connect uses.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_CUSTOMER", "PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'CrossConnect'}) @cli_util.wrap_exceptions def update_cross_connect(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, cross_connect_id, defined_tags, display_name, freeform_tags, is_active, customer_reference_name, if_match): if isinstance(cross_connect_id, six.string_types) and len(cross_connect_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if is_active is not None: _details['isActive'] = is_active if customer_reference_name is not None: _details['customerReferenceName'] = customer_reference_name client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_cross_connect( cross_connect_id=cross_connect_id, update_cross_connect_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect') and callable(getattr(client, 'get_cross_connect')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_cross_connect(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @cross_connect_group_group.command(name=cli_util.override('virtual_network.update_cross_connect_group.command_name', 'update'), help=u"""Updates the specified cross-connect group's display name. Avoid entering confidential information.""") @cli_util.option('--cross-connect-group-id', required=True, help=u"""The OCID of the cross-connect group.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--customer-reference-name', help=u"""A reference name or identifier for the physical fiber connection that this cross-connect group uses.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "PROVISIONED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'CrossConnectGroup'}) @cli_util.wrap_exceptions def update_cross_connect_group(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, cross_connect_group_id, defined_tags, display_name, customer_reference_name, freeform_tags, if_match): if isinstance(cross_connect_group_id, six.string_types) and len(cross_connect_group_id.strip()) == 0: raise click.UsageError('Parameter --cross-connect-group-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if customer_reference_name is not None: _details['customerReferenceName'] = customer_reference_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_cross_connect_group( cross_connect_group_id=cross_connect_group_id, update_cross_connect_group_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_cross_connect_group') and callable(getattr(client, 'get_cross_connect_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_cross_connect_group(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @dhcp_options_group.command(name=cli_util.override('virtual_network.update_dhcp_options.command_name', 'update'), help=u"""Updates the specified set of DHCP options. You can update the display name or the options themselves. Avoid entering confidential information. Note that the `options` object you provide replaces the entire existing set of options.""") @cli_util.option('--dhcp-id', required=True, help=u"""The OCID for the set of DHCP options.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--options', type=custom_types.CLI_COMPLEX_TYPE, help=u""" This option is a JSON list with items of type DhcpOption. For documentation on DhcpOption please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/DhcpOption.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'options': {'module': 'core', 'class': 'list[DhcpOption]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'options': {'module': 'core', 'class': 'list[DhcpOption]'}}, output_type={'module': 'core', 'class': 'DhcpOptions'}) @cli_util.wrap_exceptions def update_dhcp_options(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, dhcp_id, defined_tags, display_name, freeform_tags, options, if_match): if isinstance(dhcp_id, six.string_types) and len(dhcp_id.strip()) == 0: raise click.UsageError('Parameter --dhcp-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or options: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and options will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if options is not None: _details['options'] = cli_util.parse_json_parameter("options", options) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_dhcp_options( dhcp_id=dhcp_id, update_dhcp_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_dhcp_options') and callable(getattr(client, 'get_dhcp_options')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_dhcp_options(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_group.command(name=cli_util.override('virtual_network.update_drg.command_name', 'update'), help=u"""Updates the specified DRG's display name or tags. Avoid entering confidential information.""") @cli_util.option('--drg-id', required=True, help=u"""The OCID of the DRG.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Drg'}) @cli_util.wrap_exceptions def update_drg(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, drg_id, defined_tags, display_name, freeform_tags, if_match): if isinstance(drg_id, six.string_types) and len(drg_id.strip()) == 0: raise click.UsageError('Parameter --drg-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_drg( drg_id=drg_id, update_drg_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg') and callable(getattr(client, 'get_drg')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_drg(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @drg_attachment_group.command(name=cli_util.override('virtual_network.update_drg_attachment.command_name', 'update'), help=u"""Updates the display name for the specified `DrgAttachment`. Avoid entering confidential information.""") @cli_util.option('--drg-attachment-id', required=True, help=u"""The OCID of the DRG attachment.""") @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--route-table-id', help=u"""The OCID of the route table the DRG attachment will use. For information about why you would associate a route table with a DRG attachment, see: * [Transit Routing: Access to Multiple VCNs in Same Region] * [Transit Routing: Private Access to Oracle Services]""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ATTACHING", "ATTACHED", "DETACHING", "DETACHED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'DrgAttachment'}) @cli_util.wrap_exceptions def update_drg_attachment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, drg_attachment_id, display_name, route_table_id, if_match): if isinstance(drg_attachment_id, six.string_types) and len(drg_attachment_id.strip()) == 0: raise click.UsageError('Parameter --drg-attachment-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if display_name is not None: _details['displayName'] = display_name if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_drg_attachment( drg_attachment_id=drg_attachment_id, update_drg_attachment_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_drg_attachment') and callable(getattr(client, 'get_drg_attachment')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_drg_attachment(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @internet_gateway_group.command(name=cli_util.override('virtual_network.update_internet_gateway.command_name', 'update'), help=u"""Updates the specified internet gateway. You can disable/enable it, or change its display name or tags. Avoid entering confidential information. If the gateway is disabled, that means no traffic will flow to/from the internet even if there's a route rule that enables that traffic.""") @cli_util.option('--ig-id', required=True, help=u"""The OCID of the internet gateway.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--is-enabled', type=click.BOOL, help=u"""Whether the gateway is enabled.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'InternetGateway'}) @cli_util.wrap_exceptions def update_internet_gateway(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, ig_id, defined_tags, display_name, freeform_tags, is_enabled, if_match): if isinstance(ig_id, six.string_types) and len(ig_id.strip()) == 0: raise click.UsageError('Parameter --ig-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if is_enabled is not None: _details['isEnabled'] = is_enabled client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_internet_gateway( ig_id=ig_id, update_internet_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_internet_gateway') and callable(getattr(client, 'get_internet_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_internet_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ip_sec_connection_group.command(name=cli_util.override('virtual_network.update_ip_sec_connection.command_name', 'update'), help=u"""Updates the specified IPSec connection. To update an individual IPSec tunnel's attributes, use [UpdateIPSecConnectionTunnel].""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--cpe-local-identifier', help=u"""Your identifier for your CPE device. Can be either an IP address or a hostname (specifically, the fully qualified domain name (FQDN)). The type of identifier you provide here must correspond to the value for `cpeLocalIdentifierType`. For information about why you'd provide this value, see [If Your CPE Is Behind a NAT Device]. Example IP address: `10.0.3.3` Example hostname: `cpe.example.com`""") @cli_util.option('--cpe-local-identifier-type', type=custom_types.CliCaseInsensitiveChoice(["IP_ADDRESS", "HOSTNAME"]), help=u"""The type of identifier for your CPE device. The value you provide here must correspond to the value for `cpeLocalIdentifier`.""") @cli_util.option('--static-routes', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Static routes to the CPE. If you provide this attribute, it replaces the entire current set of static routes. A static route's CIDR must not be a multicast address or class E address. The CIDR can be either IPv4 or IPv6. Note that IPv6 addressing is currently supported only in certain regions. See [IPv6 Addresses]. Example: `10.0.1.0/24` Example: `2001:db8::/32`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'static-routes': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'static-routes': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'IPSecConnection'}) @cli_util.wrap_exceptions def update_ip_sec_connection(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, ipsc_id, defined_tags, display_name, freeform_tags, cpe_local_identifier, cpe_local_identifier_type, static_routes, if_match): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or static_routes: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and static-routes will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if cpe_local_identifier is not None: _details['cpeLocalIdentifier'] = cpe_local_identifier if cpe_local_identifier_type is not None: _details['cpeLocalIdentifierType'] = cpe_local_identifier_type if static_routes is not None: _details['staticRoutes'] = cli_util.parse_json_parameter("static_routes", static_routes) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_ip_sec_connection( ipsc_id=ipsc_id, update_ip_sec_connection_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_ip_sec_connection') and callable(getattr(client, 'get_ip_sec_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_ip_sec_connection(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ip_sec_connection_tunnel_group.command(name=cli_util.override('virtual_network.update_ip_sec_connection_tunnel.command_name', 'update'), help=u"""Updates the specified tunnel. This operation lets you change tunnel attributes such as the routing type (BGP dynamic routing or static routing). Here are some important notes: * If you change the tunnel's routing type or BGP session configuration, the tunnel will go down while it's reprovisioned. * If you want to switch the tunnel's `routing` from `STATIC` to `BGP`, make sure the tunnel's BGP session configuration attributes have been set ([bgpSessionConfig]). * If you want to switch the tunnel's `routing` from `BGP` to `STATIC`, make sure the [IPSecConnection] already has at least one valid CIDR static route.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--routing', type=custom_types.CliCaseInsensitiveChoice(["BGP", "STATIC"]), help=u"""The type of routing to use for this tunnel (either BGP dynamic routing or static routing).""") @cli_util.option('--ike-version', type=custom_types.CliCaseInsensitiveChoice(["V1", "V2"]), help=u"""Internet Key Exchange protocol version.""") @cli_util.option('--bgp-session-config', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Information for establishing a BGP session for the IPSec tunnel.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'bgp-session-config': {'module': 'core', 'class': 'UpdateIPSecTunnelBgpSessionDetails'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'bgp-session-config': {'module': 'core', 'class': 'UpdateIPSecTunnelBgpSessionDetails'}}, output_type={'module': 'core', 'class': 'IPSecConnectionTunnel'}) @cli_util.wrap_exceptions def update_ip_sec_connection_tunnel(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, ipsc_id, tunnel_id, display_name, routing, ike_version, bgp_session_config, if_match): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') if not force: if bgp_session_config: if not click.confirm("WARNING: Updates to bgp-session-config will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} if display_name is not None: _details['displayName'] = display_name if routing is not None: _details['routing'] = routing if ike_version is not None: _details['ikeVersion'] = ike_version if bgp_session_config is not None: _details['bgpSessionConfig'] = cli_util.parse_json_parameter("bgp_session_config", bgp_session_config) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_ip_sec_connection_tunnel( ipsc_id=ipsc_id, tunnel_id=tunnel_id, update_ip_sec_connection_tunnel_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_ip_sec_connection_tunnel') and callable(getattr(client, 'get_ip_sec_connection_tunnel')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_ip_sec_connection_tunnel(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @ip_sec_connection_tunnel_shared_secret_group.command(name=cli_util.override('virtual_network.update_ip_sec_connection_tunnel_shared_secret.command_name', 'update'), help=u"""Updates the shared secret (pre-shared key) for the specified tunnel. **Important:** If you change the shared secret, the tunnel will go down while it's reprovisioned.""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @cli_util.option('--shared-secret', help=u"""The shared secret (pre-shared key) to use for the tunnel. Only numbers, letters, and spaces are allowed.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @json_skeleton_utils.get_cli_json_input_option({}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'core', 'class': 'IPSecConnectionTunnelSharedSecret'}) @cli_util.wrap_exceptions def update_ip_sec_connection_tunnel_shared_secret(ctx, from_json, ipsc_id, tunnel_id, shared_secret, if_match): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if shared_secret is not None: _details['sharedSecret'] = shared_secret client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_ip_sec_connection_tunnel_shared_secret( ipsc_id=ipsc_id, tunnel_id=tunnel_id, update_ip_sec_connection_tunnel_shared_secret_details=_details, **kwargs ) cli_util.render_response(result, ctx) @ipv6_group.command(name=cli_util.override('virtual_network.update_ipv6.command_name', 'update'), help=u"""Updates the specified IPv6. You must specify the object's OCID. Use this operation if you want to: * Move an IPv6 to a different VNIC in the same subnet. * Enable/disable internet access for an IPv6. * Change the display name for an IPv6. * Update resource tags for an IPv6.""") @cli_util.option('--ipv6-id', required=True, help=u"""The [OCID] of the IPv6.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--is-internet-access-allowed', type=click.BOOL, help=u"""Whether the IPv6 can be used for internet communication. Allowed by default for an IPv6 in a public subnet. Never allowed for an IPv6 in a private subnet. If the value is `true`, the IPv6 uses its public IP address for internet communication. If you switch this from `true` to `false`, the `publicIpAddress` attribute for the IPv6 becomes null. Example: `false`""") @cli_util.option('--vnic-id', help=u"""The [OCID] of the VNIC to reassign the IPv6 to. The VNIC must be in the same subnet as the current VNIC.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Ipv6'}) @cli_util.wrap_exceptions def update_ipv6(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, ipv6_id, defined_tags, display_name, freeform_tags, is_internet_access_allowed, vnic_id, if_match): if isinstance(ipv6_id, six.string_types) and len(ipv6_id.strip()) == 0: raise click.UsageError('Parameter --ipv6-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if is_internet_access_allowed is not None: _details['isInternetAccessAllowed'] = is_internet_access_allowed if vnic_id is not None: _details['vnicId'] = vnic_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_ipv6( ipv6_id=ipv6_id, update_ipv6_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_ipv6') and callable(getattr(client, 'get_ipv6')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_ipv6(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @local_peering_gateway_group.command(name=cli_util.override('virtual_network.update_local_peering_gateway.command_name', 'update'), help=u"""Updates the specified local peering gateway (LPG).""") @cli_util.option('--local-peering-gateway-id', required=True, help=u"""The OCID of the local peering gateway.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the LPG will use. For information about why you would associate a route table with an LPG, see [Transit Routing: Access to Multiple VCNs in Same Region].""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'LocalPeeringGateway'}) @cli_util.wrap_exceptions def update_local_peering_gateway(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, local_peering_gateway_id, defined_tags, display_name, freeform_tags, route_table_id, if_match): if isinstance(local_peering_gateway_id, six.string_types) and len(local_peering_gateway_id.strip()) == 0: raise click.UsageError('Parameter --local-peering-gateway-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_local_peering_gateway( local_peering_gateway_id=local_peering_gateway_id, update_local_peering_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_local_peering_gateway') and callable(getattr(client, 'get_local_peering_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_local_peering_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @nat_gateway_group.command(name=cli_util.override('virtual_network.update_nat_gateway.command_name', 'update'), help=u"""Updates the specified NAT gateway.""") @cli_util.option('--nat-gateway-id', required=True, help=u"""The NAT gateway's [OCID].""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--block-traffic', type=click.BOOL, help=u"""Whether the NAT gateway blocks traffic through it. The default is `false`. Example: `true`""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'NatGateway'}) @cli_util.wrap_exceptions def update_nat_gateway(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, nat_gateway_id, defined_tags, display_name, freeform_tags, block_traffic, if_match): if isinstance(nat_gateway_id, six.string_types) and len(nat_gateway_id.strip()) == 0: raise click.UsageError('Parameter --nat-gateway-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if block_traffic is not None: _details['blockTraffic'] = block_traffic client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_nat_gateway( nat_gateway_id=nat_gateway_id, update_nat_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_nat_gateway') and callable(getattr(client, 'get_nat_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_nat_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @network_security_group_group.command(name=cli_util.override('virtual_network.update_network_security_group.command_name', 'update'), help=u"""Updates the specified network security group. To add or remove an existing VNIC from the group, use [UpdateVnic]. To add a VNIC to the group *when you create the VNIC*, specify the NSG's OCID during creation. For example, see the `nsgIds` attribute in [CreateVnicDetails]. To add or remove security rules from the group, use [AddNetworkSecurityGroupSecurityRules] or [RemoveNetworkSecurityGroupSecurityRules]. To edit the contents of existing security rules in the group, use [UpdateNetworkSecurityGroupSecurityRules].""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'NetworkSecurityGroup'}) @cli_util.wrap_exceptions def update_network_security_group(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, network_security_group_id, defined_tags, display_name, freeform_tags, if_match): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_network_security_group( network_security_group_id=network_security_group_id, update_network_security_group_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_network_security_group') and callable(getattr(client, 'get_network_security_group')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_network_security_group(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @security_rule_group.command(name=cli_util.override('virtual_network.update_network_security_group_security_rules.command_name', 'update-network-security-group'), help=u"""Updates one or more security rules in the specified network security group.""") @cli_util.option('--network-security-group-id', required=True, help=u"""The [OCID] of the network security group.""") @cli_util.option('--security-rules', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The NSG security rules to update. This option is a JSON list with items of type UpdateSecurityRuleDetails. For documentation on UpdateSecurityRuleDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/UpdateSecurityRuleDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @json_skeleton_utils.get_cli_json_input_option({'security-rules': {'module': 'core', 'class': 'list[UpdateSecurityRuleDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'security-rules': {'module': 'core', 'class': 'list[UpdateSecurityRuleDetails]'}}, output_type={'module': 'core', 'class': 'UpdatedNetworkSecurityGroupSecurityRules'}) @cli_util.wrap_exceptions def update_network_security_group_security_rules(ctx, from_json, network_security_group_id, security_rules): if isinstance(network_security_group_id, six.string_types) and len(network_security_group_id.strip()) == 0: raise click.UsageError('Parameter --network-security-group-id cannot be whitespace or empty string') kwargs = {} _details = {} if security_rules is not None: _details['securityRules'] = cli_util.parse_json_parameter("security_rules", security_rules) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_network_security_group_security_rules( network_security_group_id=network_security_group_id, update_network_security_group_security_rules_details=_details, **kwargs ) cli_util.render_response(result, ctx) @private_ip_group.command(name=cli_util.override('virtual_network.update_private_ip.command_name', 'update'), help=u"""Updates the specified private IP. You must specify the object's OCID. Use this operation if you want to: - Move a secondary private IP to a different VNIC in the same subnet. - Change the display name for a secondary private IP. - Change the hostname for a secondary private IP. This operation cannot be used with primary private IPs. To update the hostname for the primary IP on a VNIC, use [UpdateVnic].""") @cli_util.option('--private-ip-id', required=True, help=u"""The OCID of the private IP.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--hostname-label', help=u"""The hostname for the private IP. Used for DNS. The value is the hostname portion of the private IP's fully qualified domain name (FQDN) (for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`). Must be unique across all VNICs in the subnet and comply with [RFC 952] and [RFC 1123]. For more information, see [DNS in Your Virtual Cloud Network]. Example: `bminstance-1`""") @cli_util.option('--vnic-id', help=u"""The OCID of the VNIC to reassign the private IP to. The VNIC must be in the same subnet as the current VNIC.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'PrivateIp'}) @cli_util.wrap_exceptions def update_private_ip(ctx, from_json, force, private_ip_id, defined_tags, display_name, freeform_tags, hostname_label, vnic_id, if_match): if isinstance(private_ip_id, six.string_types) and len(private_ip_id.strip()) == 0: raise click.UsageError('Parameter --private-ip-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if hostname_label is not None: _details['hostnameLabel'] = hostname_label if vnic_id is not None: _details['vnicId'] = vnic_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_private_ip( private_ip_id=private_ip_id, update_private_ip_details=_details, **kwargs ) cli_util.render_response(result, ctx) @public_ip_group.command(name=cli_util.override('virtual_network.update_public_ip.command_name', 'update'), help=u"""Updates the specified public IP. You must specify the object's OCID. Use this operation if you want to: * Assign a reserved public IP in your pool to a private IP. * Move a reserved public IP to a different private IP. * Unassign a reserved public IP from a private IP (which returns it to your pool of reserved public IPs). * Change the display name or tags for a public IP. Assigning, moving, and unassigning a reserved public IP are asynchronous operations. Poll the public IP's `lifecycleState` to determine if the operation succeeded. **Note:** When moving a reserved public IP, the target private IP must not already have a public IP with `lifecycleState` = ASSIGNING or ASSIGNED. If it does, an error is returned. Also, the initial unassignment from the original private IP always succeeds, but the assignment to the target private IP is asynchronous and could fail silently (for example, if the target private IP is deleted or has a different public IP assigned to it in the interim). If that occurs, the public IP remains unassigned and its `lifecycleState` switches to AVAILABLE (it is not reassigned to its original private IP). You must poll the public IP's `lifecycleState` to determine if the move succeeded. Regarding ephemeral public IPs: * If you want to assign an ephemeral public IP to a primary private IP, use [CreatePublicIp]. * You can't move an ephemeral public IP to a different private IP. * If you want to unassign an ephemeral public IP from its private IP, use [DeletePublicIp], which unassigns and deletes the ephemeral public IP. **Note:** If a public IP is assigned to a secondary private IP (see [PrivateIp]), and you move that secondary private IP to another VNIC, the public IP moves with it. **Note:** There's a limit to the number of [public IPs] a VNIC or instance can have. If you try to move a reserved public IP to a VNIC or instance that has already reached its public IP limit, an error is returned. For information about the public IP limits, see [Public IP Addresses].""") @cli_util.option('--public-ip-id', required=True, help=u"""The OCID of the public IP.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--private-ip-id', help=u"""The OCID of the private IP to assign the public IP to. * If the public IP is already assigned to a different private IP, it will be unassigned and then reassigned to the specified private IP. * If you set this field to an empty string, the public IP will be unassigned from the private IP it is currently assigned to.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "ASSIGNING", "ASSIGNED", "UNASSIGNING", "UNASSIGNED", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'PublicIp'}) @cli_util.wrap_exceptions def update_public_ip(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, public_ip_id, defined_tags, display_name, freeform_tags, private_ip_id, if_match): if isinstance(public_ip_id, six.string_types) and len(public_ip_id.strip()) == 0: raise click.UsageError('Parameter --public-ip-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if private_ip_id is not None: _details['privateIpId'] = private_ip_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_public_ip( public_ip_id=public_ip_id, update_public_ip_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_public_ip') and callable(getattr(client, 'get_public_ip')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_public_ip(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @remote_peering_connection_group.command(name=cli_util.override('virtual_network.update_remote_peering_connection.command_name', 'update'), help=u"""Updates the specified remote peering connection (RPC).""") @cli_util.option('--remote-peering-connection-id', required=True, help=u"""The OCID of the remote peering connection (RPC).""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["AVAILABLE", "PROVISIONING", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'RemotePeeringConnection'}) @cli_util.wrap_exceptions def update_remote_peering_connection(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, remote_peering_connection_id, defined_tags, display_name, freeform_tags, if_match): if isinstance(remote_peering_connection_id, six.string_types) and len(remote_peering_connection_id.strip()) == 0: raise click.UsageError('Parameter --remote-peering-connection-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_remote_peering_connection( remote_peering_connection_id=remote_peering_connection_id, update_remote_peering_connection_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_remote_peering_connection') and callable(getattr(client, 'get_remote_peering_connection')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_remote_peering_connection(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @route_table_group.command(name=cli_util.override('virtual_network.update_route_table.command_name', 'update'), help=u"""Updates the specified route table's display name or route rules. Avoid entering confidential information. Note that the `routeRules` object you provide replaces the entire existing set of rules.""") @cli_util.option('--rt-id', required=True, help=u"""The OCID of the route table.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-rules', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The collection of rules used for routing destination IPs to network devices. This option is a JSON list with items of type RouteRule. For documentation on RouteRule please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/RouteRule.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'route-rules': {'module': 'core', 'class': 'list[RouteRule]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'route-rules': {'module': 'core', 'class': 'list[RouteRule]'}}, output_type={'module': 'core', 'class': 'RouteTable'}) @cli_util.wrap_exceptions def update_route_table(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, rt_id, defined_tags, display_name, freeform_tags, route_rules, if_match): if isinstance(rt_id, six.string_types) and len(rt_id.strip()) == 0: raise click.UsageError('Parameter --rt-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or route_rules: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and route-rules will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_rules is not None: _details['routeRules'] = cli_util.parse_json_parameter("route_rules", route_rules) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_route_table( rt_id=rt_id, update_route_table_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_route_table') and callable(getattr(client, 'get_route_table')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_route_table(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @security_list_group.command(name=cli_util.override('virtual_network.update_security_list.command_name', 'update'), help=u"""Updates the specified security list's display name or rules. Avoid entering confidential information. Note that the `egressSecurityRules` or `ingressSecurityRules` objects you provide replace the entire existing objects.""") @cli_util.option('--security-list-id', required=True, help=u"""The OCID of the security list.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--egress-security-rules', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Rules for allowing egress IP packets. This option is a JSON list with items of type EgressSecurityRule. For documentation on EgressSecurityRule please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/EgressSecurityRule.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--ingress-security-rules', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Rules for allowing ingress IP packets. This option is a JSON list with items of type IngressSecurityRule. For documentation on IngressSecurityRule please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/IngressSecurityRule.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'egress-security-rules': {'module': 'core', 'class': 'list[EgressSecurityRule]'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'ingress-security-rules': {'module': 'core', 'class': 'list[IngressSecurityRule]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'egress-security-rules': {'module': 'core', 'class': 'list[EgressSecurityRule]'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'ingress-security-rules': {'module': 'core', 'class': 'list[IngressSecurityRule]'}}, output_type={'module': 'core', 'class': 'SecurityList'}) @cli_util.wrap_exceptions def update_security_list(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, security_list_id, defined_tags, display_name, egress_security_rules, freeform_tags, ingress_security_rules, if_match): if isinstance(security_list_id, six.string_types) and len(security_list_id.strip()) == 0: raise click.UsageError('Parameter --security-list-id cannot be whitespace or empty string') if not force: if defined_tags or egress_security_rules or freeform_tags or ingress_security_rules: if not click.confirm("WARNING: Updates to defined-tags and egress-security-rules and freeform-tags and ingress-security-rules will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if egress_security_rules is not None: _details['egressSecurityRules'] = cli_util.parse_json_parameter("egress_security_rules", egress_security_rules) if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if ingress_security_rules is not None: _details['ingressSecurityRules'] = cli_util.parse_json_parameter("ingress_security_rules", ingress_security_rules) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_security_list( security_list_id=security_list_id, update_security_list_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_security_list') and callable(getattr(client, 'get_security_list')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_security_list(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @service_gateway_group.command(name=cli_util.override('virtual_network.update_service_gateway.command_name', 'update'), help=u"""Updates the specified service gateway. The information you provide overwrites the existing attributes of the gateway.""") @cli_util.option('--service-gateway-id', required=True, help=u"""The service gateway's [OCID].""") @cli_util.option('--block-traffic', type=click.BOOL, help=u"""Whether the service gateway blocks all traffic through it. The default is `false`. When this is `true`, traffic is not routed to any services, regardless of route rules. Example: `true`""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the service gateway will use. For information about why you would associate a route table with a service gateway, see [Transit Routing: Private Access to Oracle Services].""") @cli_util.option('--services', type=custom_types.CLI_COMPLEX_TYPE, help=u"""List of all the `Service` objects you want enabled on this service gateway. Sending an empty list means you want to disable all services. Omitting this parameter entirely keeps the existing list of services intact. You can also enable or disable a particular `Service` by using [AttachServiceId] or [DetachServiceId]. For each enabled `Service`, make sure there's a route rule with the `Service` object's `cidrBlock` as the rule's destination and the service gateway as the rule's target. See [Route Table]. This option is a JSON list with items of type ServiceIdRequestDetails. For documentation on ServiceIdRequestDetails please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/ServiceIdRequestDetails.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'services': {'module': 'core', 'class': 'list[ServiceIdRequestDetails]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'services': {'module': 'core', 'class': 'list[ServiceIdRequestDetails]'}}, output_type={'module': 'core', 'class': 'ServiceGateway'}) @cli_util.wrap_exceptions def update_service_gateway(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, service_gateway_id, block_traffic, defined_tags, display_name, freeform_tags, route_table_id, services, if_match): if isinstance(service_gateway_id, six.string_types) and len(service_gateway_id.strip()) == 0: raise click.UsageError('Parameter --service-gateway-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or services: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and services will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if block_traffic is not None: _details['blockTraffic'] = block_traffic if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_table_id is not None: _details['routeTableId'] = route_table_id if services is not None: _details['services'] = cli_util.parse_json_parameter("services", services) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_service_gateway( service_gateway_id=service_gateway_id, update_service_gateway_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_service_gateway') and callable(getattr(client, 'get_service_gateway')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_service_gateway(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @subnet_group.command(name=cli_util.override('virtual_network.update_subnet.command_name', 'update'), help=u"""Updates the specified subnet.""") @cli_util.option('--subnet-id', required=True, help=u"""The OCID of the subnet.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--dhcp-options-id', help=u"""The OCID of the set of DHCP options the subnet will use.""") @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the subnet will use.""") @cli_util.option('--security-list-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The OCIDs of the security list or lists the subnet will use. This replaces the entire current set of security lists. Remember that security lists are associated *with the subnet*, but the rules are applied to the individual VNICs in the subnet.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'security-list-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'security-list-ids': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'Subnet'}) @cli_util.wrap_exceptions def update_subnet(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, subnet_id, defined_tags, dhcp_options_id, display_name, freeform_tags, route_table_id, security_list_ids, if_match): if isinstance(subnet_id, six.string_types) and len(subnet_id.strip()) == 0: raise click.UsageError('Parameter --subnet-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or security_list_ids: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and security-list-ids will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if dhcp_options_id is not None: _details['dhcpOptionsId'] = dhcp_options_id if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if route_table_id is not None: _details['routeTableId'] = route_table_id if security_list_ids is not None: _details['securityListIds'] = cli_util.parse_json_parameter("security_list_ids", security_list_ids) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_subnet( subnet_id=subnet_id, update_subnet_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_subnet') and callable(getattr(client, 'get_subnet')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_subnet(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @tunnel_cpe_device_config_group.command(name=cli_util.override('virtual_network.update_tunnel_cpe_device_config.command_name', 'update'), help=u"""Creates or updates the set of CPE configuration answers for the specified tunnel. The answers correlate to the questions that are specific to the CPE device type (see the `parameters` attribute of [CpeDeviceShapeDetail]).""") @cli_util.option('--ipsc-id', required=True, help=u"""The OCID of the IPSec connection.""") @cli_util.option('--tunnel-id', required=True, help=u"""The [OCID] of the tunnel.""") @cli_util.option('--tunnel-cpe-device-config', type=custom_types.CLI_COMPLEX_TYPE, help=u"""The set of configuration answers for a CPE device. This option is a JSON list with items of type CpeDeviceConfigAnswer. For documentation on CpeDeviceConfigAnswer please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/CpeDeviceConfigAnswer.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @json_skeleton_utils.get_cli_json_input_option({'tunnel-cpe-device-config': {'module': 'core', 'class': 'list[CpeDeviceConfigAnswer]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'tunnel-cpe-device-config': {'module': 'core', 'class': 'list[CpeDeviceConfigAnswer]'}}, output_type={'module': 'core', 'class': 'TunnelCpeDeviceConfig'}) @cli_util.wrap_exceptions def update_tunnel_cpe_device_config(ctx, from_json, force, ipsc_id, tunnel_id, tunnel_cpe_device_config, if_match): if isinstance(ipsc_id, six.string_types) and len(ipsc_id.strip()) == 0: raise click.UsageError('Parameter --ipsc-id cannot be whitespace or empty string') if isinstance(tunnel_id, six.string_types) and len(tunnel_id.strip()) == 0: raise click.UsageError('Parameter --tunnel-id cannot be whitespace or empty string') if not force: if tunnel_cpe_device_config: if not click.confirm("WARNING: Updates to tunnel-cpe-device-config will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} if tunnel_cpe_device_config is not None: _details['tunnelCpeDeviceConfig'] = cli_util.parse_json_parameter("tunnel_cpe_device_config", tunnel_cpe_device_config) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_tunnel_cpe_device_config( ipsc_id=ipsc_id, tunnel_id=tunnel_id, update_tunnel_cpe_device_config_details=_details, **kwargs ) cli_util.render_response(result, ctx) @vcn_group.command(name=cli_util.override('virtual_network.update_vcn.command_name', 'update'), help=u"""Updates the specified VCN.""") @cli_util.option('--vcn-id', required=True, help=u"""The [OCID] of the VCN.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'Vcn'}) @cli_util.wrap_exceptions def update_vcn(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, vcn_id, defined_tags, display_name, freeform_tags, if_match): if isinstance(vcn_id, six.string_types) and len(vcn_id.strip()) == 0: raise click.UsageError('Parameter --vcn-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_vcn( vcn_id=vcn_id, update_vcn_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_vcn') and callable(getattr(client, 'get_vcn')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_vcn(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @virtual_circuit_group.command(name=cli_util.override('virtual_network.update_virtual_circuit.command_name', 'update'), help=u"""Updates the specified virtual circuit. This can be called by either the customer who owns the virtual circuit, or the provider (when provisioning or de-provisioning the virtual circuit from their end). The documentation for [UpdateVirtualCircuitDetails] indicates who can update each property of the virtual circuit. **Important:** If the virtual circuit is working and in the PROVISIONED state, updating any of the network-related properties (such as the DRG being used, the BGP ASN, and so on) will cause the virtual circuit's state to switch to PROVISIONING and the related BGP session to go down. After Oracle re-provisions the virtual circuit, its state will return to PROVISIONED. Make sure you confirm that the associated BGP session is back up. For more information about the various states and how to test connectivity, see [FastConnect Overview]. To change the list of public IP prefixes for a public virtual circuit, use [BulkAddVirtualCircuitPublicPrefixes] and [BulkDeleteVirtualCircuitPublicPrefixes]. Updating the list of prefixes does NOT cause the BGP session to go down. However, Oracle must verify the customer's ownership of each added prefix before traffic for that prefix will flow across the virtual circuit.""") @cli_util.option('--virtual-circuit-id', required=True, help=u"""The OCID of the virtual circuit.""") @cli_util.option('--bandwidth-shape-name', help=u"""The provisioned data rate of the connection. To get a list of the available bandwidth levels (that is, shapes), see [ListFastConnectProviderVirtualCircuitBandwidthShapes]. To be updated only by the customer who owns the virtual circuit.""") @cli_util.option('--cross-connect-mappings', type=custom_types.CLI_COMPLEX_TYPE, help=u"""An array of mappings, each containing properties for a cross-connect or cross-connect group associated with this virtual circuit. The customer and provider can update different properties in the mapping depending on the situation. See the description of the [CrossConnectMapping]. This option is a JSON list with items of type CrossConnectMapping. For documentation on CrossConnectMapping please see our API reference: https://docs.cloud.oracle.com/api/#/en/iaas/20160918/datatypes/CrossConnectMapping.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--customer-bgp-asn', type=click.INT, help=u"""Deprecated. Instead use `customerAsn`. If you specify values for both, the request will be rejected.""") @cli_util.option('--customer-asn', type=click.INT, help=u"""The BGP ASN of the network at the other end of the BGP session from Oracle. If the BGP session is from the customer's edge router to Oracle, the required value is the customer's ASN, and it can be updated only by the customer. If the BGP session is from the provider's edge router to Oracle, the required value is the provider's ASN, and it can be updated only by the provider. Can be a 2-byte or 4-byte ASN. Uses \"asplain\" format.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique. Avoid entering confidential information. To be updated only by the customer who owns the virtual circuit.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--gateway-id', help=u"""The OCID of the [dynamic routing gateway (DRG)] that this private virtual circuit uses. To be updated only by the customer who owns the virtual circuit.""") @cli_util.option('--provider-state', type=custom_types.CliCaseInsensitiveChoice(["ACTIVE", "INACTIVE"]), help=u"""The provider's state in relation to this virtual circuit. Relevant only if the customer is using FastConnect via a provider. ACTIVE means the provider has provisioned the virtual circuit from their end. INACTIVE means the provider has not yet provisioned the virtual circuit, or has de-provisioned it. To be updated only by the provider.""") @cli_util.option('--provider-service-key-name', help=u"""The service key name offered by the provider (if the customer is connecting via a provider).""") @cli_util.option('--reference-comment', help=u"""Provider-supplied reference information about this virtual circuit. Relevant only if the customer is using FastConnect via a provider. To be updated only by the provider.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PENDING_PROVIDER", "VERIFYING", "PROVISIONING", "PROVISIONED", "FAILED", "INACTIVE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'cross-connect-mappings': {'module': 'core', 'class': 'list[CrossConnectMapping]'}, 'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'cross-connect-mappings': {'module': 'core', 'class': 'list[CrossConnectMapping]'}, 'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}}, output_type={'module': 'core', 'class': 'VirtualCircuit'}) @cli_util.wrap_exceptions def update_virtual_circuit(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, virtual_circuit_id, bandwidth_shape_name, cross_connect_mappings, customer_bgp_asn, customer_asn, defined_tags, display_name, freeform_tags, gateway_id, provider_state, provider_service_key_name, reference_comment, if_match): if isinstance(virtual_circuit_id, six.string_types) and len(virtual_circuit_id.strip()) == 0: raise click.UsageError('Parameter --virtual-circuit-id cannot be whitespace or empty string') if not force: if cross_connect_mappings or defined_tags or freeform_tags: if not click.confirm("WARNING: Updates to cross-connect-mappings and defined-tags and freeform-tags will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if bandwidth_shape_name is not None: _details['bandwidthShapeName'] = bandwidth_shape_name if cross_connect_mappings is not None: _details['crossConnectMappings'] = cli_util.parse_json_parameter("cross_connect_mappings", cross_connect_mappings) if customer_bgp_asn is not None: _details['customerBgpAsn'] = customer_bgp_asn if customer_asn is not None: _details['customerAsn'] = customer_asn if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if gateway_id is not None: _details['gatewayId'] = gateway_id if provider_state is not None: _details['providerState'] = provider_state if provider_service_key_name is not None: _details['providerServiceKeyName'] = provider_service_key_name if reference_comment is not None: _details['referenceComment'] = reference_comment client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_virtual_circuit( virtual_circuit_id=virtual_circuit_id, update_virtual_circuit_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_virtual_circuit') and callable(getattr(client, 'get_virtual_circuit')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_virtual_circuit(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vlan_group.command(name=cli_util.override('virtual_network.update_vlan.command_name', 'update'), help=u"""Updates the specified VLAN. This could result in changes to all the VNICs in the VLAN, which can take time. During that transition period, the VLAN will be in the UPDATING state.""") @cli_util.option('--vlan-id', required=True, help=u"""The [OCID] of the VLAN.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A descriptive name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--nsg-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""A list of the OCIDs of the network security groups (NSGs) to use with this VLAN. All VNICs in the VLAN will belong to these NSGs. For more information about NSGs, see [NetworkSecurityGroup].""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--route-table-id', help=u"""The OCID of the route table the VLAN will use.""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED", "UPDATING"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'Vlan'}) @cli_util.wrap_exceptions def update_vlan(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, vlan_id, defined_tags, display_name, freeform_tags, nsg_ids, route_table_id, if_match): if isinstance(vlan_id, six.string_types) and len(vlan_id.strip()) == 0: raise click.UsageError('Parameter --vlan-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or nsg_ids: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and nsg-ids will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id']) _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if nsg_ids is not None: _details['nsgIds'] = cli_util.parse_json_parameter("nsg_ids", nsg_ids) if route_table_id is not None: _details['routeTableId'] = route_table_id client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_vlan( vlan_id=vlan_id, update_vlan_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_vlan') and callable(getattr(client, 'get_vlan')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_vlan(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx) @vnic_group.command(name=cli_util.override('virtual_network.update_vnic.command_name', 'update'), help=u"""Updates the specified VNIC.""") @cli_util.option('--vnic-id', required=True, help=u"""The OCID of the VNIC.""") @cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--display-name', help=u"""A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information.""") @cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--hostname-label', help=u"""The hostname for the VNIC's primary private IP. Used for DNS. The value is the hostname portion of the primary private IP's fully qualified domain name (FQDN) (for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`). Must be unique across all VNICs in the subnet and comply with [RFC 952] and [RFC 1123]. The value appears in the [Vnic] object and also the [PrivateIp] object returned by [ListPrivateIps] and [GetPrivateIp]. For more information, see [DNS in Your Virtual Cloud Network].""") @cli_util.option('--nsg-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""A list of the OCIDs of the network security groups (NSGs) to add the VNIC to. Setting this as an empty array removes the VNIC from all network security groups. If the VNIC belongs to a VLAN as part of the Oracle Cloud VMware Solution (instead of belonging to a subnet), the value of the `nsgIds` attribute is ignored. Instead, the VNIC belongs to the NSGs that are associated with the VLAN itself. See [Vlan]. For more information about NSGs, see [NetworkSecurityGroup].""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP) @cli_util.option('--skip-source-dest-check', type=click.BOOL, help=u"""Whether the source/destination check is disabled on the VNIC. Defaults to `false`, which means the check is performed. For information about why you would skip the source/destination check, see [Using a Private IP as a Route Target]. If the VNIC belongs to a VLAN as part of the Oracle Cloud VMware Solution (instead of belonging to a subnet), the value of the `skipSourceDestCheck` attribute is ignored. This is because the source/destination check is always disabled for VNICs in a VLAN. Example: `true`""") @cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""") @cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True) @cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["PROVISIONING", "AVAILABLE", "TERMINATING", "TERMINATED"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state SUCCEEDED --wait-for-state FAILED would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""") @cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""") @cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource to see if it has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""") @json_skeleton_utils.get_cli_json_input_option({'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}) @cli_util.help_option @click.pass_context @json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'defined-tags': {'module': 'core', 'class': 'dict(str, dict(str, object))'}, 'freeform-tags': {'module': 'core', 'class': 'dict(str, string)'}, 'nsg-ids': {'module': 'core', 'class': 'list[string]'}}, output_type={'module': 'core', 'class': 'Vnic'}) @cli_util.wrap_exceptions def update_vnic(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, vnic_id, defined_tags, display_name, freeform_tags, hostname_label, nsg_ids, skip_source_dest_check, if_match): if isinstance(vnic_id, six.string_types) and len(vnic_id.strip()) == 0: raise click.UsageError('Parameter --vnic-id cannot be whitespace or empty string') if not force: if defined_tags or freeform_tags or nsg_ids: if not click.confirm("WARNING: Updates to defined-tags and freeform-tags and nsg-ids will replace any existing values. Are you sure you want to continue?"): ctx.abort() kwargs = {} if if_match is not None: kwargs['if_match'] = if_match _details = {} if defined_tags is not None: _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags) if display_name is not None: _details['displayName'] = display_name if freeform_tags is not None: _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags) if hostname_label is not None: _details['hostnameLabel'] = hostname_label if nsg_ids is not None: _details['nsgIds'] = cli_util.parse_json_parameter("nsg_ids", nsg_ids) if skip_source_dest_check is not None: _details['skipSourceDestCheck'] = skip_source_dest_check client = cli_util.build_client('core', 'virtual_network', ctx) result = client.update_vnic( vnic_id=vnic_id, update_vnic_details=_details, **kwargs ) if wait_for_state: if hasattr(client, 'get_vnic') and callable(getattr(client, 'get_vnic')): try: wait_period_kwargs = {} if max_wait_seconds is not None: wait_period_kwargs['max_wait_seconds'] = max_wait_seconds if wait_interval_seconds is not None: wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr) result = oci.wait_until(client, client.get_vnic(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs) except oci.exceptions.MaximumWaitTimeExceeded as e: # If we fail, we should show an error, but we should still provide the information to the customer click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) sys.exit(2) except Exception: click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr) cli_util.render_response(result, ctx) raise else: click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr) cli_util.render_response(result, ctx)
[ "bytesbay@icloud.com" ]
bytesbay@icloud.com
b8ae4ce0e3842a9e15401dfc67037d1b0db337d8
8afb5afd38548c631f6f9536846039ef6cb297b9
/_REPO/MICROSOFT/computervision-recipes/utils_cv/similarity/metrics.py
1b26bc69509bdef19d2614469057bd44399d7035
[ "BSD-3-Clause", "LGPL-2.1-or-later", "Apache-2.0", "MIT" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
Python
false
false
4,948
py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import Dict, List import numpy as np import scipy from fastai.vision import LabelList from .references.evaluate import evaluate_with_query_set def vector_distance( vec1: np.ndarray, vec2: np.ndarray, method: str = "l2", l2_normalize: bool = True ) -> float: """Computes the distance between 2 vectors Inspired by https://github.com/Azure/ImageSimilarityUsingCntk= Args: vec1: First vector between which the distance will be computed vec2: Second vector method: Type of distance to be computed, e.g. "l1" or "l2" l2_normalize: Flag indicating whether the vectors should be normalized to be of unit length before the distance between them is computed Returns: Distance between the 2 input vectors """ # Pre-processing if l2_normalize: vec1 = vec1 / np.linalg.norm(vec1, 2) vec2 = vec2 / np.linalg.norm(vec2, 2) # Distance computation vecDiff = vec1 - vec2 method = method.lower() if method == "l1": dist = sum(abs(vecDiff)) elif method == "l2": dist = np.linalg.norm(vecDiff, 2) elif method == "normalizedl2": a = vec1 / np.linalg.norm(vec1, 2) b = vec2 / np.linalg.norm(vec2, 2) dist = np.linalg.norm(a - b, 2) elif method == "cosine": dist = scipy.spatial.distance.cosine(vec1, vec2) elif method == "correlation": dist = scipy.spatial.distance.correlation(vec1, vec2) elif method == "chisquared": dist = scipy.chiSquared(vec1, vec2) elif method == "normalizedchisquared": a = vec1 / sum(vec1) b = vec2 / sum(vec2) dist = scipy.chiSquared(a, b) elif method == "hamming": dist = scipy.spatial.distance.hamming(vec1 > 0, vec2 > 0) else: raise Exception("Distance method unknown: " + method) return dist def compute_distances( query_feature: np.array, feature_dict: dict, method: str = "l2" ) -> List: """Computes the distance between query_image and all the images present in feature_dict (query_image included) Args: query_feature: Features for the query image feature_dict: Dictionary of features, where key = image path and value = array of floats method: distance method Returns: List of (image path, distance) pairs. """ distances = [] for im_path, feature in feature_dict.items(): distance = vector_distance(query_feature, feature, method) distances.append((im_path, distance)) return distances def positive_image_ranks(comparative_sets) -> List[int]: """Computes the rank of the positive example for each comparative set Args: comparative_sets: List of comparative sets Returns: List of integer ranks """ return [cs.pos_rank() for cs in comparative_sets] def recall_at_k(ranks: List[int], k: int) -> float: """Computes the percentage of comparative sets where the positive image has a rank of <= k Args: ranks: List of ranks of the positive example in each comparative set k: Threshold below which the rank should be counted as true positive Returns: Percentage of comparative sets with rank <= k """ below_threshold = [x for x in ranks if x <= k] percent_in_top_k = round(100.0 * len(below_threshold) / len(ranks), 1) return percent_in_top_k def evaluate( data: LabelList, features: Dict[str, np.array], use_rerank=False, rerank_k1=20, rerank_k2=6, rerank_lambda=0.3, ): """ Computes rank@1 through rank@10 accuracy as well as mAP, optionally with re-ranking post-processor to improve accuracy (see the re-ranking implementation for more info). Args: data: Fastai's image labellist features: Dictionary of DNN features for each image use_rerank: use re-ranking rerank_k1, rerank_k2, rerank_lambda: re-ranking parameters Returns: rank_accs: accuracy at rank1 through rank10 mAP: average precision """ labels = np.array([data.y[i].obj for i in range(len(data.y))]) features = np.array([features[str(s)] for s in data.items]) # Assign each image into its own group. This serves as id during evaluation to # ensure a query image is not compared to itself during rank computation. # For the market-1501 dataset, the group ids can be used to ensure that a query # can not match to an image taken from the same camera. groups = np.array(range(len(labels))) assert len(labels) == len(groups) == features.shape[0] # Run evaluation rank_accs, mAP = evaluate_with_query_set( labels, groups, features, labels, groups, features, use_rerank, rerank_k1, rerank_k2, rerank_lambda, ) return rank_accs, mAP
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
f43357dcc279e787e5cae1f9679891f779cb1a8d
4047b22c2de7f6a898e2a3d849afedfc86e8b684
/people/migrations/0002_auto__add_relation.py
28c3a3d6021ba7c043808741c5058326e170b110
[]
no_license
stanremix/sx2
bfe1a9d55164a8cb867a44a2963c8b01334d9c46
0349ade7b820ce5852e61cbc11b5e3fb486dc286
refs/heads/master
2016-09-11T03:28:21.831141
2014-11-27T17:17:03
2014-11-27T17:17:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,589
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): # Adding model 'Relation' db.create_table('people_relation', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('is_valid', self.gf('django.db.models.fields.BooleanField')(default=True)), ('tag', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), ('create_time', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('fuser', self.gf('django.db.models.fields.related.ForeignKey')(related_name='fuser', to=orm['auth.User'])), ('tuser', self.gf('django.db.models.fields.related.ForeignKey')(related_name='tuser', to=orm['auth.User'])), ('is_like', self.gf('django.db.models.fields.BooleanField')(default=False)), ('is_mutal', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('people', ['Relation']) def backwards(self, orm): # Deleting model 'Relation' db.delete_table('people_relation') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.auth': { 'Meta': {'object_name': 'Auth'}, 'access_token': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'auth_from': ('django.db.models.fields.CharField', [], {'default': "'sina'", 'max_length': '100'}), 'auth_id': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'create_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'expire': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'tag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'people.feedback': { 'Meta': {'object_name': 'Feedback'}, 'create_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'feedback': ('django.db.models.fields.CharField', [], {'max_length': '1000'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'tag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'update_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'people.profile': { 'Meta': {'object_name': 'Profile'}, 'age': ('django.db.models.fields.IntegerField', [], {'default': '18', 'null': 'True', 'blank': 'True'}), 'avatar': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'birthday': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'create_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'desc': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'deviceid': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'gender': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_guest': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'login_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'profile_category': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'push_setting': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '20', 'null': 'True', 'blank': 'True'}), 'tag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'wx': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'zodiac': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'people.relation': { 'Meta': {'object_name': 'Relation'}, 'create_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'fuser': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'fuser'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_like': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_mutal': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'tag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'tuser': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tuser'", 'to': "orm['auth.User']"}) }, 'people.user_log': { 'Meta': {'object_name': 'User_Log'}, 'action': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'create_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'lat': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'lon': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'tag': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) } } complete_apps = ['people']
[ "stan.util@aliyun.com" ]
stan.util@aliyun.com
1145ac9e199d171b21e06440d94b3a093b820d55
6642ba118a7279cc0ddd7ae02a6f91aa2f9b346c
/gl.py
00288c88e18b10a20cdb92ed5a2440b2c2b6e439
[]
no_license
ssxday/Python35
95299fefca9587f724d21a0b357c064c341cf869
f18b47a7d8d2e79dc896430484059f8878a2e7b8
refs/heads/master
2021-01-12T03:59:13.579909
2017-04-10T05:37:09
2017-04-10T05:37:09
77,452,273
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
name = "Foo module" def foo_fun(): print('函数foo_fun:') print('变量name:', name) print('打包成了可执行文件exe')
[ "AUG@AuggiedeMacBook-Pro.local" ]
AUG@AuggiedeMacBook-Pro.local
23d42fb2b7aa7f274dc0d918d97e796fe1023c05
6e2a9fa80dd87e36b73e0e32c4212d98a382dc41
/SOURCE/level3_monster.py
093f5d0eb3d673f2162e424765a89350b8da0b18
[]
no_license
binhle3920/search-project-ai
b1f86406c9bfd338d019c9d3741f69539dba4945
90d32a42f8f58108c90f771b79a13c12add844ea
refs/heads/master
2022-12-01T23:31:54.772144
2020-08-15T09:56:43
2020-08-15T09:56:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,590
py
import random monster_init_pos = [] monster_cur_pos = [] monster_possible_pos = [] monster_over_food = [] def get_monster_init_pos(maze, size): for i in range(size[0]): for j in range(size[1]): if maze[i][j] == 3: monster_init_pos.append((i, j)) monster_over_food.append(0) def monster_possible_move(maze, size): a_monster_move = [] for monster in monster_init_pos: for i in range(-1, 2): for j in range(-1, 2): if monster[0] + i >= 0 and monster[0] + i < size[0] and monster[1] + j >= 0 and monster[1] + j < size[1]: if maze[monster[0] + i][monster[1] + j] == 0 or maze[monster[0] + i][monster[1] + j] == 2: a_monster_move.append((monster[0] + i, monster[1] + j)) monster_possible_pos.append(a_monster_move) a_monster_move = [] def possible_choice(maze, monster_number, direction): if direction == "up": pos = (monster_cur_pos[monster_number][0] + 1, monster_cur_pos[monster_number][1]) if pos in monster_possible_pos[monster_number] and maze[pos[0]][pos[1]] != 3: return pos else: return "up" elif direction == "down": pos = (monster_cur_pos[monster_number][0] - 1, monster_cur_pos[monster_number][1]) if pos in monster_possible_pos[monster_number] and maze[pos[0]][pos[1]] != 3: return pos else: return "down" elif direction == "left": pos = (monster_cur_pos[monster_number][0], monster_cur_pos[monster_number][1] - 1) if pos in monster_possible_pos[monster_number] and maze[pos[0]][pos[1]] != 3: return pos else: return "left" elif direction == "right": pos = (monster_cur_pos[monster_number][0], monster_cur_pos[monster_number][1] + 1) if pos in monster_possible_pos[monster_number] and maze[pos[0]][pos[1]] != 3: return pos else: return "right" monster_cur_pos = monster_init_pos def init_monster(maze, size): get_monster_init_pos(maze, size) monster_possible_move(maze, size) monster_path = [] for i in range(len(monster_init_pos)): monster_path.append([monster_init_pos[i]]) return monster_path def monster_move(maze, monster_path): for monster_number in range(len(monster_init_pos)): available_direction = ["up", "down", "left", "right"] while len(available_direction) > 0: direction = random.choice(available_direction) pos = possible_choice(maze, monster_number, direction) if isinstance(pos, tuple): monster_path[monster_number].append(pos) if monster_over_food[monster_number] == 1: maze[monster_cur_pos[monster_number][0]][monster_cur_pos[monster_number][1]] = 2 else: maze[monster_cur_pos[monster_number][0]][monster_cur_pos[monster_number][1]] = 0 if maze[pos[0]][pos[1]] == 2: monster_over_food[monster_number] = 1 else: monster_over_food[monster_number] = 0 maze[pos[0]][pos[1]] = 3 monster_cur_pos[monster_number] = pos break else: available_direction.pop(available_direction.index(pos)) if len(available_direction) == 0: monster_path[monster_number].append(monster_cur_pos[monster_number]) return monster_path, maze
[ "lethanhbinh3920@gmail.com" ]
lethanhbinh3920@gmail.com
177b8bcaa8463b27e3fa42b9e8c58aa040aee2c0
1f627bbd4c864b5671bf0b38bfb1d633b25d0522
/Single-server-multiple-clients/singleserver_multipleclient_client2.py
a7b25e0ea99d6a89ccd56f10d804acb081d83bf8
[]
no_license
srishilesh/15CSE312-Computer-Networks
a6361eb34039e694da8f5867d87c3add0352898e
0fe1ddd33bee65af4df60642c2ed56d0b360653e
refs/heads/master
2023-02-23T03:34:59.282957
2021-01-24T17:17:59
2021-01-24T17:17:59
221,458,642
1
0
null
null
null
null
UTF-8
Python
false
false
342
py
import socket s = socket.socket() s.connect(('127.0.0.1',12345)) inp = input(" -> ") while True: s.send(str(inp).encode()) data = s.recv(1024).decode() print("From Server: ",data) inp = input(" -> ") ans = input('\nDo you want to continue(y/n) :') if ans == 'y': continue else: break s.close()
[ "noreply@github.com" ]
srishilesh.noreply@github.com
3c0a4b1278a8cadab1ff0e8ddbbe6e43a3f18e60
35a0b95f5a13f2cf3ae92d554a65fac00262b5db
/userbot/plugins/botfeatures.py
7ccd96643d904e4ecf47b0f31c297cd599618fac
[ "MIT" ]
permissive
chettiyar/SPARKZZZ
8463237480478c1f990edd5b41fa85912afec41d
b9ed22887210c977e3750c0511e8a290c2042b3f
refs/heads/master
2022-12-28T17:42:43.188297
2020-10-16T16:07:56
2020-10-16T16:07:56
298,184,122
1
0
MIT
2020-09-24T06:06:36
2020-09-24T06:06:35
null
UTF-8
Python
false
false
8,250
py
import datetime from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from telethon.tl.functions.account import UpdateNotifySettingsRequest from userbot.utils import admin_cmd import asyncio @borg.on(admin_cmd(pattern=("sang ?(.*)"))) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```reply to text message```") return chat = "@SangMataInfo_bot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=461843263)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("The user have enabled privacy settings you cant get name history") else: await event.edit(f"{response.message.message}") @borg.on(admin_cmd(pattern=("fakemail ?(.*)"))) async def _(event): if event.fwd_from: return chat = "@fakemailbot" command = "/generate" await event.edit("```Fakemail Creating, wait```") async with borg.conversation(chat) as conv: try: m = await event.client.send_message("@fakemailbot","/generate") await asyncio.sleep(5) k = await event.client.get_messages(entity="@fakemailbot", limit=1, reverse=False) mail = k[0].text # print(k[0].text) except YouBlockedUserError: await event.reply("```Please unblock @fakemailbot and try again```") return await event.edit(mail) @borg.on(admin_cmd(pattern=("mailid ?(.*)"))) async def _(event): if event.fwd_from: return chat = "@fakemailbot" command = "/id" await event.edit("```Fakemail list getting```") async with borg.conversation(chat) as conv: try: m = await event.client.send_message("@fakemailbot","/id") await asyncio.sleep(5) k = await event.client.get_messages(entity="@fakemailbot", limit=1, reverse=False) mail = k[0].text # print(k[0].text) except YouBlockedUserError: await event.reply("```Please unblock @fakemailbot and try again```") return await event.edit(mail) @borg.on(admin_cmd(pattern=("ub ?(.*)"))) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```reply to text message```") return chat = "@uploadbot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=97342984)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @uploadbot and try again```") return if response.text.startswith("Hi!,"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await event.edit(f"{response.message.message}") @borg.on(admin_cmd(pattern=("gid ?(.*)"))) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```reply to text message```") return chat = "@getidsbot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=186675376)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```you blocked bot```") return if response.text.startswith("Hello,"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await event.edit(f"{response.message.message}") @borg.on(admin_cmd(pattern="purl ?(.*)")) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.reply("**Reply to any document.**") return reply_message = await event.get_reply_message() chat = "@FiletolinkTGbot" sender = reply_message.sender await event.edit("**Making public url...**") async with event.client.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=1011636686)) await event.client.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await a.edit("```Please unblock me (@FiletolinkTGbot) u Nigga```") return await event.delete() await event.client.send_message(event.chat_id, response.message, reply_to=reply_message) @borg.on(admin_cmd(pattern="gitdl ?(.*)")) @borg.on(sudo_cmd(pattern="gitdl ?(.*)", allow_sudo=True)) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.reply("**Reply to a github repo url.**") return reply_message = await event.get_reply_message() chat = "@gitdownloadbot" sender = reply_message.sender await event.edit("**Downloading the repository...**") async with event.client.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=1282593576)) await event.client.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await a.edit("```Please unblock me (@gitdownloadbot) u Nigga```") return await event.delete() x = await event.client.send_message(event.chat_id, response.message, reply_to=reply_message) await x.edit("Downloaded by [SPARKZZZ](t.me/), via @gitdownloadbot") @borg.on(admin_cmd(pattern="reader ?(.*)")) async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("**Reply to a URL.**") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("**Reply to a url message.**") return chat = "@chotamreaderbot" sender = reply_message.sender await event.edit("**Making instant view...**") async with event.client.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=272572121)) await event.client.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await a.edit("```Please unblock me (@chotamreaderbot) u Nigga```") return await event.delete() await event.client.send_message(event.chat_id, response.message, reply_to=reply_message)
[ "noreply@github.com" ]
chettiyar.noreply@github.com
d047998792a91cc1538c9bc48335233c601cc52c
1afa1b1929d1cd463cd9970174dd58ce2ca6eb1e
/configs/apcnet/apcnet_r50-d8_512x512_80k_ade20k.py
c839763faf490130069f1bfabab6589049462d09
[ "Apache-2.0" ]
permissive
CAU-HE/CMCDNet
2328594bf4b883384c691099c72e119b65909121
31e660f81f3b625916a4c4d60cd606dcc8717f81
refs/heads/main
2023-08-08T17:21:57.199728
2023-07-28T07:34:40
2023-07-28T07:34:40
589,927,845
12
1
null
null
null
null
UTF-8
Python
false
false
257
py
_base_ = [ '../_base_/models/apcnet_r50-d8.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] model = dict( decode_head=dict(num_classes=150), auxiliary_head=dict(num_classes=150))
[ "flyhxn@qq.com" ]
flyhxn@qq.com
2f7e86acbc73eceee702fff5496a091e73fa02fb
321b4ed83b6874eeb512027eaa0b17b0daf3c289
/208/208.implement-trie-prefix-tree.214862898.Runtime-Error.leetcode.py
0cd64973ee98610f7a71ed6cc5cebf20600aa614
[]
no_license
huangyingw/submissions
7a610613bdb03f1223cdec5f6ccc4391149ca618
bfac1238ecef8b03e54842b852f6fec111abedfa
refs/heads/master
2023-07-25T09:56:46.814504
2023-07-16T07:38:36
2023-07-16T07:38:36
143,352,065
0
1
null
null
null
null
UTF-8
Python
false
false
1,134
py
class Trie(object): class TrieNode(object): def __init__(self, content=' '): self.content = content self.isWord = False self.nexts = {} def __init__(self): root = self.TrieNode() def insert(self, word): if search(word): return current = root for i in range(0, len(word)): c = word[i] node = current.nexts.get(c, None) if not node: current.nexts[c] = self.TrieNode(c) node = current.nexts.get(c, None) current = node current.isWord = True def search(self, word): current = root for i in range(0, len(word)): node = current.nexts.get(word[i], None) if not node: return False current = node return current.isWord def startsWith(self, prefix): current = root for i in range(0, len(prefix)): node = current.nexts.get(prefix[i], None) if not node: return False current = node return True
[ "huangyingw@gmail.com" ]
huangyingw@gmail.com
a1ea1f10ef6de52a2d3e67977698cd2c1c6ca732
a81d6ccc34b1e756c95c5206be708290a274ff08
/monkeytyping.py
7e6c5ec68816f2e3118140e11bc81439b05b16d4
[]
no_license
lizhigeng66/checkio
535c28982a258a58a60aa366271875342d72cc0f
a451c2ca9bae64470df941513295442463b6b00f
refs/heads/master
2020-03-16T21:00:59.897032
2018-07-04T15:13:29
2018-07-04T15:13:29
132,981,258
0
0
null
null
null
null
UTF-8
Python
false
false
790
py
def count_words(str1, wordlist): count = 0 wordlist1 = list(wordlist) for i in wordlist1: if i in str1.lower(): count = count+1 return count if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert count_words("How aresjfhdskfhskd you?", { "how", "are", "you", "hello"}) == 3, "Example" assert count_words("Bananas, give me bananas!!!", { "banana", "bananas"}) == 2, "BANANAS!" assert count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.", {"sum", "hamlet", "infinity", "anything"}) == 1, "Weird text" print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
[ "lizhigeng66@gmail.com" ]
lizhigeng66@gmail.com
c7721ff1b8b85eeccb8763337f789f7c54a91ec3
0aa915b246ad65a1abc9b863537b0dae4bb55d55
/api/views.py
696d6c68cd059dc53378b4939535df81a7ceca8b
[ "MIT" ]
permissive
MohitS10/HelloWorld
63786afa88c29ce89359c89f2796fbbcf74ce574
b2deff72b8e2b3d30f20feb3d1f12782e63dc7f5
refs/heads/master
2020-12-26T15:48:47.109084
2016-08-26T16:20:37
2016-08-26T16:20:37
66,651,549
0
0
null
2016-08-26T13:53:44
2016-08-26T13:53:44
null
UTF-8
Python
false
false
1,133
py
from django.shortcuts import render from .models import Project,Member,Contact,Technology,Contributor from .serializers import MemberSerializer,ProjectSerializer from django.http import HttpResponse,Http404 import json # API wale endpoints def projects(request): if request.method=="GET": projects = ProjectSerializer(instance=Project.objects.all(),many=True) return HttpResponse(json.dumps(projects.data)) else: return HttpResponseForbidden('allowed only via GET') def project_details(request,project_slug): if request.method=="GET": try: project=Project.objects.get(slug=project_slug) project_serialized = ProjectSerializer(instance=project) return HttpResponse(json.dumps(project_serialized.data)) except Project.DoesNotExist: return HttpResponse(json.dumps({'error':'No project matches the given query'})); else: return HttpResponseForbidden('allowed only via GET') def members(request): if request.method=="GET": members = MemberSerializer(instance = Member.objects.all(),many=True) return HttpResponse(json.dumps(members.data)) else: return HttpResponseForbidden('allowed only via GET')
[ "abhinavbansal0@gmail.com" ]
abhinavbansal0@gmail.com
3a3f91694bd8244ed86de77d93729ab9911b4426
010287ab2ba027a1daa166f6405834751a54e0ed
/swagger_client/models/get_transaction_response.py
e1d27e4ef0b3bb1000ab1145543ab905298faf26
[]
no_license
mdodong/semuxapi-py
5ab605bc445f83f55f0465c26981879d28fbe3b0
3056eb70f43c4167de33fdda253bff1940f117cb
refs/heads/master
2020-03-11T07:49:35.874614
2019-12-16T00:20:33
2019-12-16T00:20:33
129,867,843
1
2
null
2019-12-16T00:20:34
2018-04-17T07:55:57
Python
UTF-8
Python
false
false
3,221
py
# coding: utf-8 """ Semux API Semux is an experimental high-performance blockchain platform that powers decentralized application. # noqa: E501 OpenAPI spec version: 2.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from swagger_client.models.api_handler_response import ApiHandlerResponse # noqa: F401,E501 from swagger_client.models.transaction_type import TransactionType # noqa: F401,E501 class GetTransactionResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'result': 'TransactionType' } attribute_map = { 'result': 'result' } def __init__(self, result=None): # noqa: E501 """GetTransactionResponse - a model defined in Swagger""" # noqa: E501 self._result = None self.discriminator = None if result is not None: self.result = result @property def result(self): """Gets the result of this GetTransactionResponse. # noqa: E501 :return: The result of this GetTransactionResponse. # noqa: E501 :rtype: TransactionType """ return self._result @result.setter def result(self, result): """Sets the result of this GetTransactionResponse. :param result: The result of this GetTransactionResponse. # noqa: E501 :type: TransactionType """ self._result = result def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, GetTransactionResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "noreply@github.com" ]
mdodong.noreply@github.com
fb57e686421cf3b611d518d3b5d8b489bf0284a2
ed91f03ff533fc2ff6ea509b7efe9362205b7b1e
/music/urls.py
2df36218f5350091c516b88cb7875a1bfeb979e9
[]
no_license
dishagupta22/GoMusic
4ce91a934ac6989b3e815e90e0c6b9cb3454472b
51c87ce4a2ead0ad7a050dfb8613548e50adffe5
refs/heads/master
2023-07-16T04:26:44.651623
2021-08-21T15:00:44
2021-08-21T15:00:44
398,157,893
0
0
null
null
null
null
UTF-8
Python
false
false
1,198
py
"""music URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, re_path,include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('',include('music_app.urls')), path('logout/',LogoutView.as_view(), name="logout"), ] if settings.DEBUG: #Not for production code urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ "dishagupta2203@gmail.com" ]
dishagupta2203@gmail.com
1c1c9fb5a797c3b27540cf216d0626c4d16de8d0
2c5cecd896751acda52d881b6109502da8cb7642
/latestUsage/sample_drawcell.py
3facd1157999f34823155a26a384722a47969fb9
[]
no_license
jimscafe/tkinterwidgettable
20dd470b2c5885186b62dda8c82e0429219212a1
7d06600433b254d268b4928bac5e94000139bddf
refs/heads/master
2023-02-05T21:25:29.915481
2021-01-01T19:22:03
2021-01-01T19:22:03
283,709,281
1
1
null
null
null
null
UTF-8
Python
false
false
1,473
py
import tkinter as TK from table_nf import MyTable import sampleData class Main: def __init__(self, parent): self.parent=parent #parent.geometry("500x200") mainFrame = TK.Frame(parent, borderwidth=5, bg='yellow') mainFrame.pack() self.table = MyTable(mainFrame, createColumns(), rows=10, scroll=True, # Vertical scroll forced drawCell=self.drawCell, # These are three callback functions cellClick=None, dataChanged=None) self.table.setData(sampleData.data1) def drawCell(self,widget, data): print ('Table row', widget.tableRow, 'Column',widget.tableColumn) # Visible cells print ('Data row', widget.dataCoords[0], 'Column',widget.dataCoords[1]) # actual data cells widget.setText(data) widget.configure(bg='light grey') if widget.tableColumn == 2: # Age if data > 20: widget.configure(bg='light green') def createColumns(): columns = [ {'text':'ID', 'width': 6, 'bg':'blue', 'fg':'white'}, {'text':'Name', 'width': 18, 'bg':'blue', 'fg':'white'}, {'text':'Age', 'width': 10, 'bg':'blue', 'fg':'white', 'align':'center'}, {'text':'Sex', 'width': 6, 'bg':'blue', 'fg':'white', 'align':'center',} ] return columns root = TK.Tk() main = Main(root) TK.mainloop()
[ "pdhartley@gmail.com" ]
pdhartley@gmail.com
939922049be622f0c427960ea8964b5924ed26ca
452c390d88b0fd4906bcfee0adb39c3d4331c55b
/symbolic/pnrg/pnrg.py
621c24ba41d5c9cb462043356ad894f8087d455b
[]
no_license
manupedrozo/ACST-challenges
609db97246021d804f5b0e234005d3f1790d0dd9
1dac7459085c13f7891f85c20507a93206b205a4
refs/heads/master
2023-06-17T20:50:02.349575
2021-07-17T18:26:39
2021-07-17T18:26:39
299,690,097
0
0
null
null
null
null
UTF-8
Python
false
false
77
py
from pwn import * r = remote("training.jinblack.it", 2020) r.interactive()
[ "manupedr@gmail.com" ]
manupedr@gmail.com
8ac0c577f2d05e43310d79af00afb3a45ec1796c
63788baaa835ca63af3b839850f81844a2265dbe
/student/admin.py
b8eae913119c7156613c300b4050bcfba0522189
[]
no_license
Benjamin-Mukeba/um
8ab5196ea835e78033ef3ecb5bcd7c15295e6c1d
81863555734efd9cb065e2a7ce8a32f628be23a9
refs/heads/master
2021-01-09T14:36:01.409289
2020-02-22T12:14:32
2020-02-22T12:14:32
242,339,556
0
0
null
null
null
null
UTF-8
Python
false
false
545
py
from django.contrib import admin from student.models import Student class StudentA(admin.ModelAdmin): list_display = ('nom', 'postnom', 'prenom', 'sexe', 'email', 'lieu_naissance', 'date_naissance', 'Etat_civil', 'adresse', 'faculte', 'departement', 'promotion', 'annee_academique', 'registration_date') list_filter = ('nom', 'postnom', 'prenom','registration_date',) search_fields = ('nom', 'postnom', 'prenom',) # Register your models here. admin.site.register(Student, StudentA) admin.site.site_header = "Student Registration"
[ "frank@aims.ac.za" ]
frank@aims.ac.za
e42298ba0c1dcbe10a98df243ffa6be02c19b2d1
f9044ff33302db393c0bed13df82f9c29fe1b7c3
/comment/migrations/0001_initial.py
885cfd229ec4170ff4e311e5ba15086fe85a55f9
[ "BSD-2-Clause" ]
permissive
shanbay/django-comment
f648c49e7af42dda0db128f4f7a97edc59ffa658
a14770db3f464fa7839f97b6a5d90caa8d5a5ab7
refs/heads/master
2021-01-15T22:20:17.683113
2017-08-15T09:48:39
2017-08-15T09:48:39
99,898,529
2
1
NOASSERTION
2020-02-11T21:50:17
2017-08-10T08:12:58
Python
UTF-8
Python
false
false
1,441
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-25 06:29 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '__first__'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.BigIntegerField()), ('content', models.TextField(max_length=2048)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('object_id', models.PositiveIntegerField()), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ('parent', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='comment.Comment')), ], ), migrations.AlterUniqueTogether( name='comment', unique_together=set([('user_id', 'content_type', 'object_id')]), ), migrations.AlterIndexTogether( name='comment', index_together=set([('content_type', 'object_id')]), ), ]
[ "cxbats@gmail.com" ]
cxbats@gmail.com
b4b966dcf88b5c5039b27204d7e2068bdef1dab4
033aa01ccf4be9670b26dbd6702be0852cfa8329
/QBuyPro/urls.py
ed9d8de422b93e105f7678e5c61690605b2f0c18
[]
no_license
KCooperA/QBuyPro
970425aed3ba35918ecf26f5f6e46ec7864aeabe
5e72159798a11189112232323a3066bdffd2b067
refs/heads/master
2020-07-19T19:50:12.887835
2019-09-05T07:31:22
2019-09-05T07:31:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
396
py
from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include from QBuyPro import settings urlpatterns = [ path('admin/', admin.site.urls), path('active/', include('actives.urls', namespace='active')), path('user/', include('user.urls', namespace='user')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ "610039018@qq.com" ]
610039018@qq.com
e953084a10499a5b71969ba92dfb69cb82abf533
34436c7f5497b20bdb4e12ed59517b616f19fa07
/wordcount/wordcount/settings.py
f8688335821b3d1b8dbc6e407af7db4afca5ba77
[]
no_license
aakarsh7599/django
b2bd0145882e5588c260b32ccff7072ef56b44dd
1635f5373980d598f9b1a05c8b0379fc52904f55
refs/heads/master
2020-04-17T10:49:09.490944
2019-01-19T10:21:59
2019-01-19T10:21:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,110
py
""" Django settings for wordcount project. Generated by 'django-admin startproject' using Django 2.0.1. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'f*$(piz-9jd!x$xc^w&z8#(8_kb=!gt*6((*g0#92u790y^+&9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wcount' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'wordcount.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wordcount.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'
[ "aakarsh0705@gmail.com" ]
aakarsh0705@gmail.com
b14328e032e759d2018e9088dbcc811d8c205b6e
e4124792934eaa7245ee7e3475780e5bc9644600
/apps/menu_of_the_day/views.py
94285ad0c9219e415e899477510f9d1fe9c8d2a7
[]
no_license
imaheshaher/MessApp
2e96aa4361df2e5b24eab88603952d440576d6f9
069d9c427713f1ba63375734c057641777e1173f
refs/heads/master
2022-12-28T11:56:33.594408
2020-10-13T04:05:20
2020-10-13T04:05:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,335
py
from django.shortcuts import render from rest_framework import viewsets from rest_framework.response import Response from rest_framework import generics from .models import MenuOfTheDay from .serializer import MenuOfTheDaySerializer # Create your views here. # class ListMenu(viewsets.ModelViewSet): # serializer_class = MenuOfTheDaySerializer # queryset = MenuOfTheDay.objects.all() # def list(self, request): # return Response( # self.queryset.filter( # days__in=[i[0] for i in MenuOfTheDay.DAYS_OF_WEEK]).values( # 'menu_name').values()) class ListMenu(viewsets.ModelViewSet): serializer_class = MenuOfTheDaySerializer queryset = MenuOfTheDay.objects.all() # l = [i[1] for i in MenuOfTheDay.DAYS_OF_WEEK] # print(l) def list(self, request): return Response( self.queryset.filter( days__in=[i[0] for i in MenuOfTheDay.DAYS_OF_WEEK]).values()) # def list(self, request): # return Response( # self.queryset.filter(days_in_week__in=[ # 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', # 'Saturday', 'Sunday' # ]).values()) def destroy(self, request): pass def update(self, request, pk=None): pass
[ "shubham.joshi1507@gmail.com" ]
shubham.joshi1507@gmail.com
f6a6458a5a8e4df5d30d00febb11f2c28b9701af
03004ba26a666e6112f91f0d598dcc9530caea81
/myvenv/bin/django-admin
ae1647f49ab550089305eb4623994d9c85121c83
[]
no_license
Chad-Lines/Django_REST
130015c1c3d7ffc37cbc999d3a1919f4bb19bc7a
cb3c225872e376ff00fbaa2ecee3056b638acc53
refs/heads/master
2022-12-01T08:26:54.654323
2020-08-13T20:45:16
2020-08-13T20:45:16
287,112,695
0
0
null
null
null
null
UTF-8
Python
false
false
301
#!/Users/chadlines/src/Django_REST/myvenv/bin/python3 # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
[ "chad.lines1@gmail.com" ]
chad.lines1@gmail.com
1839b0c83dcc234ac334d344b02618b07109a0c0
01369b46bf192c7fc724a366bfc6eba0819d0bf5
/test_ts_dist.py
01a8eddb562c575224c289833544b30521e157cd
[]
no_license
ymtoo/ts-dist
7fae6d802ae2e1fb5a400dce4e6b5ec66e80b66b
30de6eba0969611cda58754e212bddef2b28772e
refs/heads/master
2022-05-01T13:54:34.165145
2022-04-05T09:35:13
2022-04-05T09:35:13
153,758,139
23
8
null
null
null
null
UTF-8
Python
false
false
2,686
py
import numpy as _np import pyximport; pyximport.install(setup_args={'include_dirs': _np.get_include()}) import unittest from ts_dist import dtw_dist as dtw_dist_py from ts_dist import lcss_dist as lcss_dist_py from ts_dist import edr_dist as edr_dist_py from ts_dist_cy import dtw_dist as dtw_dist_cy from ts_dist_cy import lcss_dist as lcss_dist_cy from ts_dist_cy import edr_dist as edr_dist_cy class TSDISTTestSuite(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.X = _np.array([1, -1, 0, 0, 0]) self.Y = _np.array([0, 0, 1, -1, 0]) def test_dtw_dist_py(self): dist_0_dep = dtw_dist_py(self.X, self.Y, mode="dependent") dist_0_indep = dtw_dist_py(self.X, self.Y, mode="independent") dist_1_dep = dtw_dist_py(self.X, self.Y, w=1, mode="dependent") dist_1_indep = dtw_dist_py(self.X, self.Y, w=1, mode="independent") self.assertAlmostEqual(dist_0_dep, 2.000, places=4) self.assertAlmostEqual(dist_0_dep, dist_0_indep, places=4) self.assertAlmostEqual(dist_1_dep, 4.000, places=4) self.assertAlmostEqual(dist_1_dep, dist_1_indep, places=4) def test_lcss_dist_py(self): dist_0 = lcss_dist_py(self.X, self.Y, delta=_np.inf, epsilon=0.5) dist_1 = lcss_dist_py(self.X, self.Y, delta=2, epsilon=0.5) self.assertAlmostEqual(dist_0, 0.4000, places=4) self.assertAlmostEqual(dist_1, 0.6000, places=4) def test_edr_dist_py(self): dist_0 = edr_dist_py(self.X, self.Y, epsilon=0.5) self.assertAlmostEqual(dist_0, 0.8000, places=4) def test_dtw_dist_cy(self): dist_0_dep = dtw_dist_cy(self.X, self.Y, mode="dependent") dist_0_indep = dtw_dist_cy(self.X, self.Y, mode="independent") dist_1_dep = dtw_dist_cy(self.X, self.Y, w=1, mode="dependent") dist_1_indep = dtw_dist_cy(self.X, self.Y, w=1, mode="independent") self.assertAlmostEqual(dist_0_dep, 2.000, places=4) self.assertAlmostEqual(dist_0_dep, dist_0_indep, places=4) self.assertAlmostEqual(dist_1_dep, 4.000, places=4) self.assertAlmostEqual(dist_1_dep, dist_1_indep, places=4) def test_lcss_dist_cy(self): dist_0 = lcss_dist_cy(self.X, self.Y, delta=_np.inf, epsilon=0.5) dist_1 = lcss_dist_cy(self.X, self.Y, delta=2, epsilon=0.5) self.assertAlmostEqual(dist_0, 0.4000, places=4) self.assertAlmostEqual(dist_1, 0.6000, places=4) def test_edr_dist_cy(self): dist_0 = edr_dist_cy(self.X, self.Y, epsilon=0.5) self.assertAlmostEqual(dist_0, 0.8000, places=4) if __name__ == "__main__": unittest.main()
[ "too_ym86@yahoo.com" ]
too_ym86@yahoo.com
c8649b4f6a6bb5bd7b4a034c30a54372255542a7
3bd703927b710564d3bcfeaee4ad51afc9a4d8d3
/Tutorials/Python Machine Learning Scikit-Learn Tutorial/script.py
429f58d123014c5b9a066d3373cb325aef54edb4
[]
no_license
joneswan/DataCamp
995def48b17434a64fda91f834f94219c044a0ce
7de1deb1995bdbddddefeb3a12faba555cf76c37
refs/heads/master
2021-09-26T22:19:12.160299
2018-11-03T14:09:29
2018-11-03T14:09:29
104,729,903
0
1
null
null
null
null
UTF-8
Python
false
false
84
py
# -*- coding: utf-8 -*- """ Created on Fri Apr 21 23:46:42 2017 @author: jwan """
[ "joneswan.tech@gmail.com" ]
joneswan.tech@gmail.com
9f52177716f5b91e2d0e9259a9379a611950e331
6ee404818f72394208190c3df694b399074f2a08
/tagteam/archive/pexpect_create_tags.py
f77a4d66604eb351c44f9b70387ac03e2f376ee6
[]
no_license
ivanyeo/CassandraMySQLBenchmarkMinerva
ff8f3104523456aba04b9ce8b8fb0dfc854d98ea
71f6007187b4b37f62dab7f1ab00be1f08425e02
refs/heads/master
2021-01-01T05:44:48.587944
2014-05-24T05:40:54
2014-05-24T05:40:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
211
py
#!/usr/bin/python import pexpect child = pexpect.spawn('python manage.py shell', timeout=None) child.expect('>>> ') child.sendline('execfile("create_tags.py")') child.expect('>>> ') child.sendline('exit()')
[ "ivanyeo@cs.ucla.edu" ]
ivanyeo@cs.ucla.edu
764489758b16ca15c1c43e429135db4e36bb80ae
ba92e696948a7895ea9c48c2bf3414a97bb99605
/p016.py
4328aa3f58e501a3648065e06b6a9a0800c9b429
[]
no_license
dmmfix/pyeuler
72d1898841749a06cf66b91fb8a2664c1804a632
1bac27d41dbf98f224e99f95b973160cd6d8b190
refs/heads/master
2021-01-20T01:32:51.588234
2017-04-27T06:37:35
2017-04-27T06:37:35
89,293,391
0
0
null
null
null
null
UTF-8
Python
false
false
68
py
#!/usr/bin/python import euler print(sum(euler.digits(1 << 1000)))
[ "dmmfix@fb.com" ]
dmmfix@fb.com
cd9b2cdd3de1794e859351c6ef5fb1a6a003a39c
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R2/benchmark/startCirq309.py
cedbf8ea5e7fd2369f2515194eef4efdd203b9d7
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,079
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=3 # total number=62 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[2])) # number=38 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=39 c.append(cirq.H.on(input_qubit[2])) # number=40 c.append(cirq.H.on(input_qubit[2])) # number=59 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=60 c.append(cirq.H.on(input_qubit[2])) # number=61 c.append(cirq.H.on(input_qubit[2])) # number=42 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=43 c.append(cirq.H.on(input_qubit[2])) # number=44 c.append(cirq.H.on(input_qubit[2])) # number=48 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=49 c.append(cirq.H.on(input_qubit[2])) # number=50 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=54 c.append(cirq.X.on(input_qubit[2])) # number=55 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=56 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=47 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=37 c.append(cirq.H.on(input_qubit[2])) # number=51 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=52 c.append(cirq.H.on(input_qubit[2])) # number=53 c.append(cirq.H.on(input_qubit[2])) # number=25 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=26 c.append(cirq.H.on(input_qubit[2])) # number=27 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=8 c.append(cirq.rx(0.17592918860102857).on(input_qubit[2])) # number=34 c.append(cirq.rx(-0.3989822670059037).on(input_qubit[1])) # number=30 c.append(cirq.H.on(input_qubit[1])) # number=9 c.append(cirq.H.on(input_qubit[1])) # number=18 c.append(cirq.rx(2.3310617489636263).on(input_qubit[2])) # number=58 c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=19 c.append(cirq.H.on(input_qubit[1])) # number=20 c.append(cirq.Y.on(input_qubit[1])) # number=14 c.append(cirq.H.on(input_qubit[1])) # number=22 c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=23 c.append(cirq.rx(-0.9173450548482197).on(input_qubit[1])) # number=57 c.append(cirq.H.on(input_qubit[1])) # number=24 c.append(cirq.Z.on(input_qubit[2])) # number=3 c.append(cirq.Z.on(input_qubit[1])) # number=41 c.append(cirq.X.on(input_qubit[1])) # number=17 c.append(cirq.Y.on(input_qubit[2])) # number=5 c.append(cirq.X.on(input_qubit[2])) # number=21 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=15 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=16 c.append(cirq.X.on(input_qubit[2])) # number=28 c.append(cirq.X.on(input_qubit[2])) # number=29 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq309.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
b63900024e9705c6c672dfbc212899b782369e55
e8ed08121d7d0ecb7c2ec462021e4e3f49e1f565
/core/models/__init__.py
2d58873ffa7b1b962cd1f355ffac53985e09bd0e
[]
no_license
DebraYona/django-demo-shop
aa628952cca0350164bf7fb3cc09345777f9fe9f
42959693995ea7aa9f3289fefc49d77e7c4a9cb9
refs/heads/main
2023-01-29T00:18:33.571288
2020-12-01T06:03:35
2020-12-01T06:03:35
317,356,788
0
0
null
null
null
null
UTF-8
Python
false
false
131
py
from core.models.product import Product from core.models.category import Category __all__ = [ 'Category', 'Product', ]
[ "debra.chacaliaza@unmsm.edu.pe" ]
debra.chacaliaza@unmsm.edu.pe
26dbad4bf374aa5dfab60fe34579a10b3053625f
1183972397f69c64845f1ebce53efe3d0bc600e1
/Healthcare.py
0d4c90df4894f995cb5f9664b2df0568c55142ab
[ "MIT" ]
permissive
SreekarPraneethMarri/SLAC
f7e5105962152c56d07c67dccf6e495f9382b4e3
e7fbee0dbac23bbdc52ffbf3e691708758d036bf
refs/heads/main
2023-01-12T05:49:53.339739
2020-11-08T04:00:03
2020-11-08T04:00:03
310,979,890
0
0
null
null
null
null
UTF-8
Python
false
false
7,821
py
import subprocess import string import random from tkinter import * import webbrowser print ("Welcome") def callback(event): webbrowser.open_new(event) def main_ho(x): if(x==1): dept() elif(x==2): print("########### BMI ##############") while (True): name = input("Enter the name of patient ") if (name!=""): break else: print("Incorrect Input. Please Verify it and Enter again") continue while(True): email = input("Enter the email address of patient ") if (email!=""): break else: print("Incorrect Input. Please Verify it and Enter again") continue while (True): phone = input("Enter the mobile number of patient ") if (phone!="" and len(phone)==10): break else: print("Incorrect Input. Please Verify it and Enter again") continue while(True): a=float(input("Enter the weight(in kg) of the patient")) if (a!=""): break else: print("Incorrrect Input. Please Enter again") continue b=float(input("Enter the height(in m) of the patient (Upto 2 decimal places)")) bmi=a/pow(b,2) print("Your BMI is",bmi) if (bmi<18.5): print("You are undwerweight") elif (18.5<bmi<25): print("You are healthy") elif (25<bmi<30): print("You are overweight") else: print("You are obese") elif(x==3): contact() else: print("Please check your input") def dept(): print("The departments in our healthcare are:") print("1. General Physician") print("2. ENT") print("3. Dermetology") print("4. Orthopadics") ni = int(input("Please enter your choice")) if(ni == 1): print("General Physician") print("The cost for consultation per patient is: ₹800") nip = int(input("Enter the number of patients")) if(nip != 0 and nip < 5): cost = 800*nip print("The total cost is: ",cost) checkchoice = input("Proceed to PAYMENT?(y/n)") if(checkchoice == "y"): checkout(nip,cost) elif(checkchoice == "n"): print("Thanks so much for stopping by! Wising You A Fast Recovery!!") else: print("Bad input. Please check your input") if(ni == 2): print("ENT") print("The cost for consultation per patient is: ₹850") nip = int(input("Enter the number of patients")) if(nip != 0 and nip < 5): cost = 850*nip print("The total cost is: ",cost) checkchoice = input("Proceed to PAYMENT?(y/n)") if(checkchoice == "y"): checkout(nip,cost) elif(checkchoice == "n"): print("Thanks so much for stopping by! Wising You A Fast Recovery!!") else: print("Bad input. Please check your input") if(ni == 3): print("Dermetology") print("The cost for consultation per patient is: ₹700") nip = int(input("Enter the number of patients")) if(nip != 0 and nip < 5): cost = 700*nip print("The total cost is: ",cost) checkchoice = input("Proceed to PAYMENT?(y/n)") if(checkchoice == "y"): checkout(nip,cost) elif(checkchoice == "n"): print("Thanks so much for stopping by! Have a great Day!!") else: print("Bad input. Please check your input") if(ni == 4): print("Orthopadics") print("The cost for consultation per patient is: ₹750") nip = int(input("Enter the number of patients")) if(nip != 0 and nip < 5): cost = 750*nip print("The total cost is: ",cost) checkchoice = input("Proceed to PAYMENT?(y/n)") if(checkchoice == "y"): checkout(nip,cost) elif(checkchoice == "n"): print("Thanks so much for stopping by! Have a great Day!!") else: print("Bad input. Please check your input") if(ni >4 or ni <= 0): print("Invalid Input! Please correct the same") def checkout(pax,price): print("SPVM CITRUS PAY -- PAYMENT GATEWAY") print("Total number of patients: ",pax) print("TOTAL COST: ",price) for i in range(0, pax): while (True): name = input("Enter the name of Patient ") if (name!=""): break else: print("Incorrect Input. Please Verify it and Enter again") continue while(True): email = input("Enter the email address of patient ") if (email!=""): break else: print("Incorrect Input. Please Verify it and Enter again") continue while (True): phone = input("Enter the mobile number of patient ") if (phone!="" and len(phone)==10): break else: print("Incorrect Input. Please Verify it and Enter again") continue print("Payment Options") print("1. CREDIT / DEBIT CARD") print("2. WALLETS") pay = int(input("ENTER YOUR PAYMENT METHOD ")) if (pay == 1): while (True): s = input("Enter your 16 Digit Card Number ") if (len(s) == 16): break else: print("Incorrect Input. Please Verify it and Enter again") continue while(True): pin = input("Please enter your CVC ") if (len(pin)!=3): continue else: break print("PAYMENT SUCCESSFUL! We hope that you will get well soon !") elif (pay == 2): root = Tk() link1 = Label(root, text="Paytm Gateway", fg="orange", cursor="hand2") link1.pack() link1.bind("<Button-1>", lambda e: callback("www.paytm.com")) link2 = Label(root, text="Google Pay", fg="blue", cursor="hand2") link2.pack() link2.bind("<Button-1>", lambda e: callback("www.gpay.com")) link3 = Label(root, text="PhonePe", fg="blue", cursor="hand2") link3.pack() link3.bind("<Button-1>", lambda e: callback("https://www.phonepe.com/en/")) button = Button(root, text="Click to Complete Payment", command=lambda:root.destroy()).pack() root.mainloop() print("PAYMENT SUCCESSFUL! We hope that you will get well soon !") def contact(): print("~~~~~~~~~~~~~~ SPVH Healthcare ~~~~~~~~~~~~~") print("Address: CA 21, Mahatma Gandhi Road, Bangalore, India") print("Email: consult.spvhhealth@gmail.com") print("Web: www.spvhhealth.in") print("Please feel free to contact us regarding any emergency services. We're available 24x7 for our valuable customers. Thank you.") ch = "y" while(ch=="y"): print("Welcome to Healthcare") print("1. Departments") print("2. Health Status") print("3. Contact Us") n = int(input("Enter your choice :")) main_ho(n) ch = input("Do you wish to continue? (y/n) ") if(ch == "n"): print("Thank you! Wishing you a Fast Recovery! ")
[ "noreply@github.com" ]
SreekarPraneethMarri.noreply@github.com
5e1a33695962ffc7bcf5f91b5f3d237c529c161c
c49ba441a2f4fc94e54358a7436b9c12d538279a
/agent/src/agent/pipeline/config/stages/topology.py
219269d7ada6d1bd0c80d1ee56e62e3962f7989f
[ "Apache-2.0" ]
permissive
anodot/daria
86523a9f699577c8cf61120e2c27589a4ade48bb
4aa800e26b585a8582ec2e088384a474148d114d
refs/heads/master
2023-07-20T11:36:58.353251
2023-07-17T17:33:57
2023-07-17T17:33:57
224,878,130
16
6
Apache-2.0
2023-07-12T13:07:25
2019-11-29T15:23:32
Python
UTF-8
Python
false
false
853
py
import urllib.parse from agent.pipeline.config.stages.base import JythonProcessor class TopologyScript(JythonProcessor): JYTHON_SCRIPT = 'topology/transform.py' DATA_EXTRACTOR_API_ENDPOINT = 'data_extractors/topology' def _get_script_params(self) -> list[dict]: return [ { 'key': 'TOPOLOGY_TRANSFORM_RECORDS_URL', 'value': self._get_source_url(), }, ] def _get_source_url(self) -> str: return urllib.parse.urljoin( self.pipeline.streamsets.agent_external_url, '/'.join([ self.DATA_EXTRACTOR_API_ENDPOINT, '${pipeline:id()}', ]) ) class DirectoryCsvToJson(JythonProcessor): JYTHON_SCRIPT = 'topology/csv_to_json.py' def _get_script_params(self) -> list[dict]: return []
[ "noreply@github.com" ]
anodot.noreply@github.com
c57b9cb1f61e8fc94173c23d6f467792d8b13e28
78918441c6735b75adcdf20380e5b6431891b21f
/config/urls.py
11cc46512420154574ca40cfbbc304780f4853c7
[]
no_license
dede-20191130/PracticeDjango_2
eba40532d5ce8bd4fd13fbd15d94f31942111cfa
23593c0fa4c4dff04bd76583e8176e600ca69014
refs/heads/master
2020-12-23T14:23:08.039363
2020-02-27T12:16:00
2020-02-27T12:16:00
237,176,619
0
0
null
null
null
null
UTF-8
Python
false
false
990
py
"""config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from blog.urls import router as blog_router urlpatterns = [ path('admin/', admin.site.urls), path('mybook/', include('mybook.urls')), path('api/', include('api.urls')), path('blog_api/', include(blog_router.urls)), path('ajax_prac_1/', include('ajax_prac_1.urls')), ]
[ "1044adad@gmail.com" ]
1044adad@gmail.com
8cd1044d36b864f55eaca00f3c97733a42414a42
f1fb01d49b60e37e21b5c19034bde60470cd451d
/knowledgebase/accounts/forms.py
1afaa65b7f826d5a7bdd510123d5e1dd6bfc56b4
[]
no_license
shirolapov/knowledgebase
d59209d561a083bb7192867c5bf583b8223c6b98
95bcb6443fd67e97599ff5cb9a4cea7689dc0e9f
refs/heads/master
2021-09-08T04:45:38.168806
2018-03-07T07:12:18
2018-03-07T07:12:18
124,057,124
0
0
null
null
null
null
UTF-8
Python
false
false
1,675
py
from django.forms import ModelForm, TextInput, EmailInput, PasswordInput from django.contrib.auth.models import User class UserForm(ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] widgets = { 'username': TextInput(attrs={'class': 'form-control', 'required': True}), 'first_name': TextInput(attrs={'class': 'form-control', 'required': True}), 'last_name': TextInput(attrs={'class': 'form-control', 'required': True}), 'email': EmailInput(attrs={'class': 'form-control', 'required': True}), 'password': PasswordInput(attrs={'class': 'form-control', 'required': True}) } class UserChangeForm(ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'is_active'] widgets = { 'username': TextInput(attrs={'class': 'form-control', 'required': True}), 'first_name': TextInput(attrs={'class': 'form-control', 'required': True}), 'last_name': TextInput(attrs={'class': 'form-control', 'required': True}), 'email': EmailInput(attrs={'class': 'form-control', 'required': True}), } def is_valid(self): valid = super(UserChangeForm, self).is_valid() return valid def clean(self): username = self.cleaned_data.get('username') first_name = self.cleaned_data.get('first_name') last_name = self.cleaned_data.get('last_name') email = self.cleaned_data.get('email') is_active = self.cleaned_data.get('is_active') return self.cleaned_data
[ "kirill.shirolapov@gmail.com" ]
kirill.shirolapov@gmail.com
e354377e9ee551f2a5df6e3d8bd6929cee8a1c7c
049ece80895f6cb20a01af88745f4e6d636c5062
/minitimestorefuel.py
d1177dd18cef6e4d596308888a55f78830c305cd
[]
no_license
reshmahayathbi1999/prolevel
6a07d3a9a9123c0a4add03ff0ef157a0ae641e74
c7f56e0bf57c6ea266aa0e7e7de3d28670bcdffc
refs/heads/master
2020-06-22T11:23:17.548612
2019-07-19T09:19:18
2019-07-19T09:19:18
197,706,210
0
0
null
null
null
null
UTF-8
Python
false
false
361
py
w1, x, y, z = map(int,input().split()) count1 = 0 x1 = x-y if(x1 >= 0): di = (w1-y)*2 for i in range(z): if(i == z-1): di = di/2 if(x1 < di): x1 = x count1 += 1 x1 = x1-di if(x1 < 0): count1 = -1 break di = 2*w1-di print(count1) else: print(-1)
[ "noreply@github.com" ]
reshmahayathbi1999.noreply@github.com
3eb5bad1d6f0abb913e0438f5f6df4145dda0a71
30b5179e32c3f31b56b100238ee9d14449d02071
/tests/components/netatmo/test_device_trigger.py
8f387996906359ea3f86f1da66108d05415e7dc9
[ "Apache-2.0" ]
permissive
Verbalinsurection/Home-Assistant-core
e149c13ecae32c34b7cabd0216abcfddd6244bdc
5f69ae436003c75b1eeac2ec488049197e87e9ff
refs/heads/dev
2023-09-01T18:34:53.715026
2023-02-14T21:17:22
2023-02-14T21:17:22
247,318,244
0
0
Apache-2.0
2023-02-22T06:14:24
2020-03-14T17:04:17
Python
UTF-8
Python
false
false
10,250
py
"""The tests for Netatmo device triggers.""" import pytest import homeassistant.components.automation as automation from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.netatmo import DOMAIN as NETATMO_DOMAIN from homeassistant.components.netatmo.const import ( CLIMATE_TRIGGERS, INDOOR_CAMERA_TRIGGERS, NETATMO_EVENT, OUTDOOR_CAMERA_TRIGGERS, ) from homeassistant.components.netatmo.device_trigger import SUBTYPES from homeassistant.const import ATTR_DEVICE_ID from homeassistant.helpers import device_registry as dr from homeassistant.setup import async_setup_component from tests.common import ( MockConfigEntry, assert_lists_same, async_capture_events, async_get_device_automations, async_mock_service, ) @pytest.fixture def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation") @pytest.mark.parametrize( "platform,device_type,event_types", [ ("camera", "Smart Outdoor Camera", OUTDOOR_CAMERA_TRIGGERS), ("camera", "Smart Indoor Camera", INDOOR_CAMERA_TRIGGERS), ("climate", "Smart Valve", CLIMATE_TRIGGERS), ("climate", "Smart Thermostat", CLIMATE_TRIGGERS), ], ) async def test_get_triggers( hass, device_registry, entity_registry, platform, device_type, event_types ): """Test we get the expected triggers from a netatmo devices.""" config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, model=device_type, ) entity_registry.async_get_or_create( platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id ) expected_triggers = [] for event_type in event_types: if event_type in SUBTYPES: for subtype in SUBTYPES[event_type]: expected_triggers.append( { "platform": "device", "domain": NETATMO_DOMAIN, "type": event_type, "subtype": subtype, "device_id": device_entry.id, "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678", "metadata": {"secondary": False}, } ) else: expected_triggers.append( { "platform": "device", "domain": NETATMO_DOMAIN, "type": event_type, "device_id": device_entry.id, "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678", "metadata": {"secondary": False}, } ) triggers = [ trigger for trigger in await async_get_device_automations( hass, DeviceAutomationType.TRIGGER, device_entry.id ) if trigger["domain"] == NETATMO_DOMAIN ] assert_lists_same(triggers, expected_triggers) @pytest.mark.parametrize( "platform,camera_type,event_type", [("camera", "Smart Outdoor Camera", trigger) for trigger in OUTDOOR_CAMERA_TRIGGERS] + [("camera", "Smart Indoor Camera", trigger) for trigger in INDOOR_CAMERA_TRIGGERS] + [ ("climate", "Smart Valve", trigger) for trigger in CLIMATE_TRIGGERS if trigger not in SUBTYPES ] + [ ("climate", "Smart Thermostat", trigger) for trigger in CLIMATE_TRIGGERS if trigger not in SUBTYPES ], ) async def test_if_fires_on_event( hass, calls, device_registry, entity_registry, platform, camera_type, event_type ): """Test for event triggers firing.""" mac_address = "12:34:56:AB:CD:EF" connection = (dr.CONNECTION_NETWORK_MAC, mac_address) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={connection}, identifiers={(NETATMO_DOMAIN, mac_address)}, model=camera_type, ) entity_registry.async_get_or_create( platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id ) events = async_capture_events(hass, "netatmo_event") assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": NETATMO_DOMAIN, "device_id": device_entry.id, "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678", "type": event_type, }, "action": { "service": "test.automation", "data_template": { "some": ( "{{trigger.event.data.type}} - {{trigger.platform}} - {{trigger.event.data.device_id}}" ) }, }, }, ] }, ) device = device_registry.async_get_device(set(), {connection}) assert device is not None # Fake that the entity is turning on. hass.bus.async_fire( event_type=NETATMO_EVENT, event_data={ "type": event_type, ATTR_DEVICE_ID: device.id, }, ) await hass.async_block_till_done() assert len(events) == 1 assert len(calls) == 1 assert calls[0].data["some"] == f"{event_type} - device - {device.id}" @pytest.mark.parametrize( "platform,camera_type,event_type,sub_type", [ ("climate", "Smart Valve", trigger, subtype) for trigger in SUBTYPES for subtype in SUBTYPES[trigger] ] + [ ("climate", "Smart Thermostat", trigger, subtype) for trigger in SUBTYPES for subtype in SUBTYPES[trigger] ], ) async def test_if_fires_on_event_with_subtype( hass, calls, device_registry, entity_registry, platform, camera_type, event_type, sub_type, ): """Test for event triggers firing.""" mac_address = "12:34:56:AB:CD:EF" connection = (dr.CONNECTION_NETWORK_MAC, mac_address) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={connection}, identifiers={(NETATMO_DOMAIN, mac_address)}, model=camera_type, ) entity_registry.async_get_or_create( platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id ) events = async_capture_events(hass, "netatmo_event") assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": NETATMO_DOMAIN, "device_id": device_entry.id, "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678", "type": event_type, "subtype": sub_type, }, "action": { "service": "test.automation", "data_template": { "some": ( "{{trigger.event.data.type}} - {{trigger.event.data.data.mode}} - " "{{trigger.platform}} - {{trigger.event.data.device_id}}" ) }, }, }, ] }, ) device = device_registry.async_get_device(set(), {connection}) assert device is not None # Fake that the entity is turning on. hass.bus.async_fire( event_type=NETATMO_EVENT, event_data={ "type": event_type, "data": { "mode": sub_type, }, ATTR_DEVICE_ID: device.id, }, ) await hass.async_block_till_done() assert len(events) == 1 assert len(calls) == 1 assert calls[0].data["some"] == f"{event_type} - {sub_type} - device - {device.id}" @pytest.mark.parametrize( "platform,device_type,event_type", [("climate", "NAPlug", trigger) for trigger in CLIMATE_TRIGGERS], ) async def test_if_invalid_device( hass, device_registry, entity_registry, platform, device_type, event_type ): """Test for event triggers firing.""" mac_address = "12:34:56:AB:CD:EF" connection = (dr.CONNECTION_NETWORK_MAC, mac_address) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={connection}, identifiers={(NETATMO_DOMAIN, mac_address)}, model=device_type, ) entity_registry.async_get_or_create( platform, NETATMO_DOMAIN, "5678", device_id=device_entry.id ) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": NETATMO_DOMAIN, "device_id": device_entry.id, "entity_id": f"{platform}.{NETATMO_DOMAIN}_5678", "type": event_type, }, "action": { "service": "test.automation", "data_template": { "some": ( "{{trigger.event.data.type}} - {{trigger.platform}} - {{trigger.event.data.device_id}}" ) }, }, }, ] }, )
[ "noreply@github.com" ]
Verbalinsurection.noreply@github.com
7e7ed9ae32b1f7fe700f938aff6c085707608464
6d051f9348d547fa9e49d63f53afd7967b4f8043
/djangobmf/contrib/timesheet/permissions.py
e2842070051de28418392bb2b99afd7d6f047b33
[ "BSD-3-Clause" ]
permissive
caputomarcos/django-bmf
39d7f1284ebf58e12e914f0a217368f8a664ef6b
0d07a7d3f6a3ecfaca6c9376e764add1715cfd33
refs/heads/develop
2022-02-09T08:23:52.983948
2015-11-16T01:48:22
2015-11-16T01:48:22
46,672,438
0
0
NOASSERTION
2022-02-02T10:46:15
2015-11-22T17:57:11
Python
UTF-8
Python
false
false
396
py
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from djangobmf.permissions import ModulePermission class TimesheetPermission(ModulePermission): def filter_queryset(self, qs, user): if user.has_perm('%s.can_manage' % qs.model._meta.app_label, qs.model): return qs return qs.filter(employee=user.djangobmf.employee or -1)
[ "sebastian@elmnt.de" ]
sebastian@elmnt.de
b81fdb42fa0ec0cbe0bece06a4ab3c9033f7c166
d4608a5cd7db2edf3ef9470efd74b0761ab07efc
/src/pal_python/pal_launch.py
d38262f2c4bc532450ce2c652ab8f4b8d00eaea8
[]
no_license
efernandez/pal_python
378c233fad4776e202804d5e79e885d803c6b4a0
5c1ebeb9e716fbb619b4f120737ee86869e6533a
refs/heads/master
2021-01-15T09:15:28.257787
2014-03-27T18:01:28
2014-03-27T18:01:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,488
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pal_python: pal_launch.py # # Copyright (c) 2013 PAL Robotics SL. All Rights Reserved # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all # copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Authors: # * Siegfried-A. Gevatter # * Enrique Fernandez import os import sys import subprocess from pal_python import pal_path # TODO: move this to pal_command/pal_execute? def execute_command(*command): """ Run the given command and wait for completion. Return the exit code, or None if the command couldn't be run at all. """ sys.stderr.write('Running command: "%s".\n' % ' '.join(command)) try: retcode = subprocess.call(command, shell=False) if retcode < 0: sys.stderr.write(' -> Terminated by signal %d.\n' % -retcode) else: sys.stderr.write(' -> Returned %d.\n' % retcode) return retcode except OSError as e: sys.stderr.write(' -> Execution failed: %s\n' % e) return None def spawn_command(*command): """ Run the given command, without waiting for completion. Return the Popen object (which provides .send_signal, .kill(), .wait(), etc), or None if the command couldn't be run at all. The command is created with its own process group; this mean that signals (eg. Ctrl+C) won't be forwarded to it. """ sys.stderr.write('Spawning command: "%s".\n' % ' '.join(command)) try: return subprocess.Popen(command, shell=False, preexec_fn=os.setpgrp) except OSError as e: sys.stderr.write(' -> Execution failed: %s\n' % e) return None # NavigationFunctions.py used to log Command+Result to /tmp/navigation_sm.log. # It also treated 36608, 15 and 256 as zero, without saying why. class LaunchError(OSError): """ Exception executing a file from the launch directory (usually a *Start.sh or *Stop.sh script). """ def __init__(self, component, launchfile, code): super(LaunchError, self).__init__() self.component = component self.errno = code self.filename = launchfile self.strerror = '"%s" failed with code %d' % (launchfile, code) self.message = self.strerror # TODO: Move ErrorCollection to pal_common.py and here have # LaunchErrorCollection(OSError, ErrorCollection), plus # add methods for merging ErrorCollections? class LaunchErrorCollection(OSError): """ Exception aggregating one or more exceptions that occurred trying to perform several related actions (eg. launching various components). """ def __init__(self, errors=None): super(LaunchErrorCollection, self).__init__() self.errors = errors if errors is not None else [] def add_error(self, error): self.errors.append(error) @property def message(self): return ' | '.join(e.message for e in self.errors) def __nonzero__(self): """ False if this error collection is empty (ie. no errors). """ return not bool(self.errors) def roslaunch(stack, fname, *params): roslaunch_bin = pal_path.get_ros_bin_path('roslaunch') launchfile = fname if fname.endswith('.launch') else '%s.launch' % fname process = spawn_command(roslaunch_bin, stack, launchfile, *params) if process is None: raise LaunchError(stack, launchfile, '[execution failed]') def rosrun(stack, fname, *params): rosrun_bin = pal_path.get_ros_bin_path('rosrun') process = spawn_command(rosrun_bin, stack, fname, *params) if process is None: raise LaunchError(stack, fname, '[execution failed]') def start(component): launchfile = '%sStart.sh' % component result = execute_command(pal_path.get_launch_path(launchfile)) if result != 0: raise LaunchError(component, launchfile, result) def stop(component): launchfile = '%sStop.sh' % component result = execute_command(pal_path.get_launch_path(launchfile)) if result != 0: raise LaunchError(component, launchfile, result) def run(launchfile, *args): result = execute_command(pal_path.get_launch_path(launchfile), *args) if result != 0: raise LaunchError(launchfile, launchfile, result) def start_all(*components): errors = LaunchErrorCollection() # TODO: write execute_command_async (using subprocess.Popen) and # use it here to run all in parallel? Maybe only if parallel=True? for component in components: try: start(component) except LaunchError, e: errors.add_error(e) if errors: raise errors def stop_all(*components): errors = LaunchErrorCollection() for component in components: try: stop(component) except LaunchError, e: errors.add_error(e) if errors: raise errors
[ "siegfried.gevatter@pal-robotics.com" ]
siegfried.gevatter@pal-robotics.com
591be998f5d765da792edc90a9f6aa7b76101519
aa2c6ff3746c860d06750f4b2238a06903ad1378
/jeyzth42/lib/base.py
337ca607132e694b9cb569b0ead46e1206816202
[]
no_license
jeyzth/jeyzth42
3d5fb7bf847397dfb09aa0998d797a4a3a9ddbec
82f479efeba4adf4db44d4ddb7bb9c2afbff8e52
refs/heads/master
2016-09-06T20:39:49.197154
2015-07-19T01:35:52
2015-07-19T01:35:52
39,333,527
0
0
null
null
null
null
UTF-8
Python
false
false
754
py
# -*- coding: utf-8 -*- """The base Controller API.""" from tg import TGController, tmpl_context from tg import request __all__ = ['BaseController'] class BaseController(TGController): """ Base class for the controllers in the application. Your web application should have one of these. The root of your application is used to compute URLs used by your app. """ def __call__(self, environ, context): """Invoke the Controller""" # TGController.__call__ dispatches to the Controller method # the request is routed to. request.identity = request.environ.get('repoze.who.identity') tmpl_context.identity = request.identity return TGController.__call__(self, environ, context)
[ "jeyzth@gmail.com" ]
jeyzth@gmail.com
ab3aa0cc571115f2af8b988585586d1e19a40995
f394598dad4276f9667e702b7360ab14dcd10cfc
/unsolved/girl_in_apple_orchard.py
df6154d23878102ec46d8c9491ae7ea415648287
[]
no_license
siowyisheng/python-problem-solving
fe9ded3761e637883467cb81abc01bcb0a54b589
7e32767a3ac710ecfc37f205ee35eda194400122
refs/heads/master
2020-03-21T19:57:56.118616
2019-06-28T08:12:09
2019-06-28T08:12:09
138,980,214
0
0
null
null
null
null
UTF-8
Python
false
false
519
py
A girl is walking along an apple orchard with a bag in each hand. She likes to pick apples from each tree as she goes along, but is meticulous about not putting different kinds of apples in the same bag. Given an input describing the types of apples she will pass on her path, in order, determine the length of the longest portion of her path that consists of just two types of apple trees. For example, given the input [2, 1, 2, 3, 3, 1, 3, 5], the longest portion will involve types 1 and 3, with a length of four.
[ "siowyisheng@gmail.com" ]
siowyisheng@gmail.com
0af73a0872ef6a53d8a2fd26ebe105463a65d54b
c3dc08fe8319c9d71f10473d80b055ac8132530e
/challenge-101/roger-bell-west/python/ch-1.py
214318e188fde9285e6af4b6769df93d2f5fcbb2
[]
no_license
southpawgeek/perlweeklychallenge-club
d4b70d9d8e4314c4dfc4cf7a60ddf457bcaa7a1e
63fb76188e132564e50feefd2d9d5b8491568948
refs/heads/master
2023-01-08T19:43:56.982828
2022-12-26T07:13:05
2022-12-26T07:13:05
241,471,631
1
0
null
2020-02-18T21:30:34
2020-02-18T21:30:33
null
UTF-8
Python
false
false
1,569
py
#! /usr/bin/python3 import math def pas(aa): a=aa[::-1] n=len(a) f2=int(math.sqrt(n)) f1=0 while 1: if n % f2 == 0: f1=int(n/f2) break f2 -= 1 out=list() for i in range(f2): out.append([0] * f1) x=-1 y=0 maxx=f1-1 maxy=f2-1 minx=0 miny=1 cnt=1 while cnt: while x < maxx: x += 1 out[y][x]=a.pop() if len(a)==0: cnt=0 break maxx -= 1 if cnt: while y < maxy: y += 1 out[y][x]=a.pop() if len(a)==0: cnt=0 break maxy -= 1 if cnt: while x > minx: x -= 1 out[y][x]=a.pop() if len(a)==0: cnt=0 break minx += 1 if cnt: while y > miny: y -= 1 out[y][x]=a.pop() if len(a)==0: cnt=0 break miny += 1 return out import unittest class TestPas(unittest.TestCase): def test_ex1(self): self.assertEqual(pas([*range(1,4+1)]),[[1,2],[4,3]],'example 1') def test_ex2(self): self.assertEqual(pas([*range(1,6+1)]),[[1,2,3],[6,5,4]],'example 2') def test_ex3(self): self.assertEqual(pas([*range(1,12+1)]),[[1,2,3,4],[10,11,12,5],[9,8,7,6]],'example 3') unittest.main()
[ "roger@firedrake.org" ]
roger@firedrake.org
ac84b2fbaaad045cba87e7975ff99c844d6017e9
dd660ea2bee9fdf568da47f9760568c0d5c91049
/tf_lab/test_tf_dataset_v2.py
cea3a4d2abb1f18e193a923db06594a1d2d494ea
[]
no_license
kanhua/lyft-3d-main
4cad265b9c92a62ab79ebab4e01e2ffe2ad8f025
1c74500f0bf5d52317af29cb350368832eb42aba
refs/heads/master
2021-08-07T18:48:05.983138
2020-09-17T00:49:19
2020-09-17T00:49:19
219,532,364
0
0
null
null
null
null
UTF-8
Python
false
false
564
py
import tensorflow as tf from itertools import count g=tf.Graph() with g.as_default(): dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]) iter = tf.compat.v1.data.make_one_shot_iterator(dataset) el = iter.get_next() el = iter.get_next() el2=tf.compat.v1.add(el,el) with tf.compat.v1.Session() as sess: try: for x in count(): data_numpy=sess.run(el2) print(data_numpy) except tf.errors.OutOfRangeError: print("Process finished") pass
[ "kanhua.lee@gmail.com" ]
kanhua.lee@gmail.com
256350fd1e0ca70d3eb2d92a6df9eeeb0952e532
b41e0def0792c55ee12a452bf34c1e339487b42c
/model_assessment/plot_mean_std_u200.py
a58b62ebd84e74ca23c302160d690d985032580b
[]
no_license
marisolosman/assessment_SH_zonal_asymmetries
ba6e0a9c38019313367dbbe5914c45aa4f23b19e
dc400f09be8c6845ce86d28e2ab7bc9bfb37fcc8
refs/heads/master
2022-12-25T00:52:31.678839
2022-12-19T13:34:37
2022-12-19T13:34:37
194,651,414
0
2
null
null
null
null
UTF-8
Python
false
false
5,268
py
#plor meand and std for HGT 200 A-N for ERA Interim and S4 import numpy as np import datetime import pandas as pd import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter import os os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE' def PlotMeanStd(model_m, model_sd, lat_model, lon_model, observ_m, observ_sd, lat_observ, lon_observ, title, filename): proj = ccrs.PlateCarree(central_longitude=180) fig = plt.figure(1,(10, 6.7), 300) ax =plt.subplot(2, 1, 1, projection=proj) clevs = np.arange(0, 12, 2) barra = plt.cm.get_cmap('YlOrRd') ax.set_extent([0, 359, -90, 20], crs=ccrs.PlateCarree()) im = ax.contourf(lon_observ, lat_observ, observ_sd, clevs, transform=ccrs.PlateCarree(), cmap=barra, extend='max', vmin=clevs[0], vmax=clevs[-1]) barra.set_under(barra(0)) barra.set_over(barra(barra.N-1)) ax.coastlines() ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5) ax.gridlines(crs=proj, linewidth=0.3, linestyle='-') lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) CS = ax.contour(lon_observ, lat_observ, observ_m, levels=np.arange(-20, 110, 10), linewidths=0.4, colors='green', transform=ccrs.PlateCarree()) ax.clabel(CS, np.arange(-20, 110, 20), inline=1, fontsize=10, fmt='%2.0f') plt.title('ERA Interim', fontsize=10) ax =plt.subplot(2, 1, 2, projection=proj) barra = plt.cm.get_cmap('YlOrRd') ax.set_extent([0, 359, -90, 20], crs=ccrs.PlateCarree()) im = ax.contourf(lon_model, lat_model, model_sd, clevs, transform=ccrs.PlateCarree(), cmap=barra, extend='max', vmin=0, vmax=clevs[-1]) barra.set_under(barra(0)) barra.set_over(barra(barra.N-1)) ax.add_feature(cartopy.feature.COASTLINE) ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5) ax.gridlines(crs=proj, linewidth=0.3, linestyle='-') lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) CS = ax.contour(lon_model, lat_model, model_m, levels=np.arange(-20, 110, 10), linewidths=0.4, colors='green', transform=ccrs.PlateCarree()) ax.clabel(CS, np.arange(-20, 110, 20), inline=1, fontsize=10, fmt='%2.0f') plt.title('ECMWF S4', fontsize=10) plt.suptitle(title, fontsize=12, x=0.47, y=0.9) fig.subplots_adjust(right=0.8) fig.subplots_adjust(bottom=0.17, top=0.82, hspace=0.2, wspace=0.05) cbar_ax = fig.add_axes([0.33, 0.1, 0.25, 0.05]) fig.colorbar(im, cax=cbar_ax, orientation='horizontal') plt.savefig(filename, dpi=300, bbox_inches='tight', orientation='landscape', papertype='A4') plt.clf() plt.cla() plt.close() ROUTE = '~/datos/data/' FIG_PATH = '/home/users/vg140344/assessment_SH_zonal_asymmetries/figures/model_assessment/' ERAI = 'winds_erai_200.nc4' winds_erai = xr.open_dataset(ROUTE + ERAI) winds_erai.time.values = winds_erai.valid_time.values #remove data from august 2002 to february 2003 winds_erai = winds_erai.sel(time=winds_erai.time.values[np.logical_or(winds_erai.time.values<=np.datetime64('2002-07-31'), winds_erai.time.values>=np.datetime64('2003-03-01'))]) winds_erai_mean = winds_erai.sel(**{'time':slice('1981-08-01', '2018-02-01')}).groupby('time.month').mean(dim='time', skipna='True') winds_erai_sd = winds_erai.sel(**{'time':slice('1981-08-01', '2018-02-01')}).groupby('time.month').std(dim='time', skipna='True') FILE = './fogt/monthly_winds200_aug_feb.nc4' winds_s4 = xr.open_dataset(ROUTE + FILE) winds_s4_mean = winds_s4.mean(dim='realiz') winds_s4_sd = winds_s4.std(dim='realiz') lon_s4, lat_s4 = np.meshgrid(winds_s4.longitude.values, winds_s4.latitude.values) lon_erai, lat_erai = np.meshgrid(winds_erai.longitude.values, winds_erai.latitude.values) month = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb'] mm = [7, 8, 9, 10, 11, 0, 1] for i in np.arange(0, 7): title = 'U 200-hPa Mean (contour) and SD (shaded) - ' + month[i] filename = FIG_PATH + 'u200_mu_sd_' + month[i] + '.png' PlotMeanStd(winds_s4_mean.u.values[i, :, :], winds_s4_sd.u.values[i, :, :], lat_s4, lon_s4, winds_erai_mean.u.values[mm[i], :, :], winds_erai_sd.u.values[mm[i], :, :], lat_erai, lon_erai, title, filename) #seasonal means season = ['ASO', 'SON', 'OND', 'NDJ', 'DJF'] lmonth = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec'] for i in np.arange(0, 5): winds_erai_seas_mean = winds_erai['u'].sel(**{'time':slice('1981-08-01', '2018-02-01')}).resample(time='QS-' + lmonth[i]).mean(dim='time') winds_s4_smean = np.mean(winds_s4.u.values[i:i + 3, :, :, :], axis=0) mes = datetime.datetime.strptime(lmonth[i], '%b').month winds_erai_smean = winds_erai_seas_mean.sel(time= (winds_erai_seas_mean['time.month'] == mes)) title = 'U 200-hPa Mean (contour) and SD (shaded) - ' + season[i] filename = FIG_PATH + 'u200_mu_sd_' + season[i] + '.png' PlotMeanStd(np.mean(winds_s4_smean, axis=0), np.std(winds_s4_smean, axis=0), lat_s4, lon_s4, np.nanmean(winds_erai_smean, axis=0), np.nanstd(winds_erai_smean, axis=0), lat_erai, lon_erai, title, filename)
[ "marisolosman17@gmail.com" ]
marisolosman17@gmail.com
c0de6eaf5e7552a449c505f9bd7b126394fdc0fd
54fb604d26a203b4d2cd90c9d0331c052c11093d
/get_binmatrix_for_genes_in_sigclust.py
137696a4bb19be587b4b810617ad60c066ef6a9d
[]
no_license
bmmoore43/GO-term-enrichment
ee73c032b4fb7fcce16236fae3a22c775bdd3e94
e024a97047672674027f07795f0fcfd346c0bf7d
refs/heads/master
2023-02-09T13:21:26.943229
2023-02-03T17:42:29
2023-02-03T17:42:29
191,232,092
0
1
null
2023-02-03T16:51:49
2019-06-10T19:23:00
Python
UTF-8
Python
false
false
7,555
py
""" script by Bethany Moore PURPOSE: given a cluster file, pathway file, and significant enrichment file, gets binary matrix of genes vs. cluster where 1= gene is \ significantly enriched and 0= gene not enriched in a given cluster. Gene's pathway also written as second column. INPUT: REQUIRED: -cl = file with enrichment for significant clusters (from parse_enrich_get_sig_clust.py: format is filename + .fisher.pqvalue)... if you want all clusters use -cl ALL -dir = directory with cluster files where file contains: gene \t cluster -path = file with gene, pathways: path1//path2// OPTIONAL: -genes = list of genes you want to extract. This option only gets a matrix that contains clusters with this list of genes -pval = p-value cutoff for cluster significance -qval = q-value cutoff for cluster significance OUTPUT: binary matrix: filename_binmatrix.txt """ import sys, os GENE_LIST=[] QVAL="" PVAL="" for i in range (1,len(sys.argv),2): if sys.argv[i] == '-cl': sig_clust= sys.argv[i+1] if sig_clust == "ALL": pass else: sig_clust_file= open(sig_clust,'r') # file with enrichment for significant clusters if sys.argv[i] == '-dir': clustdir= sys.argv[i+1] # directory with cluster files where file contains: gene \t cluster if sys.argv[i] == '-path': path_file= open(sys.argv[i+1],'r') # file with gene, pathways: path1//path2// if sys.argv[i] == '-genes': GENE_LIST= sys.argv[i+1].strip().split(',') GENE_LIST= [i.lower() for i in GENE_LIST] if sys.argv[i] == '-qval': QVAL= float(sys.argv[i+1]) if sys.argv[i] == '-pval': PVAL= float(sys.argv[i+1]) print(GENE_LIST) def clear_quotes(string): #returns string without quotes string = string.strip() while '"' in string: string = string.replace('"',"") return string def get_sig_clusts(inp, D, PVAL, QVAL): header= inp.readline() for line in inp: L= line.strip().split('\t') fileinfo= L[0] clust= L[2] pval= L[8] qval= L[9] clust=clear_quotes(clust) clust= str(clust) print(clust) if PVAL != "": if float(pval) <= PVAL: if fileinfo not in D.keys(): D[fileinfo]=[clust] else: D[fileinfo].append(clust) elif QVAL != "": if float(qval) <= QVAL: if fileinfo not in D.keys(): D[fileinfo]=[clust] else: D[fileinfo].append(clust) else: if fileinfo not in D.keys(): D[fileinfo]=[clust] else: D[fileinfo].append(clust) return D D1={} if sig_clust != "ALL": clust_dict= get_sig_clusts(sig_clust_file, D1, PVAL, QVAL) print(clust_dict) sig_clust_file.close() def get_path_dict(inp, D): header= inp.readline().strip().split('\t') header_len= len(header) header_len2= header_len-2 for line in inp: L= line.strip().split('\t') #gene= L[0].split('.')[0].lower() gene=L[0]#.upper() gene= clear_quotes(gene) enzyme= [L[1]] if len(L)==header_len: data= L[2:] else: data=[] for i in range(header_len2): data.append("NA") data2= enzyme+data if gene not in D.keys(): D[gene]=data2 else: print(gene," duplicate gene") return D, header D2={} path_dict, pheader= get_path_dict(path_file, D2) print(path_dict) path_file.close() gene_dict={} clust_fin_list=[] all_gene_list=[] if sig_clust == "ALL": for file in os.listdir(clustdir): print(file) geneclust_file = open(clustdir+"/"+str(file)) geneclust_dict={} header= geneclust_file.readline() if file.endswith("_default_node.txt") or file.endswith("_defaultnode.txt") or file.endswith("_defaultnode_mod.txt"): print(file) clust= str(file.split("_default")[0]) print(clust) for line in geneclust_file: print(line) L= line.strip().split('\t') #gene= L[1].split('.')[0].lower() gene=L[1]#.upper() gene= clear_quotes(gene) if clust not in geneclust_dict.keys(): geneclust_dict[clust]=[gene] else: geneclust_dict[clust].append(gene) else: for line in geneclust_file: L= line.strip().split('\t') #gene= L[0].split('.')[0].lower() gene=L[0]#.upper() gene= clear_quotes(gene) clust= str(L[1]) if clust not in geneclust_dict.keys(): geneclust_dict[clust]=[gene] else: geneclust_dict[clust].append(gene) #print(geneclust_dict) geneclust_file.close() for key in geneclust_dict.keys(): genelist= geneclust_dict[key] #cluster_fin=str(file)+"_"+str(key) cluster_fin=str(key) if len(GENE_LIST)== 0: if cluster_fin not in clust_fin_list: clust_fin_list.append(cluster_fin) for gene in genelist: if gene not in gene_dict.keys(): gene_dict[gene]=[cluster_fin] else: gene_dict[gene].append(cluster_fin) if gene not in all_gene_list: all_gene_list.append(gene) else: pass else: for gene in genelist: if gene in GENE_LIST: if cluster_fin not in clust_fin_list: clust_fin_list.append(cluster_fin) for gene in genelist: if gene not in gene_dict.keys(): gene_dict[gene]=[cluster_fin] else: if cluster_fin not in gene_dict[gene]: gene_dict[gene].append(cluster_fin) else: pass if gene not in all_gene_list: all_gene_list.append(gene) else: pass else: pass else: for file in clust_dict.keys(): print(file) if file in os.listdir(clustdir): clust_list= clust_dict[file] print(clust_list) geneclust_file = open(clustdir+"/"+str(file)) geneclust_dict={} header= geneclust_file.readline() for line in geneclust_file: L= line.strip().split('\t') gene=L[0]#.upper() #gene= L[0].split('.')[0].lower() gene= clear_quotes(gene) clust= str(L[1]) if clust not in geneclust_dict.keys(): geneclust_dict[clust]=[gene] else: geneclust_dict[clust].append(gene) geneclust_file.close() for clust in clust_list: if clust in geneclust_dict.keys(): print(clust) genelist= geneclust_dict[clust] cluster_fin=str(file)+"_"+str(clust) if len(GENE_LIST)== 0: if cluster_fin not in clust_fin_list: clust_fin_list.append(cluster_fin) for gene in genelist: if gene not in gene_dict.keys(): gene_dict[gene]=[cluster_fin] else: gene_dict[gene].append(cluster_fin) if gene not in all_gene_list: all_gene_list.append(gene) else: pass else: for gene in genelist: if gene in GENE_LIST: if cluster_fin not in clust_fin_list: clust_fin_list.append(cluster_fin) for gene in genelist: if gene not in gene_dict.keys(): gene_dict[gene]=[cluster_fin] else: if cluster_fin not in gene_dict[gene]: gene_dict[gene].append(cluster_fin) else: pass if gene not in all_gene_list: all_gene_list.append(gene) else: pass else: pass print(gene_dict) output= open(str(sig_clust)+"_binmatrix.txt","w") headerstr1= "\t".join(pheader) headerstr2= "\t".join(clust_fin_list) output.write('%s\t%s\n' % (headerstr1,headerstr2)) pheadlen=len(pheader)-1 for gene in all_gene_list: gclust_list= gene_dict[gene] output.write("%s\t" % gene) if gene in path_dict.keys(): paths= path_dict[gene] #print(paths) pathstr= "\t".join(paths) else: path1=[] for i in range(pheadlen): path1.append("NA") pathstr= "\t".join(path1) output.write("%s\t" % pathstr) for clust in clust_fin_list: if clust in gclust_list: output.write("1\t") else: output.write("0\t") output.write("\n") output.close()
[ "bmjohns43@gmail.com" ]
bmjohns43@gmail.com
4ff990ad51fbbcc7a3aae361b076a5e4bf65d12a
75b1bae760da0762812890edf4e0533ba1a75f59
/sorting_algos/__init__.py
a0a4595b22c0cd53d586617fb6da2e68c208e27f
[ "MIT" ]
permissive
k-the-foodie/sorting_algos
a961af2a28fdb3c062ff028ef1a7859db9a5af93
be092484f5f07fc939ccef623a450b428571a3a0
refs/heads/master
2021-09-01T19:27:01.823036
2017-12-28T12:29:56
2017-12-28T12:29:56
114,809,788
0
0
null
null
null
null
UTF-8
Python
false
false
161
py
# -*- coding: utf-8 -*- """Top-level package for sorting_algos.""" __author__ = """Kunal Shah""" __email__ = 'kunal.shah.1993@gmail.com' __version__ = '0.1.0'
[ "kunal.shah.1993@gmail.com" ]
kunal.shah.1993@gmail.com
a16a54b32b0c5ced26c25d966e195d7cc4a0be04
bd6ab3c6bcb774d7c00549a9dad7aea4ffcb646f
/parser.py
3e6de07eddfddcd086663c3162e014782e0920b9
[]
no_license
dfmorse23/SPD1.5Project
eb5b539053cbd1c5309fdfff4789aec8e8624e9e
e60db763525c9e6ffee89fed9ad2cdec8f896dd8
refs/heads/master
2022-11-16T02:10:25.809032
2020-07-17T01:59:06
2020-07-17T01:59:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,467
py
import sys from cmd import Cmd import pandas as pd class Data(): def __init__(self, filename): self.dataName = filename self.df = pd.read_csv(filename) self.df_name = "df" self.transformed_data = "" self.transformed = 0 self.kmeans = 0 self.target = 0 self.returnList = [] pass def _add(self, str, indent=0): for i in range(0, indent): str = " " + str self.returnList.append(str) return self._add def _endblock(self): self.returnList.append("") def _dataProcesses(self): self._add("import pandas as pd")("import numpy as np")("import matplotlib.pyplot as plt")("import seaborn as sns") self._add("{} = pd.read_csv({})".format(self.df_name, self.dataName)) self._endblock() def _drop(self, col): # Col = list of columns self._add("{} = {}.drop(columns={})".format(self.df_name, self.df_name, list(col))) self._endblock() def _target(self, tar): # Tar = string name of column self.target = 1 self._add("en_target = {}[{}]".format(self.df_name, tar)) self._endblock() def _newdf(self, newname): self._add("{} = {}".format(newname, self.df_name)) self.df_name = newname self._endblock() self.target = 1 def _scaleData(self): if self.transformed == 0: self._add("from sklearn.preprocessing import StandardScaler") self.transformed_data = "data_transformed" self.transformed = 1 self._add("scalar = StandardScaler()")("data_transformed = scalar.fit_transform({})".format(self.df_name)) self._endblock() def _kMeans(self, range=10): if self.kmeans == 0: self._add("import numpy as np")("from scipy.spatial import distance") self.kmeans = 1 self._add("dis = []")("K = range(1, {})".format(range))("for k in K:") self._add("km = KMeans(n_clusters=k)", 1)("km.fit({})".format(self.transformed_data), 1)("dis.append(sum(np.min(distance.cdist({}, km.cluster_centers_, 'euclidean'), axis=1)) / {}.shape[0])".format(self.transformed_data, self.transformed_data), 1) self._add("plt.plot(K, dis, 'bx-')")("plt.xlabel('k')")("plt.ylabel('Distortion')")("plt.title('The Elbow Method showing the optimal k')")("plt.show()") self._endblock() def _corre(self): self._add("data_corelation = {}.corr()".format(self.df_name))("sns.heatmap(data_corelation)") self._endblock() def _linearReg(self, col1, col2): self._add("from sklearn.model_selection import train_test_split")("X = np.array({}['{}'])".format(self.df_name, col1))("y = np.array({}['{}'])".format(self.df_name, col2)) self._add("X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)") self._endblock() self._add("from sklearn.linear_model import LinearRegression")("from sklearn.metrics import r2_score") self._endblock() self._add("reg = LinearRegression()")("X_train = np.array(X_train).reshape(-1, 1)")("y_train = np.array(y_train).reshape(-1, 1)") self._endblock() self._add("X_test = np.array(X_test).reshape(-1, 1)")("testvals = reg.predict(X_test)") self._add("")("print(reg.coef_)")("print(Tax_reg.intercept_)")("print(Tax_reg.score(X_test, y_test))") self._endblock() def _prepca(self, tar): if self.target == 0: self._target(tar) self._drop(tar) self._scaleData() self._endblock() def _pca(self): self._add("from sklearn.decomposition import PCA")("pca = PCA(n_components=2)")("principalComponents = pca.fit_transform({})".format(self.transformed_data)) self._add("principalDf = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2'])") self._add("finalDf = pd.concat([principalDf, en_target], axis=1)") self._endblock() def _logreg(self, col): self._add("feature_cols = {}".format(col))("X = pima[feature_cols]")("y = pima[{}]".format("en_target")) self._add("X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)") self._endblock() self._add("from sklearn.linear_model import LogisticRegression")("logreg = LogisticRegression()")("logreg.fit(X_train, y_train)") self._endblock() self._add("y_pred = logreg.predict(X_test)") class Shell(Cmd): prompt = 'Data Shell: ' def _(self, c): return c.split(" ") def __init__(self, filename): super().__init__() self.data = Data(filename) self.data._dataProcesses() def do_exit(self, np): return True def emptyline(self): pass def do_show(self, np): print(self.data.df) def do_drop(self, np): np = self._(np) self.data._drop(np) self.data.df.drop(columns=np) def do_linearreg(self, np): np = self._(np) if len(np) < 2: print("Please enter two valid column names.") return 0 self.data._linearReg(np[0], np[1]) def do_kmeans(self, np): if self.data.transformed == 0: self.data._scaleData() self.data._kMeans() def do_return(self, np): for i in self.data.returnList: print(i) return True def do_new(self, np): np = self._(np) if len(np) < 1: print('Please enter a valid dataframe name') return 0 self.data._newdf(np[0]) self.data.transformed = 0 def do_pca(self, np): np = self._(np) if self.data.target == 0: print("Please define a target column") return self.data._prepca(np[0]) self.data._pca() def do_logreg(self, np): np = self._(np) if self.data.target == 0: print("Please define a target column") return if len(np) < 1: print("Please enter the columns you want to log reg") return self.data._logreg(np) def do_target(self, np): np = self._(np) if len(np) < 1: print("Please enter target column") self.data._target(np[0]) self.data._drop(np[0]) if __name__ == '__main__': dt = Shell(sys.argv[1]) dt.cmdloop()
[ "darkblackvoid@yahoo.com" ]
darkblackvoid@yahoo.com
cd3e2be0a15ce970152bebec2f952ca08d0ba242
f94ab3b7b7468979494e6825bdace1e72fbff16a
/recoverTree.py
e582ec4d6217371cde88ee2d754a21c3be147a90
[]
no_license
sbsreedh/Trees-5
0527362c4f272f6ee281505940c86c6e334e7263
a185930839657bb8dc30ea4676be24d64396fb4e
refs/heads/master
2022-11-08T15:05:32.260309
2020-06-13T19:04:10
2020-06-13T19:04:10
271,957,655
0
0
null
2020-06-13T06:57:14
2020-06-13T06:57:14
null
UTF-8
Python
false
false
2,313
py
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right #Time Complexity:O(N) #SC:O(N) #Algorithm: #1.Explore left children assign the last encountered root as prev. and the previous level node as root. If there is no children further return and explore right side. #2. if at any time of you see prev.val<root.val, there is a breach, we set first, mid and last pointer and do swap accordingly. class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return self.prev=None self.first=None self.last=None self.mid=None self.flag=False self.inorder(root) if self.last and self.first: temp=self.last.val self.last.val=self.first.val self.first.val=temp elif self.first : temp=self.mid.val self.mid.val=self.first.val self.first.val=temp # def inorder(self,root): # stack=[] # while root or stack: # while root: # stack.append(root) # root=root.left # root=stack.pop() # if self.prev and root.val<self.prev.val: # if not self.flag: # self.flag=True # self.first=self.prev # self.mid=root # else: # self.last=root # self.prev=root # root=root.right def inorder(self,root): if not root: return self.inorder(root.left)#SC:O(1), no extra space # stack=[] # while root or stack: # while root: # stack.append(root) # root=root.left # root=stack.pop() if self.prev and root.val<self.prev.val: if not self.flag: self.flag=True self.first=self.prev self.mid=root else: self.last=root self.prev=root self.inorder(root.right)
[ "noreply@github.com" ]
sbsreedh.noreply@github.com
1bffcbb02c72f33a80496f918b1d05e1419a2fd8
c2e93819a7f469cd5ac2828487598abd9f315739
/event/migrations/0001_initial.py
72afc4fbd76e138255be6af5c5eaeead7db4e829
[]
no_license
DanikNik/urfu
887be900a417f4db8aae8f784f2bd6edd42669d8
32fe566025c510940f73a2f3d740cef4bb5fa49c
refs/heads/master
2020-03-25T18:04:28.915761
2018-09-06T07:33:22
2018-09-06T07:33:22
144,011,917
0
0
null
null
null
null
UTF-8
Python
false
false
1,203
py
# Generated by Django 2.1 on 2018-08-23 14:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('account', '0004_auto_20180823_1346'), ] operations = [ migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='event.Event')), ('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.Person')), ], ), migrations.AddField( model_name='event', name='members', field=models.ManyToManyField(through='event.Membership', to='account.Person'), ), ]
[ "nikolsky.dan@gmail.com" ]
nikolsky.dan@gmail.com
a2ef8bc783f0d38289453a9c786deca1dfdffe58
d83f9719409383c664f5e85657618e5000b1b539
/jenkins1.py
ddc3c7b827e02aa759269aeb83be32d2f2e5ecf8
[]
no_license
shrish1111/jenkins_projects
89dc0c8721719ea6809c931f54260b4818aecda0
c8bb914edd4da11c738bbc9df217da8ff1784c4c
refs/heads/master
2020-05-05T03:32:20.619300
2019-05-07T20:20:44
2019-05-07T20:20:44
179,676,609
0
0
null
null
null
null
UTF-8
Python
false
false
59
py
#this is a test project1 print("hi, this is project one")
[ "shrish.chamoli@gmail.com" ]
shrish.chamoli@gmail.com
8d10d73283042f260c275caa78cfa0a123a6d152
7508a7c68b19259743729779219ed83c94e8a820
/geoscan_ws/src/gs_logger/setup.py
546df4f980aa33f2d8e4e1e6b16c83e7582299d8
[]
no_license
ITMO-lab/geoscan_pioneer_max
0a9946f26fd4228c3694e08934df9975cb30e5ce
a25fefad94e7b389d8d040a6d32e7d8388866131
refs/heads/master
2022-11-27T06:29:07.571265
2020-08-07T15:25:52
2020-08-07T15:25:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
190
py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup() d['packages'] = ['gs_logger'] setup(**d)
[ "ilya@eadsoft.com" ]
ilya@eadsoft.com
b73c9813a5eeeefc76d8a3e11dbda6456ee83c45
539d84c6f3ee281787ed50883ef748e827c8637e
/4th/homework_9/id_69/322-CoinChange.py
99f391847588d587c195a53e014676e1fe3b7657
[]
no_license
StuQAlgorithm/AlgorithmHomework
513678422ff4a984b90d137d7dabe075d23f5dcf
88da6b274e49ce97d432e1f4d4de8efa55593836
refs/heads/master
2021-01-21T06:52:35.934321
2017-10-09T02:12:52
2017-10-09T02:12:52
101,950,372
6
12
null
2017-10-09T02:12:53
2017-08-31T02:31:32
Python
UTF-8
Python
false
false
2,201
py
# https://leetcode.com/problems/coin-change/description/ # You are given coins of different denominations and a total amount of money amount. # Write a function to compute the fewest number of coins that you need to make up that amount. # If that amount of money cannot be made up by any combination of the coins, return -1. # Example 1: # coins = [1, 2, 5], amount = 11 # return 3 (11 = 5 + 5 + 1) # Example 2: # coins = [2], amount = 3 # return -1. # Note: # You may assume that you have an infinite number of each kind of coin. # Credits: # Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. import sys from collections import deque class Solution(object): # dp def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ if not coins: return -1 if amount == 0: return 0 MAX = 0x7fffffff # Using float("inf") would be slower. dp = [0] + [MAX] * amount for i in range(1, amount + 1): dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1 return dp[amount] if dp[amount] < MAX else -1 # [dp[amount], -1][dp[amount] == MAX] # bst def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ if not coins: return -1 if amount == 0: return 0 value = deque([0]) size = len(value) count = 0 visited = set(value) while value: count += 1 for i in range(size): v = value.popleft() for coin in coins: newval = v + coin if newval == amount: return count elif newval > amount: continue elif newval not in visited: visited.add(newval) value.append(newval) size = len(value) return -1 if __name__ == '__main__': sol = Solution() print(sol.coinChange([1],1)) # [1], 0 ; [1],1 ; [1,2,5], 100
[ "lyl.lucas@gmail.com" ]
lyl.lucas@gmail.com
24460fde23af0571b0746245d8b896480757ab02
ccad086a2c92209052e2d6c16229a5b4957f8b40
/GameTutorial.py
5b87eac4bb22cc7a196bc6f27590b1e0051a6709
[]
no_license
rat-and-rojangles/Luigi-s-Universe
48b3d1d2581b54305c19b6429b57f1b4e23a6ef6
c4c34f65d2923c5cec5a376d7ff89ce07c97a889
refs/heads/master
2021-05-31T12:28:05.138033
2016-02-27T23:18:15
2016-02-27T23:18:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,179
py
import pygame from pygame.locals import * import sys, os, math, random import MainScreen from LevelTutorial import * from Enemy import * from HUD import * from TextOption import * WHITE=(255,255,255) GRAY=(127,127,127) BLACK=(0,0,0) RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255) LIGHT_RED=(255,127,127) LIGHT_GREEN=(127,255,127) LIGHT_BLUE=(127,127,255) DRAWPRIORITY=["crashman","pipe","enemy"] FPS = 30 pygame.mixer.init() unpauseSound=pygame.mixer.Sound('sound/unpause.wav') def RelRect(actor, camera): return pygame.Rect(actor.rect.x-camera.rect.x, actor.rect.y-camera.rect.y, actor.rect.w, actor.rect.h) class Camera(object): '''Class for center screen on the player''' def __init__(self, screen, player, level): self.player = player self.rect = screen.get_rect() self.rect.center = self.player.center self.world_rect = level.world_rect def update(self): if self.player.centerx > self.rect.centerx + 25: self.rect.centerx = self.player.centerx - 25 if self.player.centerx < self.rect.centerx - 25: self.rect.centerx = self.player.centerx + 25 if self.player.centery > self.rect.centery + 25: self.rect.centery = self.player.centery - 25 if self.player.centery < self.rect.centery - 25: self.rect.centery = self.player.centery + 25 self.rect.clamp_ip(self.world_rect) def draw_sprites(self, surf, sprites): for s in sprites: if s.rect.colliderect(self.rect): if s.type=="block" and s.bumping: surf.blit(s.image, (RelRect(s, self).x,RelRect(s, self).y+s.bumpDisp)) if s.bumpDisp==0 and s.bumpDirection>0: s.bumping=False s.bumpDisp=0 s.bumpDirection=-3 elif s.bumpDisp==-12: s.bumpDirection=3 s.bumpDisp=-9 else: s.bumpDisp+=s.bumpDirection else: surf.blit(s.image, RelRect(s, self)) #crashman is always on top. pipes are next priority, then enemies def draw_sprites_prio(self, surf, sprites, crashman): for s in sprites: if s.rect.colliderect(self.rect): if s.type not in DRAWPRIORITY: if s.type=="block" and s.bumping: surf.blit(s.image, (RelRect(s, self).x,RelRect(s, self).y+s.bumpDisp)) if s.bumpDisp==0 and s.bumpDirection>0: s.bumping=False s.bumpDisp=0 s.bumpDirection=-3 elif s.bumpDisp==-12: s.bumpDirection=3 s.bumpDisp=-9 else: s.bumpDisp+=s.bumpDirection else: surf.blit(s.image, RelRect(s, self)) for s in sprites: if s.rect.colliderect(self.rect): if s.type=="enemy": surf.blit(s.image, RelRect(s, self)) for s in sprites: if s.rect.colliderect(self.rect): if s.type=="pipe": surf.blit(s.image, RelRect(s, self)) surf.blit(crashman.image,RelRect(crashman,self)) #message with stransparent bg def messageScreenOverlay(screen, message): fontObj=pygame.font.Font('gamefiles/OCRAEXT.TTF', 32) textSurfaceObj=fontObj.render(message, False, WHITE) textShadow=fontObj.render(message, False, BLACK) textRectObj=textSurfaceObj.get_rect() textRectObj.center=screen.get_rect().center screen.blit(textShadow,(textRectObj[0],textRectObj[1]+2)) screen.blit(textShadow,(textRectObj[0],textRectObj[1]-2)) screen.blit(textShadow,(textRectObj[0]+2,textRectObj[1])) screen.blit(textShadow,(textRectObj[0]-2,textRectObj[1])) screen.blit(textSurfaceObj,textRectObj) pygame.display.update() waitForKey() def drawRenderedMessage(screen, messageImg, messageShadow, rect): screen.blit(messageShadow,(rect[0],rect[1]+2)) screen.blit(messageShadow,(rect[0],rect[1]-2)) screen.blit(messageShadow,(rect[0]+2,rect[1])) screen.blit(messageShadow,(rect[0]-2,rect[1])) screen.blit(messageImg,rect) pygame.display.update() def waitForKey(): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: return def waitForKeys(keyConstants): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP and (event.key in keyConstants): return def waitForKeysDown(keyConstants): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key in keyConstants): return def pauseScreen(screen, character): pygame.mixer.music.pause() TextOption.pauseSound.play() rawBG=pygame.image.load("menu/darkenScreen.png") bgImg= pygame.transform.scale(rawBG, (1024,600)) bgRect=bgImg.get_rect() bgRect.center=(512,300) screen.blit(bgImg,bgRect) pygame.display.flip() #one third of the way from the top titleLogoImage=pygame.image.load("menu/pause.png").convert_alpha() titleLogoRect=titleLogoImage.get_rect() titleLogoRect.center=(512,bgRect.height/3) options=(TextOption("Resume","resume"),TextOption("Restart Tutorial","restart"),TextOption("Main Menu","mainmenu"),TextOption("QUIT","quit")) options[3].setSelectedColor(RED) #options[2].setUnselectedColor(GRAY) #alignment of menu options verticalspace=bgRect.height-titleLogoRect.bottom heightOfOptions=0 for op in options: heightOfOptions=heightOfOptions+op.rect.height+5 currentY=int((verticalspace-heightOfOptions)/2+titleLogoRect.bottom) for op in options: op.rect.top=currentY currentY=currentY+op.rect.height+5 selectedIndex=0 screen.blit(bgImg,bgRect) screen.blit(titleLogoImage,titleLogoRect) while True: #think of condition later for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() #control selection if event.type == KEYDOWN and event.key == K_UP: TextOption.cursorSound.play() if selectedIndex==0: selectedIndex=len(options)-1 else: selectedIndex-=1 if event.type == KEYDOWN and event.key == K_DOWN: TextOption.cursorSound.play() if selectedIndex==len(options)-1: selectedIndex=0 else: selectedIndex+=1 if event.type == KEYDOWN and event.key == K_ESCAPE: unpauseSound.play() pygame.mixer.music.unpause() return if event.type == KEYDOWN and event.key == K_RETURN: TextOption.selectSound.play() if options[selectedIndex].action=="resume": unpauseSound.play() pygame.mixer.music.unpause() return elif options[selectedIndex].action=="restart": unpauseSound.play() pygame.mixer.music.unpause() pygame.mixer.music.rewind() pygame.mixer.music.play(-1) playGame(screen,character,"Welcome to Luigi's Universe. \nHit the ? blocks for more information.") elif options[selectedIndex].action=="mainmenu": MainScreen.titleScreen(screen,character) elif options[selectedIndex].action=="quit": pygame.quit() sys.exit() for op in options: op.selected=False options[selectedIndex].selected=True #screen.blit(bgImg,bgRect) #screen.blit(titleLogoImage,titleLogoRect) for op in options: op.draw(screen) pygame.display.flip() def objectiveProgress(oType,numDefeated,totalTime): if oType=="exterminate": return numDefeated elif oType=="survival": return totalTime def objectiveComplete(oCount,oMax): if oCount>=oMax: return True else: return False def tps(orologio,fps): temp = orologio.tick(fps) tps = temp / 1000. return tps def splashscreen(screen,image,rect): screen.blit(image,rect) pygame.display.flip() waitForKeysDown((K_ESCAPE,K_SPACE,K_RETURN)) def playGame(screen, character, currentInfoText): screen_rect = screen.get_rect() level = LevelTutorial("level/tutorial/tutorial.txt", character, currentInfoText) world = level.world crashman = level.crashman pygame.mouse.set_visible(True) camera = Camera(screen, crashman.rect, level) all_sprite = level.all_sprite clock = pygame.time.Clock() up = down = left = right = False x, y = 0, 0 #randomly selects an enemy port enemy_list=[] activePortIndex=random.randrange(len(level.enemy_ports)) activePort=level.enemy_ports[activePortIndex] #untilNextSpawn=level.spawn_delay untilNextSpawn=0 totalTime=0 enemyCount=0 hud=HUD() #this is the while true loop while crashman.alive : for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_ESCAPE or event.key==K_RETURN): up=down=left=right=False pauseScreen(screen,character) #control crashman keys = pygame.key.get_pressed() #checking pressed keys if keys[pygame.K_UP] or keys[pygame.K_SPACE]: up=True else: up=False if keys[pygame.K_DOWN]: down=True else: down=False if keys[pygame.K_LEFT]: left=True else: left=False if keys[pygame.K_RIGHT]: right=True else: right=False #sequential spawn order if untilNextSpawn<=0 and enemyCount<level.enemy_max: print "ENEMY HERE NOW" e=Enemy(activePort[0],activePort[1],activePort[2],level) enemy_list.append(e) level.all_sprite.add(e) world.append(e) activePortIndex+=1 if activePortIndex>=len(level.enemy_ports): activePortIndex=0 activePort=level.enemy_ports[activePortIndex] untilNextSpawn=level.spawn_delay enemyCount+=1 #random spawn order """if untilNextSpawn<=0 and enemyCount<level.enemy_max: print "ENEMY HERE NOW" e=Enemy(activePort[0],activePort[1],activePort[2],level) enemy_list.append(e) level.all_sprite.add(e) world.append(e) activePortIndex=random.randrange(len(level.enemy_ports)) activePort=level.enemy_ports[activePortIndex] untilNextSpawn=level.spawn_delay enemyCount+=1""" #removes dead enemies for e in enemy_list: if e.alive==False: print "ded del thjo" enemy_list.remove(e) all_sprite.remove(e) world.remove(e) enemyCount-=1 if e.freshkick==True: hud.enemies_defeated+=1 hud.update() e.freshkick=False #timer and spawn countdown #updates hud time tpt = tps(clock, FPS) totalTime+=tpt if hud.time!=math.floor(totalTime): hud.time=math.floor(totalTime) hud.update() if enemyCount<level.enemy_max: untilNextSpawn-=tpt print str(enemyCount)+": "+str(untilNextSpawn) #DRAW ORDER: #bg, world, elemental, hud #camera.draw_sprites(screen, all_sprite) level.drawBG(screen) camera.draw_sprites_prio(screen, all_sprite, crashman) if level.elemental: level.elementalOverlay.draw(screen) hud.draw(screen) level.drawInfo(screen) #final updates crashman.update(up, down, left, right) for e in enemy_list: e.update(tpt) camera.update() pygame.display.flip() ################################# #game complete #pygame.display.flip() playGame(screen,character, level.currentInfoBlock.infoText)
[ "starfox139@yahoo.com" ]
starfox139@yahoo.com
91117b19352d55ffd475a2a6b3864904f968a699
2fb888de6aefd029cffff9a2f4894035d16ce6d5
/myapp/views.py
00e9711f910035c70ae86b3d6bfe76737bad1cd2
[]
no_license
Changolaxtra/djangoTest1
ad6251b4797aaeb0582adfbd19d59cd56ff1e251
c4ea932c5b9d7f8924f390ffbac304fa7f619b8f
refs/heads/master
2022-12-28T08:46:38.670302
2020-09-23T04:27:19
2020-09-23T04:27:19
297,848,547
0
0
null
null
null
null
UTF-8
Python
false
false
351
py
from django.shortcuts import render from django.http import HttpResponse from .models import Book # Create your views here. def index(request): book_list = Book.objects.all() context = { 'book_list': book_list } return render(request, 'myapp/index.html', context) def products(request): return HttpResponse('Products')
[ "dan.rojasx@gmail.com" ]
dan.rojasx@gmail.com
59bc43fe1887c763a42db251c74f7dc8883f6ca0
501c60d76cc3091dc5e0784391275d7801397c2c
/agedBrie.py
6e0100f94908af8ab0e674f259066b753e88f3c6
[]
no_license
patezno/Gilded-rose
18063241d9cf0d4616c49e98838020e06135d910
be6dd4177b0372b78fbe53b0f491d9ed9563f312
refs/heads/master
2020-04-15T12:52:50.150554
2019-02-14T18:27:22
2019-02-14T18:27:22
164,690,624
0
0
null
null
null
null
UTF-8
Python
false
false
344
py
from regularItem import RegularItem class AgedBrie(RegularItem): def update_quality(self): if self.getSellIn() >= 0: self.setQuality(1) else: self.setQuality(2) if __name__ == '__main__': # test case 1 pato = AgedBrie('pato', 9, 4) pato.update_quality() pato.getQuality() == 5
[ "patezno97@gmail.com" ]
patezno97@gmail.com
98d60b21a5c679f28850ad8f5ff63c51f628bec9
8fa938eddcc75eb7dff1f2055c49cb3817a00c63
/Basic - Part1/ex25.py
401a85059bdce57303b2f6a7d352f47c800826bd
[]
no_license
jayhebe/w3resource_exercises
f27109759d112b0611574aa70eb378ace447c2a0
b29aa7c806f6021a8988e83bb9f674522a41380d
refs/heads/master
2020-05-07T09:23:24.039271
2020-01-30T15:05:06
2020-01-30T15:05:06
180,374,062
2
0
null
null
null
null
UTF-8
Python
false
false
270
py
def value_in_group(group, value): if value in group: return True else: return False if __name__ == '__main__': print(value_in_group([1, 2, 3, 4], 3)) print(value_in_group([2, 3, 4, 5], 3)) print(value_in_group([2, 3, 4, 5], 8))
[ "jayhebe1983@sina.com" ]
jayhebe1983@sina.com
ca16cb570cabc3a43ee4ced4dde4251c62ad535f
cd6780f8df34207eb21983c98cfb18981a42a284
/intermediate-project-/code.py
d2fa3f6f5ab1d810e42e6896c6ea334c97df9205
[ "MIT" ]
permissive
Manan-1226/greyatom-python-for-data-science
ca6bd3d2c7085eca706fd0ab31ee8221618a14b2
815745f17873d4811d8d437e638bfbefaccfcfae
refs/heads/master
2022-11-06T23:54:05.334034
2020-06-28T04:22:35
2020-06-28T04:22:35
269,128,612
0
0
null
null
null
null
UTF-8
Python
false
false
4,123
py
# -------------- #Code starts here #Function to read file def read_file(path): #Opening of the file located in the path in 'read' mode file = open(path,'r') #Reading of the first line of the file and storing it in a variable sentence = file.readline() #Closing of the file file.close() #Returning the first line of the file return (sentence) #Calling the function to read file sample_message = read_file(file_path) #Printing the line of the file print(sample_message) message_1 = read_file(file_path_1) message_2 = read_file(file_path_2) print (message_1,message_2) #Function to fuse message def fuse_msg(message_a,message_b): #Integer division of two numbers a=int(message_a) b=int(message_b) #Returning the quotient in string format quotient = b//a return(str(quotient)) #Calling the function to read file message_1 = read_file(file_path_1) #Calling the function to read file message_2 = read_file(file_path_2) #Calling the function 'fuse_msg' secret_msg_1 = fuse_msg(message_1,message_2) #Printing the secret message print(secret_msg_1) #Function to substitute the message def substitute_msg(message_c): sub = 'nothing' #If-else to compare the contents of the file if(message_c =='Red'): sub = 'Army General' elif(message_c == 'Green'): sub = 'Data Scientist' else: sub = 'Marine Biologist' #Returning the substitute of the message return(sub) #Calling the function to read file message_3 = read_file(file_path_3) print(message_3) #Calling the function 'substitute_msg' secret_msg_2 = substitute_msg(message_3) #Printing the secret message print(secret_msg_2) #Function to compare message def compare_msg(message_d,message_e): #Splitting the message into a list a_list = message_d.split() #Splitting the message into a list b_list = message_e.split() #Comparing the elements from both the lists c_list = [ i for i in a_list if i not in b_list] #Combining the words of a list back to a single string sentence final_msg = " ".join(c_list) #Returning the sentence return(final_msg) #Calling the function to read file message_4 = read_file(file_path_4) print(message_4) #Calling the function to read file message_5 = read_file(file_path_5) print(message_5) #Calling the function 'compare messages' secret_msg_3 = compare_msg(message_4,message_5) #Printing the secret message print(secret_msg_3) #Function to filter message def extract_msg(message_f): #Splitting the message into a list a_list = message_f.split() #Creating the lambda function to identify even length words even_word = lambda x : len(x)%2==0 #Splitting the message into a list b_list = list(filter(even_word,a_list)) #print(b_list) #Combining the words of a list back to a single string sentence final_msg = " ".join(b_list) #Returning the sentence return(final_msg) #Calling the function to read file message_6 = read_file(file_path_6) print(message_6) #Calling the function 'filter_msg' secret_msg_4 = extract_msg(message_6) #Printing the secret message print(secret_msg_4) #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] # define the path where you final_path= user_data_dir + '/secret_message.txt' #Combine the secret message parts into a single complete secret message secret_msg = " ".join(message_parts) #Function to write inside a file def write_file(secret_msg,path): #Opening a file named 'secret_message' in 'write' mode f=open(path,'a+') #Writing to the file f.write(secret_msg) #Closing the file f.close() #Calling the function to write inside the file write_file(secret_msg,final_path) #Printing the entire secret message print(secret_msg) #Code ends here
[ "Manan-1226@users.noreply.github.com" ]
Manan-1226@users.noreply.github.com
94edcc6d24f273466db2cb36c4e6537a754ee8c7
b1e554cc2f73896da2474e6229dc865c2e291906
/app/core/migrations/0002_tag.py
b7f7bd0af4f9d13930386a810171f4c2886ce946
[ "MIT" ]
permissive
Justoo1/recipe-app-api
0d8a2854588c6e00193633112aedc6075393a330
91282b8bc993e7871dfff28feca5110ef76d370f
refs/heads/master
2022-12-18T13:07:52.810958
2020-09-23T04:15:42
2020-09-23T04:15:42
296,110,694
0
0
null
null
null
null
UTF-8
Python
false
false
683
py
# Generated by Django 2.1.15 on 2020-09-21 09:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "amankrahjay@gmail.com" ]
amankrahjay@gmail.com
00449eccc8ef7abf5c0b1a98674c42fbd5bcfb81
033841f8c0ee04bbefa628c12acef15607501f0e
/assignment1/variables.py
92b72c6134f8aec14cd0acc1292344605e005a02
[]
no_license
jwsawyer87/hello-world
d341e25b707e503b2cf98e17e873313a8cd448fc
0737299285c7b9e5ba619800d1e3cb01396b2522
refs/heads/master
2020-04-21T10:53:00.959797
2019-02-23T15:14:07
2019-02-23T15:14:07
169,501,059
1
1
null
2019-02-07T14:23:48
2019-02-07T01:00:16
null
UTF-8
Python
false
false
32
py
shoe_size=10 print (shoe_size)
[ "Trish@Trishas-MBP.attlocal.net" ]
Trish@Trishas-MBP.attlocal.net
6a3d9bef64ac5e972b4d4a898b8e65e546cfa9fa
59a6cae7f00a44af899067d5282fcdfc1aaf97aa
/lists/tests.py
c17fdc109816d730f672450e8ceb6b3fe439cae2
[]
no_license
gboned/gboned
71893fe56ed5b4665e0bec2ce1705155c5caebc2
04206503f71a902ec5266807e4463a2868dc00c5
refs/heads/master
2021-05-20T13:04:33.637892
2020-04-02T02:42:43
2020-04-02T02:42:43
252,309,485
0
0
null
null
null
null
UTF-8
Python
false
false
1,280
py
from django.urls import resolve from django.test import TestCase from django.http import HttpRequest from lists.views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): # resolve es la función que Django usa internamente para resolver la URL # y encontrar cuál función de view debe mapear found = resolve('/') # Comprobamos que "/" (la raíz de la página) encuentra una función llamada home_page self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): # Creamos objeto HttpRequest, que es lo que Django ve cuando el navegador de un # usuario pide una página request = HttpRequest() # Lo pasamos a nuestra vista home_page, que devuelve una respuesta response = home_page(request) # Extraemos el .content de la respuesta, con decode lo convertimos a HTML html = response.content.decode('utf8') # El fichero HTML debe empezar con <html> self.assertTrue(html.startswith('<html>')) # Debe contener el título de la página self.assertIn('<title>To-Do lists</title>', html) # Y debe terminar con </html> self.assertTrue(html.endswith('</html>'))
[ "gboned@cifpfbmoll.eu" ]
gboned@cifpfbmoll.eu
ae07dc6b69c91b9aebdc683249dee11c47e0b6fe
6a1d1ac076a3d5a8c8bb2f5bd52facb52e98bbc4
/tests/test_all.py
b991996a67ab47d76d4fe3177b4c24b01b528c69
[ "MIT" ]
permissive
DanLindeman/ConferenceScheduler
c7184fb43bbfcb78d279b729f1b99d82542a62a9
c54be5f545d4742ef9468797ce473e0a4590cb45
refs/heads/master
2016-09-08T00:28:43.924594
2015-08-02T17:51:25
2015-08-02T17:51:25
40,087,708
0
0
null
null
null
null
UTF-8
Python
false
false
406
py
"""Sample integration test module.""" # pylint: disable=no-self-use import unittest from conference_scheduler import sample class TestConference_scheduler(unittest.TestCase): """Sample integration test class.""" def test_network_stuff(self): assert sample.function_with_network_stuff() is True def test_disk_stuff(self): assert sample.function_with_disk_stuff() is False
[ "lindemda@gmail.com" ]
lindemda@gmail.com