blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2
values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107
values | src_encoding stringclasses 20
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 4 6.02M | extension stringclasses 78
values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65ac8f89ebae6060700a99c9045854f6270f1016 | 669f7a51a4f44f8b116cb6e0ef67eb1bd3f2e213 | /profile/migrations/0004_auto_20150516_0404.py | 2e9100839bbc85e1bcdf27e5483c1ae766b3854a | [] | no_license | lijianmin/PortalProject | 19581aa232569f15780e0710ab142198762e9fd3 | ac419c5a6cda0a4b70c558412f43332de8a63dbd | refs/heads/master | 2020-05-18T04:45:54.654445 | 2015-09-11T02:12:01 | 2015-09-11T02:12:01 | 27,471,598 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 476 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('profile', '0003_auto_20150516_0343'),
]
operations = [
migrations.AddField(
model_name='clinicianprofile',
name='clinic_of_practice',
field=models.ForeignKey(default=1, to='profile.Clinic'),
preserve_default=False,
),
]
| [
"li.jianmin@outlook.com"
] | li.jianmin@outlook.com |
e155c56c8ce10e75791d2759b9b55b3147c39156 | b01d41cd9f3de55ffa2cfe15150e14eb923ebe9d | /aluguel_functions.py | c7ac28707ba2b44d40b8e3de9409a35a00075a30 | [] | no_license | dem19/cod1 | 5b9e9d9c9cb61e4edd43800e1e0c20a50f7b8fd3 | 59cdb83800d0741a2eebef57c9aef354cdba7e65 | refs/heads/master | 2020-08-05T20:43:24.544351 | 2019-10-03T23:56:22 | 2019-10-03T23:56:22 | 212,703,242 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,806 | py | # Lista de carros disponíveis para locação
carros = [['Ferrari', 1220.00], ['Hilux', 150.00], ['Golf', 80.00], ['Amarok', 150.00], ['Cobalt', 60.00],
['Punto', 60.00], ['New Fiesta', 60.00], ['Focus', 100.00], ['S10', 150.00], ['Corolla', 100.00]]
# Lista de carros disponíveis
carros_disponiveis = carros
# Lista de carros alugados
carros_alugados = []
# Histórico de locação
historico = []
def pesquisa(nome):
name = nome.lower()
for d, e in enumerate(carros):
if e[0].lower() == name:
return d
return None
def c_disponivel():
lista=list(carros_disponiveis)
print(lista)
# Item 2 resolvido
def c_alugado():
lista = list(carros_alugados)
print(lista)
def ver_carros():
p = pesquisa((input("Nome: ")))
if p != None:
lista = list(carros)
print(lista[p])
def alugar_carros():
print("Alugar um carro")
nome = input("Qual é o seu nome: ")
p = pesquisa((input("Qual é a marca do carro: ")))
if p != None:
lista = list(carros)
print(nome," - Alugol a:",lista[p])
carros_disponiveis.pop(p)
carros_alugados.append(lista[p])
historico.append(lista[p]+[nome])
print("Carro Alugado")
def D_carro():
dias = float(input('O carro foi alugado por quantos dias? '))
km = float(input('Quantos km foram rodados? '))
preco = float(input('Qual é o preço por dia do carro? '))
pkl = float(input('Qual é o preço por km do carro? '))
d = dias * preco
k = km * pkl
total = d + k
print(total, "a pagar!")
print("Carro devolvido")
def exibe_historico():
for locacao in historico:
print('Carro: ', locacao[0], 'Valor: ',
locacao[1], 'Locatário: ', locacao[2])
| [
"dem19vieira@gmail.com"
] | dem19vieira@gmail.com |
d6312b5a597df9bc5ff3924b57d6b30e9061caea | cd73b6a44c2b891f24be427d9b0abe6ebf4221b3 | /ingestion/4.ingest_drivers_file.py | 4937b9fb06bc589e5c1d6472150016bb2fe60ca6 | [] | no_license | shabilmuhammed/formula1 | d56241e5c907b1519093e4965d77882cd54ebba4 | 5266a153384e08fcacf9a16426e5108e7fd659e8 | refs/heads/main | 2023-08-03T23:01:13.637484 | 2021-09-25T08:19:51 | 2021-09-25T08:19:51 | 405,344,015 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,797 | py | # Databricks notebook source
# MAGIC %md
# MAGIC ### Ingest Drivers File
# COMMAND ----------
# MAGIC %md
# MAGIC ### Step 1 Read
# COMMAND ----------
dbutils.widgets.text('p_data_source','')
v_data_source = dbutils.widgets.get('p_data_source')
# COMMAND ----------
dbutils.widgets.text('p_file_date','2021-03-21')
v_file_date = dbutils.widgets.get('p_file_date')
# COMMAND ----------
# MAGIC %run "../includes/configuration"
# COMMAND ----------
# MAGIC %run "../includes/common_functions"
# COMMAND ----------
from pyspark.sql.types import StringType,StructField,StructType,DateType,IntegerType
# COMMAND ----------
name_schema = StructType(fields = [StructField("forename",StringType(),True),
StructField("surname",StringType(),True)
])
# COMMAND ----------
drivers_schema = StructType(fields = [StructField("driverId",IntegerType(),False),
StructField("driverRef",StringType(),False),
StructField("number",IntegerType(),False),
StructField("code",StringType(),False),
StructField("name",name_schema),
StructField("dob",DateType(),False),
StructField("nationality",StringType(),False),
StructField("url",StringType(),False),
])
# COMMAND ----------
drivers_df = spark.read \
.schema(drivers_schema) \
.json(f'{raw_folder_path}/{v_file_date}/drivers.json')
# COMMAND ----------
display(drivers_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ### Rename and add columns
# COMMAND ----------
from pyspark.sql.functions import concat,current_timestamp,col,lit
# COMMAND ----------
drivers_with_columns_df = drivers_df.withColumnRenamed('driverId','driver_id') \
.withColumnRenamed('driverRef','driver_ref') \
.withColumn('ingestion_date',current_timestamp()) \
.withColumn('name',concat(drivers_df.name.forename,lit(' '),drivers_df.name.surname)) \
.withColumn('data_source',lit(v_data_source)) \
.withColumn('file_date',lit(v_file_date))
# COMMAND ----------
display(drivers_with_columns_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ### Drop column
# COMMAND ----------
drivers_final_df = drivers_with_columns_df.drop(col('url'))
# COMMAND ----------
drivers_final_df.write.mode('overwrite').format('delta').saveAsTable('f1_processed.drivers')
# COMMAND ----------
# MAGIC %sql
# MAGIC select * from f1_processed.races
# COMMAND ----------
dbutils.notebook.exit('Success') | [
"noreply@github.com"
] | noreply@github.com |
7b2ae6979df18c1e5d9c6f4544cb5b8e95eb7e4a | 6d50225574554cf651b7693f22115f6e0a2f3c58 | /upyutils/SD_AM.py | 59562cc33a81736240fbd8568190cf173f43efb0 | [
"MIT"
] | permissive | tovam/upydev | abc8f9af5667821bb4644bafcead5f847a4114a1 | 0f9b73cb55750c291d2d016a3fd29d2feb71b8fc | refs/heads/master | 2022-10-03T12:43:38.699244 | 2020-06-07T12:58:19 | 2020-06-07T12:58:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,434 | py | #!/usr/bin/env python
# @Author: carlosgilgonzalez
# @Date: 2019-07-05T20:19:56+01:00
# @Last modified by: carlosgilgonzalez
# @Last modified time: 2019-07-10T00:55:01+01:00
from machine import SPI, Pin
import sdcard
import os
import time
# sd detect pin (15)
sd_detect = Pin(15, Pin.IN, pull=None)
sd_detect.value()
# sd sig (A5)
sd_sig = Pin(4, Pin.OUT)
sd_sig.value()
sd_sig.on()
sd_sig.value()
sd_detect.value()
# Callback
# LED
led = Pin(13, Pin.OUT)
sd_out = True
spi = SPI(1, baudrate=10000000, sck=Pin(5), mosi=Pin(18), miso=Pin(19))
cs = Pin(21, Pin.OUT)
# sd = sdcard.SDCard(spi, cs)
sd = None
irq_busy_sd = False
def pd_txtfiles(path, tabs=0):
print("txt Files on filesystem:")
print("====================")
files = [filename for filename in os.listdir(
path) if filename[-3:] == 'txt']
for file in files:
stats = os.stat(path + "/" + file)
filesize = stats[6]
isdir = stats[0] & 0x4000
_kB = 1024
if filesize < _kB:
sizestr = str(filesize) + " by"
elif filesize < _kB**2:
sizestr = "%0.1f KB" % (filesize / _kB)
elif filesize < _kB**3:
sizestr = "%0.1f MB" % (filesize / _kB**2)
else:
sizestr = "%0.1f GB" % (filesize / _kB**3)
prettyprintname = ""
for _ in range(tabs):
prettyprintname += " "
prettyprintname += file
if isdir:
prettyprintname += "/"
print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr))
# # recursively print directory contents
# if isdir:
# print_directory(path + "/" + file, tabs + 1)
def toggle_led_sd(x, butpress=sd_detect, light=led, sd_spi=spi, sd_cs=cs, getinfo=pd_txtfiles):
global irq_busy_sd, sd_out, sd
if irq_busy_sd:
return
else:
irq_busy_sd = True
if butpress.value() == 1: # reverse op == 0
if sd_out is True:
print('SD card detected')
for i in range(4):
led.value(not led.value())
time.sleep_ms(250)
butpress.init(Pin.OUT)
sd = sdcard.SDCard(sd_spi, sd_cs)
time.sleep_ms(1000)
os.mount(sd, '/sd')
print(os.listdir('/'))
# butpress.value(0) # reverse op == 1
butpress.init(Pin.IN)
getinfo("/sd")
sd_out = False
# butpress.init(Pin.IN, Pin.PULL_UP)
elif butpress.value() == 0:
if sd_out is False:
print('SD card removed')
for i in range(4):
led.value(not led.value())
time.sleep_ms(250)
time.sleep_ms(1000)
butpress.init(Pin.OUT)
os.umount('/sd')
time.sleep_ms(1000)
sd_out = True
irq_busy_sd = False
sd_detect.irq(trigger=3, handler=toggle_led_sd)
if sd_detect.value() == 1:
print('SD card detected')
for i in range(4):
led.value(not led.value())
time.sleep_ms(250)
sd_detect.init(Pin.OUT)
sd = sdcard.SDCard(spi, cs)
time.sleep_ms(1000)
os.mount(sd, '/sd')
print(os.listdir('/'))
# butpress.value(0) # reverse op == 1
sd_detect.init(Pin.IN)
pd_txtfiles("/sd")
sd_out = False
else:
print('SD card not detected')
| [
"carlosgilglez@gmail.com"
] | carlosgilglez@gmail.com |
3d3825f888aec7cd056ba5190bb0a6127a5432f8 | 19f96fdd86f1a29f4eec3d18d9e513865f1f512f | /webWork_backup/webflask/test_py3/lib/python3.5/sre_parse.py | 15237a5119fe22a7d3f6e358267c5f4a2c5922c9 | [] | no_license | Cattmonkey/openWork | e133376eeea3bbf5279f9199b18aa8cf44f21637 | 3e1f21f0c6bce7ec114cc8d6311746c4a2cc426b | refs/heads/master | 2020-03-14T00:58:41.610424 | 2018-05-04T09:59:03 | 2018-05-04T09:59:03 | 131,368,011 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 42 | py | /root/anaconda3/lib/python3.5/sre_parse.py | [
"yyxdyx01@163.com"
] | yyxdyx01@163.com |
a8f81f661bea3a7f30495e1a4166983529aed21b | b6cee1025bd4b2e394b5560279001dc6d932317f | /Configurations/VBS_OS/Full2017_v6/FitDir/samples.py | 2aa774049ae8ec465776ce75509f8acb44bcf463 | [] | no_license | sebsiebert/PlotsConfigurations | cbf84c371907089247064a0aa20f33d2d2c33ace | c9d00f37480a949da481481786c4d54ee0cb546f | refs/heads/master | 2021-07-02T00:23:34.867049 | 2020-05-25T11:38:10 | 2020-05-25T11:38:10 | 216,592,710 | 0 | 0 | null | 2019-10-21T14:44:56 | 2019-10-21T14:44:55 | null | UTF-8 | Python | false | false | 14,166 | py | import os
import inspect
configurations = os.path.realpath(inspect.getfile(inspect.currentframe())) # this file
configurations = os.path.dirname(configurations) # Full2017_v6
configurations = os.path.dirname(configurations) # ggH
configurations = os.path.dirname(configurations) # Configurations
from LatinoAnalysis.Tools.commonTools import getSampleFiles, getBaseW, getBaseWnAOD, addSampleWeight
def nanoGetSampleFiles(inputDir, sample):
try:
if _samples_noload:
return [sample]
except NameError:
pass
return getSampleFiles(inputDir, sample, True, 'nanoLatino_')
# samples
try:
len(samples)
except NameError:
import collections
samples = collections.OrderedDict()
################################################
################# SKIMS ########################
################################################
dataReco = 'Run2017_102X_nAODv5_Full2017v6'
mcProduction = 'Fall2017_102X_nAODv5_Full2017v6'
mcSteps = 'MCl1loose2017v6__MCCorr2017v6__l2loose__l2tightOR2017v6{var}'
fakeSteps = 'DATAl1loose2017v6__l2loose__fakeW'
dataSteps = 'DATAl1loose2017v6__l2loose__l2tightOR2017v6'
##############################################
###### Tree base directory for the site ######
##############################################
SITE=os.uname()[1]
if 'iihe' in SITE:
treeBaseDir = '/pnfs/iihe/cms/store/user/xjanssen/HWW2015'
elif 'cern' in SITE:
treeBaseDir = '/eos/cms/store/group/phys_higgs/cmshww/amassiro/HWWNano'
def makeMCDirectory(var=''):
if var:
return os.path.join(treeBaseDir, mcProduction, mcSteps.format(var='__' + var))
else:
return os.path.join(treeBaseDir, mcProduction, mcSteps.format(var=''))
mcDirectory = makeMCDirectory()
fakeDirectory = os.path.join(treeBaseDir, dataReco, fakeSteps)
dataDirectory = os.path.join(treeBaseDir, dataReco, dataSteps)
################################################
############ DATA DECLARATION ##################
################################################
DataRun = [
['B','Run2017B-Nano1June2019-v1'],
['C','Run2017C-Nano1June2019-v1'],
['D','Run2017D-Nano1June2019-v1'],
['E','Run2017E-Nano1June2019-v1'],
['F','Run2017F-Nano1June2019-v1']
]
DataSets = ['MuonEG','SingleMuon','SingleElectron','DoubleMuon', 'DoubleEG']
DataTrig = {
'MuonEG' : ' Trigger_ElMu' ,
'SingleMuon' : '!Trigger_ElMu && Trigger_sngMu' ,
'SingleElectron' : '!Trigger_ElMu && !Trigger_sngMu && Trigger_sngEl',
'DoubleMuon' : '!Trigger_ElMu && !Trigger_sngMu && !Trigger_sngEl && Trigger_dblMu',
'DoubleEG' : '!Trigger_ElMu && !Trigger_sngMu && !Trigger_sngEl && !Trigger_dblMu && Trigger_dblEl'
}
#########################################
############ MC COMMON ##################
#########################################
# SFweight does not include btag weights
mcCommonWeightNoMatch = 'XSWeight*SFweight*METFilter_MC'
mcCommonWeight = 'XSWeight*SFweight*PromptGenLepMatch2l*METFilter_MC'
###########################################
############# BACKGROUNDS ###############
###########################################
###### DY #######
useDYtt = False
ptllDYW_NLO = '(((0.623108 + 0.0722934*gen_ptll - 0.00364918*gen_ptll*gen_ptll + 6.97227e-05*gen_ptll*gen_ptll*gen_ptll - 4.52903e-07*gen_ptll*gen_ptll*gen_ptll*gen_ptll)*(gen_ptll<45)*(gen_ptll>0) + 1*(gen_ptll>=45))*(abs(gen_mll-90)<3) + (abs(gen_mll-90)>3))'
ptllDYW_LO = '((0.632927+0.0456956*gen_ptll-0.00154485*gen_ptll*gen_ptll+2.64397e-05*gen_ptll*gen_ptll*gen_ptll-2.19374e-07*gen_ptll*gen_ptll*gen_ptll*gen_ptll+6.99751e-10*gen_ptll*gen_ptll*gen_ptll*gen_ptll*gen_ptll)*(gen_ptll>0)*(gen_ptll<100)+(1.41713-0.00165342*gen_ptll)*(gen_ptll>=100)*(gen_ptll<300)+1*(gen_ptll>=300))'
if useDYtt:
files = nanoGetSampleFiles(mcDirectory, 'DYJetsToTT_MuEle_M-50') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-10to50-LO')
samples['DY'] = {
'name': files,
'weight': mcCommonWeight + "*( !(Sum$(PhotonGen_isPrompt==1 && PhotonGen_pt>15 && abs(PhotonGen_eta)<2.6) > 0 &&\
Sum$(LeptonGen_isPrompt==1 && LeptonGen_pt>15)>=2) )",
'FilesPerJob': 5,
}
addSampleWeight(samples,'DY','DYJetsToTT_MuEle_M-50',ptllDYW_NLO)
addSampleWeight(samples,'DY','DYJetsToLL_M-10to50-LO',ptllDYW_LO)
else:
files = nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-10to50-LO') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-100to200') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-200to400') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-400to600_ext1') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-600to800') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-800to1200') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-1200to2500') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-50_HT-2500toInf') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-4to50_HT-100to200') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-4to50_HT-200to400') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-4to50_HT-400to600') + \
nanoGetSampleFiles(mcDirectory, 'DYJetsToLL_M-4to50_HT-600toInf')
samples['DY'] = {
'name': files,
'weight': mcCommonWeight + "*( !(Sum$(PhotonGen_isPrompt==1 && PhotonGen_pt>15 && abs(PhotonGen_eta)<2.6) > 0 &&\
Sum$(LeptonGen_isPrompt==1 && LeptonGen_pt>15)>=2) )",
'FilesPerJob': 8,
}
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50', '('+ptllDYW_NLO+')*(LHE_HT < 100)')
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-10to50-LO', '('+ptllDYW_LO+')*(LHE_HT < 100)')
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-100to200', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-200to400', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-400to600_ext1', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-600to800', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-800to1200', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-1200to2500', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-50_HT-2500toInf', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-4to50_HT-100to200', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-4to50_HT-200to400', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-4to50_HT-400to600', ptllDYW_LO)
addSampleWeight(samples, 'DY', 'DYJetsToLL_M-4to50_HT-600toInf', ptllDYW_LO)
###### Top #######
files = nanoGetSampleFiles(mcDirectory, 'TTTo2L2Nu') + \
nanoGetSampleFiles(mcDirectory, 'ST_s-channel') + \
nanoGetSampleFiles(mcDirectory, 'ST_t-channel_antitop') + \
nanoGetSampleFiles(mcDirectory, 'ST_t-channel_top') + \
nanoGetSampleFiles(mcDirectory, 'ST_tW_antitop') + \
nanoGetSampleFiles(mcDirectory, 'ST_tW_top') + \
nanoGetSampleFiles(mcDirectory, 'TTTo2L2Nu_PSWeights')
samples['top'] = {
'name': files,
'weight': mcCommonWeight,
'FilesPerJob': 1,
}
TTTo2L2Nu_baseW = getBaseWnAOD(mcDirectory, mcProduction, ['TTTo2L2Nu', 'TTTo2L2Nu_PSWeights'])
addSampleWeight(samples, 'top', 'TTTo2L2Nu', TTTo2L2Nu_baseW + "/baseW")
addSampleWeight(samples, 'top', 'TTTo2L2Nu_PSWeights', TTTo2L2Nu_baseW + "/baseW")
#addSampleWeight(samples,'top','TTTo2L2Nu', 'Top_pTrw')
#addSampleWeight(samples, 'top', 'TTTo2L2Nu_PSWeights', 'Top_pTrw')
###### WW ########
'''
samples['WW'] = {
'name': nanoGetSampleFiles(mcDirectory, 'WWTo2L2Nu'),
'weight': mcCommonWeight + '*nllW',
'FilesPerJob': 1
}
'''
samples['WW'] = {
'name': nanoGetSampleFiles(mcDirectory, 'WpWmJJ_QCD_noTop'),
'weight': mcCommonWeight, #+ '*nllW',
'FilesPerJob': 1
}
# k-factor 1.4 already taken into account in XSWeight
files = nanoGetSampleFiles(mcDirectory, 'GluGluToWWToENEN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToENMN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToENTN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToMNEN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToMNMN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToMNTN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToTNEN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToTNMN') + \
nanoGetSampleFiles(mcDirectory, 'GluGluToWWToTNTN')
samples['ggWW'] = {
'name': files,
'weight': mcCommonWeight + '*1.53/1.4', # updating k-factor
'FilesPerJob': 10
}
######## Vg ########
files = nanoGetSampleFiles(mcDirectory, 'Wg_MADGRAPHMLM') + \
nanoGetSampleFiles(mcDirectory, 'ZGToLLG')
samples['Vg'] = {
'name': files,
'weight': mcCommonWeightNoMatch + '*!(Gen_ZGstar_mass > 0)',
'FilesPerJob': 10
}
######## VgS ########
files = nanoGetSampleFiles(mcDirectory, 'Wg_MADGRAPHMLM') + \
nanoGetSampleFiles(mcDirectory, 'ZGToLLG') + \
nanoGetSampleFiles(mcDirectory, 'WZTo3LNu_mllmin01')
samples['VgS'] = {
'name': files,
'weight': mcCommonWeight + ' * (gstarLow * 0.94 + gstarHigh * 1.14)',
'FilesPerJob': 15,
'subsamples': {
'L': 'gstarLow',
'H': 'gstarHigh'
}
}
addSampleWeight(samples, 'VgS', 'Wg_MADGRAPHMLM', '(Gen_ZGstar_mass > 0 && Gen_ZGstar_mass < 0.1)')
addSampleWeight(samples, 'VgS', 'ZGToLLG', '(Gen_ZGstar_mass > 0)')
addSampleWeight(samples, 'VgS', 'WZTo3LNu_mllmin01', '(Gen_ZGstar_mass > 0.1)')
############ VZ ############
files = nanoGetSampleFiles(mcDirectory, 'ZZTo2L2Nu') + \
nanoGetSampleFiles(mcDirectory, 'ZZTo2L2Q') + \
nanoGetSampleFiles(mcDirectory, 'ZZTo4L') + \
nanoGetSampleFiles(mcDirectory, 'WZTo2L2Q')
samples['VZ'] = {
'name': files,
'weight': mcCommonWeight + '*1.11',
'FilesPerJob': 2
}
########## VVV #########
files = nanoGetSampleFiles(mcDirectory, 'ZZZ') + \
nanoGetSampleFiles(mcDirectory, 'WZZ') + \
nanoGetSampleFiles(mcDirectory, 'WWZ') + \
nanoGetSampleFiles(mcDirectory, 'WWW')
#+ nanoGetSampleFiles(mcDirectory, 'WWG'), #should this be included? or is it already taken into account in the WW sample?
samples['VVV'] = {
'name': files,
'weight': mcCommonWeight
}
###########################################
############# SIGNALS ##################
###########################################
signals = []
#### ggH -> WW
samples['ggH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'GluGluHToWWTo2L2NuPowheg_M125'),
'weight': [mcCommonWeight, {'class': 'Weight2MINLO', 'args': '%s/src/LatinoAnalysis/Gardener/python/data/powheg2minlo/NNLOPS_reweight.root' % os.getenv('CMSSW_BASE')}],
'FilesPerJob': 4,
'linesToAdd': ['.L %s/src/PlotsConfigurations/Configurations/Differential/weight2MINLO.cc+' % os.getenv('CMSSW_BASE')]#% configurations]
}
#signals.append('ggH_hww')
############ VBF H->WW ############
samples['qqH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'VBFHToWWTo2L2NuPowheg_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 3
}
#signals.append('qqH_hww')
############# ZH H->WW ############
samples['ZH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'HZJ_HToWWTo2L2Nu_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 1
}
#signals.append('ZH_hww')
samples['ggZH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'GluGluZH_HToWWTo2L2Nu_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 2
}
#signals.append('ggZH_hww')
############ WH H->WW ############
samples['WH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'HWplusJ_HToWW_M125') + nanoGetSampleFiles(mcDirectory, 'HWminusJ_HToWW_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 2
}
#signals.append('WH_hww')
############ ttH ############
samples['ttH_hww'] = {
'name': nanoGetSampleFiles(mcDirectory, 'ttHToNonbb_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 1
}
#signals.append('ttH_hww')
############ H->TauTau ############
samples['ggH_htt'] = {
'name': nanoGetSampleFiles(mcDirectory, 'GluGluHToTauTau_M125_ext1'),
'weight': mcCommonWeight,
'FilesPerJob': 1
}
#signals.append('ggH_htt')
samples['qqH_htt'] = {
'name': nanoGetSampleFiles(mcDirectory, 'VBFHToTauTau_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 2
}
#signals.append('qqH_htt')
samples['ZH_htt'] = {
'name': nanoGetSampleFiles(mcDirectory, 'HZJ_HToTauTau_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 2
}
#signals.append('ZH_htt')
samples['WH_htt'] = {
'name': nanoGetSampleFiles(mcDirectory, 'HWplusJ_HToTauTau_M125'),# + nanoGetSampleFiles(mcDirectory, 'HWminusJ_HToTauTau_M125'),
'weight': mcCommonWeight,
'FilesPerJob': 2
}
#signals.append('WH_htt')
############ VBS #############
samples['WWewk'] = {
'name': nanoGetSampleFiles(mcDirectory, 'WpWmJJ_EWK_noTop'),
'weight': mcCommonWeight + '*0.2571' + '*(Sum$(abs(GenPart_pdgId)==6 || GenPart_pdgId==25)==0)', # update xsec + filter tops and Higgs
'FilesPerJob': 2
}
signals.append('WWewk')
###########################################
################## FAKE ###################
###########################################
samples['Fake'] = {
'name': [],
'weight': 'METFilter_DATA*fakeW',
'weights': [],
'isData': ['all'],
'FilesPerJob': 30
}
for _, sd in DataRun:
for pd in DataSets:
files = nanoGetSampleFiles(fakeDirectory, pd + '_' + sd)
samples['Fake']['name'].extend(files)
samples['Fake']['weights'].extend([DataTrig[pd]] * len(files))
samples['Fake']['subsamples'] = {
'em': 'abs(Lepton_pdgId[0]) == 11',
'me': 'abs(Lepton_pdgId[0]) == 13'
}
###########################################
################## DATA ###################
###########################################
samples['DATA'] = {
'name': [],
'weight': 'METFilter_DATA*LepWPCut',
'weights': [],
'isData': ['all'],
'FilesPerJob': 40
}
for _, sd in DataRun:
for pd in DataSets:
files = nanoGetSampleFiles(dataDirectory, pd + '_' + sd)
samples['DATA']['name'].extend(files)
samples['DATA']['weights'].extend([DataTrig[pd]] * len(files))
| [
"mattia.lizzo@cern.ch"
] | mattia.lizzo@cern.ch |
7fd6cc206cbf849679c3093579e88856a844bacd | 8a219d787acbda085908a3257a71325a859f86ae | /project2_1.py | 1f2aa45e4644c20acd6201861dfdb960fc27edd6 | [] | no_license | noey26/codeit_python | defe06f600e77cb5b3c86e44c3e669196e6fbc47 | 413107456ced46ca4a592cba12e6c975d1d9b1c0 | refs/heads/main | 2023-06-10T03:30:00.683670 | 2021-07-03T02:00:13 | 2021-07-03T02:00:13 | 380,436,686 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 319 | py | from random import randint
def generate_numbers():
numbers = []
while len(numbers) < 3:
num = randint(0, 9)
if num not in numbers:
numbers.append(num)
print("0과 9 사이의 서로 다른 숫자 3개를 랜덤한 순서로 뽑았습니다.\n")
return numbers | [
"noreply@github.com"
] | noreply@github.com |
5f7170cabbe1221af79c1612f5794ea230d81a04 | 261891baf843fb0a75508529c93e0c797b962256 | /ordered_to_do_list/wsgi.py | fac3a6d989dff63be7f83e5e2e703a7c1049f16e | [] | no_license | skomer/ordered_to_do_list | 178d4e1d13fd6363e6a786978523cea002e5cea8 | f50061474d7f03bf9f27e8fd1924937c57b6a993 | refs/heads/master | 2021-01-10T03:21:39.530822 | 2015-11-23T11:58:41 | 2015-11-23T11:58:41 | 46,717,342 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | """
WSGI config for ordered_to_do_list project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ordered_to_do_list.settings")
application = get_wsgi_application()
| [
"jo@isthebest.com"
] | jo@isthebest.com |
af1c43bc34c97ef127669166263c2789a325f744 | fcc0352bd54837b4cb99fcfea4adf0329898335c | /config.py | 87f725f73870534fee32cd8680688f5040c58316 | [] | no_license | ginapaal/new_askmate | 002fa734581da2b94f20d52179cc97c52c7880bf | a7fd3108b49eb81c3117a9ad86817355069ace25 | refs/heads/master | 2021-01-01T16:36:58.566445 | 2017-07-24T14:27:29 | 2017-07-24T14:27:29 | 97,871,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | global db_name
db_name = "askmate"
global user
user = "gina"
global password
password = "thebest"
| [
"paalginaa@gmail.com"
] | paalginaa@gmail.com |
cce1f9877bc6de0375b15a85c3651dd7a8f027de | d1df1a4f1d2e3adf3c18651da6424a36f1879b55 | /train.py | 963f4e3d55601c7e379c150256a118a28776072f | [] | no_license | China-ChallengeHub/astronomy-TOP3 | 17e5531cb860a52d4fbf42b70062ae0adcb9a90b | f7a78577d2a27b38b43a4c10be1641a5ab1714c5 | refs/heads/master | 2022-12-23T13:44:51.774158 | 2020-05-15T14:48:44 | 2020-05-15T14:48:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,852 | py | import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import random
import warnings
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
import keras
from keras_radam import RAdam
from keras import backend as K
from keras.callbacks import Callback
from keras.utils import to_categorical
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from sklearn.metrics import roc_auc_score, accuracy_score, log_loss, f1_score, precision_score, recall_score
import tensorflow as tf
import keras.backend.tensorflow_backend as KTF
from tools import Metrics
import resnet
#setting
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto(log_device_placement=False)
config.gpu_options.per_process_gpu_memory_fraction = 0.9
session = tf.Session(config=config)
KTF.set_session(session)
path = os.getcwd()
path_sub = path + '/../data/sub/'
path_data = path + '/../data/raw/'
path_model = path + '/../data/model/'
path_result = path + '/../data/result/'
path_pickle = path + '/../data/pickle/'
path_profile = path + '/../data/profile/'
for i in [path + '/../data/', path_sub, path_data, path_model, path_result, path_pickle, path_profile]:
try:
os.mkdir(i)
except:
pass
#ready
label = 'answer'
drop_clos = [label, 'id', 'sum']
data = pd.read_pickle(path_pickle+'data.pickle')
train_label = data[label]
encoder = LabelEncoder()
train_label = encoder.fit_transform(train_label)
num_classes = len(encoder.classes_ )
train_data_use = data.drop(drop_clos, axis=1)
train_data_use = np.array(train_data_use)
train_data_use = train_data_use.reshape([train_data_use.shape[0], train_data_use.shape[1], 1, 1])
data = data[['id', label]]
#train
fold_n = 10
kfold = StratifiedKFold(n_splits=fold_n, shuffle=True, random_state=2019)
kf = kfold.split(train_data_use, train_label)
for i in range(num_classes):
data['class%s'%i] = 0
for i, (train_fold, validate) in enumerate(kf):
print('Fold', str(i+1)+'/'+str(fold_n))
train_labels = to_categorical(train_label, num_classes=num_classes)
X_train, X_validate, label_train, label_validate = train_data_use[
train_fold], train_data_use[validate], train_labels[train_fold], train_labels[validate]
monitor = 'val_acc'
modelPath = path_model+"fold%s_best.hdf5"%i
early_stopping = EarlyStopping(monitor=monitor, patience=5, mode='max', verbose=0)
plateau = ReduceLROnPlateau(factor=0.1, monitor=monitor, patience=2, mode='max', verbose=0)
checkpoint = ModelCheckpoint(modelPath, save_best_only=True, monitor=monitor, mode='max', verbose=1)
callbacks_list = [Metrics(valid_data=(X_validate, label_validate)), early_stopping, plateau, checkpoint]
model = resnet.resnet_34(train_data_use.shape[1], train_data_use.shape[2], train_data_use.shape[3], num_classes)
Optimizer = RAdam(total_steps=10000, warmup_proportion=0.1, min_lr=1e-6)
try:
model.load_weights(modelPath, by_name=True)
except:
model.compile(loss='categorical_crossentropy', optimizer=Optimizer, metrics=['acc'])
history = model.fit(X_train, label_train, epochs=100, batch_size=128,
verbose=0, shuffle=True, callbacks=callbacks_list,
validation_data=(X_validate, label_validate))
model.load_weights(modelPath, by_name=True)
oof_proba = model.predict(X_validate, verbose=1, batch_size=1024)
print('Best score:', f1_score(label_validate.argmax(axis=-1), np.array(oof_proba).argmax(axis=-1), average='macro'))
for i in range(num_classes):
data.loc[validate, 'class%s'%i] = oof_proba[:, i]
data.to_csv(path_result+'oof.csv', index=False)
| [
"noreply@github.com"
] | noreply@github.com |
fad4abccc68ce712fe65536359e5615c148ae203 | 68fe96ed82637b898d240ce68c232da9422933df | /eden_cats_blog/apps/message/migrations/0002_auto_20180915_0122.py | a8b80fffe87711368fc4ba411d2d7cdaddd5e636 | [] | no_license | imquanquan/Project-01-DjangoBlog | 696c75168009118ce70a66bd836aa3ed1432032e | 6d72326e428c70cdc859852a00de2302aac91bf0 | refs/heads/master | 2020-03-29T13:23:20.114686 | 2018-09-23T07:22:25 | 2018-09-23T07:22:25 | 149,956,056 | 0 | 0 | null | 2018-09-23T07:04:43 | 2018-09-23T07:04:43 | null | UTF-8 | Python | false | false | 456 | py | # Generated by Django 2.0.5 on 2018-09-14 17:22
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('message', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='message',
name='content',
field=ckeditor_uploader.fields.RichTextUploadingField(max_length=320, verbose_name='留言'),
),
]
| [
"625310581@qq.com"
] | 625310581@qq.com |
f634288f413b4e857362ca44e08fa34dbfd9a73e | 9045885cbfeaf52c32f9ae73fc7f00848532e3c0 | /tests/test_create_new_data_product.py | 87e2319dd3a6dc99245492e0f7360cb9555151d0 | [] | no_license | gkourupes/ion-ux | 30cc35f97e40e89a0dd37212868a70c8acb4cf55 | 45e6669425f98b2ef002c184f03afef66f662245 | refs/heads/master | 2021-01-15T08:10:53.643315 | 2014-04-15T23:10:13 | 2014-04-15T23:10:13 | 17,454,719 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,761 | py | __author__ = 'Seman'
import sys
sys.path.append('.')
import unittest
import flask
from nose.plugins.attrib import attr
import main
from service_api import ServiceApi
import random
from common import *
@attr('UNIT')
class DataProductIntTest(unittest.TestCase):
def setUp(self):
self.org_name = "CI Bench Test Facility"
self.user = "Beta Operator User"
self.app_client = main.app.test_client()
self.app_context = main.app.test_request_context()
self.sa = ServiceApi()
def tearDown(self):
pass
def create_new_data_product(self, resource_type, org_id, resource_name=None):
with self.app_context:
# Create a new resource
self.sa.signon_user_testmode(self.user)
instrument_device_id, org_has_resource_instrument_id = self.sa.create_resource(resource_type=resource_type, org_id=org_id, resource_name=resource_name)
self.assertIsNotNone(instrument_device_id)
self.assertIs(is_it_id(instrument_device_id), True)
self.assertIsNotNone(org_has_resource_instrument_id)
self.assertIs(is_it_id(org_has_resource_instrument_id), True)
# Get the data from service gateway and verify
resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True)
resource_obj = resource.get('resource')
resource_association = resource.get('associations')
self.assertIsNotNone(resource_obj)
self.assertEqual(resource_obj.get('name'), resource_name)
# Verify the resource can be updated
new_name = " Unit Test New Instrument Name " + str(int(random.random() * 1000))
resource_obj['name'] = new_name
response = self.sa.update_resource(resource_type, resource_obj, [])
# Verify the name has been updated
resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True)
resource_obj = resource.get('resource')
self.assertIsNotNone(resource_obj)
self.assertEqual(resource_obj.get('name'), new_name)
# Put back the name
resource_obj['name'] = resource_name
response = self.sa.update_resource(resource_type, resource_obj, [])
resource = self.sa.get_prepare(resource_type, instrument_device_id, None, True)
resource_obj = resource.get('resource')
self.assertIsNotNone(resource_obj)
self.assertEqual(resource_obj.get('name'), resource_name)
# Logout by clearing the session
flask.session.clear()
# Try to update the instrument data as a guest
response = self.sa.update_resource(resource_type, resource_obj, [])
self.assertTrue(len(response) > 0, "Service Gateway is supposed to return unauthorized error for updating a resource as a guest")
error = response[0].get('GatewayError')
self.assertIsNotNone(error, "Service Gateway is supposed to return unauthorized error for updating a resource as a guest")
error = error.get('Exception')
self.assertEqual(error.lower(), "unauthorized", "Service Gateway is supposed to return unauthorized error for updating a resource as a guest")
def test_create_data_product(self):
instrument_name = "Unit Test Data Product " + str(int(random.random() * 1000))
resource_type = 'DataProduct'
org_id = get_org_id(org_name=self.org_name)
self.assertIsNotNone(org_id)
self.assertTrue(is_it_id(org_id))
self.create_new_data_product(resource_type=resource_type, org_id=org_id, resource_name=instrument_name)
if __name__ == '__main__':
unittest.main()
| [
"sseman@gmail.com"
] | sseman@gmail.com |
f765d4f0f9fee8a3e3efee2a41a5265bbd2c1370 | b99bc3f3e6da10aca6fffa7b4f4abd614514440e | /test/otlad.py | 0b7024148ded216487838fcc63c5f96ec0ad95fa | [] | no_license | petayyyy/IOR2020 | 5b36d42b57b3f17eb79f7c2922175dda156bb637 | debdd8cb0ef05e69d2919f3e3a563d41e2534063 | refs/heads/master | 2022-11-02T14:22:57.602858 | 2020-06-21T13:54:28 | 2020-06-21T13:54:28 | 268,279,030 | 0 | 3 | null | 2020-06-21T09:28:06 | 2020-05-31T12:49:49 | Python | UTF-8 | Python | false | false | 1,403 | py | import cv2
import numpy as np
import time
if __name__ == '__main__':
def nothing(*arg):
pass
cv2.namedWindow( "result" )
cv2.namedWindow( "settings" )
cv2.createTrackbar('h1', 'settings', 0, 255, nothing)
cv2.createTrackbar('s1', 'settings', 0, 255, nothing)
cv2.createTrackbar('v1', 'settings', 0, 255, nothing)
cv2.createTrackbar('h2', 'settings', 255, 255, nothing)
cv2.createTrackbar('s2', 'settings', 255, 255, nothing)
cv2.createTrackbar('v2', 'settings', 255, 255, nothing)
crange = [0,0,0, 0,0,0]
cam = cv2.VideoCapture('IMG_5310.MOV')
while True:
ret, img = cam.read()
#img = cv2.imread('ior_final.png')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h1 = cv2.getTrackbarPos('h1', 'settings')
s1 = cv2.getTrackbarPos('s1', 'settings')
v1 = cv2.getTrackbarPos('v1', 'settings')
h2 = cv2.getTrackbarPos('h2', 'settings')
s2 = cv2.getTrackbarPos('s2', 'settings')
v2 = cv2.getTrackbarPos('v2', 'settings')
h_min = np.array((h1, s1, v1), np.uint8)
h_max = np.array((h2, s2, v2), np.uint8)
thresh = cv2.inRange(hsv, h_min, h_max)
cv2.imshow('result', thresh)
cv2.imshow('img', img)
time.sleep(0.2)
ch = cv2.waitKey(5)
if ch == 27:
break
cap.release()
cv2.destroyAllWindows()
| [
"noreply@github.com"
] | noreply@github.com |
a89274a540eccad2f64b0f01e06449ec329ce901 | 66052f5ba08ddac0a56ee140af17cf78b1ff1174 | /PLURALSIGHT_BEGINNERS/lib/python3.9/site-packages/anyio/_core/_compat.py | 8a0cfd088eadb36ec9786f05ab4ea9ab959ecd8e | [] | no_license | enriquefariasrdz/Python | 34704ceed001bbe8a23471eebefbe536b00031a5 | b9191f7ad87b709a1b83c5cb3797a866b56aaa0d | refs/heads/master | 2022-12-26T03:06:26.481456 | 2022-04-20T14:09:57 | 2022-04-20T14:09:57 | 27,020,899 | 1 | 1 | null | 2022-12-18T21:02:43 | 2014-11-23T03:33:52 | Python | UTF-8 | Python | false | false | 5,668 | py | from abc import ABCMeta, abstractmethod
from contextlib import AbstractContextManager
from types import TracebackType
from typing import (
TYPE_CHECKING, Any, AsyncContextManager, Callable, ContextManager, Generator, Generic,
Iterable, List, Optional, Tuple, Type, TypeVar, Union, overload)
from warnings import warn
if TYPE_CHECKING:
from ._testing import TaskInfo
else:
TaskInfo = object
T = TypeVar('T')
AnyDeprecatedAwaitable = Union['DeprecatedAwaitable', 'DeprecatedAwaitableFloat',
'DeprecatedAwaitableList[T]', TaskInfo]
@overload
async def maybe_async(__obj: TaskInfo) -> TaskInfo:
...
@overload
async def maybe_async(__obj: 'DeprecatedAwaitableFloat') -> float:
...
@overload
async def maybe_async(__obj: 'DeprecatedAwaitableList[T]') -> List[T]:
...
@overload
async def maybe_async(__obj: 'DeprecatedAwaitable') -> None:
...
async def maybe_async(__obj: 'AnyDeprecatedAwaitable[T]') -> Union[TaskInfo, float, List[T], None]:
"""
Await on the given object if necessary.
This function is intended to bridge the gap between AnyIO 2.x and 3.x where some functions and
methods were converted from coroutine functions into regular functions.
Do **not** try to use this for any other purpose!
:return: the result of awaiting on the object if coroutine, or the object itself otherwise
.. versionadded:: 2.2
"""
return __obj._unwrap()
class _ContextManagerWrapper:
def __init__(self, cm: ContextManager[T]):
self._cm = cm
async def __aenter__(self) -> T:
return self._cm.__enter__()
async def __aexit__(self, exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> Optional[bool]:
return self._cm.__exit__(exc_type, exc_val, exc_tb)
def maybe_async_cm(cm: Union[ContextManager[T], AsyncContextManager[T]]) -> AsyncContextManager[T]:
"""
Wrap a regular context manager as an async one if necessary.
This function is intended to bridge the gap between AnyIO 2.x and 3.x where some functions and
methods were changed to return regular context managers instead of async ones.
:param cm: a regular or async context manager
:return: an async context manager
.. versionadded:: 2.2
"""
if not isinstance(cm, AbstractContextManager):
raise TypeError('Given object is not an context manager')
return _ContextManagerWrapper(cm)
def _warn_deprecation(awaitable: 'AnyDeprecatedAwaitable[Any]', stacklevel: int = 1) -> None:
warn(f'Awaiting on {awaitable._name}() is deprecated. Use "await '
f'anyio.maybe_async({awaitable._name}(...)) if you have to support both AnyIO 2.x '
f'and 3.x, or just remove the "await" if you are completely migrating to AnyIO 3+.',
DeprecationWarning, stacklevel=stacklevel + 1)
class DeprecatedAwaitable:
def __init__(self, func: Callable[..., 'DeprecatedAwaitable']):
self._name = f'{func.__module__}.{func.__qualname__}'
def __await__(self) -> Generator[None, None, None]:
_warn_deprecation(self)
if False:
yield
def __reduce__(self) -> Tuple[Type[None], Tuple[()]]:
return type(None), ()
def _unwrap(self) -> None:
return None
class DeprecatedAwaitableFloat(float):
def __new__(
cls, x: float, func: Callable[..., 'DeprecatedAwaitableFloat']
) -> 'DeprecatedAwaitableFloat':
return super().__new__(cls, x)
def __init__(self, x: float, func: Callable[..., 'DeprecatedAwaitableFloat']):
self._name = f'{func.__module__}.{func.__qualname__}'
def __await__(self) -> Generator[None, None, float]:
_warn_deprecation(self)
if False:
yield
return float(self)
def __reduce__(self) -> Tuple[Type[float], Tuple[float]]:
return float, (float(self),)
def _unwrap(self) -> float:
return float(self)
class DeprecatedAwaitableList(List[T]):
def __init__(self, iterable: Iterable[T] = (), *,
func: Callable[..., 'DeprecatedAwaitableList[T]']):
super().__init__(iterable)
self._name = f'{func.__module__}.{func.__qualname__}'
def __await__(self) -> Generator[None, None, List[T]]:
_warn_deprecation(self)
if False:
yield
return list(self)
def __reduce__(self) -> Tuple[Type[List[T]], Tuple[List[T]]]:
return list, (list(self),)
def _unwrap(self) -> List[T]:
return list(self)
class DeprecatedAsyncContextManager(Generic[T], metaclass=ABCMeta):
@abstractmethod
def __enter__(self) -> T:
pass
@abstractmethod
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> Optional[bool]:
pass
async def __aenter__(self) -> T:
warn(f'Using {self.__class__.__name__} as an async context manager has been deprecated. '
f'Use "async with anyio.maybe_async_cm(yourcontextmanager) as foo:" if you have to '
f'support both AnyIO 2.x and 3.x, or just remove the "async" from "async with" if '
f'you are completely migrating to AnyIO 3+.', DeprecationWarning)
return self.__enter__()
async def __aexit__(self, exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> Optional[bool]:
return self.__exit__(exc_type, exc_val, exc_tb)
| [
"enriquefariasrdz@gmail.com"
] | enriquefariasrdz@gmail.com |
ed65d8cabf8d7f04c1951349663419deb2979c50 | 0d9b5c2842721c2246d4b58890511d154fa6df1b | /myadmin/migrations/0018_auto_20180311_1219.py | b7424714cb179baa93c9eeaf22cf4097a6e17e01 | [] | no_license | bhavingandha9/senseshop | 862c13056cd4f53b265d040fc05337e6e46841e9 | b2982399bc8223c5eeeb25ce9e1edbd4449d6e93 | refs/heads/master | 2021-04-30T08:10:23.039521 | 2018-06-06T16:21:53 | 2018-06-06T16:21:53 | 121,368,692 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 462 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2018-03-11 06:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myadmin', '0017_auto_20180311_1212'),
]
operations = [
migrations.AlterField(
model_name='product',
name='image',
field=models.ImageField(blank=True, upload_to=''),
),
]
| [
"="
] | = |
a801bf0d64265cc7658aad4473cabf19d4a34b01 | 3a1369119642b8bd566f24f10ddc83e4f9cbaebc | /richmatt/settings.py | a258cfa1ac8929380b43cfeb3dadafa11823da22 | [] | no_license | devvspaces/richmatt | 0367851648998decbaa403b4f7993ad06b9265c3 | d87861f5860d221bd2d0a0258f9425a0a8f776be | refs/heads/master | 2023-05-03T16:40:13.408390 | 2021-05-24T01:17:34 | 2021-05-24T01:17:34 | 370,189,413 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,029 | py | import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zphp7jl56)4ai8w03x*_ml(7*2+76^_4of8!=&4#wql!ry!@e@'
# 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',
'gallery',
'products'
]
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 = 'richmatt.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 = 'richmatt.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "assets"),
]
# STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT=os.path.join(BASE_DIR,"media")
MEDIA_URL='/media/' | [
"devvspaces@gmail.com"
] | devvspaces@gmail.com |
1c9d6d1b19a780047de3250d3cfd2da9a63db53c | 3ad3c58bc289fa1a556db153b55ae2bbdcec893f | /src/allocation/domain/commands.py | 95e4dfc10b375fc15e183f6bc96f0812df8d37cc | [] | no_license | vic3r/python-AP | 7f25b9dc2523d561f53e8f03e1d8ac5820edce86 | 5c56c7a3e93e9ee0a56564efbbff449cb4dafc95 | refs/heads/master | 2023-02-10T10:43:31.728232 | 2021-01-02T01:22:35 | 2021-01-02T01:22:35 | 288,585,808 | 0 | 0 | null | 2021-01-02T01:22:36 | 2020-08-18T23:29:05 | Python | UTF-8 | Python | false | false | 357 | py | from datetime import date
from dataclasses import dataclass
from typing import Optional
class Command:
pass
@dataclass
class Allocate(Command):
orderid: str
sku: str
qty: int
@dataclass
class CreateBatch(Command):
ref: str
sku: str
qty: int
eta: Optional[date] = None
@dataclass
class ChangeBatchQuantity(Command):
ref: str
qty: int
| [
"victor.g64r@gmail.com"
] | victor.g64r@gmail.com |
2401bcbfd8e0d6468d2d63b5be24459926d9e483 | 2b79c8fb6540407dedb72133df1c921342d7cf2e | /api/views.py | c69f1c05fe956d70da1b6e43df0659b799282a47 | [] | no_license | prakhariitbhu/process_manager | de526aec10fb8c74549fed5699ea8901d2975969 | dc4e7c797f91e07a95602615954f12013cb71428 | refs/heads/master | 2023-08-23T08:32:48.760967 | 2020-09-24T10:42:14 | 2020-09-24T10:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,526 | py | from rest_framework import permissions
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from .serializers import *
from .models import *
class NewTaskView(generics.GenericAPIView):
"""
Creates a new task (i.e. the sample_process.py).
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSerializer
def get(self, *args, **kwargs):
serializer = self.get_serializer()
response = serializer.create_new_task()
return Response(response.data, status=status.HTTP_200_OK)
class TaskStatusView(generics.RetrieveAPIView):
"""
View the detail of a task.
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSerializer
queryset = Task.objects.all()
class AllTasksView(generics.ListAPIView):
"""
Views the status of all the tasks.
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSummarySerializer
queryset = Task.objects.all()
class PauseTaskView(generics.GenericAPIView):
"""
Pauses a task.
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSerializer
lookup_field = 'pk'
queryset = Task.objects.all()
def get_object(self):
if getattr(self, 'swagger_fake_view', False):
return None
return super().get_object()
def get_serializer_context(self):
return {
'request': self.request,
'format': self.format_kwarg,
'view': self,
'task':self.get_object()
}
def get(self, *args, **kwargs):
serailzer = self.get_serializer()
response = serailzer.pause_task()
return Response(response.data, status=status.HTTP_200_OK)
class ResumeTaskView(generics.GenericAPIView):
"""
Resumes a task.
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSerializer
lookup_field = 'pk'
queryset = Task.objects.all()
def get_object(self):
if getattr(self, 'swagger_fake_view', False):
return None
return super().get_object()
def get_serializer_context(self):
return {
'request': self.request,
'format': self.format_kwarg,
'view': self,
'task':self.get_object()
}
def get(self, *args, **kwargs):
serailzer = self.get_serializer()
response = serailzer.resume_task()
return Response(response.data, status=status.HTTP_200_OK)
class KillTaskView(generics.GenericAPIView):
"""
Kills a task.
"""
authentication_classes = []
permission_classes = (permissions.AllowAny,)
serializer_class = TaskSerializer
lookup_field = 'pk'
queryset = Task.objects.all()
def get_object(self):
if getattr(self, 'swagger_fake_view', False):
return None
return super().get_object()
def get_serializer_context(self):
return {
'request': self.request,
'format': self.format_kwarg,
'view': self,
'task':self.get_object()
}
def get(self, *args, **kwargs):
serailzer = self.get_serializer()
response = serailzer.kill_task()
return Response(response.data, status=status.HTTP_200_OK)
| [
"mittalnishant14@outlook.com"
] | mittalnishant14@outlook.com |
8d4aec3e05712c58f8371298b8e14eac7762533b | 4621b15ae0d6f8a86d6eb34f00577f4d1d777271 | /bubble_sort.py | 3214dbe15f4e7945d1589555c297cc99fc87759f | [] | no_license | catVSdog/algorithm_python | 91eeac632fc5ee0da9028173375d6318079af74b | b51d91232c547769ae0683ce9c3d1ed97bde4e47 | refs/heads/master | 2021-07-08T16:17:58.859817 | 2021-03-23T06:29:25 | 2021-03-23T06:29:25 | 231,876,949 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,008 | py | """
冒泡排序
"""
import random
class BubbleSort:
@staticmethod
def process(array):
array_length = len(array)
for i in range(array_length - 1, -1, -1):
for j in range(i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
@staticmethod
def process_enhance(array):
array_length = len(array)
for i in range(array_length - 1, -1, -1):
flag = False # 标识位-本次循环是否进行了数据交换
for j in range(i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
flag = True
if flag is False: # 如果本次没有发生数据交换,说明已经排序完成,结束循环
return array
if __name__ == '__main__':
a = [i for i in range(14)]
random.shuffle(a)
print(a)
print(BubbleSort.process_enhance(a))
| [
"windorbird@gmail.com"
] | windorbird@gmail.com |
7641c594700e0e0ee757a5c8b3413260b0cea11d | f50df195f44371fb4948a4b1109c4b383768a9f7 | /src/old/distanciatrie.py | f5bcd6c6ab7a76de8a664ced3b5ceddd991ea345 | [] | no_license | comp4a/alt | e885a0a74440a8b1f4d3376e0384097ef7844946 | 3188dc8e40be58418c5e14a405aca858af8453cc | refs/heads/master | 2020-07-29T22:41:52.347792 | 2020-01-10T21:26:37 | 2020-01-10T21:26:37 | 209,988,103 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,009 | py | import numpy as np
def levenshtein_distance2(x, y):
current_row = np.zeros((1+len(x)))
previous_row = np.zeros((1+len(x)))
current_row[0] = 0
for i in range(1, len(x)+1):
current_row[i] = current_row[i-1] + 1
for j in range(1, len(y)+1):
previous_row, current_row = current_row, previous_row
current_row[0] = previous_row[0] + 1
for i in range(1, len(x)+1):
current_row[i] = min(current_row[i-1] + 1,
previous_row[i] + 1,
previous_row[i-1] + (x[i-1] != y[j-1]))
return current_row[len(x)]
def distances(index,word):
word_list = index.keys()
distance_list = []
for i,word2 in enumerate(word_list):
distance = levenshtein_distance2(word2,word)
distance_list.append( (word2,distance) )
return distance_list
index = {"patata":[1,2,3],
"patatero":[1,2,3],
"patan":[1,2,3]}
print(distances(index,"patata"))
def trie_distances(trie, word):
res = {}
| [
"luis.serranohernandez.1415@gmail.com"
] | luis.serranohernandez.1415@gmail.com |
ddc8177b8bdbdb0209448592a21c02dc8c281600 | e9a6a6f60677d876272fd56eb37a47faaba47562 | /util/visualizer.py | e526630d8425c1d62b64fdf1d09fd74baf632970 | [] | no_license | Meimeiainaonao/SPGNet | b94725d360d7e6f0ac50a2ee3896b353704c26ef | e0c114ddb31100de2c0c9aa7d58812ec85521758 | refs/heads/main | 2023-04-10T02:13:56.287913 | 2021-04-26T02:11:22 | 2021-04-26T02:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,750 | py | from __future__ import division, print_function
import torch
import torchvision
import os
import time
import util.io as io
import numpy as np
from util import pose_util, flow_util
def seg_to_rgb(seg_map, with_face=False):
if isinstance(seg_map, np.ndarray):
if seg_map.ndim == 3:
seg_map = seg_map[np.newaxis,:]
seg_map = torch.from_numpy(seg_map.transpose([0,3,1,2]))
elif isinstance(seg_map, torch.Tensor):
seg_map = seg_map.cpu()
if seg_map.dim() == 3:
seg_map = seg_map.unsqueeze(0)
if with_face:
face = seg_map[:,-3::]
seg_map = seg_map[:,0:-3]
if seg_map.size(1) > 1:
seg_map = seg_map.max(dim=1, keepdim=True)[1]
else:
seg_map = seg_map.long()
b,c,h,w = seg_map.size()
assert c == 1
cmap = [[73,0,255], [255,0,0], [255,0,219], [255, 219,0], [0,255,146], [0,146,255], [146,0,255], [255,127,80], [0,255,0], [0,0,255],
[37, 0, 127], [127,0,0], [127,0,109], [127,109,0], [0,127,73], [0,73,127], [73,0, 127], [127, 63, 40], [0,127,0], [0,0,127]]
cmap = torch.Tensor(cmap)/255.
cmap = cmap[0:(seg_map.max()+1)]
rgb_map = cmap[seg_map.view(-1)]
rgb_map = rgb_map.view(b, h, w, 3)
rgb_map = rgb_map.transpose(1,3).transpose(2,3)
rgb_map.sub_(0.5).div_(0.5)
if with_face:
face_mask = ((seg_map == 1) | (seg_map == 2)).float()
rgb_map = rgb_map * (1 - face_mask) + face * face_mask
return rgb_map
def merge_visual(visuals):
imgs = []
vis_list = []
for name, (vis, vis_type) in visuals.items():
vis = vis.cpu()
if vis_type == 'rgb':
vis_ = vis
elif vis_type == 'seg':
vis_ = seg_to_rgb(vis)
elif vis_type == 'pose':
pose_maps = vis.numpy().transpose(0,2,3,1)
vis_ = np.stack([pose_util.draw_pose_from_map(m)[0] for m in pose_maps])
vis_ = vis.new(vis_.transpose(0,3,1,2)).float()/127.5 - 1.
elif vis_type == 'flow':
flows = vis.numpy().transpose(0,2,3,1)
vis_ = np.stack([flow_util.flow_to_rgb(f) for f in flows])
vis_ = vis.new(vis_.transpose(0,3,1,2)).float()/127.5 - 1.
elif vis_type == 'vis':
if vis.size(1) == 3:
vis = vis.argmax(dim=1, keepdim=True)
vis_ = vis.new(vis.size(0), 3, vis.size(2), vis.size(3)).float()
vis_[:,0,:,:] = (vis==1).float().squeeze(dim=1)*2-1 # red: not visible
vis_[:,1,:,:] = (vis==0).float().squeeze(dim=1)*2-1 # green: visible
vis_[:,2,:,:] = (vis==2).float().squeeze(dim=1)*2-1 # blue: background
elif vis_type == 'softmask':
vis_ = (vis*2-1).repeat(1,3,1,1)
imgs.append(vis_)
vis_list.append(name)
imgs = torch.stack(imgs, dim=1)
imgs = imgs.view(imgs.size(0)*imgs.size(1), imgs.size(2), imgs.size(3), imgs.size(4))
imgs.clamp_(-1., 1.)
return imgs, vis_list
class Visualizer(object):
def __init__(self, opt):
self.opt = opt
self.exp_dir = os.path.join('./checkpoints', opt.id)
self.log_file = None
def __del__(self):
if self.log_file:
self.log_file.close()
def _open_log_file(self):
fn = 'train_log.txt' if self.opt.is_train else 'test_log.txt'
self.log_file = open(os.path.join(self.exp_dir, fn), 'a')
print(time.ctime(), file=self.log_file)
print('pytorch version: %s' % torch.__version__, file=self.log_file)
def log(self, info='', errors={}, log_in_file=True):
'''
Save log information into log file
Input:
info (dict or str): model id, iteration number, learning rate, etc.
error (dict): output of loss functions or metrics.
Output:
log_str (str)
'''
if isinstance(info, str):
info_str = info
elif isinstance(info, dict):
info_str = ' '.join(['{}: {}'.format(k,v) for k, v in info.items()])
error_str = ' '.join(['%s: %.4f'%(k,v) for k, v in errors.items()])
log_str = '[%s] %s' %(info_str, error_str)
if log_in_file:
if self.log_file is None:
self._open_log_file()
print(log_str, file=self.log_file)
return log_str
def visualize_results(self, visuals, filename):
io.mkdir_if_missing(os.path.dirname(filename))
imgs, vis_item_list = merge_visual(visuals)
torchvision.utils.save_image(imgs, filename, nrow=len(visuals), normalize=True)
fn_list = os.path.join(os.path.dirname(filename), 'vis_item_list.txt')
io.save_str_list(vis_item_list, fn_list)
| [
"943470791@qq.com"
] | 943470791@qq.com |
290707c62b48bcf3b1ac4f5299f0750b0444809f | 9a2f32b98577ecd019cbf7380b6491660daed968 | /GMATE/main.py | 79873cad31764c91fa06871fea8e031e4b47fd9a | [
"MIT"
] | permissive | lexrupy/gmate-editor | 4b2151015dc7fa1ee5aa92b3e8cb32bd4e7d5738 | 7036d58a083ad6c05c1eb4cf7cb92405b369adb7 | refs/heads/master | 2016-09-06T07:01:38.561724 | 2009-04-17T13:18:28 | 2009-04-17T13:18:28 | 177,728 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 508 | py | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
import editor
class Gmate(object):
def __init__(self):
self.editor = editor.GmateEditor()
self.editor.show()
def run(self, file_uri=None):
if file_uri:
self.editor.open_uri(file_uri)
else:
self.editor.new_document()
gtk.main()
| [
"lexrupy@gmail.com"
] | lexrupy@gmail.com |
4483cfc690cadb80db163d482895ba32ba6d0f6e | 00d2a7104f5ef42b67c4a0f356a2bc85058ebca4 | /easter_eggs.py | 70e84c4932be483b77eeb2c53762b5730f665a40 | [] | no_license | Gabzcr/NinjaBot | db61a176f25bd90657beb9ee77c9fa34d4f9b5de | acf2083cf656594c0647beab25131de322e2ce19 | refs/heads/master | 2022-12-11T18:02:50.231728 | 2022-12-04T11:23:06 | 2022-12-04T11:23:06 | 168,880,334 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,469 | py | import random
import re
def easter_eggs(content):
res = None
if ":Ninja:" in content:
res = "Rejoins-moi, camarade <:Ninja:541390402104852485> !"
elif content.lower() == "easter egg":
res = "il n'y a aucun easter egg ici :innocent:."
elif content.lower() == "uranie puffin" or content.lower() == "uranie":
res = "je ne me permettrais pas de lancer Mlle Puffin !"
elif content.lower() == "dreyfus":
res = "la question ne sera pas posée !"
elif content.lower() == "crocell":
file = open("crocell_jokes.txt", "r")
l = file.read().split("\n\n")
index = random.randint(0,len(l) - 1)
res = l[index]
file.close()
elif "!r" in content or "!roll" in content:
res = "(i) la première règle de la récursion est (i)."
elif content == "666":
res = "vous avez obtenu un **666**."
elif content == "42":
res = "vous avez obtenu **la Réponse**."
else:
c2 = re.split("d|D", content)
try:
if c2[0] == '':
nb_of_dices = 1
else:
nb_of_dices = int(c2[0])
value_of_dices = int(c2[1])
except:
return(None)
if nb_of_dices != 1:
return(None)
if value_of_dices == 666:
res = "vous avez obtenu un **666**."
elif value_of_dices == 42:
res = "vous avez obtenu **la Réponse**."
return(res)
| [
"noreply@github.com"
] | noreply@github.com |
8a588419d1faefe481fdb4c509263a550fb95dd1 | 4fc973c1614ce860762842060cd873c05cd2e8cc | /f2d.py | c63dfa904c824a85d33e849f8b4f7ea8c5ea2058 | [] | no_license | CarlosPena00/ObjectDetectionV2 | 44a987277049ee9861a1a73a7959d01385ee44c1 | 928a4a1dc1220eeea829264985e1d6ed6a459a5b | refs/heads/master | 2021-01-23T15:58:57.125982 | 2017-06-11T20:34:00 | 2017-06-11T20:34:00 | 93,279,666 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,624 | py | # -*- coding: utf-8 -*-
import cv2
import pandas as pd
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import sys
sys.path.insert(0, 'Descriptors/hog')
sys.path.insert(0, 'Descriptors/lbp')
sys.path.insert(0, 'utils')
from lbp import LBP
from hog import HOG
from utils import Utils
import time
IMSIZE = 76
# Constant
HOG_URL = "./Descriptors/hog/"
LBP_URL = "./Descriptors/lbp/"
SAVE = "./Descriptors/Save/"
SAMPLE_IMAGES = "./SampleImages/"
RESULT = "./Results/"
UTILS = "./utils/"
DATA_URL = "./Data/"
NEGATIVE_FOLDER = "negativeFolder.csv"
POSITIVE_FOLDER = "positiveFolder.csv"
HISTOGRAM = "Histogram/"
NEGATIVE = "Negative/"
POSITIVE = "Positive/"
SCALER = "Scaler"
MODEL = "Model"
LINEAR = "linear"
RBF = "rbf"
RF = "rf"
JPG = ".jpg"
PNG = ".png"
SAV = ".sav"
CSV = ".csv"
NUMBER_OF_DIMS = 1764
class F2D:
'Apply the selected Descriptors into the selected foldes'
def __init__(self, positive=True, argMin=0, argMax=100, blur=False, openCV=True):
if positive is True:
self.csvFolder = POSITIVE_FOLDER
self.folder = POSITIVE
else:
self.csvFolder = NEGATIVE_FOLDER
self.folder = NEGATIVE
data = pd.read_csv(UTILS + self.csvFolder)
self.listOfFolder = data.iloc[:, :].values
self.argMin = max(argMin, 0)
self.argMax = min(argMax, self.listOfFolder.shape[0])
self.blur = blur
self.openCV = openCV
def savePlotOfHistogram(self, hist, globalHist, fileName='hist'):
if self.descriptor == 'HOG':
url = HOG_URL + HISTOGRAM
if self.descriptor == 'LBP':
url = LBP_URL + HISTOGRAM
hog = hist.ravel()
histOfHist = np.zeros(shape=9, dtype=float)
for z in range(0, 9):
histOfHist[z] = sum(hog[i] for i in range(len(hog)) if i % 9 == z)
globalHist[z] += histOfHist[z]
plt.plot(histOfHist)
plt.savefig(url + fileName + ".png")
plt.close()
def transform(self, descriptor='HOG', histogram=False):
self.descriptor = descriptor
self.hog = HOG()
self.lbp = LBP()
self.Ut = Utils()
self.histogram = histogram
for i in range(self.argMin, self.argMax):
self.folderName = self.listOfFolder[i][0]
self.typeOfFolder = "." + self.listOfFolder[i][1]
self.cut = self.listOfFolder[i][2]
self.numberOfImgs = self.listOfFolder[i][3]
self.saveFile = self.folderName[:-1] + CSV
print "----- Start Folder: " + self.folderName + " -----"
time.sleep(2)
if descriptor == 'HOG':
self.url = HOG_URL
self.dims = NUMBER_OF_DIMS
self.color = 1
self.fmt = "%f"
elif descriptor == 'LBP':
self.url = LBP_URL
self.dims = 5776
self.color = 0
self.fmt = "%d"
self.__fold2features()
def __getFeatures(self, img):
if self.descriptor == 'HOG':
return self.hog.getOpenCV(img)
if self.descriptor == 'LBP':
histLBP = local_binary_pattern(img,8,1)
return histLBP.ravel()
def __fold2features(self):
lista = np.empty([1, self.dims])
for f in tqdm(range(1, self.numberOfImgs + 1)):
src = cv2.imread(DATA_URL + self.folderName +
str(f) + self.typeOfFolder, self.color)
rows, cols = src.shape[0], src.shape[1]
if rows > 1 and cols > 1:
if self.blur:
src = cv2.pyrUp(cv2.pyrDown(src))
rows, cols = src.shape[0], src.shape[1]
if self.cut:
maxRows = rows / IMSIZE
maxCols = cols / IMSIZE
else:
maxRows = 1
maxCols = 1
for j in range(0, maxRows):
for i in range(0, maxCols):
if self.cut is True:
roi, xMin, xMax, yMin, yMax = Utils.getRoi(
src, j, i, px=IMSIZE)
else:
roi = src
rowsR, colsR = roi.shape[0], roi.shape[1]
if rowsR < 1 or colsR < 1:
print "f2d.py fold2Hog 88 ERRO roi.shape > (1,1)"
continue
if rowsR != IMSIZE or colsR != IMSIZE:
roi = cv2.resize(roi, (IMSIZE, IMSIZE))
rowsR, colsR = roi.shape[0], roi.shape[1]
hist = self.__getFeatures(roi)
lista = np.vstack((lista, hist))
else:
print "f2d.py fold2Hog 99 ERRO roi.shape > (1,1)"
hist = np.zeros(NUMBER_OF_DIMS)
lista = np.vstack((lista, hist))
# globalHistMean = globalHist/float(f)
# Save plot of Histogram
X = np.delete(lista, (0), axis=0)
np.savetxt(self.url + self.folder + self.folderName[:-1] + CSV,
X, delimiter=',', fmt=self.fmt)
from skimage.feature import local_binary_pattern
import cv2 #12499
if __name__ == "__main__":
f2d = F2D(positive=False, argMin=1, argMax=2)
#f2d.transform(descriptor='HOG')
f2d.transform(descriptor='LBP')
#src = cv2.imread("./SampleImages/sample01.jpg",0)
#print src.shape
#lbp = local_binary_pattern(src,8,1) | [
"chcp@cin.ufpe.br"
] | chcp@cin.ufpe.br |
b9a09539940e2d33d6a8d05ef2b9f880a83c5b2d | 5a93ed7313da594b5f925f7c32826e3b518ab6a7 | /datasets/__init__.py | b32ea5ffa784c6ca842c26b97a78edbc68515df8 | [
"MIT"
] | permissive | Yajha/deep-functional-dictionaries | 3e96828d517b1eda441dde55f8cbfe70965b856f | deecf8c6c85e253cfa52be7c6b3c308d5e5aaf81 | refs/heads/master | 2020-04-03T14:51:39.008685 | 2018-10-24T22:25:50 | 2018-10-24T22:25:50 | 155,338,959 | 1 | 0 | MIT | 2018-10-30T06:58:55 | 2018-10-30T06:58:54 | null | UTF-8 | Python | false | false | 262 | py | # Minhyuk Sung (mhsung@cs.stanford.edu)
# May 2018
from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and \
not f.endswith('__init__.py')]
| [
"smh0816@gmail.com"
] | smh0816@gmail.com |
08b0dad81e5e71b3cae78ec016032fb429f273de | 36693d993ffc64c47610a8d947f3d692dfefdacb | /yelp/queries.py | d056c3c885cb502af87981a29400ae736f21edb6 | [] | no_license | Marques-30/Travel_Assistant | 61ff58eefcbdc3d4e080428de2d1a6ca73c9297f | 36647bfaa60cb8c7351132d4699d2b4423b84c38 | refs/heads/main | 2023-01-13T15:51:33.226204 | 2020-11-18T06:20:07 | 2020-11-18T06:20:07 | 303,597,281 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 731 | py | search_query = '''
query GetResults($amount: Int, $term: String, $location: String, $price: String)
{
search(term: $term,
location: $location,
limit: $amount
price: $price
sort_by: "distance") {
total
business {
name
price
location {
address1
city
}
hours {
open {
day
start
end
}
}
reviews {
user {
name
}
rating
text
}
}
}
}
'''
| [
"gallegosjorge403@gmail.com"
] | gallegosjorge403@gmail.com |
9514de01d4409c032e185b1b737f384da6209452 | 67817340c5e06c0e66c3307c7f5b7f0c3c7bb658 | /235680/src/model/multiple_output/rnn.py | b8d5519d2bcb5e0338888b99aa9d16b487e175af | [] | no_license | parkjuida/dacon | 110f836dd407e5eb704ca6c412afc6a1eb7c5c9e | 5730871a7a89676d0ce95a784fbd287591e149b6 | refs/heads/master | 2023-03-25T21:23:25.033117 | 2021-03-14T12:27:20 | 2021-03-14T12:27:20 | 324,297,048 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 586 | py | import tensorflow as tf
class Lstm(tf.keras.Model):
def call(self, inputs, training=None, mask=None):
return self._model(inputs)
def get_config(self):
pass
def __init__(self, output_steps, num_features):
super().__init__()
self._model = tf.keras.Sequential([
tf.keras.layers.LSTM(32, return_sequences=False),
tf.keras.layers.Dense(output_steps * num_features,
kernel_initializer=tf.initializers.zeros),
tf.keras.layers.Reshape([output_steps, num_features])
])
| [
"bees1114@naver.com"
] | bees1114@naver.com |
90d23475f6fc52836c2fd16713ae807c4f1b7aab | 96eeee9aff9584ca58be9e1c877bb565d6e994de | /Fuel.py | 39e553e0553f9c851aecf8365922e5946255a63f | [] | no_license | anisha1095/2021_Challenge_Hack_my_Fleet | ece911da6fef24dd777f536a988d2f0e9d146eb3 | 18629fc31dbb71236cbc61395a82d959ec2842bc | refs/heads/main | 2023-03-31T12:05:06.937242 | 2021-04-11T22:20:38 | 2021-04-11T22:20:38 | 356,477,487 | 0 | 2 | null | 2021-04-11T21:25:53 | 2021-04-10T05:11:16 | Python | UTF-8 | Python | false | false | 2,797 | py | import pandas as pd
import datetime
from bokeh.plotting import figure, show, output_file
from bokeh.models import DatetimeTickFormatter
from math import pi
import statistics
from bokeh.models.widgets import Div
from bokeh.layouts import column
def getFuelInsights (dataset):
print("Loading fuel insights")
groupedDict = dataset.groupby(['Asset type', 'AssetID']).apply(lambda x: dict(zip(x['Date'], x['Fuel Level (%)']))).to_dict()
fuelData = {}
for key in groupedDict.keys():
value = groupedDict[key]
tmp = 0
lastDate = '0'
refilDates = {}
for date in value.keys():
if tmp == 0:
tmp = value[date]
lastDate = date
continue
if (int(value[date]) > int(tmp)):
d0 = datetime.datetime(int(lastDate.split("-")[0]), int(lastDate.split("-")[1]), int(lastDate.split("-")[2]))
d1 = datetime.datetime(int(date.split("-")[0]), int(date.split("-")[1]), int(date.split("-")[2]))
delta = d1 - d0
refilDates[pd.to_datetime(date, format='%Y-%m-%d')] = delta.days
lastDate = date
tmp = value[date]
fuelData[str(key[0])+"_"+str(key[1])] = refilDates
print("Loaded Fuel Insights")
return fuelData
def showFuelInsightsFor(fuelData, asssetId = "1022017", assetType = "Excavator"):
p = figure(title="Fuel Refill Dates vs days it worked before refill", x_axis_label='Refill Date',
y_axis_label='No of Days', plot_width=1000)
x = list(fuelData[assetType + "_" + asssetId].keys())
y = list(fuelData[assetType + "_" + asssetId].values())
p.circle(x, y, fill_alpha=0.2, size=5)
p.xaxis.formatter = DatetimeTickFormatter(
hours=["%d %B %Y"],
days=["%d %B %Y"],
months=["%d %B %Y"],
years=["%d %B %Y"],
)
p.xaxis.major_label_orientation = pi/4
# lastDate = x[-1]
# # A naive approach to choose the next prediction date.
# # We can use Machine learning time series prediction (ARIMA Approach) to predict the next few dates for refill.
# delta = statistics.mode(y)
# nextPredictedDate = lastDate + datetime.timedelta(days=delta)
# print("Next Refill Date : " + nextPredictedDate)
output_file("./templates/Fuel.html")
div_exp00 = Div(
text=""" <b>FUEL REFILL HISTORY GRAPH</b>
""",
width=300, style={'font-size': '100%'})
div_exp01 = Div(
text=""" This graph analyses the history of fuel refills that happened for each asset ID. Predicting the next refill date can help us figure out when a particular asset needs fuel and can help us set alerts.""",
width=300)
show(column(div_exp00, div_exp01, p))
| [
"anishajauhari10@gmail.com"
] | anishajauhari10@gmail.com |
d99f160d8ad572b13e39fa68ab9d1c9ebaeb17c3 | 493c7d9678a0724736fb9dd7c69580a94099d2b4 | /apps/organization/models.py | 81669bc929ff0415215ac5e9aca33cf0d6ca3b2d | [] | no_license | cuixiaozhao/MxOnline | e253c8c5f5fa81747d8e1ca064ce032e9bd42566 | c96ae16cea9ad966df36e9fcacc902c2303e765c | refs/heads/master | 2020-03-29T18:47:11.158275 | 2018-10-22T14:06:50 | 2018-10-22T14:06:50 | 150,231,387 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,442 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
# Create your models here.
class CityDict(models.Model):
name = models.CharField(max_length=20, verbose_name=u"城市")
desc = models.CharField(max_length=200, verbose_name=u"描述")
add_time = models.CharField(default=datetime.now, verbose_name=u"添加时间", max_length=30)
class Meta:
verbose_name = u"城市"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.name
class CourseOrg(models.Model):
name = models.CharField(max_length=50, verbose_name=u"机构名称")
desc = models.TextField(verbose_name=u"机构描述")
category = models.CharField(default="pxjg", max_length=20, choices=(("pxjg", "培训机构"), ("gr", "个人"), ("gx", "高校"),))
click_nums = models.IntegerField(default=0, verbose_name=u"点击数")
fav_nums = models.IntegerField(default=0, verbose_name=u"收藏数")
image = models.ImageField(upload_to="org/%Y/%m", verbose_name=u"LOGO")
address = models.CharField(max_length=150, verbose_name=u"机构地址")
city = models.ForeignKey(CityDict, verbose_name=u"所在城市")
students = models.IntegerField(default=0, verbose_name=u"学生人数")
course_nums = models.IntegerField(default=0, verbose_name=u"学习人数")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"课程机构"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.name
class Teacher(models.Model):
org = models.ForeignKey(CourseOrg, verbose_name=u"所属机构")
name = models.CharField(max_length=50, verbose_name=u"教师名")
work_years = models.IntegerField(default=0, verbose_name=u"工作年限")
work_company = models.CharField(max_length=50, verbose_name=u"就职公司")
work_position = models.CharField(max_length=50, verbose_name=u"公司职位")
points = models.CharField(max_length=50, verbose_name=u"教学特点")
click_nums = models.IntegerField(default=0, verbose_name=u"点击数")
fav_nums = models.IntegerField(default=0, verbose_name=u"收藏数")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"教师"
verbose_name_plural = verbose_name
| [
"19930911cXS"
] | 19930911cXS |
eff3356ac3f99b2fc9ed8694843cb006b0ae49f2 | 434b0d5e2021dd849f417ecdbf21211c68222431 | /experiments/QuickSort.py | 2be2ea2f64cc097a10e7b8748fd26a76aa521edd | [
"MIT"
] | permissive | johnpaulguzman/Algorithm-Analyzer | a4bef4b358c41d509ebe6112adc082956752f538 | e93abfb51f2f67b6df1af8d95cc6855ad7de69f2 | refs/heads/master | 2021-01-22T21:38:02.376402 | 2017-08-09T02:04:48 | 2017-08-09T02:04:48 | 85,454,334 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | def quick_sort(items):
if len(items) > 1:
pivot_index = 0
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
larger_items.append(val)
quick_sort(smaller_items)
quick_sort(larger_items)
items[:] = (smaller_items+
[items[pivot_index]]+larger_items)
def f(n): #quick_sort sort worst case
quick_sort(range(n,0,-1)) | [
"john_paul_guzman@dlsu.edu.ph"
] | john_paul_guzman@dlsu.edu.ph |
a8850c43ea34d791480a5a1dfaec3ef2d6f2f7b3 | 102687dc2cf18270f18c10ccde58b8a2c25c7316 | /wer.py | d460d18b621c0ec4e727299a677093198d0d86b6 | [] | no_license | hammondm/g2p2021 | 18a74021c3198afbf537747751214d28dc57c672 | d0fb7f944ec278222b8203f4ff1a9426b85b4ba1 | refs/heads/main | 2023-05-11T23:54:10.924703 | 2021-06-01T21:36:01 | 2021-06-01T21:36:01 | 372,967,168 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,058 | py | #calculate WER from CER
#average number of chars in training transcripotions
#calculated with avg.py
languages = {
'ady':5.9925,
'gre':6.73125,
'ice':5.72,
'ita':6.625,
'khm':5.5125,
'lav':5.94375,
'mlt_latn':5.1675,
'rum':6.1475,
'slv':5.7475,
'wel_sw':5.18375
}
import sys
import numpy as np
#cer
val = float(sys.argv[1])
#sample size in words
size = int(sys.argv[2])
accuracies = np.zeros(len(languages))
for n,language in enumerate(languages):
#word length
length = int(languages[language])
#make array for all letters
x = np.zeros(size*length)
#generate the right number of errors
ones = round(val*size*length)
#put errors in array
x[:ones] = 1
#randommize errors
x = np.random.permutation(x)
#break array into word lengths
x = x.reshape(size,length)
#calculate number of correct words
correct = np.where(x.sum(axis=1) == 0)[0].shape[0]
#calculate percent accuracy
accuracy = correct/size
accuracies[n] = accuracy
print(f'\t{language}: {accuracy:.3f}')
print(f'accuracy overall: {accuracies.sum()/len(languages):.3f}')
| [
"hammond@u.arizona.edu"
] | hammond@u.arizona.edu |
b96d3a781c03d215c27f636478125a1b32347736 | ba3d8969e5f52c6287aad879b969a148a1b1df7c | /controllers/vcms_upd_company_branch.py | dd85cae13a263d55abf2b456fef159e7b9449bb6 | [] | no_license | clubfly/python_flask | 0848e04fa9de9e219d4e7025c4d4c70ff291b532 | f1e93d6ce6516cbd3afd6ccbffea9909f8ee4aa3 | refs/heads/master | 2022-07-09T15:28:10.347699 | 2020-04-08T02:00:21 | 2020-04-08T02:00:21 | 253,957,066 | 1 | 0 | null | 2022-06-22T01:39:27 | 2020-04-08T01:44:54 | Python | UTF-8 | Python | false | false | 500 | py | from flask import jsonify,render_template,session,escape,request
from utils.htmlbuilder import HtmlBuilder
from utils.vcmsengineerfunction import VcmsEngineerFunction
from utils.vcmsadminfunction import VcmsAdminFunction
def vcms_upd_company_branch(self,functions,actions,html_template,page_settings,parameter_dict):
return_data = {}
if session["user_rank_sn"] == 3 :
return_data = VcmsAdminFunction().set_company_branch(page_settings,parameter_dict)
return jsonify(return_data)
| [
"henry.wang@viscovery.com"
] | henry.wang@viscovery.com |
c79587653a00006ecde791bc38617cb404e4a559 | 9ed18ddd8fa3f8dab53d2d3af43b5ecc03a5bfe9 | /training_utils/dump_rnn_mod.py | 1223abf8d1e16b4c60a8cc6f35beacc4510a4c36 | [
"Apache-2.0"
] | permissive | OscarLiau/RNNoise_Wrapper | 371c2ef7b48258a8ed69f1f5724126ccdc1c9e96 | 10647eba5c1dc678dc3fd443d111400792fefef6 | refs/heads/master | 2023-04-22T16:21:23.308409 | 2020-11-25T15:14:52 | 2020-11-25T15:14:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,575 | py | #!/usr/bin/python
from __future__ import print_function
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import GRU
from keras.models import load_model
from keras.constraints import Constraint
from keras import backend as K
import sys
import re
import numpy as np
def printVector(f, vector, name):
v = np.reshape(vector, (-1));
#print('static const float ', name, '[', len(v), '] = \n', file=f)
f.write('static const rnn_weight {}[{}] = {{\n '.format(name, len(v)))
for i in range(0, len(v)):
f.write('{}'.format(min(127, int(round(256*v[i])))))
if (i!=len(v)-1):
f.write(',')
else:
break;
if (i%8==7):
f.write("\n ")
else:
f.write(" ")
#print(v, file=f)
f.write('\n};\n\n')
return;
def printLayer(f, hf, struct_rnnmodel_buf, layer):
weights = layer.get_weights()
printVector(f, weights[0], layer.name + '_weights')
if len(weights) > 2:
printVector(f, weights[1], layer.name + '_recurrent_weights')
printVector(f, weights[-1], layer.name + '_bias')
name = layer.name
activation = re.search('function (.*) at', str(layer.activation)).group(1).upper()
if len(weights) > 2:
f.write('const GRULayer {} = {{\n {}_bias,\n {}_weights,\n {}_recurrent_weights,\n {}, {}, ACTIVATION_{}\n}};\n\n'
.format(name, name, name, name, weights[0].shape[0], int(weights[0].shape[1]/3), activation))
struct_rnnmodel_buf.append(' {},\n'.format(int(weights[0].shape[1]/3)))
struct_rnnmodel_buf.append(' &{},\n\n'.format(name))
hf.write(' int {}_size;\n'.format(name))
hf.write(' const GRULayer *{};\n\n'.format(name))
else:
f.write('const DenseLayer {} = {{\n {}_bias,\n {}_weights,\n {}, {}, ACTIVATION_{}\n}};\n\n'
.format(name, name, name, weights[0].shape[0], weights[0].shape[1], activation))
struct_rnnmodel_buf.append(' {},\n'.format(weights[0].shape[1]))
struct_rnnmodel_buf.append(' &{},\n\n'.format(name))
hf.write(' int {}_size;\n'.format(name))
hf.write(' const DenseLayer *{};\n\n'.format(name))
def mean_squared_sqrt_error(y_true, y_pred):
return K.mean(K.square(K.sqrt(y_pred) - K.sqrt(y_true)), axis=-1)
def my_crossentropy(y_true, y_pred):
return K.mean(2*K.abs(y_true-0.5) * K.binary_crossentropy(y_pred, y_true), axis=-1)
def mymask(y_true):
return K.minimum(y_true+1., 1.)
def msse(y_true, y_pred):
return K.mean(mymask(y_true) * K.square(K.sqrt(y_pred) - K.sqrt(y_true)), axis=-1)
def mycost(y_true, y_pred):
return K.mean(mymask(y_true) * (10*K.square(K.square(K.sqrt(y_pred) - K.sqrt(y_true))) + K.square(K.sqrt(y_pred) - K.sqrt(y_true)) + 0.01*K.binary_crossentropy(y_pred, y_true)), axis=-1)
def my_accuracy(y_true, y_pred):
return K.mean(2*K.abs(y_true-0.5) * K.equal(y_true, K.round(y_pred)), axis=-1)
class WeightClip(Constraint):
def __init__(self, c=2, name='WeightClip'):
self.c = c
def __call__(self, p):
return K.clip(p, -self.c, self.c)
def get_config(self):
return {'name': self.__class__.__name__, 'c': self.c}
model = load_model(sys.argv[1], custom_objects={'msse': msse, 'mean_squared_sqrt_error': mean_squared_sqrt_error, 'my_crossentropy': my_crossentropy, 'mycost': mycost, 'WeightClip': WeightClip})
weights = model.get_weights()
f = open(sys.argv[2], 'w')
hf = open(sys.argv[3], 'w')
f.write('/*This file is automatically generated from a Keras model*/\n\n')
f.write('#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif\n\n#include "rnn.h"\n#include "rnn_data.h"\n\n')
hf.write('/*This file is automatically generated from a Keras model*/\n\n')
hf.write('#ifndef RNN_DATA_H\n#define RNN_DATA_H\n\n#include "rnn.h"\n\n')
hf.write('struct RNNModel {\n')
layer_list = []
struct_rnnmodel_buf = ['const struct RNNModel rnnoise_model_orig = {\n']
for i, layer in enumerate(model.layers):
if len(layer.get_weights()) > 0:
printLayer(f, hf, struct_rnnmodel_buf, layer)
if len(layer.get_weights()) > 2:
layer_list.append(layer.name)
struct_rnnmodel_buf[-1] = struct_rnnmodel_buf[-1].replace(',\n', '')
struct_rnnmodel_buf.append('};\n')
f.writelines(struct_rnnmodel_buf)
hf.write('};\n\n')
hf.write('struct RNNState {\n const RNNModel *model;\n')
for i, name in enumerate(layer_list):
hf.write(' float *{}_state;\n'.format(name))
hf.write('};\n\n')
hf.write('\n#endif\n')
f.close()
hf.close()
| [
"vladsklim@gmail.com"
] | vladsklim@gmail.com |
f16c16345110a69ede186dddce47a6a807b85e47 | c5697952039d0056145aa5c6df32f571cc27bbdd | /app/salesmanager/forms.py | fe499fe9271bd7e53069d893b9827a053867079c | [] | no_license | unutulmaz/flask-restaurant-demo | 562794ba083ca2f2fdb3f3cdf7f9aeb6e2130cba | 9f0851e83c4691da038ef0ef3bbbec39ac736026 | refs/heads/master | 2020-05-19T18:55:39.050404 | 2015-03-09T14:27:23 | 2015-03-09T14:27:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 660 | py | from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, SubmitField, FileField, FloatField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo
from wtforms import ValidationError
from ..models import User, Role, Restaurant, FoodItem
class RestaurantForm(Form):
name = StringField('restaurantName')
description = TextAreaField('description')
city = StringField('city')
submit = SubmitField('submit')
class FoodItemForm(Form):
price = FloatField('price')
#image = FileField('image file')
name = StringField('food name')
description = TextAreaField('description')
submit = SubmitField('submit')
| [
"donsol53@gmail.com"
] | donsol53@gmail.com |
4ab8bc83cb1ffc30313f0d61577d05d77710a241 | 019161650422d0901ffb925eb7a7fa93d18f5b76 | /3D点云/00.配套资料(代码、讲义、作业、参考文献)/00.配套资料(代码、讲义、作业、参考文献)/03.3D数据表示和转换/HW/octree_pcl.py | 9c7a1e0d0f6d0c938fda59cf6586c393b2c17e74 | [] | no_license | seaside2mm/SLAM_3D_Study | a5e62d363d29e4091fa479e045d7b1d6be929053 | 5b33730220e7ca5b6ae47500e42ee747eb72e0c4 | refs/heads/master | 2023-02-13T22:09:07.767953 | 2021-01-06T12:20:21 | 2021-01-06T12:20:21 | 312,931,959 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 660 | py | import pcl
import numpy as np
np.random.seed(1234)
cloud = pcl.PointCloud()
cloud.from_array(np.random.rand(100,3).astype(np.float32))
octree = cloud.make_octreeSearch(0.2)
octree.add_point_from_input_cloud()
searchPoint = pcl.PointCloud()
searchPoint.from_array(np.random.rand(5,3).astype(np.float32))
K = 10
print("\n#################### KNN with K: %d ################3"%K)
[idx, dist] = octree.nearest_K_search_from_cloud(searchPoint, K)
for idx0, dist0, pnt in zip(idx, dist, searchPoint):
print("search center:",pnt)
for i,d in zip(idx0, dist0):
x,y,z = cloud[i]
print(" id:%d, dist:%.4f, (%.4f,%.4f,%.4f)"%(i,d**0.5,x,y,z)) | [
"seasidezhang@gmail.com"
] | seasidezhang@gmail.com |
fda61ebeedcfdbf6898f42867f02806644a0d0df | 613eaf8503a1864727fab47acdacbcf24f4baadc | /scripts/fetch.py | f3d9466d37dbc03fc8cf527e58081e0c2fd09c79 | [
"MIT"
] | permissive | karthikb351/thumbsdb | 4d23ffce01d70ba507fd03a8fe87695ae1df5f4d | 99d010303d7196cf2a787b1276870cefa82b0ae6 | refs/heads/master | 2021-01-23T07:02:43.731247 | 2017-11-22T00:19:19 | 2017-11-22T00:19:19 | 30,406,396 | 3 | 2 | null | 2015-07-27T10:52:13 | 2015-02-06T10:06:09 | JavaScript | UTF-8 | Python | false | false | 1,623 | py | """ Pull All Youtube Videos from a Playlist """
import json
from apiclient.discovery import build
DEVELOPER_KEY = "AIzaSyDLMAhvP1smHaSJ_iwjLEEgXqqNhhQkVok"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def fetch_all_youtube_videos(playlistId):
"""
Fetches a playlist of videos from youtube
We splice the results together in no particular order
Parameters:
parm1 - (string) playlistId
Returns:
playListItem Dict
"""
youtube = build(YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
res = youtube.playlistItems().list(
part="snippet",
playlistId=playlistId,
maxResults="50"
).execute()
nextPageToken = res.get('nextPageToken')
while ('nextPageToken' in res):
nextPage = youtube.playlistItems().list(
part="snippet",
playlistId=playlistId,
maxResults="50",
pageToken=nextPageToken
).execute()
videoItems = youtube.videos().list(
part="snippet,contentDetails",
id=",".join([item['snippet']['resourceId']['videoId'] for item in nextPage['items']])
).execute()
res['items'] = res['items'] + videoItems['items']
if 'nextPageToken' not in nextPage:
res.pop('nextPageToken', None)
else:
nextPageToken = nextPage['nextPageToken']
return res
if __name__ == '__main__':
videos = fetch_all_youtube_videos("PLC6A6E798515CCFE0")
print len(videos['items'])
with open('data.json', 'w') as f:
json.dump(videos['items'], f)
| [
"karthikb351@gmail.com"
] | karthikb351@gmail.com |
041f93f380cb1c8e295a74f2957684446e8341f5 | eadea2403ff0ddc6fa89899937cfec337993ee67 | /db_repository/versions/040_migration.py | 009fa7322b88067859c017fba89a7691ca7c6d8f | [] | no_license | rpp114/sbt_notes | f724e90b7e50b294dd16515ce898774a2219d534 | 2d5bf9a431caa2f7b6123e5242dc46be2a818599 | refs/heads/master | 2023-07-07T12:45:46.691008 | 2023-06-27T02:19:28 | 2023-06-27T02:19:28 | 97,987,457 | 0 | 0 | null | 2022-10-12T03:49:52 | 2017-07-21T21:21:23 | Python | UTF-8 | Python | false | false | 1,319 | py | from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
regional_center = Table('regional_center', post_meta,
Column('id', INTEGER, primary_key=True, nullable=False),
Column('rc_id', INTEGER),
Column('company_id', INTEGER),
Column('name', VARCHAR(length=55)),
Column('appt_reference_name', VARCHAR(length=55)),
Column('address', VARCHAR(length=255)),
Column('city', VARCHAR(length=55)),
Column('state', VARCHAR(length=10), default=ColumnDefault('CA')),
Column('zipcode', VARCHAR(length=15)),
Column('primary_contact_name', VARCHAR(length=55)),
Column('primary_contact_phone', VARCHAR(length=55)),
Column('primary_contact_email', VARCHAR(length=55)),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['regional_center'].columns['company_id'].create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['regional_center'].columns['company_id'].drop()
| [
"ray@home-pc.socal.rr.com"
] | ray@home-pc.socal.rr.com |
6d29c5ec586425f53f6a28cfef8c986200a49985 | 1b16ae7be2f97bfc287ff5778213a463f04bcb84 | /crawl/ProducerConsumer.py | 13ed8913f400eb16a3188515dd20437860eb11b5 | [] | no_license | minisin/pytools | fddb69b5deac52cedb1ae193f91ff63550c625c6 | f7f979707695c1ad4d74c82954545dcd6ea46307 | refs/heads/master | 2021-01-15T22:38:20.211148 | 2015-01-17T10:46:34 | 2015-01-17T10:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,209 | py | #! /usr/bin/python
# encoding:utf-8
import os
import sys
import logging
import re
import urllib2
from datetime import datetime
import time
from multiprocessing import Pool, Process, Manager
import threading
from Queue import Queue
import signal
import logging
MAX_THD_NUM = 1000
class TProducer(threading.Thread):
def __init__(self, queue, consumer_num = MAX_THD_NUM):
threading.Thread.__init__(self)
self.setDaemon(True)
self.queue = queue
self.consumer_num = consumer_num
def run(self, *args):
logging.info('start producer')
self.produce_all(*args)
for i in range(self.consumer_num):
self.queue.put(None)
logging.info('end producer')
def produce_all(self, *args):
time.sleep(1)
self.queue.put(1)
logging.info('producer, not implemented, put one element in q')
class TConsumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.setDaemon(True)
self.queue = queue
def run(self, *args):
logging.info('start consumer')
global is_exit
while True:
ret = self.consume_one(*args)
if ret == -1:
break
logging.info('end consumer')
def consume_one(self, *args):
time.sleep(1)
logging.info('consumer, not implemented, get one element from q')
oneObj = self.queue.get()
if not oneObj:
logging.info('consumer: get None obj, exit')
return -1
def handler(signum, frame):
global is_exit
logging.info('caught kill signal, set is_exit')
is_exit = True
sys.exit(-1)
def init_kill_signal():
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
def main():
init_kill_signal()
logging.basicConfig(level=logging.INFO, filename='log')
q = Queue()
for i in range(5):
t = TConsumer(q)
t.start()
p = TProducer(q)
p.start()
alive = True
while alive:
alive = False
alive = alive or p.isAlive()
logging.info('p alive:' + str(alive))
time.sleep(1)
if __name__ == '__main__':
main()
| [
"weiguozheng466@jk.cn"
] | weiguozheng466@jk.cn |
b6f092ec717c1826e99b02587701066605c34069 | 5f20633536ae7f74933be34c7495370306a7278f | /main.py | f944d71ca28f52c2288f8a43e97379dc189a04fc | [] | no_license | ShonTitor/-proyecto-3-ci5437 | 0817b8f694ae4a4115a51078123170060968a4ae | 46ee73d9ffac1795d8eaa2aa039a8a53bb5681fa | refs/heads/main | 2023-06-23T13:17:18.746747 | 2021-07-24T03:03:51 | 2021-07-24T03:03:51 | 385,099,695 | 0 | 0 | null | 2021-07-12T02:12:04 | 2021-07-12T02:12:04 | null | UTF-8 | Python | false | false | 5,783 | py | import os
import sys
import datetime
import json
from icalendar import Calendar, Event
with open(sys.argv[1], "r") as f:
s = f.read()
data = json.loads(s)
print(data)
participants = data["participants"]
start_date = datetime.date.fromisoformat(data['start_date'])
end_date = datetime.date.fromisoformat(data['end_date'])
start_time = datetime.time.fromisoformat(data['start_time'])
end_time = datetime.time.fromisoformat(data['end_time'])
print("starts at", start_date, start_time)
print("ends at", end_date, end_time)
days = end_date - start_date + datetime.timedelta(days=1)
days = days.days
hours = datetime.datetime.combine(datetime.date.min, end_time) - datetime.datetime.combine(datetime.date.min, start_time)
hours = hours.seconds//3600
timeslots_per_day = hours//2
total_timeslots = timeslots_per_day * days
print(days, "days,", hours, "hours per day,", timeslots_per_day, "timeslots per day")
n_participants = len(data["participants"])
n_games = n_participants*(n_participants-1)
n_vars = n_games * total_timeslots
print(n_participants, "participants,", n_games, "games in total")
print(n_vars, "variables")
clauses = []
# cada juego ocurre en al menos un timeslot
game_clauses = [[j for j in range(i, i+total_timeslots)] for i in range(1, n_vars+1, total_timeslots)]
clauses += game_clauses
# cada juego ocurre en un solo timeslot
for clause in game_clauses:
for i in range(len(clause)):
for j in range(i+1, len(clause)):
clauses.append([-clause[i], -clause[j]])
# solo ocurre un juego por timeslot
timeslot_vars = [[i+slot for i in range(1, n_vars, total_timeslots)] for slot in range(total_timeslots)]
for var_list in timeslot_vars:
for i in range(len(var_list)):
for j in range(i+1, len(var_list)):
clauses.append([-var_list[i], -var_list[j]])
def get_var(participant_home, participant_visitor, timeslot):
assert(participant_home != participant_visitor)
game = participant_visitor
if participant_visitor > participant_home :
game -= 1
n = 1
n += participant_home * (n_participants-1) * total_timeslots
n += game * total_timeslots
n += timeslot
return n
def get_vars(participant_home, participant_visitor, day):
n = get_var(participant_home, participant_visitor, day * timeslots_per_day)
return [n+i for i in range(timeslots_per_day)]
# un participante puede jugar a lo sumo una vez por día
for day in range(days):
for player1 in range(n_participants):
acum = []
for player2 in range(n_participants):
if player1 == player2:
continue
acum += get_vars(player1, player2, day)
acum += get_vars(player2, player1, day)
for i in range(len(acum)):
for j in range(i+1, len(acum)):
clauses.append([-acum[i], -acum[j]])
# un participante no puede jugar de "local" en dos días consecutivos
# un participante no puede jugar de "visitante" en dos días consecutivos
for player1 in range(n_participants):
for day in range(days-1):
local1 = []
local2 = []
visitor1 = []
visitor2 = []
for player2 in range(n_participants):
if player1 == player2:
continue
local1 += get_vars(player1, player2, day)
local2 += get_vars(player1, player2, day+1)
visitor1 += get_vars(player2, player1, day)
visitor2 += get_vars(player2, player1, day+1)
for list1, list2 in [(local1, local2), (visitor1, visitor2)]:
for v1 in list1:
for v2 in list2:
clauses.append([-v1, -v2])
out = "p cnf {} {}\n".format(n_vars, len(clauses))
out += " 0\n".join([" ".join(map(str, clause)) for clause in clauses])+" 0"
open("sat.txt", "a").close()
with open("sat.txt", "w", encoding="utf-8") as f:
f.truncate()
f.write(out)
glucose_command = "glucose/simp/glucose_static sat.txt sat_sol.txt"
os.system(glucose_command)
with open("sat_sol.txt", "r") as f:
s = f.read()
if 'UNSAT' in s:
sys.exit(0)
solution = filter(lambda n: n>0, [int(i) for i in s.split(" ")])
def var_to_event(var):
timeslot = var % total_timeslots - 1
game = var // total_timeslots
player1 = game // (n_participants - 1)
player2 = game % (n_participants - 1)
if player1 <= player2:
player2 += 1
#print(var, get_var(player1, player2, timeslot))
assert(get_var(player1, player2, timeslot) == var)
day = timeslot // timeslots_per_day
time = timeslot % timeslots_per_day
#print(timeslot, participants[player1], participants[player2], day, time)
event_day = start_date + datetime.timedelta(days=day)
event_time = datetime.datetime.combine(datetime.date.min, start_time) + datetime.timedelta(hours=time*2)
event_time = event_time.time()
event_end_time = datetime.datetime.combine(datetime.date.min, start_time) + datetime.timedelta(hours=time*2+2)
event_end_time = event_end_time.time()
event_date = datetime.datetime.combine(event_day, event_time)
event_end_date = datetime.datetime.combine(event_day, event_end_time)
event = Event()
event.add('summary', '{} (local) VS {} (visitor)'.format(participants[player1], participants[player2]))
event.add('dtstart', event_date)
event.add('dtend', event_end_date)
return event
cal = Calendar()
cal['summary'] = data["tournament_name"]
cal.add('attendee', participants)
for var in solution:
cal.add_component(var_to_event(var))
cal_content = cal.to_ical().decode("utf-8")
if len(sys.argv) > 2:
filename = sys.argv[2]
else:
filename = data["tournament_name"]+".ics"
open(filename, "a").close()
with open(filename, "w", encoding="utf-8") as f:
f.truncate()
f.write(cal_content) | [
"14-10576@usb.ve"
] | 14-10576@usb.ve |
c9ce9b181da48ad6ce843987d89628b88aa22eea | c3c1b799e3b6b7bf17382c59fec3ad476da13bac | /Python3/project_euler/001_050/031.py | 16ad69d8d8e92b03375906153b58cf313665b61e | [
"MIT"
] | permissive | gaddeprasanna/general | cb53684dc5b03ef804867f7a23e1ae1d4bf3ea18 | 1843cefc15e4b4b2be5a72e4c48fb6720d2bf4e1 | refs/heads/master | 2021-01-18T02:13:12.387978 | 2014-06-26T18:35:21 | 2014-06-26T18:35:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,080 | py | __author__ = 'Aseem'
def prob_031():
#TODO Needs to be refactored
ways = 1
for i in range(3):
sum_a = i * 100
for j in range(5):
sum_b = sum_a + j*50
if sum_b > 200:
break
for k in range(11):
sum_c = sum_b + k*20
if sum_c > 200:
break
for l in range(21):
sum_d = sum_c + l*10
if sum_d > 200:
break
for m in range(41):
sum_e = sum_d + m*5
if sum_e > 200:
break
for n in range(101):
sum_f = sum_e + n*2
if sum_f > 200:
break
for o in range(201):
if sum_f + o == 200:
ways += 1
return ways
import time
s = time.time()
print(prob_031())
print(time.time() - s)
| [
"aseembansal@live.com"
] | aseembansal@live.com |
3a7ec7608fdf44cc95166937882742abb6bbd003 | 51bc5977a0c8461f9dd84d3bc0f41604c79544dd | /mpl_plotter_mock_data.py | 47cfddaa667c4e633fd0c4cdb3a001d179f163ec | [] | no_license | diegoslm/Data_Analysis | 1edb853697bfc45c45f8eb3a43886a9762d8f828 | 3e3668e3ed7d26f216546ce39c3cc8b5a072fba9 | refs/heads/master | 2022-10-26T12:47:23.012995 | 2020-06-09T23:42:43 | 2020-06-09T23:42:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,064 | py | import numpy as np
import pandas as pd
from numpy import sin, cos
from matplotlib import cbook
class MockData:
def filled_julia(self, xyz_2d=False, xyz_3d=False, df=False):
w, h, zoom = 1920, 1920, 1
cX, cY = -0.7, 0.27015
moveX, moveY = 0.0, 0.0
maxIter = 255
z = np.zeros(shape=(w, h))
for x in range(w):
for y in range(h):
zx = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX
zy = 1.0 * (y - h / 2) / (0.5 * zoom * h) + moveY
i = maxIter
while zx * zx + zy * zy < 4 and i > 1:
tmp = zx * zx - zy * zy + cX
zy, zx = 2.0 * zx * zy + cY, tmp
i -= 1
z[x, y] = (i << 21) + (i << 10) + i * 8
x = np.linspace(0, w, w)
y = np.linspace(0, h, h)
if xyz_2d is True:
return x, y, z
if xyz_3d is True:
x, y = np.meshgrid(x, y)
return x, y, z
if df is True:
return pd.DataFrame(z)
return np.linspace(0, w, w), np.linspace(0, h, h), z
def spirograph(self):
# Plot a spirograph
R = 125
d = 200
r = 50
dtheta = 0.2
steps = 8 * int(6 * 3.14 / dtheta)
x = np.zeros(shape=(steps, 1))
y = np.zeros(shape=(steps, 1))
theta = 0
for step in range(0, steps):
theta = theta + dtheta
x[step] = (R - r) * cos(theta) + d * cos(((R - r) / r) * theta)
y[step] = (R - r) * sin(theta) - d * sin(((R - r) / r) * theta)
return x, y
def sinewave(self):
steps = 100
x_max = 215
x = np.linspace(-x_max, x_max, steps)
y = 50 * np.sin(2 * np.pi * (x + x_max) / x_max)
return x, y
def waterdropdf(self):
d = 1000
x = np.linspace(-3, 3, d)
y = np.linspace(-3, 3, d)
x, y = np.meshgrid(x, y)
z = -(1 + cos(12 * np.sqrt(x * x + y * y))) / (0.5 * (x * x + y * y) + 2)
return pd.DataFrame(z)
def waterdrop3d(self):
d = 100
x = np.linspace(-3, 3, d)
y = np.linspace(-3, 3, d)
x, y = np.meshgrid(x, y)
z = -(1 + np.cos(12 * np.sqrt(x * x + y * y))) / (0.5 * (x * x + y * y) + 2)
print(x.shape, y.shape)
return x, y, z
def random3d(self):
np.random.seed(123)
x, y = np.random.uniform(size=(100, 2)).T
z = -(1 + np.cos(12 * np.sqrt(x * x + y * y))) / (0.5 * (x * x + y * y) + 2)
return x, y, z
def hill(self):
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
np.load(file) as dem:
z = dem['elevation']
nrows, ncols = z.shape
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
x, y = np.meshgrid(x, y)
region = np.s_[5:50, 5:50]
x, y, z = x[region], y[region], z[region]
return x, y, z
| [
"antonlopezr99@gmail.com"
] | antonlopezr99@gmail.com |
801122e3e9e4fe26fb5476460ac4012f5554371e | 59150007a9a3ee68ddfb26a170e3647545c214bb | /test/test_new_or_updated_record.py | 1a81f21190d52c2d2705f1dc58997360a789d3bd | [
"Apache-2.0"
] | permissive | nwton/fork_mdsina_selectel-dns-api | 4bc98c6784017163676f494147d0ac773ffaab46 | 30b02260a3bf86e0fbbafad372292aafb13206ee | refs/heads/master | 2020-08-29T02:11:02.664804 | 2018-04-22T10:06:37 | 2018-04-22T10:06:37 | 217,890,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,392 | py | # coding: utf-8
"""
Selectel DNS API
Simple Selectel DNS API.
OpenAPI spec version: 1.0.0
Contact: info@mdsina.ru
Generated by: https://github.com/swagger-api/swagger-codegen.git
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 __future__ import absolute_import
import os
import sys
import unittest
import selectel_dns_api
from selectel_dns_api.rest import ApiException
from selectel_dns_api.models.new_or_updated_record import NewOrUpdatedRecord
class TestNewOrUpdatedRecord(unittest.TestCase):
""" NewOrUpdatedRecord unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testNewOrUpdatedRecord(self):
"""
Test NewOrUpdatedRecord
"""
model = selectel_dns_api.models.new_or_updated_record.NewOrUpdatedRecord()
if __name__ == '__main__':
unittest.main()
| [
"dmikhailov@plesk.com"
] | dmikhailov@plesk.com |
7ef676003fc406424f41ca8edfb9128e95122731 | a68648f0d55fd249507f9b96f15a5626c7d7beb6 | /raterprojectapi/apps.py | 22594ac496c1a5c0d165e9bc3078c6a619d5be01 | [] | no_license | devinmgarcia/raterproject-api | c15d361d5829fdcffbde571a01a8f10443e14ee6 | 01eb238cd05886845708ca0067dbe718784f08e1 | refs/heads/main | 2023-07-01T22:35:14.059354 | 2021-08-12T15:18:02 | 2021-08-12T15:18:02 | 392,051,562 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 162 | py | from django.apps import AppConfig
class RaterprojectapiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'raterprojectapi'
| [
"devinmgarcia@gmail.com"
] | devinmgarcia@gmail.com |
f76aa429deacb462b453c1aa6ca3b11698465f27 | 716935ca840b972067b9cda0e5462af8fc68f804 | /Preprocess/Preprocess.py | a3321fd594d03d4e2fb5dbc57789c17cef91546d | [] | no_license | zch997974853/Graduation-Project | afbda94165c2592e3ffdcd7f2403ad4f305a97fc | 4fec90248c4ad7f948b60ce495866f67d23a7c95 | refs/heads/master | 2021-03-25T23:25:55.516395 | 2020-03-16T09:16:06 | 2020-03-16T09:16:06 | 247,654,224 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,169 | py | # 主函数Preprocess.py
# 功能:将逻辑分析仪采集得到的.csv数据转化为图像
# 涉及到的子函数:
# 1、GetSpiData:提取出.csv文件中的SPI总线数据
# 2、GetFlashData:提取出SPI总线数据中写入Flash芯片的数据
# 3、GetRawData:将Flash芯片中的数据按节点提取出来
# 4、Transpic:将节点补长度并转化为图像
# 使用到的变量:
# 路径变量:
# Data_dir:逻辑分析仪导出的.csv文件地址
# Raw_dir:预处理后所有类型节点图像输出地址
# InodeData_dir:预处理后inode类型节点图像输出地址
# InodeContent_dir:预处理后有内容的inode类型节点的图像输出地址
# 关键中间过程变量:
# CsvData:.csv中的文件内容
# SpiData:SPI总线数据
# FlashData:写入Flash芯片的数据
# DirentData:dirent类型节点数据
# InodeData:inode类型节点数据
# MaxLengthData:补至最大长度后的节点数据
# PicData:转化生成的图像数据
#
import os
import csv
from PIL import Image
import numpy as np
# CalculateStr:计算小端字符串代表的值
def CalculateStr(str):
result = 0
i = 0
maxlength = len(str)
while i < maxlength:
result += int(str[i],16) * pow(256, i)
i += 1
return result
# GetSpiData:提取出.csv文件中的SPI总线数据
def GetSpiData(FILE):
f = open(FILE)
CsvData = f.read()
#CsvData = pd.read_csv(FILE)
Spi = []
index = 0
maxlength = len(CsvData) - 5
count = 0
while index < maxlength:
'''
if CsvData[index:index+4] == 'MISO':
index += 9
while CsvData[index:index+2] != '0x':
index += 1
Spi.append(CsvData[index+2:index+4])
index += 47
else:
index += 1
'''
##
if CsvData[index:index + 3] == '(0x':
count += 1
if count % 2 == 0:
index += 3
Spi.append(CsvData[index:index+2])
else:
index += 9
else:
index += 1
print('GetSpiData Success')
#print(Spi)
return Spi
# GetFlashData:提取出SPI总线数据中写入Flash芯片的数据
def GetFlashData(Spi):
Flash = []
index = 0
maxlength = len(Spi) - 4
while index < maxlength:
if Spi[index:index+4] == ['06', '05', '00', '02']:
#if (Spi[index:index + 4] == ['06', '05', '00', '02']) | (Spi[index:index + 4] == ['06', '04', '00', '02']):
index += 7
while (Spi[index:index+3] != ['04', '05', '00']) & (Spi[index:index+3] != ['05', '00', '05']) & (Spi[index:index+3] != ['05', '00', '06']):
Flash.append(Spi[index])
#print(index)
index += 1
if index == maxlength:
Flash.append(Spi[index])
Flash.append(Spi[index + 1])
Flash.append(Spi[index + 2])
#print(index)
break
else:
index += 1
print('GetFlashData Success')
#print(Flash)
return Flash
# Transpic:将节点补长度并转化为图像
def Transpic(raw, dir, name):
MAXLENGTH = 16 * 16
MAX_i = 65 # 最大行数
MAX_j = 65 # 最大列数
result = np.zeros((MAX_i,MAX_j,3))
for i in range(MAX_i):
for j in range(MAX_j):
if (i * MAX_i + j < len(raw)):
result[i][j][0] = int(raw[i * MAX_i + j], 16)
result[i][j][1] = int(raw[i * MAX_i + j], 16)
result[i][j][2] = int(raw[i * MAX_i + j], 16)
im = Image.fromarray(result.astype(np.uint8))
im.save(dir + '\\' + name)
return result
def Transcsv(jffs2_raw_inode, csv_file):
MAXLENGTH = 65 * 65
with open(csv_file, 'a+', newline='') as f:
csv_write = csv.writer(f)
destination = []
for item in jffs2_raw_inode:
destination.append(int(item, 16))
destination = list([ ] + destination + [0] * (MAXLENGTH - len(destination)))
csv_write.writerow(destination)
# GetRawData:将Flash芯片中的数据按节点提取出来
def GetRawData(Flash, save_dir, csv_file, work_mode1=0, work_mode2=0, init_number=0):
index = 0
dirent_num = 0
inode_num = 0
picversion = init_number
maxlength = len(Flash) - 4
while index < maxlength:
if Flash[index:index + 4] == ['85', '19', '01', 'E0']:
dirent_num += 1
nodetype = Flash[index:index + 4]
index += 4
totlen = Flash[index:index + 4]
index += 4
hdr_crc = Flash[index:index + 4]
index += 4
pio = Flash[index:index + 4]
index += 4
version = Flash[index:index + 4]
index += 4
ino = Flash[index:index + 4]
index += 4
mctime = Flash[index:index + 4]
index += 4
unuseds = Flash[index:index + 4]
index += 4
node_crc = Flash[index:index + 4]
index += 4
name_crc = Flash[index:index + 4]
index += 4
name_length = CalculateStr(totlen) - 40
name = Flash[index:index + name_length]
index += name_length
jffs2_raw_dirent = nodetype + totlen + hdr_crc + pio + version + ino + mctime + unuseds + node_crc + name_crc + name
print('Found a jffs2_raw_dirent', dirent_num, ', length:', len(jffs2_raw_dirent))
print(jffs2_raw_dirent)
elif Flash[index:index + 4] == ['85', '19', '02', 'E0']:
inode_num += 1
nodetype = Flash[index:index + 4]
index += 4
totlen = Flash[index:index + 4]
index += 4
hdr_crc = Flash[index:index + 4]
index += 4
ino = Flash[index:index + 4]
index += 4
version = Flash[index:index + 4]
index += 4
mode = Flash[index:index + 4]
index += 4
ugid = Flash[index:index + 4]
index += 4
isize = Flash[index:index + 4]
index += 4
atime = Flash[index:index + 4]
index += 4
mtime = Flash[index:index + 4]
index += 4
ctime = Flash[index:index + 4]
index += 4
offset = Flash[index:index + 4]
index += 4
csize = Flash[index:index + 4]
index += 4
dsize = Flash[index:index + 4]
index += 4
comprs = Flash[index:index + 4]
index += 4
data_crc = Flash[index:index + 4]
index += 4
node_crc = Flash[index:index + 4]
index += 4
data_length = CalculateStr(totlen) - 68
data = Flash[index:index + data_length]
index += data_length
jffs2_raw_inode = nodetype + totlen + hdr_crc + ino + version + mode + ugid + isize + atime + mtime + ctime + offset + csize + dsize + comprs + data_crc + node_crc + data
print('Found a jffs2_raw_inode',inode_num, ', length:', len(jffs2_raw_inode))
print(jffs2_raw_inode)
if data_length != 0:
picversion += 1
print('Found a jffs2_raw_inode', inode_num, ', length:', len(jffs2_raw_inode))
print(jffs2_raw_inode)
if work_mode1:
Transpic(jffs2_raw_inode, save_dir, str(picversion)+'.jpg')
if work_mode2:
Transcsv(jffs2_raw_inode, csv_file)
else:
index += 1
return picversion
# 对单个file处理
def Preprocess(file, init_number, path, csv_file, work_mode1=0, work_mode2=0):
SpiData = GetSpiData(file) # 提取出.csv文件中的SPI总线数据
FlashData = GetFlashData(SpiData) # 提取出SPI总线数据中写入Flash芯片的数据
init_number = GetRawData(FlashData, path, csv_file, work_mode1, work_mode2, init_number) # GetRawData:将Flash芯片中的数据按节点提取出来
print('COMPLETE!')
return init_number
# 主函数
def work():
path = os.getcwd()
init_number = 0
Data_dir = path + "\\Data" # 数据路径
Raw_dir = path + "\\Raw"
InodeData_dir = path + "\\InodeData"
InodeContent_dir = path + "\\InodeContent"
Test_dir = path + "\\Test" # 图像输出目标路径
csv_file = Test_dir + "\\test.csv" # 节点输出目标csv
fileList = os.listdir(Data_dir)
for file in fileList:
print(file)
init_number = Preprocess(Data_dir+"\\"+file, init_number, Test_dir, csv_file, work_mode1=1, work_mode2=1)
if __name__ == '__main__':
work()
#Preprocess("C:\\Users\\tonym\\Desktop\\Preprocess\\test_data\\Data.csv", 0, 0, 0, work_mode1=0, work_mode2=0)
| [
"noreply@github.com"
] | noreply@github.com |
3b24a7fea645a70407a8d0ad9eb7f57491b4f6bf | 5fe6541cba14f8d8e9ce484e50d334641ceb0455 | /server/__init__.py | cd56829e5fa1e12a903e47e0b8da44aa56ca89f6 | [] | no_license | allan869/my_platform | d8b7b6649e9698a95c6ea84779f05c2c2ac2b2c4 | b100a4a7201cd6e4f660ee8634db08b16e71cbbc | refs/heads/master | 2021-09-01T06:19:42.222721 | 2017-12-25T09:16:36 | 2017-12-25T09:16:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,520 | py | # coding:utf-8
data = [
{
"Name": "Tiger Nixon",
"Position": "System Architect",
"Office": "Edinburgh",
"Extn": "5421",
"Start": "2011/04/25",
"Salary": "$320,800"
},
{
"Name": "Garrett Winters",
"Position": "Accountant",
"Office": "Tokyo",
"Extn": "8422",
"Start": "2011/07/25",
"Salary": "$170,750"
},
{
"Name": "Ashton Cox",
"Position": "Junior Technical Author",
"Office": "San Francisco",
"Extn": "1562",
"Start": "2009/01/12",
"Salary": "$86,000"
},
{
"Name": "Cedric Kelly",
"Position": "Senior Javascript Developer",
"Office": "Edinburgh",
"Extn": "6224",
"Start": "2012/03/29",
"Salary": "$433,060"
},
{
"Name": "Airi Satou",
"Position": "Accountant",
"Office": "Tokyo",
"Extn": "5407",
"Start": "2008/11/28",
"Salary": "$162,700"
},
{
"Name": "Brielle Williamson",
"Position": "Integration Specialist",
"Office": "New York",
"Extn": "4804",
"Start": "2012/12/02",
"Salary": "$372,000"
},
{
"Name": "Herrod Chandler",
"Position": "Sales Assistant",
"Office": "San Francisco",
"Extn": "9608",
"Start": "2012/08/06",
"Salary": "$137,500"
},
{
"Name": "Rhona Davidson",
"Position": "Integration Specialist",
"Office": "Tokyo",
"Extn": "6200",
"Start": "2010/10/14",
"Salary": "$327,900"
},
{
"Name": "Colleen Hurst",
"Position": "Javascript Developer",
"Office": "San Francisco",
"Extn": "2360",
"Start": "2009/09/15",
"Salary": "$205,500"
},
{
"Name": "Sonya Frost",
"Position": "Software Engineer",
"Office": "Edinburgh",
"Extn": "1667",
"Start": "2008/12/13",
"Salary": "$103,600"
},
{
"Name": "Jena Gaines",
"Position": "Office Manager",
"Office": "London",
"Extn": "3814",
"Start": "2008/12/19",
"Salary": "$90,560"
},
{
"Name": "Quinn Flynn",
"Position": "Support Lead",
"Office": "Edinburgh",
"Extn": "9497",
"Start": "2013/03/03",
"Salary": "$342,000"
},
{
"Name": "Charde Marshall",
"Position": "Regional Director",
"Office": "San Francisco",
"Extn": "6741",
"Start": "2008/10/16",
"Salary": "$470,600"
},
{
"Name": "Haley Kennedy",
"Position": "Senior Marketing Designer",
"Office": "London",
"Extn": "3597",
"Start": "2012/12/18",
"Salary": "$313,500"
},
{
"Name": "Tatyana Fitzpatrick",
"Position": "Regional Director",
"Office": "London",
"Extn": "1965",
"Start": "2010/03/17",
"Salary": "$385,750"
},
{
"Name": "Michael Silva",
"Position": "Marketing Designer",
"Office": "London",
"Extn": "1581",
"Start": "2012/11/27",
"Salary": "$198,500"
},
{
"Name": "Paul Byrd",
"Position": "Chief Financial Officer (CFO)",
"Office": "New York",
"Extn": "3059",
"Start": "2010/06/09",
"Salary": "$725,000"
},
{
"Name": "Gloria Little",
"Position": "Systems Administrator",
"Office": "New York",
"Extn": "1721",
"Start": "2009/04/10",
"Salary": "$237,500"
},
{
"Name": "Bradley Greer",
"Position": "Software Engineer",
"Office": "London",
"Extn": "2558",
"Start": "2012/10/13",
"Salary": "$132,000"
},
{
"Name": "Dai Rios",
"Position": "Personnel Lead",
"Office": "Edinburgh",
"Extn": "2290",
"Start": "2012/09/26",
"Salary": "$217,500"
},
{
"Name": "Jenette Caldwell",
"Position": "Development Lead",
"Office": "New York",
"Extn": "1937",
"Start": "2011/09/03",
"Salary": "$345,000"
},
{
"Name": "Yuri Berry",
"Position": "Chief Marketing Officer (CMO)",
"Office": "New York",
"Extn": "6154",
"Start": "2009/06/25",
"Salary": "$675,000"
},
{
"Name": "Caesar Vance",
"Position": "Pre-Sales Support",
"Office": "New York",
"Extn": "8330",
"Start": "2011/12/12",
"Salary": "$106,450"
},
{
"Name": "Doris Wilder",
"Position": "Sales Assistant",
"Office": "Sidney",
"Extn": "3023",
"Start": "2010/09/20",
"Salary": "$85,600"
},
{
"Name": "Angelica Ramos",
"Position": "Chief Executive Officer (CEO)",
"Office": "London",
"Extn": "5797",
"Start": "2009/10/09",
"Salary": "$1,200,000"
},
{
"Name": "Gavin Joyce",
"Position": "Developer",
"Office": "Edinburgh",
"Extn": "8822",
"Start": "2010/12/22",
"Salary": "$92,575"
},
{
"Name": "Jennifer Chang",
"Position": "Regional Director",
"Office": "Singapore",
"Extn": "9239",
"Start": "2010/11/14",
"Salary": "$357,650"
},
{
"Name": "Brenden Wagner",
"Position": "Software Engineer",
"Office": "San Francisco",
"Extn": "1314",
"Start": "2011/06/07",
"Salary": "$206,850"
},
{
"Name": "Fiona Green",
"Position": "Chief Operating Officer (COO)",
"Office": "San Francisco",
"Extn": "2947",
"Start": "2010/03/11",
"Salary": "$850,000"
},
{
"Name": "Shou Itou",
"Position": "Regional Marketing",
"Office": "Tokyo",
"Extn": "8899",
"Start": "2011/08/14",
"Salary": "$163,000"
},
{
"Name": "Michelle House",
"Position": "Integration Specialist",
"Office": "Sidney",
"Extn": "2769",
"Start": "2011/06/02",
"Salary": "$95,400"
},
{
"Name": "Suki Burks",
"Position": "Developer",
"Office": "London",
"Extn": "6832",
"Start": "2009/10/22",
"Salary": "$114,500"
},
{
"Name": "Prescott Bartlett",
"Position": "Technical Author",
"Office": "London",
"Extn": "3606",
"Start": "2011/05/07",
"Salary": "$145,000"
},
{
"Name": "Gavin Cortez",
"Position": "Team Leader",
"Office": "San Francisco",
"Extn": "2860",
"Start": "2008/10/26",
"Salary": "$235,500"
},
{
"Name": "Martena Mccray",
"Position": "Post-Sales support",
"Office": "Edinburgh",
"Extn": "8240",
"Start": "2011/03/09",
"Salary": "$324,050"
},
{
"Name": "Unity Butler",
"Position": "Marketing Designer",
"Office": "San Francisco",
"Extn": "5384",
"Start": "2009/12/09",
"Salary": "$85,675"
},
{
"Name": "Howard Hatfield",
"Position": "Office Manager",
"Office": "San Francisco",
"Extn": "7031",
"Start": "2008/12/16",
"Salary": "$164,500"
},
{
"Name": "Hope Fuentes",
"Position": "Secretary",
"Office": "San Francisco",
"Extn": "6318",
"Start": "2010/02/12",
"Salary": "$109,850"
},
{
"Name": "Vivian Harrell",
"Position": "Financial Controller",
"Office": "San Francisco",
"Extn": "9422",
"Start": "2009/02/14",
"Salary": "$452,500"
},
{
"Name": "Timothy Mooney",
"Position": "Office Manager",
"Office": "London",
"Extn": "7580",
"Start": "2008/12/11",
"Salary": "$136,200"
},
{
"Name": "Jackson Bradshaw",
"Position": "Director",
"Office": "New York",
"Extn": "1042",
"Start": "2008/09/26",
"Salary": "$645,750"
},
{
"Name": "Olivia Liang",
"Position": "Support Engineer",
"Office": "Singapore",
"Extn": "2120",
"Start": "2011/02/03",
"Salary": "$234,500"
},
{
"Name": "Bruno Nash",
"Position": "Software Engineer",
"Office": "London",
"Extn": "6222",
"Start": "2011/05/03",
"Salary": "$163,500"
},
{
"Name": "Sakura Yamamoto",
"Position": "Support Engineer",
"Office": "Tokyo",
"Extn": "9383",
"Start": "2009/08/19",
"Salary": "$139,575"
},
{
"Name": "Thor Walton",
"Position": "Developer",
"Office": "New York",
"Extn": "8327",
"Start": "2013/08/11",
"Salary": "$98,540"
},
{
"Name": "Finn Camacho",
"Position": "Support Engineer",
"Office": "San Francisco",
"Extn": "2927",
"Start": "2009/07/07",
"Salary": "$87,500"
},
{
"Name": "Serge Baldwin",
"Position": "Data Coordinator",
"Office": "Singapore",
"Extn": "8352",
"Start": "2012/04/09",
"Salary": "$138,575"
},
{
"Name": "Zenaida Frank",
"Position": "Software Engineer",
"Office": "New York",
"Extn": "7439",
"Start": "2010/01/04",
"Salary": "$125,250"
},
{
"Name": "Zorita Serrano",
"Position": "Software Engineer",
"Office": "San Francisco",
"Extn": "4389",
"Start": "2012/06/01",
"Salary": "$115,000"
},
{
"Name": "Jennifer Acosta",
"Position": "Junior Javascript Developer",
"Office": "Edinburgh",
"Extn": "3431",
"Start": "2013/02/01",
"Salary": "$75,650"
},
{
"Name": "Cara Stevens",
"Position": "Sales Assistant",
"Office": "New York",
"Extn": "3990",
"Start": "2011/12/06",
"Salary": "$145,600"
},
{
"Name": "Hermione Butler",
"Position": "Regional Director",
"Office": "London",
"Extn": "1016",
"Start": "2011/03/21",
"Salary": "$356,250"
},
{
"Name": "Lael Greer",
"Position": "Systems Administrator",
"Office": "London",
"Extn": "6733",
"Start": "2009/02/27",
"Salary": "$103,500"
},
{
"Name": "Jonas Alexander",
"Position": "Developer",
"Office": "San Francisco",
"Extn": "8196",
"Start": "2010/07/14",
"Salary": "$86,500"
},
{
"Name": "Shad Decker",
"Position": "Regional Director",
"Office": "Edinburgh",
"Extn": "6373",
"Start": "2008/11/13",
"Salary": "$183,000"
},
{
"Name": "Michael Bruce",
"Position": "Javascript Developer",
"Office": "Singapore",
"Extn": "5384",
"Start": "2011/06/27",
"Salary": "$183,000"
},
{
"Name": "Donna Snider",
"Position": "Customer Support",
"Office": "New York",
"Extn": "4226",
"Start": "2011/01/25",
"Salary": "$112,000"
}
] | [
"zhangkai@xiaoneng.cn"
] | zhangkai@xiaoneng.cn |
aa9594d992223ef130256bf660885e67ee952849 | 5a66d961d5d0542be0fcb3f83961d2f07bab2401 | /TestBeam/code/OnlineMonitor.py | 4a11f624b167a20c232b38943ae7e8bb036d636b | [] | no_license | PADME-Experiment/padme-fw | 1f2b56899e311b958945d0b1c4f934dfeeba761a | bec2a83e3a32b8db38977c404d78f4f36a384f30 | refs/heads/develop | 2023-08-06T11:27:10.402467 | 2023-07-18T10:15:50 | 2023-07-18T10:15:50 | 44,676,186 | 11 | 6 | null | 2023-07-18T10:15:52 | 2015-10-21T12:57:21 | C++ | UTF-8 | Python | false | false | 3,412 | py | #!/usr/bin/python
import sys
import signal
import getopt
import os
import time
import subprocess
from MergerClass import MergerClass
# Define global variables used in the signal_handler
gui_process = 0
gui_log_handle = 0
def main():
# This will use the $PADME environment variable if set
PADME = os.getenv('PADME',"..")
# Dir where all log files are kept
#log_dir = PADME+"/RunControl/log"
log_dir = "/home/daq/DAQ/log"
# Path where one can find the "data" directory containing DAQ files
daq_data_dir = PADME+"/RunControl"
# Temporary files used during monitoring
merged_dir = PADME+"/TestBeam/tmp"
merged_list = merged_dir+"/monitor.list"
merged_file_template = merged_dir+"/monitor"
merged_last_file = merged_dir+"/monitor_last_file"
# Executable used to merge events and write RAW files
padme_merge = PADME+"/Level1/PadmeLevel1.exe"
# Executable which handles the OnlineMonitor GUI
padme_monitor = PADME+"/TestBeam/Monitor.exe"
# Log file for the OnlineMonitor GUI
gui_log_file = "Monitor.log"
# Get name of run to monitor from line arg
run_name = "dummy_run"
try:
opts, args = getopt.getopt(sys.argv[1:],"hr:")
except getopt.GetoptError:
print 'OnlineMonitor -r <run name>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'OnlineMonitor -r <run name>'
sys.exit()
elif opt == '-r':
run_name = arg
print 'Monitoring run',run_name
# Verify that required run is running (or was runned)
log_path = log_dir+"/"+run_name
if (not os.path.exists(log_path)):
print "Path",log_path,"does not exist"
sys.exit(1)
if (not os.path.isdir(log_path)):
print "Path",log_path,"is not a directory"
sys.exit(1)
# Open GUI log file
if os.path.exists(gui_log_file): os.remove(gui_log_file)
global gui_log_handle
gui_log_handle = open(gui_log_file,"w")
# Start graphical monitor program
#cmd = padme_monitor+" -i "+merged_file
#os.system(cmd)
global gui_process
try:
gui_process = subprocess.Popen([padme_monitor,"-i",merged_last_file],stdout=gui_log_handle,stderr=subprocess.STDOUT,bufsize=1)
except OSError as e:
print "ERROR executing",padme_monitor,"-",e
return 0
print "Online Monitor GUI started with process id",gui_process.pid
# Instantiate the Merger program and configure it
merger = MergerClass()
merger.run_name = run_name
merger.log_path = log_path
merger.daq_data_dir = daq_data_dir
merger.merged_list = merged_list
merger.merged_file_template = merged_file_template
merger.merged_last_file = merged_last_file
merger.padme_merge = padme_merge
# Catch CTRL-C to exit gracefully
signal.signal(signal.SIGINT, signal_handler)
# Pass control to Merger
merger.Start()
def signal_handler(signal,frame):
global gui_process
print('Ctrl+C received: exiting')
# Kill GUI process
print "Terminating GUI"
gui_process.terminate()
time.sleep(2)
gui_process.poll()
if (gui_process.returncode == None):
print "Problem terminating GUI: killing it"
gui_process.kill()
global gui_log_handle
gui_log_handle.close()
sys.exit(0)
# Execution starts here
main()
| [
"emanuele.leonardi@roma1.infn.it"
] | emanuele.leonardi@roma1.infn.it |
3ef2f9b1a315cb330f5f3eaf5e432de24dbfa906 | 5e20392dc4487c75e1e3061c1416a895317ca7c2 | /navmenu/deserializer.py | 4b44a7a7ef7a6f991eed691cd1c8a35cbeeeef7d | [
"MIT"
] | permissive | rashidsh/navmenu | 7072f3cee55469ccbe7f79eb5ce81c86a3aab4bb | ec67b820462cc102417e214cd74eb7b1b97ad1f1 | refs/heads/master | 2023-08-18T02:20:26.021801 | 2021-10-03T16:56:54 | 2021-10-03T16:56:54 | 366,816,317 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,269 | py | from types import ModuleType
from typing import Optional, Sequence
from . import actions
from . import contents
from . import item_contents
from . import items
from . import menus
from . import responses
def filter_kwargs(data: dict, extra_excludes: Optional[Sequence] = None) -> dict:
if extra_excludes is None:
extra_excludes = ()
return {k: v for k, v in data.items() if k not in ('type', *extra_excludes)}
def deserialize_action(data: dict, function_container: ModuleType):
class_ = getattr(actions, data['type'])
if 'function' in data:
templates = {}
if 'templates' in data:
for template in data['templates']:
if 'message' in template:
template['message'] = getattr(responses, template['message']['type'])(
**filter_kwargs(template['message'])
)
templates[template['case']] = getattr(responses, template['type'])(
**filter_kwargs(template, ('case', ))
)
return class_(
**filter_kwargs(data, ('function', 'templates')),
function=getattr(function_container, data['function']),
templates=templates,
)
else:
return class_(**filter_kwargs(data))
def deserialize_item_content(data: dict):
return getattr(item_contents, data['type'])(**filter_kwargs(data))
def deserialize_item(data: dict, function_container: ModuleType):
kwargs = filter_kwargs(data, ('action', 'content'))
if 'action' in data:
kwargs['action'] = deserialize_action(data['action'], function_container)
if 'content' in data:
kwargs['content'] = deserialize_item_content(data['content'])
return getattr(items, data['type'])(**kwargs)
def deserialize_content(data: dict):
return getattr(contents, data['type'])(**filter_kwargs(data))
def deserialize_menu(data: dict, function_container: ModuleType, custom_menu_handlers):
class_ = getattr(menus, data['type'])
if 'items' in data:
return class_(
**filter_kwargs(data, ('content', 'items', 'default_action')),
content=deserialize_content(data['content']),
items=[deserialize_item(i, function_container) for i in data['items']],
default_action=(
deserialize_action(data['default_action'], function_container) if 'default_action' in data else None
),
)
else:
return class_(
**filter_kwargs(data, ('handler', )),
handler=next(i for i in custom_menu_handlers if i.__name__ == data['handler']),
)
def deserialize(data: dict, function_container: ModuleType = None, custom_menu_handlers: Sequence = None) -> dict:
"""Deserialize the dictionary to a menu list.
Args:
data: Data to deserialize.
function_container: A module that contains custom functions to be called by actions.
custom_menu_handlers: A sequence of custom classes to control menus.
Returns:
A dictionary mapping menu names to menus.
"""
return {
menu_name: deserialize_menu(menu, function_container, custom_menu_handlers)
for menu_name, menu in data['menus'].items()
}
| [
"42511322+rashidsh@users.noreply.github.com"
] | 42511322+rashidsh@users.noreply.github.com |
0c523cd7eb4c4c58a325908b8590b74af2335528 | 8a99a91f7e83c347f6cc2e8d2d2b9100c6e2fd3c | /Netmiko_Examples/netmiko_imported_functions.py | 0dc8da64c5570b0fd79a16ec0241a11ea69dce33 | [] | no_license | gnasses/DevNetStudyGroup | ba69ca6f2bc8f2892c0bb7293f4a868df2060a6f | 882fc5f24fb1d17d436f3a62ae2a26870fe8b269 | refs/heads/main | 2023-07-15T06:54:39.869010 | 2021-08-25T20:38:00 | 2021-08-25T20:38:00 | 381,394,468 | 2 | 1 | null | 2021-07-01T15:48:21 | 2021-06-29T14:29:45 | null | UTF-8 | Python | false | false | 1,708 | py | from netmiko import Netmiko
import time
import util
mydevice = '192.168.1.57'
mycommand = 'show mac address-table'
results = util.cisco_command(mydevice, mycommand)
for dic in results:
for sub in dic:
#print ("MAC Address: " + dic['destination_address'] + " Port: " + dic['destination_port'])
mac = dic['destination_address']
port = dic['destination_port']
if not port == 'CPU' and 'fcec' in mac:
print ('MAC Address: ' + mac + ' Port: ' + port)
#Differential Output
# pre_list = []
# post_list = []
# results = util.cisco_command(mydevice, mycommand)
# for dic in results:
# for sub in dic:
# mac = dic['destination_address']
# port = dic['destination_port']
# entry = {mac : port}
# if not port == 'CPU' and entry not in pre_list:
# pre_list.append(entry)
# #print ('MAC Address: ' + mac + ' Port: ' + port)
# print ('Pausing 45 seconds!!!!!!!')
# time.sleep(45)
# post_results = util.cisco_command(mydevice, mycommand)
# for dic in post_results:
# for sub in dic:
# mac = dic['destination_address']
# port = dic['destination_port']
# entry = {mac : port}
# if not port == 'CPU' and entry not in post_list:
# post_list.append(entry)
# #print ('MAC Address: ' + mac + ' Port: ' + port)
# adds = [x for x in post_list if x not in pre_list]
# subs = [x for x in pre_list if x not in post_list]
# print ("Pre-List:")
# print (pre_list)
# print ()
# print ("Post-List:")
# print (post_list)
# print ()
# print ("Added Entries: ")
# print (adds)
# print ()
# print ("Removed Entries: ")
# print (subs)
# print ()
| [
"noreply@github.com"
] | noreply@github.com |
7e7469802b3c5b924e652ee98673659d9cfede94 | 6a5477e9bfae8110b2203182ad1db0517d09b2f2 | /Realestate4/Tagent4/models.py | 132aff2e669b0c6bb3868eae0e56314f45160235 | [] | no_license | Jagadishbommareddy/multiadress | b90f46ef80b50ddae8d8499e3e8c2d56d10796a9 | a8fa8f5fe2803f66bd7e5a8668e82b589df846b5 | refs/heads/master | 2021-01-23T10:04:07.921653 | 2017-09-06T12:16:31 | 2017-09-06T12:16:31 | 102,604,529 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,237 | py | from django.core.urlresolvers import reverse
from django.db import models
from .validations import *
class Agent(models.Model):
agent_id= models.AutoField(primary_key=True)
first_name= models.CharField(max_length=20,validators=[validate_first_name])
last_name= models.CharField(max_length=20,validators=[validate_last_name])
age=models.IntegerField()
education= models.CharField(max_length=50,validators=[validate_education])
company_name=models.CharField(max_length=50)
specialization= models.CharField(max_length=100,validators=[validate_specelization])
experence=models.IntegerField()
agent_notes=models.TextField()
def get_absolute_url(self):
return reverse('agent-update', kwargs={'pk': self.pk})
class Address(models.Model):
agent= models.ForeignKey(Agent)
address_id= models.AutoField(primary_key=True)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
city = models.CharField(max_length=20,validators=[validate_city])
state= models.CharField(max_length=20,validators=[validate_state])
landmark= models.CharField(max_length=20,validators=[validate_landmark])
pincode= models.IntegerField()
| [
"noreply@github.com"
] | noreply@github.com |
23ce5ed6bff83c3d562926676dce10e0e8fbb16b | e9480213b444129c4a3a0fb66a5e686a9f17c6da | /app03/views.py | 7c0ba022981562e7b5f3e7289c457be631b6b576 | [] | no_license | IronDukeLinux/CRM_project | 293c0ef0a8e0161d0d8c8495edf211f81b3bfe0b | 65ef7675df16cf846dbffe9408ce040d40e0edb9 | refs/heads/master | 2020-03-27T23:44:08.082325 | 2018-09-04T12:22:16 | 2018-09-04T12:22:16 | 147,341,523 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 519 | py | from django.shortcuts import render
from app03.models import Book
from app03.page import MyPage
# Create your views here.
def index(request):
# 创建数据
# li = [Book(title='python_%s' % i, price=i*i) for i in range(1, 101)]
# Book.objects.bulk_create(li)
page_num = request.GET.get('page', 1)
data_list = Book.objects.all()
page_obj = MyPage(page_num, data_list.count(), request)
data_list = data_list[page_obj.start: page_obj.end]
return render(request, "index.html", locals())
| [
"1211515452@qq.com"
] | 1211515452@qq.com |
2483ff0fde5338d50146941302debdfaf00f2b29 | 27aaadf435779c29012233cb1dacf27bd9dd0d0f | /adp-20210720/alibabacloud_adp20210720/client.py | 0742f891433504b77026d9a6761b748bb785d24a | [
"Apache-2.0"
] | permissive | aliyun/alibabacloud-python-sdk | afadedb09db5ba6c2bc6b046732b2a6dc215f004 | e02f34e07a7f05e898a492c212598a348d903739 | refs/heads/master | 2023-08-22T20:26:44.695288 | 2023-08-22T12:27:39 | 2023-08-22T12:27:39 | 288,972,087 | 43 | 29 | null | 2022-09-26T09:21:19 | 2020-08-20T10:08:11 | Python | UTF-8 | Python | false | false | 309,365 | py | # -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from typing import Dict
from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_endpoint_util.client import Client as EndpointUtilClient
from alibabacloud_adp20210720 import models as adp_20210720_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
class Client(OpenApiClient):
"""
*\
"""
def __init__(
self,
config: open_api_models.Config,
):
super().__init__(config)
self._endpoint_rule = ''
self.check_config(config)
self._endpoint = self.get_endpoint('adp', self._region_id, self._endpoint_rule, self._network, self._suffix, self._endpoint_map, self._endpoint)
def get_endpoint(
self,
product_id: str,
region_id: str,
endpoint_rule: str,
network: str,
suffix: str,
endpoint_map: Dict[str, str],
endpoint: str,
) -> str:
if not UtilClient.empty(endpoint):
return endpoint
if not UtilClient.is_unset(endpoint_map) and not UtilClient.empty(endpoint_map.get(region_id)):
return endpoint_map.get(region_id)
return EndpointUtilClient.get_endpoint_rules(product_id, region_id, endpoint_rule, network, suffix)
def add_environment_nodes_with_options(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddEnvironmentNodesResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.application_disk):
body['applicationDisk'] = request.application_disk
if not UtilClient.is_unset(request.cpu):
body['cpu'] = request.cpu
if not UtilClient.is_unset(request.data_disk):
body['dataDisk'] = request.data_disk
if not UtilClient.is_unset(request.etcd_disk):
body['etcdDisk'] = request.etcd_disk
if not UtilClient.is_unset(request.host_name):
body['hostName'] = request.host_name
if not UtilClient.is_unset(request.labels):
body['labels'] = request.labels
if not UtilClient.is_unset(request.master_private_ips):
body['masterPrivateIPs'] = request.master_private_ips
if not UtilClient.is_unset(request.memory):
body['memory'] = request.memory
if not UtilClient.is_unset(request.os):
body['os'] = request.os
if not UtilClient.is_unset(request.root_password):
body['rootPassword'] = request.root_password
if not UtilClient.is_unset(request.system_disk):
body['systemDisk'] = request.system_disk
if not UtilClient.is_unset(request.taints):
body['taints'] = request.taints
if not UtilClient.is_unset(request.trident_system_disk):
body['tridentSystemDisk'] = request.trident_system_disk
if not UtilClient.is_unset(request.trident_system_size_disk):
body['tridentSystemSizeDisk'] = request.trident_system_size_disk
if not UtilClient.is_unset(request.worker_private_ips):
body['workerPrivateIPs'] = request.worker_private_ips
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddEnvironmentNodesResponse(),
self.call_api(params, req, runtime)
)
async def add_environment_nodes_with_options_async(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddEnvironmentNodesResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.application_disk):
body['applicationDisk'] = request.application_disk
if not UtilClient.is_unset(request.cpu):
body['cpu'] = request.cpu
if not UtilClient.is_unset(request.data_disk):
body['dataDisk'] = request.data_disk
if not UtilClient.is_unset(request.etcd_disk):
body['etcdDisk'] = request.etcd_disk
if not UtilClient.is_unset(request.host_name):
body['hostName'] = request.host_name
if not UtilClient.is_unset(request.labels):
body['labels'] = request.labels
if not UtilClient.is_unset(request.master_private_ips):
body['masterPrivateIPs'] = request.master_private_ips
if not UtilClient.is_unset(request.memory):
body['memory'] = request.memory
if not UtilClient.is_unset(request.os):
body['os'] = request.os
if not UtilClient.is_unset(request.root_password):
body['rootPassword'] = request.root_password
if not UtilClient.is_unset(request.system_disk):
body['systemDisk'] = request.system_disk
if not UtilClient.is_unset(request.taints):
body['taints'] = request.taints
if not UtilClient.is_unset(request.trident_system_disk):
body['tridentSystemDisk'] = request.trident_system_disk
if not UtilClient.is_unset(request.trident_system_size_disk):
body['tridentSystemSizeDisk'] = request.trident_system_size_disk
if not UtilClient.is_unset(request.worker_private_ips):
body['workerPrivateIPs'] = request.worker_private_ips
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddEnvironmentNodesResponse(),
await self.call_api_async(params, req, runtime)
)
def add_environment_nodes(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentNodesRequest,
) -> adp_20210720_models.AddEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.add_environment_nodes_with_options(uid, request, headers, runtime)
async def add_environment_nodes_async(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentNodesRequest,
) -> adp_20210720_models.AddEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.add_environment_nodes_with_options_async(uid, request, headers, runtime)
def add_environment_product_versions_with_options(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentProductVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddEnvironmentProductVersionsResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.product_version_info_list):
body['productVersionInfoList'] = request.product_version_info_list
if not UtilClient.is_unset(request.product_version_uidlist):
body['productVersionUIDList'] = request.product_version_uidlist
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddEnvironmentProductVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddEnvironmentProductVersionsResponse(),
self.call_api(params, req, runtime)
)
async def add_environment_product_versions_with_options_async(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentProductVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddEnvironmentProductVersionsResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.product_version_info_list):
body['productVersionInfoList'] = request.product_version_info_list
if not UtilClient.is_unset(request.product_version_uidlist):
body['productVersionUIDList'] = request.product_version_uidlist
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddEnvironmentProductVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddEnvironmentProductVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def add_environment_product_versions(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentProductVersionsRequest,
) -> adp_20210720_models.AddEnvironmentProductVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.add_environment_product_versions_with_options(uid, request, headers, runtime)
async def add_environment_product_versions_async(
self,
uid: str,
request: adp_20210720_models.AddEnvironmentProductVersionsRequest,
) -> adp_20210720_models.AddEnvironmentProductVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.add_environment_product_versions_with_options_async(uid, request, headers, runtime)
def add_product_component_version_with_options(
self,
uid: str,
component_version_uid: str,
request: adp_20210720_models.AddProductComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddProductComponentVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_version_spec_uid):
body['componentVersionSpecUID'] = request.component_version_spec_uid
if not UtilClient.is_unset(request.component_version_spec_values):
body['componentVersionSpecValues'] = request.component_version_spec_values
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions/{OpenApiUtilClient.get_encode_param(component_version_uid)}',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddProductComponentVersionResponse(),
self.call_api(params, req, runtime)
)
async def add_product_component_version_with_options_async(
self,
uid: str,
component_version_uid: str,
request: adp_20210720_models.AddProductComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddProductComponentVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_version_spec_uid):
body['componentVersionSpecUID'] = request.component_version_spec_uid
if not UtilClient.is_unset(request.component_version_spec_values):
body['componentVersionSpecValues'] = request.component_version_spec_values
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions/{OpenApiUtilClient.get_encode_param(component_version_uid)}',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddProductComponentVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def add_product_component_version(
self,
uid: str,
component_version_uid: str,
request: adp_20210720_models.AddProductComponentVersionRequest,
) -> adp_20210720_models.AddProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.add_product_component_version_with_options(uid, component_version_uid, request, headers, runtime)
async def add_product_component_version_async(
self,
uid: str,
component_version_uid: str,
request: adp_20210720_models.AddProductComponentVersionRequest,
) -> adp_20210720_models.AddProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.add_product_component_version_with_options_async(uid, component_version_uid, request, headers, runtime)
def add_product_version_config_with_options(
self,
uid: str,
request: adp_20210720_models.AddProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_release_name):
body['componentReleaseName'] = request.component_release_name
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_release_name):
body['parentComponentReleaseName'] = request.parent_component_release_name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddProductVersionConfigResponse(),
self.call_api(params, req, runtime)
)
async def add_product_version_config_with_options_async(
self,
uid: str,
request: adp_20210720_models.AddProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_release_name):
body['componentReleaseName'] = request.component_release_name
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_release_name):
body['parentComponentReleaseName'] = request.parent_component_release_name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddProductVersionConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def add_product_version_config(
self,
uid: str,
request: adp_20210720_models.AddProductVersionConfigRequest,
) -> adp_20210720_models.AddProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.add_product_version_config_with_options(uid, request, headers, runtime)
async def add_product_version_config_async(
self,
uid: str,
request: adp_20210720_models.AddProductVersionConfigRequest,
) -> adp_20210720_models.AddProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.add_product_version_config_with_options_async(uid, request, headers, runtime)
def add_resource_snapshot_with_options(
self,
request: adp_20210720_models.AddResourceSnapshotRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddResourceSnapshotResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
body = {}
if not UtilClient.is_unset(request.name):
body['name'] = request.name
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddResourceSnapshot',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/resource-snapshots',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddResourceSnapshotResponse(),
self.call_api(params, req, runtime)
)
async def add_resource_snapshot_with_options_async(
self,
request: adp_20210720_models.AddResourceSnapshotRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.AddResourceSnapshotResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
body = {}
if not UtilClient.is_unset(request.name):
body['name'] = request.name
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='AddResourceSnapshot',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/resource-snapshots',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.AddResourceSnapshotResponse(),
await self.call_api_async(params, req, runtime)
)
def add_resource_snapshot(
self,
request: adp_20210720_models.AddResourceSnapshotRequest,
) -> adp_20210720_models.AddResourceSnapshotResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.add_resource_snapshot_with_options(request, headers, runtime)
async def add_resource_snapshot_async(
self,
request: adp_20210720_models.AddResourceSnapshotRequest,
) -> adp_20210720_models.AddResourceSnapshotResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.add_resource_snapshot_with_options_async(request, headers, runtime)
def batch_add_environment_nodes_with_options(
self,
uid: str,
request: adp_20210720_models.BatchAddEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.BatchAddEnvironmentNodesResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.instance_list):
body['instanceList'] = request.instance_list
if not UtilClient.is_unset(request.overwrite):
body['overwrite'] = request.overwrite
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='BatchAddEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/batch/nodes',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.BatchAddEnvironmentNodesResponse(),
self.call_api(params, req, runtime)
)
async def batch_add_environment_nodes_with_options_async(
self,
uid: str,
request: adp_20210720_models.BatchAddEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.BatchAddEnvironmentNodesResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.instance_list):
body['instanceList'] = request.instance_list
if not UtilClient.is_unset(request.overwrite):
body['overwrite'] = request.overwrite
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='BatchAddEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/batch/nodes',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.BatchAddEnvironmentNodesResponse(),
await self.call_api_async(params, req, runtime)
)
def batch_add_environment_nodes(
self,
uid: str,
request: adp_20210720_models.BatchAddEnvironmentNodesRequest,
) -> adp_20210720_models.BatchAddEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.batch_add_environment_nodes_with_options(uid, request, headers, runtime)
async def batch_add_environment_nodes_async(
self,
uid: str,
request: adp_20210720_models.BatchAddEnvironmentNodesRequest,
) -> adp_20210720_models.BatchAddEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.batch_add_environment_nodes_with_options_async(uid, request, headers, runtime)
def batch_add_product_version_config_with_options(
self,
uid: str,
request: adp_20210720_models.BatchAddProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.BatchAddProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.product_version_config_list):
body['productVersionConfigList'] = request.product_version_config_list
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='BatchAddProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/batch/configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.BatchAddProductVersionConfigResponse(),
self.call_api(params, req, runtime)
)
async def batch_add_product_version_config_with_options_async(
self,
uid: str,
request: adp_20210720_models.BatchAddProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.BatchAddProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.product_version_config_list):
body['productVersionConfigList'] = request.product_version_config_list
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='BatchAddProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/batch/configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.BatchAddProductVersionConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def batch_add_product_version_config(
self,
uid: str,
request: adp_20210720_models.BatchAddProductVersionConfigRequest,
) -> adp_20210720_models.BatchAddProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.batch_add_product_version_config_with_options(uid, request, headers, runtime)
async def batch_add_product_version_config_async(
self,
uid: str,
request: adp_20210720_models.BatchAddProductVersionConfigRequest,
) -> adp_20210720_models.BatchAddProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.batch_add_product_version_config_with_options_async(uid, request, headers, runtime)
def create_deliverable_with_options(
self,
request: adp_20210720_models.CreateDeliverableRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliverableResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation):
body['foundation'] = request.foundation
if not UtilClient.is_unset(request.products):
body['products'] = request.products
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliverableResponse(),
self.call_api(params, req, runtime)
)
async def create_deliverable_with_options_async(
self,
request: adp_20210720_models.CreateDeliverableRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliverableResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation):
body['foundation'] = request.foundation
if not UtilClient.is_unset(request.products):
body['products'] = request.products
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliverableResponse(),
await self.call_api_async(params, req, runtime)
)
def create_deliverable(
self,
request: adp_20210720_models.CreateDeliverableRequest,
) -> adp_20210720_models.CreateDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_deliverable_with_options(request, headers, runtime)
async def create_deliverable_async(
self,
request: adp_20210720_models.CreateDeliverableRequest,
) -> adp_20210720_models.CreateDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_deliverable_with_options_async(request, headers, runtime)
def create_delivery_instance_with_options(
self,
request: adp_20210720_models.CreateDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliveryInstanceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_uid):
body['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.deliverable_config_uid):
body['deliverableConfigUID'] = request.deliverable_config_uid
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.env_uid):
body['envUID'] = request.env_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliveryInstanceResponse(),
self.call_api(params, req, runtime)
)
async def create_delivery_instance_with_options_async(
self,
request: adp_20210720_models.CreateDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliveryInstanceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_uid):
body['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.deliverable_config_uid):
body['deliverableConfigUID'] = request.deliverable_config_uid
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.env_uid):
body['envUID'] = request.env_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliveryInstanceResponse(),
await self.call_api_async(params, req, runtime)
)
def create_delivery_instance(
self,
request: adp_20210720_models.CreateDeliveryInstanceRequest,
) -> adp_20210720_models.CreateDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_delivery_instance_with_options(request, headers, runtime)
async def create_delivery_instance_async(
self,
request: adp_20210720_models.CreateDeliveryInstanceRequest,
) -> adp_20210720_models.CreateDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_delivery_instance_with_options_async(request, headers, runtime)
def create_delivery_package_with_options(
self,
request: adp_20210720_models.CreateDeliveryPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliveryPackageResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.delivery_instance_uid):
body['deliveryInstanceUID'] = request.delivery_instance_uid
if not UtilClient.is_unset(request.origin_deliverable_uid):
body['originDeliverableUID'] = request.origin_deliverable_uid
if not UtilClient.is_unset(request.package_content_type):
body['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_type):
body['packageType'] = request.package_type
if not UtilClient.is_unset(request.platform):
body['platform'] = request.platform
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliveryPackageResponse(),
self.call_api(params, req, runtime)
)
async def create_delivery_package_with_options_async(
self,
request: adp_20210720_models.CreateDeliveryPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateDeliveryPackageResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.delivery_instance_uid):
body['deliveryInstanceUID'] = request.delivery_instance_uid
if not UtilClient.is_unset(request.origin_deliverable_uid):
body['originDeliverableUID'] = request.origin_deliverable_uid
if not UtilClient.is_unset(request.package_content_type):
body['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_type):
body['packageType'] = request.package_type
if not UtilClient.is_unset(request.platform):
body['platform'] = request.platform
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateDeliveryPackageResponse(),
await self.call_api_async(params, req, runtime)
)
def create_delivery_package(
self,
request: adp_20210720_models.CreateDeliveryPackageRequest,
) -> adp_20210720_models.CreateDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_delivery_package_with_options(request, headers, runtime)
async def create_delivery_package_async(
self,
request: adp_20210720_models.CreateDeliveryPackageRequest,
) -> adp_20210720_models.CreateDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_delivery_package_with_options_async(request, headers, runtime)
def create_environment_with_options(
self,
request: adp_20210720_models.CreateEnvironmentRequest,
headers: adp_20210720_models.CreateEnvironmentHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateEnvironmentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.annotations):
body['annotations'] = request.annotations
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.location):
body['location'] = request.location
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.platform):
body['platform'] = request.platform
if not UtilClient.is_unset(request.platform_list):
body['platformList'] = request.platform_list
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.type):
body['type'] = request.type
if not UtilClient.is_unset(request.vendor_config):
body['vendorConfig'] = request.vendor_config
if not UtilClient.is_unset(request.vendor_type):
body['vendorType'] = request.vendor_type
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateEnvironmentResponse(),
self.call_api(params, req, runtime)
)
async def create_environment_with_options_async(
self,
request: adp_20210720_models.CreateEnvironmentRequest,
headers: adp_20210720_models.CreateEnvironmentHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateEnvironmentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.annotations):
body['annotations'] = request.annotations
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.location):
body['location'] = request.location
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.platform):
body['platform'] = request.platform
if not UtilClient.is_unset(request.platform_list):
body['platformList'] = request.platform_list
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.type):
body['type'] = request.type
if not UtilClient.is_unset(request.vendor_config):
body['vendorConfig'] = request.vendor_config
if not UtilClient.is_unset(request.vendor_type):
body['vendorType'] = request.vendor_type
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateEnvironmentResponse(),
await self.call_api_async(params, req, runtime)
)
def create_environment(
self,
request: adp_20210720_models.CreateEnvironmentRequest,
) -> adp_20210720_models.CreateEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateEnvironmentHeaders()
return self.create_environment_with_options(request, headers, runtime)
async def create_environment_async(
self,
request: adp_20210720_models.CreateEnvironmentRequest,
) -> adp_20210720_models.CreateEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateEnvironmentHeaders()
return await self.create_environment_with_options_async(request, headers, runtime)
def create_environment_license_with_options(
self,
uid: str,
request: adp_20210720_models.CreateEnvironmentLicenseRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateEnvironmentLicenseResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.company_name):
body['companyName'] = request.company_name
if not UtilClient.is_unset(request.contact):
body['contact'] = request.contact
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.expire_time):
body['expireTime'] = request.expire_time
if not UtilClient.is_unset(request.license_quota):
body['licenseQuota'] = request.license_quota
if not UtilClient.is_unset(request.machine_fingerprint):
body['machineFingerprint'] = request.machine_fingerprint
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.scenario):
body['scenario'] = request.scenario
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.type):
body['type'] = request.type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateEnvironmentLicenseResponse(),
self.call_api(params, req, runtime)
)
async def create_environment_license_with_options_async(
self,
uid: str,
request: adp_20210720_models.CreateEnvironmentLicenseRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateEnvironmentLicenseResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.company_name):
body['companyName'] = request.company_name
if not UtilClient.is_unset(request.contact):
body['contact'] = request.contact
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.expire_time):
body['expireTime'] = request.expire_time
if not UtilClient.is_unset(request.license_quota):
body['licenseQuota'] = request.license_quota
if not UtilClient.is_unset(request.machine_fingerprint):
body['machineFingerprint'] = request.machine_fingerprint
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.scenario):
body['scenario'] = request.scenario
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.type):
body['type'] = request.type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateEnvironmentLicenseResponse(),
await self.call_api_async(params, req, runtime)
)
def create_environment_license(
self,
uid: str,
request: adp_20210720_models.CreateEnvironmentLicenseRequest,
) -> adp_20210720_models.CreateEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_environment_license_with_options(uid, request, headers, runtime)
async def create_environment_license_async(
self,
uid: str,
request: adp_20210720_models.CreateEnvironmentLicenseRequest,
) -> adp_20210720_models.CreateEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_environment_license_with_options_async(uid, request, headers, runtime)
def create_foundation_reference_with_options(
self,
request: adp_20210720_models.CreateFoundationReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateFoundationReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_config):
body['clusterConfig'] = request.cluster_config
if not UtilClient.is_unset(request.component_configs):
body['componentConfigs'] = request.component_configs
if not UtilClient.is_unset(request.foundation_reference_configs):
body['foundationReferenceConfigs'] = request.foundation_reference_configs
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.origin_foundation_reference_uid):
body['originFoundationReferenceUID'] = request.origin_foundation_reference_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateFoundationReferenceResponse(),
self.call_api(params, req, runtime)
)
async def create_foundation_reference_with_options_async(
self,
request: adp_20210720_models.CreateFoundationReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateFoundationReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_config):
body['clusterConfig'] = request.cluster_config
if not UtilClient.is_unset(request.component_configs):
body['componentConfigs'] = request.component_configs
if not UtilClient.is_unset(request.foundation_reference_configs):
body['foundationReferenceConfigs'] = request.foundation_reference_configs
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.origin_foundation_reference_uid):
body['originFoundationReferenceUID'] = request.origin_foundation_reference_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateFoundationReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def create_foundation_reference(
self,
request: adp_20210720_models.CreateFoundationReferenceRequest,
) -> adp_20210720_models.CreateFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_foundation_reference_with_options(request, headers, runtime)
async def create_foundation_reference_async(
self,
request: adp_20210720_models.CreateFoundationReferenceRequest,
) -> adp_20210720_models.CreateFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_foundation_reference_with_options_async(request, headers, runtime)
def create_product_with_options(
self,
request: adp_20210720_models.CreateProductRequest,
headers: adp_20210720_models.CreateProductHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.categories):
body['categories'] = request.categories
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.display_name):
body['displayName'] = request.display_name
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.product_name):
body['productName'] = request.product_name
if not UtilClient.is_unset(request.vendor):
body['vendor'] = request.vendor
if not UtilClient.is_unset(request.without_product_version):
body['withoutProductVersion'] = request.without_product_version
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductResponse(),
self.call_api(params, req, runtime)
)
async def create_product_with_options_async(
self,
request: adp_20210720_models.CreateProductRequest,
headers: adp_20210720_models.CreateProductHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.categories):
body['categories'] = request.categories
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.display_name):
body['displayName'] = request.display_name
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.product_name):
body['productName'] = request.product_name
if not UtilClient.is_unset(request.vendor):
body['vendor'] = request.vendor
if not UtilClient.is_unset(request.without_product_version):
body['withoutProductVersion'] = request.without_product_version
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductResponse(),
await self.call_api_async(params, req, runtime)
)
def create_product(
self,
request: adp_20210720_models.CreateProductRequest,
) -> adp_20210720_models.CreateProductResponse:
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateProductHeaders()
return self.create_product_with_options(request, headers, runtime)
async def create_product_async(
self,
request: adp_20210720_models.CreateProductRequest,
) -> adp_20210720_models.CreateProductResponse:
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateProductHeaders()
return await self.create_product_with_options_async(request, headers, runtime)
def create_product_deployment_with_options(
self,
request: adp_20210720_models.CreateProductDeploymentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductDeploymentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.namespace):
body['namespace'] = request.namespace
if not UtilClient.is_unset(request.old_product_version_uid):
body['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_config):
body['packageConfig'] = request.package_config
if not UtilClient.is_unset(request.package_uid):
body['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.timeout):
body['timeout'] = request.timeout
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProductDeployment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductDeploymentResponse(),
self.call_api(params, req, runtime)
)
async def create_product_deployment_with_options_async(
self,
request: adp_20210720_models.CreateProductDeploymentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductDeploymentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.namespace):
body['namespace'] = request.namespace
if not UtilClient.is_unset(request.old_product_version_uid):
body['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_config):
body['packageConfig'] = request.package_config
if not UtilClient.is_unset(request.package_uid):
body['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.timeout):
body['timeout'] = request.timeout
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProductDeployment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductDeploymentResponse(),
await self.call_api_async(params, req, runtime)
)
def create_product_deployment(
self,
request: adp_20210720_models.CreateProductDeploymentRequest,
) -> adp_20210720_models.CreateProductDeploymentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_product_deployment_with_options(request, headers, runtime)
async def create_product_deployment_async(
self,
request: adp_20210720_models.CreateProductDeploymentRequest,
) -> adp_20210720_models.CreateProductDeploymentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_product_deployment_with_options_async(request, headers, runtime)
def create_product_version_with_options(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.base_product_version_uid):
query['baseProductVersionUID'] = request.base_product_version_uid
body = {}
if not UtilClient.is_unset(request.version):
body['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}/versions',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def create_product_version_with_options_async(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.base_product_version_uid):
query['baseProductVersionUID'] = request.base_product_version_uid
body = {}
if not UtilClient.is_unset(request.version):
body['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='CreateProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}/versions',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def create_product_version(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionRequest,
) -> adp_20210720_models.CreateProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.create_product_version_with_options(uid, request, headers, runtime)
async def create_product_version_async(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionRequest,
) -> adp_20210720_models.CreateProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.create_product_version_with_options_async(uid, request, headers, runtime)
def create_product_version_package_with_options(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionPackageRequest,
headers: adp_20210720_models.CreateProductVersionPackageHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductVersionPackageResponse:
"""
@deprecated
@param request: CreateProductVersionPackageRequest
@param headers: CreateProductVersionPackageHeaders
@param runtime: runtime options for this request RuntimeOptions
@return: CreateProductVersionPackageResponse
Deprecated
"""
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_engine_type):
query['clusterEngineType'] = request.cluster_engine_type
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.old_foundation_reference_uid):
query['oldFoundationReferenceUID'] = request.old_foundation_reference_uid
if not UtilClient.is_unset(request.old_product_version_uid):
query['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_content_type):
query['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_tool_type):
query['packageToolType'] = request.package_tool_type
if not UtilClient.is_unset(request.package_type):
query['packageType'] = request.package_type
if not UtilClient.is_unset(request.platform):
query['platform'] = request.platform
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='CreateProductVersionPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/packages',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductVersionPackageResponse(),
self.call_api(params, req, runtime)
)
async def create_product_version_package_with_options_async(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionPackageRequest,
headers: adp_20210720_models.CreateProductVersionPackageHeaders,
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.CreateProductVersionPackageResponse:
"""
@deprecated
@param request: CreateProductVersionPackageRequest
@param headers: CreateProductVersionPackageHeaders
@param runtime: runtime options for this request RuntimeOptions
@return: CreateProductVersionPackageResponse
Deprecated
"""
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_engine_type):
query['clusterEngineType'] = request.cluster_engine_type
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.old_foundation_reference_uid):
query['oldFoundationReferenceUID'] = request.old_foundation_reference_uid
if not UtilClient.is_unset(request.old_product_version_uid):
query['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_content_type):
query['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_tool_type):
query['packageToolType'] = request.package_tool_type
if not UtilClient.is_unset(request.package_type):
query['packageType'] = request.package_type
if not UtilClient.is_unset(request.platform):
query['platform'] = request.platform
real_headers = {}
if not UtilClient.is_unset(headers.common_headers):
real_headers = headers.common_headers
if not UtilClient.is_unset(headers.client_token):
real_headers['ClientToken'] = UtilClient.to_jsonstring(headers.client_token)
req = open_api_models.OpenApiRequest(
headers=real_headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='CreateProductVersionPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/packages',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.CreateProductVersionPackageResponse(),
await self.call_api_async(params, req, runtime)
)
def create_product_version_package(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionPackageRequest,
) -> adp_20210720_models.CreateProductVersionPackageResponse:
"""
@deprecated
@param request: CreateProductVersionPackageRequest
@return: CreateProductVersionPackageResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateProductVersionPackageHeaders()
return self.create_product_version_package_with_options(uid, request, headers, runtime)
async def create_product_version_package_async(
self,
uid: str,
request: adp_20210720_models.CreateProductVersionPackageRequest,
) -> adp_20210720_models.CreateProductVersionPackageResponse:
"""
@deprecated
@param request: CreateProductVersionPackageRequest
@return: CreateProductVersionPackageResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = adp_20210720_models.CreateProductVersionPackageHeaders()
return await self.create_product_version_package_with_options_async(uid, request, headers, runtime)
def delete_environment_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentResponse(),
self.call_api(params, req, runtime)
)
async def delete_environment_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_environment(
self,
uid: str,
) -> adp_20210720_models.DeleteEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_environment_with_options(uid, headers, runtime)
async def delete_environment_async(
self,
uid: str,
) -> adp_20210720_models.DeleteEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_environment_with_options_async(uid, headers, runtime)
def delete_environment_license_with_options(
self,
uid: str,
license_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentLicenseResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses/{OpenApiUtilClient.get_encode_param(license_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentLicenseResponse(),
self.call_api(params, req, runtime)
)
async def delete_environment_license_with_options_async(
self,
uid: str,
license_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentLicenseResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses/{OpenApiUtilClient.get_encode_param(license_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentLicenseResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_environment_license(
self,
uid: str,
license_uid: str,
) -> adp_20210720_models.DeleteEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_environment_license_with_options(uid, license_uid, headers, runtime)
async def delete_environment_license_async(
self,
uid: str,
license_uid: str,
) -> adp_20210720_models.DeleteEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_environment_license_with_options_async(uid, license_uid, headers, runtime)
def delete_environment_node_with_options(
self,
uid: str,
node_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentNodeResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentNodeResponse(),
self.call_api(params, req, runtime)
)
async def delete_environment_node_with_options_async(
self,
uid: str,
node_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentNodeResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentNodeResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_environment_node(
self,
uid: str,
node_uid: str,
) -> adp_20210720_models.DeleteEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_environment_node_with_options(uid, node_uid, headers, runtime)
async def delete_environment_node_async(
self,
uid: str,
node_uid: str,
) -> adp_20210720_models.DeleteEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_environment_node_with_options_async(uid, node_uid, headers, runtime)
def delete_environment_product_version_with_options(
self,
uid: str,
product_version_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentProductVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions/{OpenApiUtilClient.get_encode_param(product_version_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def delete_environment_product_version_with_options_async(
self,
uid: str,
product_version_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteEnvironmentProductVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteEnvironmentProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions/{OpenApiUtilClient.get_encode_param(product_version_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteEnvironmentProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_environment_product_version(
self,
uid: str,
product_version_uid: str,
) -> adp_20210720_models.DeleteEnvironmentProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_environment_product_version_with_options(uid, product_version_uid, headers, runtime)
async def delete_environment_product_version_async(
self,
uid: str,
product_version_uid: str,
) -> adp_20210720_models.DeleteEnvironmentProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_environment_product_version_with_options_async(uid, product_version_uid, headers, runtime)
def delete_product_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductResponse(),
self.call_api(params, req, runtime)
)
async def delete_product_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_product(
self,
uid: str,
) -> adp_20210720_models.DeleteProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_product_with_options(uid, headers, runtime)
async def delete_product_async(
self,
uid: str,
) -> adp_20210720_models.DeleteProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_product_with_options_async(uid, headers, runtime)
def delete_product_component_version_with_options(
self,
uid: str,
relation_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductComponentVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductComponentVersionResponse(),
self.call_api(params, req, runtime)
)
async def delete_product_component_version_with_options_async(
self,
uid: str,
relation_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductComponentVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductComponentVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_product_component_version(
self,
uid: str,
relation_uid: str,
) -> adp_20210720_models.DeleteProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_product_component_version_with_options(uid, relation_uid, headers, runtime)
async def delete_product_component_version_async(
self,
uid: str,
relation_uid: str,
) -> adp_20210720_models.DeleteProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_product_component_version_with_options_async(uid, relation_uid, headers, runtime)
def delete_product_instance_config_with_options(
self,
config_uid: str,
request: adp_20210720_models.DeleteProductInstanceConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductInstanceConfigResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='DeleteProductInstanceConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductInstanceConfigResponse(),
self.call_api(params, req, runtime)
)
async def delete_product_instance_config_with_options_async(
self,
config_uid: str,
request: adp_20210720_models.DeleteProductInstanceConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductInstanceConfigResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='DeleteProductInstanceConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductInstanceConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_product_instance_config(
self,
config_uid: str,
request: adp_20210720_models.DeleteProductInstanceConfigRequest,
) -> adp_20210720_models.DeleteProductInstanceConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_product_instance_config_with_options(config_uid, request, headers, runtime)
async def delete_product_instance_config_async(
self,
config_uid: str,
request: adp_20210720_models.DeleteProductInstanceConfigRequest,
) -> adp_20210720_models.DeleteProductInstanceConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_product_instance_config_with_options_async(config_uid, request, headers, runtime)
def delete_product_version_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def delete_product_version_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_product_version(
self,
uid: str,
) -> adp_20210720_models.DeleteProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_product_version_with_options(uid, headers, runtime)
async def delete_product_version_async(
self,
uid: str,
) -> adp_20210720_models.DeleteProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_product_version_with_options_async(uid, headers, runtime)
def delete_product_version_config_with_options(
self,
uid: str,
config_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductVersionConfigResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductVersionConfigResponse(),
self.call_api(params, req, runtime)
)
async def delete_product_version_config_with_options_async(
self,
uid: str,
config_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.DeleteProductVersionConfigResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='DeleteProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='DELETE',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.DeleteProductVersionConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def delete_product_version_config(
self,
uid: str,
config_uid: str,
) -> adp_20210720_models.DeleteProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.delete_product_version_config_with_options(uid, config_uid, headers, runtime)
async def delete_product_version_config_async(
self,
uid: str,
config_uid: str,
) -> adp_20210720_models.DeleteProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.delete_product_version_config_with_options_async(uid, config_uid, headers, runtime)
def generate_product_instance_deployment_config_with_options(
self,
request: adp_20210720_models.GenerateProductInstanceDeploymentConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.package_content_type):
body['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_uid):
body['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.product_version_uidlist):
body['productVersionUIDList'] = request.product_version_uidlist
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='GenerateProductInstanceDeploymentConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/package-configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse(),
self.call_api(params, req, runtime)
)
async def generate_product_instance_deployment_config_with_options_async(
self,
request: adp_20210720_models.GenerateProductInstanceDeploymentConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.package_content_type):
body['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_uid):
body['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.product_version_uidlist):
body['productVersionUIDList'] = request.product_version_uidlist
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='GenerateProductInstanceDeploymentConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/package-configs',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def generate_product_instance_deployment_config(
self,
request: adp_20210720_models.GenerateProductInstanceDeploymentConfigRequest,
) -> adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.generate_product_instance_deployment_config_with_options(request, headers, runtime)
async def generate_product_instance_deployment_config_async(
self,
request: adp_20210720_models.GenerateProductInstanceDeploymentConfigRequest,
) -> adp_20210720_models.GenerateProductInstanceDeploymentConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.generate_product_instance_deployment_config_with_options_async(request, headers, runtime)
def get_component_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetComponentResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetComponent',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetComponentResponse(),
self.call_api(params, req, runtime)
)
async def get_component_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetComponentResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetComponent',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetComponentResponse(),
await self.call_api_async(params, req, runtime)
)
def get_component(
self,
uid: str,
) -> adp_20210720_models.GetComponentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_component_with_options(uid, headers, runtime)
async def get_component_async(
self,
uid: str,
) -> adp_20210720_models.GetComponentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_component_with_options_async(uid, headers, runtime)
def get_component_version_with_options(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetComponentVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.without_chart_content):
query['withoutChartContent'] = request.without_chart_content
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}/versions/{OpenApiUtilClient.get_encode_param(version_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetComponentVersionResponse(),
self.call_api(params, req, runtime)
)
async def get_component_version_with_options_async(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetComponentVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.without_chart_content):
query['withoutChartContent'] = request.without_chart_content
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}/versions/{OpenApiUtilClient.get_encode_param(version_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetComponentVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def get_component_version(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetComponentVersionRequest,
) -> adp_20210720_models.GetComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_component_version_with_options(uid, version_uid, request, headers, runtime)
async def get_component_version_async(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetComponentVersionRequest,
) -> adp_20210720_models.GetComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_component_version_with_options_async(uid, version_uid, request, headers, runtime)
def get_deliverable_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetDeliverableResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetDeliverableResponse(),
self.call_api(params, req, runtime)
)
async def get_deliverable_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetDeliverableResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetDeliverableResponse(),
await self.call_api_async(params, req, runtime)
)
def get_deliverable(
self,
uid: str,
) -> adp_20210720_models.GetDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_deliverable_with_options(uid, headers, runtime)
async def get_deliverable_async(
self,
uid: str,
) -> adp_20210720_models.GetDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_deliverable_with_options_async(uid, headers, runtime)
def get_delivery_package_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetDeliveryPackageResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetDeliveryPackageResponse(),
self.call_api(params, req, runtime)
)
async def get_delivery_package_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetDeliveryPackageResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetDeliveryPackageResponse(),
await self.call_api_async(params, req, runtime)
)
def get_delivery_package(
self,
uid: str,
) -> adp_20210720_models.GetDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_delivery_package_with_options(uid, headers, runtime)
async def get_delivery_package_async(
self,
uid: str,
) -> adp_20210720_models.GetDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_delivery_package_with_options_async(uid, headers, runtime)
def get_environment_with_options(
self,
uid: str,
tmp_req: adp_20210720_models.GetEnvironmentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.GetEnvironmentShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentResponse(),
self.call_api(params, req, runtime)
)
async def get_environment_with_options_async(
self,
uid: str,
tmp_req: adp_20210720_models.GetEnvironmentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.GetEnvironmentShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentResponse(),
await self.call_api_async(params, req, runtime)
)
def get_environment(
self,
uid: str,
request: adp_20210720_models.GetEnvironmentRequest,
) -> adp_20210720_models.GetEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_environment_with_options(uid, request, headers, runtime)
async def get_environment_async(
self,
uid: str,
request: adp_20210720_models.GetEnvironmentRequest,
) -> adp_20210720_models.GetEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_environment_with_options_async(uid, request, headers, runtime)
def get_environment_delivery_instance_with_options(
self,
request: adp_20210720_models.GetEnvironmentDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentDeliveryInstanceResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.env_uid):
query['envUID'] = request.env_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironmentDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentDeliveryInstanceResponse(),
self.call_api(params, req, runtime)
)
async def get_environment_delivery_instance_with_options_async(
self,
request: adp_20210720_models.GetEnvironmentDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentDeliveryInstanceResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.env_uid):
query['envUID'] = request.env_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironmentDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentDeliveryInstanceResponse(),
await self.call_api_async(params, req, runtime)
)
def get_environment_delivery_instance(
self,
request: adp_20210720_models.GetEnvironmentDeliveryInstanceRequest,
) -> adp_20210720_models.GetEnvironmentDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_environment_delivery_instance_with_options(request, headers, runtime)
async def get_environment_delivery_instance_async(
self,
request: adp_20210720_models.GetEnvironmentDeliveryInstanceRequest,
) -> adp_20210720_models.GetEnvironmentDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_environment_delivery_instance_with_options_async(request, headers, runtime)
def get_environment_license_with_options(
self,
uid: str,
license_uid: str,
tmp_req: adp_20210720_models.GetEnvironmentLicenseRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentLicenseResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.GetEnvironmentLicenseShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses/{OpenApiUtilClient.get_encode_param(license_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentLicenseResponse(),
self.call_api(params, req, runtime)
)
async def get_environment_license_with_options_async(
self,
uid: str,
license_uid: str,
tmp_req: adp_20210720_models.GetEnvironmentLicenseRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentLicenseResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.GetEnvironmentLicenseShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetEnvironmentLicense',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses/{OpenApiUtilClient.get_encode_param(license_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentLicenseResponse(),
await self.call_api_async(params, req, runtime)
)
def get_environment_license(
self,
uid: str,
license_uid: str,
request: adp_20210720_models.GetEnvironmentLicenseRequest,
) -> adp_20210720_models.GetEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_environment_license_with_options(uid, license_uid, request, headers, runtime)
async def get_environment_license_async(
self,
uid: str,
license_uid: str,
request: adp_20210720_models.GetEnvironmentLicenseRequest,
) -> adp_20210720_models.GetEnvironmentLicenseResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_environment_license_with_options_async(uid, license_uid, request, headers, runtime)
def get_environment_node_with_options(
self,
uid: str,
node_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentNodeResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentNodeResponse(),
self.call_api(params, req, runtime)
)
async def get_environment_node_with_options_async(
self,
uid: str,
node_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetEnvironmentNodeResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetEnvironmentNodeResponse(),
await self.call_api_async(params, req, runtime)
)
def get_environment_node(
self,
uid: str,
node_uid: str,
) -> adp_20210720_models.GetEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_environment_node_with_options(uid, node_uid, headers, runtime)
async def get_environment_node_async(
self,
uid: str,
node_uid: str,
) -> adp_20210720_models.GetEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_environment_node_with_options_async(uid, node_uid, headers, runtime)
def get_foundation_component_reference_with_options(
self,
component_reference_uid: str,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationComponentReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationComponentReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/components/{OpenApiUtilClient.get_encode_param(component_reference_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationComponentReferenceResponse(),
self.call_api(params, req, runtime)
)
async def get_foundation_component_reference_with_options_async(
self,
component_reference_uid: str,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationComponentReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationComponentReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/components/{OpenApiUtilClient.get_encode_param(component_reference_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationComponentReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def get_foundation_component_reference(
self,
component_reference_uid: str,
uid: str,
) -> adp_20210720_models.GetFoundationComponentReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_foundation_component_reference_with_options(component_reference_uid, uid, headers, runtime)
async def get_foundation_component_reference_async(
self,
component_reference_uid: str,
uid: str,
) -> adp_20210720_models.GetFoundationComponentReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_foundation_component_reference_with_options_async(component_reference_uid, uid, headers, runtime)
def get_foundation_reference_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/info',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationReferenceResponse(),
self.call_api(params, req, runtime)
)
async def get_foundation_reference_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/info',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def get_foundation_reference(
self,
uid: str,
) -> adp_20210720_models.GetFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_foundation_reference_with_options(uid, headers, runtime)
async def get_foundation_reference_async(
self,
uid: str,
) -> adp_20210720_models.GetFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_foundation_reference_with_options_async(uid, headers, runtime)
def get_foundation_version_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationVersionResponse(),
self.call_api(params, req, runtime)
)
async def get_foundation_version_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetFoundationVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetFoundationVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetFoundationVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def get_foundation_version(
self,
uid: str,
) -> adp_20210720_models.GetFoundationVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_foundation_version_with_options(uid, headers, runtime)
async def get_foundation_version_async(
self,
uid: str,
) -> adp_20210720_models.GetFoundationVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_foundation_version_with_options_async(uid, headers, runtime)
def get_product_with_options(
self,
uid: str,
request: adp_20210720_models.GetProductRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.with_icon_url):
query['withIconURL'] = request.with_icon_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductResponse(),
self.call_api(params, req, runtime)
)
async def get_product_with_options_async(
self,
uid: str,
request: adp_20210720_models.GetProductRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.with_icon_url):
query['withIconURL'] = request.with_icon_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product(
self,
uid: str,
request: adp_20210720_models.GetProductRequest,
) -> adp_20210720_models.GetProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_with_options(uid, request, headers, runtime)
async def get_product_async(
self,
uid: str,
request: adp_20210720_models.GetProductRequest,
) -> adp_20210720_models.GetProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_with_options_async(uid, request, headers, runtime)
def get_product_component_version_with_options(
self,
relation_uid: str,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductComponentVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductComponentVersionResponse(),
self.call_api(params, req, runtime)
)
async def get_product_component_version_with_options_async(
self,
relation_uid: str,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductComponentVersionResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='GetProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductComponentVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product_component_version(
self,
relation_uid: str,
uid: str,
) -> adp_20210720_models.GetProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_component_version_with_options(relation_uid, uid, headers, runtime)
async def get_product_component_version_async(
self,
relation_uid: str,
uid: str,
) -> adp_20210720_models.GetProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_component_version_with_options_async(relation_uid, uid, headers, runtime)
def get_product_deployment_with_options(
self,
deployment_uid: str,
request: adp_20210720_models.GetProductDeploymentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductDeploymentResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.with_param_config):
query['withParamConfig'] = request.with_param_config
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductDeployment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments/{OpenApiUtilClient.get_encode_param(deployment_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductDeploymentResponse(),
self.call_api(params, req, runtime)
)
async def get_product_deployment_with_options_async(
self,
deployment_uid: str,
request: adp_20210720_models.GetProductDeploymentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductDeploymentResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.with_param_config):
query['withParamConfig'] = request.with_param_config
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductDeployment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments/{OpenApiUtilClient.get_encode_param(deployment_uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductDeploymentResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product_deployment(
self,
deployment_uid: str,
request: adp_20210720_models.GetProductDeploymentRequest,
) -> adp_20210720_models.GetProductDeploymentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_deployment_with_options(deployment_uid, request, headers, runtime)
async def get_product_deployment_async(
self,
deployment_uid: str,
request: adp_20210720_models.GetProductDeploymentRequest,
) -> adp_20210720_models.GetProductDeploymentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_deployment_with_options_async(deployment_uid, request, headers, runtime)
def get_product_version_with_options(
self,
uid: str,
request: adp_20210720_models.GetProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.with_documentation_url):
query['withDocumentationURL'] = request.with_documentation_url
if not UtilClient.is_unset(request.with_extend_resource_url):
query['withExtendResourceURL'] = request.with_extend_resource_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def get_product_version_with_options_async(
self,
uid: str,
request: adp_20210720_models.GetProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.with_documentation_url):
query['withDocumentationURL'] = request.with_documentation_url
if not UtilClient.is_unset(request.with_extend_resource_url):
query['withExtendResourceURL'] = request.with_extend_resource_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product_version(
self,
uid: str,
request: adp_20210720_models.GetProductVersionRequest,
) -> adp_20210720_models.GetProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_version_with_options(uid, request, headers, runtime)
async def get_product_version_async(
self,
uid: str,
request: adp_20210720_models.GetProductVersionRequest,
) -> adp_20210720_models.GetProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_version_with_options_async(uid, request, headers, runtime)
def get_product_version_differences_with_options(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetProductVersionDifferencesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionDifferencesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.pre_version_uid):
query['preVersionUID'] = request.pre_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersionDifferences',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}/versions/{OpenApiUtilClient.get_encode_param(version_uid)}/differences',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionDifferencesResponse(),
self.call_api(params, req, runtime)
)
async def get_product_version_differences_with_options_async(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetProductVersionDifferencesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionDifferencesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.pre_version_uid):
query['preVersionUID'] = request.pre_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersionDifferences',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/integration/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}/versions/{OpenApiUtilClient.get_encode_param(version_uid)}/differences',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionDifferencesResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product_version_differences(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetProductVersionDifferencesRequest,
) -> adp_20210720_models.GetProductVersionDifferencesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_version_differences_with_options(uid, version_uid, request, headers, runtime)
async def get_product_version_differences_async(
self,
uid: str,
version_uid: str,
request: adp_20210720_models.GetProductVersionDifferencesRequest,
) -> adp_20210720_models.GetProductVersionDifferencesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_version_differences_with_options_async(uid, version_uid, request, headers, runtime)
def get_product_version_package_with_options(
self,
uid: str,
request: adp_20210720_models.GetProductVersionPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionPackageResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.old_foundation_reference_uid):
query['oldFoundationReferenceUID'] = request.old_foundation_reference_uid
if not UtilClient.is_unset(request.old_product_version_uid):
query['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_content_type):
query['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_type):
query['packageType'] = request.package_type
if not UtilClient.is_unset(request.package_uid):
query['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.platform):
query['platform'] = request.platform
if not UtilClient.is_unset(request.with_url):
query['withURL'] = request.with_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersionPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/packages',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionPackageResponse(),
self.call_api(params, req, runtime)
)
async def get_product_version_package_with_options_async(
self,
uid: str,
request: adp_20210720_models.GetProductVersionPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetProductVersionPackageResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.old_foundation_reference_uid):
query['oldFoundationReferenceUID'] = request.old_foundation_reference_uid
if not UtilClient.is_unset(request.old_product_version_uid):
query['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.package_content_type):
query['packageContentType'] = request.package_content_type
if not UtilClient.is_unset(request.package_type):
query['packageType'] = request.package_type
if not UtilClient.is_unset(request.package_uid):
query['packageUID'] = request.package_uid
if not UtilClient.is_unset(request.platform):
query['platform'] = request.platform
if not UtilClient.is_unset(request.with_url):
query['withURL'] = request.with_url
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetProductVersionPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/packages',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetProductVersionPackageResponse(),
await self.call_api_async(params, req, runtime)
)
def get_product_version_package(
self,
uid: str,
request: adp_20210720_models.GetProductVersionPackageRequest,
) -> adp_20210720_models.GetProductVersionPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_product_version_package_with_options(uid, request, headers, runtime)
async def get_product_version_package_async(
self,
uid: str,
request: adp_20210720_models.GetProductVersionPackageRequest,
) -> adp_20210720_models.GetProductVersionPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_product_version_package_with_options_async(uid, request, headers, runtime)
def get_resource_snapshot_with_options(
self,
request: adp_20210720_models.GetResourceSnapshotRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetResourceSnapshotResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.uid):
query['uid'] = request.uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetResourceSnapshot',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/resource-snapshots',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetResourceSnapshotResponse(),
self.call_api(params, req, runtime)
)
async def get_resource_snapshot_with_options_async(
self,
request: adp_20210720_models.GetResourceSnapshotRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetResourceSnapshotResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.uid):
query['uid'] = request.uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetResourceSnapshot',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/resource-snapshots',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetResourceSnapshotResponse(),
await self.call_api_async(params, req, runtime)
)
def get_resource_snapshot(
self,
request: adp_20210720_models.GetResourceSnapshotRequest,
) -> adp_20210720_models.GetResourceSnapshotResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_resource_snapshot_with_options(request, headers, runtime)
async def get_resource_snapshot_async(
self,
request: adp_20210720_models.GetResourceSnapshotRequest,
) -> adp_20210720_models.GetResourceSnapshotResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_resource_snapshot_with_options_async(request, headers, runtime)
def get_workflow_status_with_options(
self,
request: adp_20210720_models.GetWorkflowStatusRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetWorkflowStatusResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.workflow_type):
query['workflowType'] = request.workflow_type
if not UtilClient.is_unset(request.xuid):
query['xuid'] = request.xuid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetWorkflowStatus',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/workflows/status',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetWorkflowStatusResponse(),
self.call_api(params, req, runtime)
)
async def get_workflow_status_with_options_async(
self,
request: adp_20210720_models.GetWorkflowStatusRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.GetWorkflowStatusResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.workflow_type):
query['workflowType'] = request.workflow_type
if not UtilClient.is_unset(request.xuid):
query['xuid'] = request.xuid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='GetWorkflowStatus',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/workflows/status',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.GetWorkflowStatusResponse(),
await self.call_api_async(params, req, runtime)
)
def get_workflow_status(
self,
request: adp_20210720_models.GetWorkflowStatusRequest,
) -> adp_20210720_models.GetWorkflowStatusResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.get_workflow_status_with_options(request, headers, runtime)
async def get_workflow_status_async(
self,
request: adp_20210720_models.GetWorkflowStatusRequest,
) -> adp_20210720_models.GetWorkflowStatusResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.get_workflow_status_with_options_async(request, headers, runtime)
def init_environment_resource_with_options(
self,
uid: str,
request: adp_20210720_models.InitEnvironmentResourceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.InitEnvironmentResourceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.access_key_id):
body['accessKeyID'] = request.access_key_id
if not UtilClient.is_unset(request.access_key_secret):
body['accessKeySecret'] = request.access_key_secret
if not UtilClient.is_unset(request.security_token):
body['securityToken'] = request.security_token
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='InitEnvironmentResource',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/resources',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.InitEnvironmentResourceResponse(),
self.call_api(params, req, runtime)
)
async def init_environment_resource_with_options_async(
self,
uid: str,
request: adp_20210720_models.InitEnvironmentResourceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.InitEnvironmentResourceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.access_key_id):
body['accessKeyID'] = request.access_key_id
if not UtilClient.is_unset(request.access_key_secret):
body['accessKeySecret'] = request.access_key_secret
if not UtilClient.is_unset(request.security_token):
body['securityToken'] = request.security_token
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='InitEnvironmentResource',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/resources',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.InitEnvironmentResourceResponse(),
await self.call_api_async(params, req, runtime)
)
def init_environment_resource(
self,
uid: str,
request: adp_20210720_models.InitEnvironmentResourceRequest,
) -> adp_20210720_models.InitEnvironmentResourceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.init_environment_resource_with_options(uid, request, headers, runtime)
async def init_environment_resource_async(
self,
uid: str,
request: adp_20210720_models.InitEnvironmentResourceRequest,
) -> adp_20210720_models.InitEnvironmentResourceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.init_environment_resource_with_options_async(uid, request, headers, runtime)
def list_component_versions_with_options(
self,
uid: str,
tmp_req: adp_20210720_models.ListComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListComponentVersionsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListComponentVersionsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}/versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListComponentVersionsResponse(),
self.call_api(params, req, runtime)
)
async def list_component_versions_with_options_async(
self,
uid: str,
tmp_req: adp_20210720_models.ListComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListComponentVersionsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListComponentVersionsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components/{OpenApiUtilClient.get_encode_param(uid)}/versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListComponentVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_component_versions(
self,
uid: str,
request: adp_20210720_models.ListComponentVersionsRequest,
) -> adp_20210720_models.ListComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_component_versions_with_options(uid, request, headers, runtime)
async def list_component_versions_async(
self,
uid: str,
request: adp_20210720_models.ListComponentVersionsRequest,
) -> adp_20210720_models.ListComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_component_versions_with_options_async(uid, request, headers, runtime)
def list_components_with_options(
self,
request: adp_20210720_models.ListComponentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListComponentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.category):
query['category'] = request.category
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.public):
query['public'] = request.public
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListComponents',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListComponentsResponse(),
self.call_api(params, req, runtime)
)
async def list_components_with_options_async(
self,
request: adp_20210720_models.ListComponentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListComponentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.category):
query['category'] = request.category
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.public):
query['public'] = request.public
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListComponents',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/components',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListComponentsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_components(
self,
request: adp_20210720_models.ListComponentsRequest,
) -> adp_20210720_models.ListComponentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_components_with_options(request, headers, runtime)
async def list_components_async(
self,
request: adp_20210720_models.ListComponentsRequest,
) -> adp_20210720_models.ListComponentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_components_with_options_async(request, headers, runtime)
def list_delivery_instance_change_records_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListDeliveryInstanceChangeRecords',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances/{OpenApiUtilClient.get_encode_param(uid)}/delivery-records',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse(),
self.call_api(params, req, runtime)
)
async def list_delivery_instance_change_records_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListDeliveryInstanceChangeRecords',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances/{OpenApiUtilClient.get_encode_param(uid)}/delivery-records',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_delivery_instance_change_records(
self,
uid: str,
) -> adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_delivery_instance_change_records_with_options(uid, headers, runtime)
async def list_delivery_instance_change_records_async(
self,
uid: str,
) -> adp_20210720_models.ListDeliveryInstanceChangeRecordsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_delivery_instance_change_records_with_options_async(uid, headers, runtime)
def list_delivery_package_with_options(
self,
request: adp_20210720_models.ListDeliveryPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListDeliveryPackageResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.deliverable_uid):
query['deliverableUID'] = request.deliverable_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListDeliveryPackageResponse(),
self.call_api(params, req, runtime)
)
async def list_delivery_package_with_options_async(
self,
request: adp_20210720_models.ListDeliveryPackageRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListDeliveryPackageResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.deliverable_uid):
query['deliverableUID'] = request.deliverable_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListDeliveryPackage',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-packages',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListDeliveryPackageResponse(),
await self.call_api_async(params, req, runtime)
)
def list_delivery_package(
self,
request: adp_20210720_models.ListDeliveryPackageRequest,
) -> adp_20210720_models.ListDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_delivery_package_with_options(request, headers, runtime)
async def list_delivery_package_async(
self,
request: adp_20210720_models.ListDeliveryPackageRequest,
) -> adp_20210720_models.ListDeliveryPackageResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_delivery_package_with_options_async(request, headers, runtime)
def list_environment_licenses_with_options(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentLicensesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentLicensesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.scope):
query['scope'] = request.scope
if not UtilClient.is_unset(request.type):
query['type'] = request.type
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironmentLicenses',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentLicensesResponse(),
self.call_api(params, req, runtime)
)
async def list_environment_licenses_with_options_async(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentLicensesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentLicensesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.scope):
query['scope'] = request.scope
if not UtilClient.is_unset(request.type):
query['type'] = request.type
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironmentLicenses',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/licenses',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentLicensesResponse(),
await self.call_api_async(params, req, runtime)
)
def list_environment_licenses(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentLicensesRequest,
) -> adp_20210720_models.ListEnvironmentLicensesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_environment_licenses_with_options(uid, request, headers, runtime)
async def list_environment_licenses_async(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentLicensesRequest,
) -> adp_20210720_models.ListEnvironmentLicensesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_environment_licenses_with_options_async(uid, request, headers, runtime)
def list_environment_nodes_with_options(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentNodesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentNodesResponse(),
self.call_api(params, req, runtime)
)
async def list_environment_nodes_with_options_async(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentNodesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentNodesResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironmentNodes',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentNodesResponse(),
await self.call_api_async(params, req, runtime)
)
def list_environment_nodes(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentNodesRequest,
) -> adp_20210720_models.ListEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_environment_nodes_with_options(uid, request, headers, runtime)
async def list_environment_nodes_async(
self,
uid: str,
request: adp_20210720_models.ListEnvironmentNodesRequest,
) -> adp_20210720_models.ListEnvironmentNodesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_environment_nodes_with_options_async(uid, request, headers, runtime)
def list_environment_tunnels_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentTunnelsResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListEnvironmentTunnels',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentTunnelsResponse(),
self.call_api(params, req, runtime)
)
async def list_environment_tunnels_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentTunnelsResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListEnvironmentTunnels',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentTunnelsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_environment_tunnels(
self,
uid: str,
) -> adp_20210720_models.ListEnvironmentTunnelsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_environment_tunnels_with_options(uid, headers, runtime)
async def list_environment_tunnels_async(
self,
uid: str,
) -> adp_20210720_models.ListEnvironmentTunnelsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_environment_tunnels_with_options_async(uid, headers, runtime)
def list_environments_with_options(
self,
request: adp_20210720_models.ListEnvironmentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.foundation_type):
query['foundationType'] = request.foundation_type
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.instance_status):
query['instanceStatus'] = request.instance_status
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.type):
query['type'] = request.type
if not UtilClient.is_unset(request.vendor_type):
query['vendorType'] = request.vendor_type
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentsResponse(),
self.call_api(params, req, runtime)
)
async def list_environments_with_options_async(
self,
request: adp_20210720_models.ListEnvironmentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListEnvironmentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.cluster_uid):
query['clusterUID'] = request.cluster_uid
if not UtilClient.is_unset(request.foundation_type):
query['foundationType'] = request.foundation_type
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.instance_status):
query['instanceStatus'] = request.instance_status
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.type):
query['type'] = request.type
if not UtilClient.is_unset(request.vendor_type):
query['vendorType'] = request.vendor_type
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListEnvironments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListEnvironmentsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_environments(
self,
request: adp_20210720_models.ListEnvironmentsRequest,
) -> adp_20210720_models.ListEnvironmentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_environments_with_options(request, headers, runtime)
async def list_environments_async(
self,
request: adp_20210720_models.ListEnvironmentsRequest,
) -> adp_20210720_models.ListEnvironmentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_environments_with_options_async(request, headers, runtime)
def list_foundation_component_versions_with_options(
self,
uid: str,
request: adp_20210720_models.ListFoundationComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationComponentVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.parent_component_relation_uid):
query['parentComponentRelationUID'] = request.parent_component_relation_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationComponentVersionsResponse(),
self.call_api(params, req, runtime)
)
async def list_foundation_component_versions_with_options_async(
self,
uid: str,
request: adp_20210720_models.ListFoundationComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationComponentVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.parent_component_relation_uid):
query['parentComponentRelationUID'] = request.parent_component_relation_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationComponentVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_foundation_component_versions(
self,
uid: str,
request: adp_20210720_models.ListFoundationComponentVersionsRequest,
) -> adp_20210720_models.ListFoundationComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_foundation_component_versions_with_options(uid, request, headers, runtime)
async def list_foundation_component_versions_async(
self,
uid: str,
request: adp_20210720_models.ListFoundationComponentVersionsRequest,
) -> adp_20210720_models.ListFoundationComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_foundation_component_versions_with_options_async(uid, request, headers, runtime)
def list_foundation_reference_components_with_options(
self,
request: adp_20210720_models.ListFoundationReferenceComponentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationReferenceComponentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.foundation_version_uid):
query['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.only_enabled):
query['onlyEnabled'] = request.only_enabled
if not UtilClient.is_unset(request.parent_component_reference_uid):
query['parentComponentReferenceUID'] = request.parent_component_reference_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationReferenceComponents',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationReferenceComponentsResponse(),
self.call_api(params, req, runtime)
)
async def list_foundation_reference_components_with_options_async(
self,
request: adp_20210720_models.ListFoundationReferenceComponentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationReferenceComponentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.foundation_reference_uid):
query['foundationReferenceUID'] = request.foundation_reference_uid
if not UtilClient.is_unset(request.foundation_version_uid):
query['foundationVersionUID'] = request.foundation_version_uid
if not UtilClient.is_unset(request.only_enabled):
query['onlyEnabled'] = request.only_enabled
if not UtilClient.is_unset(request.parent_component_reference_uid):
query['parentComponentReferenceUID'] = request.parent_component_reference_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationReferenceComponents',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationReferenceComponentsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_foundation_reference_components(
self,
request: adp_20210720_models.ListFoundationReferenceComponentsRequest,
) -> adp_20210720_models.ListFoundationReferenceComponentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_foundation_reference_components_with_options(request, headers, runtime)
async def list_foundation_reference_components_async(
self,
request: adp_20210720_models.ListFoundationReferenceComponentsRequest,
) -> adp_20210720_models.ListFoundationReferenceComponentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_foundation_reference_components_with_options_async(request, headers, runtime)
def list_foundation_versions_with_options(
self,
request: adp_20210720_models.ListFoundationVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.sort_direct):
query['sortDirect'] = request.sort_direct
if not UtilClient.is_unset(request.sort_key):
query['sortKey'] = request.sort_key
if not UtilClient.is_unset(request.type):
query['type'] = request.type
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationVersionsResponse(),
self.call_api(params, req, runtime)
)
async def list_foundation_versions_with_options_async(
self,
request: adp_20210720_models.ListFoundationVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListFoundationVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.sort_direct):
query['sortDirect'] = request.sort_direct
if not UtilClient.is_unset(request.sort_key):
query['sortKey'] = request.sort_key
if not UtilClient.is_unset(request.type):
query['type'] = request.type
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListFoundationVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation/versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListFoundationVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_foundation_versions(
self,
request: adp_20210720_models.ListFoundationVersionsRequest,
) -> adp_20210720_models.ListFoundationVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_foundation_versions_with_options(request, headers, runtime)
async def list_foundation_versions_async(
self,
request: adp_20210720_models.ListFoundationVersionsRequest,
) -> adp_20210720_models.ListFoundationVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_foundation_versions_with_options_async(request, headers, runtime)
def list_product_component_versions_with_options(
self,
uid: str,
request: adp_20210720_models.ListProductComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductComponentVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.category):
query['category'] = request.category
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.release_name):
query['releaseName'] = request.release_name
if not UtilClient.is_unset(request.sort_direct):
query['sortDirect'] = request.sort_direct
if not UtilClient.is_unset(request.sort_key):
query['sortKey'] = request.sort_key
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductComponentVersionsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_component_versions_with_options_async(
self,
uid: str,
request: adp_20210720_models.ListProductComponentVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductComponentVersionsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.category):
query['category'] = request.category
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.release_name):
query['releaseName'] = request.release_name
if not UtilClient.is_unset(request.sort_direct):
query['sortDirect'] = request.sort_direct
if not UtilClient.is_unset(request.sort_key):
query['sortKey'] = request.sort_key
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductComponentVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/component-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductComponentVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_component_versions(
self,
uid: str,
request: adp_20210720_models.ListProductComponentVersionsRequest,
) -> adp_20210720_models.ListProductComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_component_versions_with_options(uid, request, headers, runtime)
async def list_product_component_versions_async(
self,
uid: str,
request: adp_20210720_models.ListProductComponentVersionsRequest,
) -> adp_20210720_models.ListProductComponentVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_component_versions_with_options_async(uid, request, headers, runtime)
def list_product_deployments_with_options(
self,
request: adp_20210720_models.ListProductDeploymentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductDeploymentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductDeployments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductDeploymentsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_deployments_with_options_async(
self,
request: adp_20210720_models.ListProductDeploymentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductDeploymentsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductDeployments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/deployments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductDeploymentsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_deployments(
self,
request: adp_20210720_models.ListProductDeploymentsRequest,
) -> adp_20210720_models.ListProductDeploymentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_deployments_with_options(request, headers, runtime)
async def list_product_deployments_async(
self,
request: adp_20210720_models.ListProductDeploymentsRequest,
) -> adp_20210720_models.ListProductDeploymentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_deployments_with_options_async(request, headers, runtime)
def list_product_environments_with_options(
self,
uid: str,
tmp_req: adp_20210720_models.ListProductEnvironmentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductEnvironmentsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductEnvironmentsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
query = {}
if not UtilClient.is_unset(request.compatible_product_version_uid):
query['compatibleProductVersionUID'] = request.compatible_product_version_uid
if not UtilClient.is_unset(request.env_type):
query['envType'] = request.env_type
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.product_version_spec_uid):
query['productVersionSpecUID'] = request.product_version_spec_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductEnvironments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/products/{OpenApiUtilClient.get_encode_param(uid)}/environments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductEnvironmentsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_environments_with_options_async(
self,
uid: str,
tmp_req: adp_20210720_models.ListProductEnvironmentsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductEnvironmentsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductEnvironmentsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
query = {}
if not UtilClient.is_unset(request.compatible_product_version_uid):
query['compatibleProductVersionUID'] = request.compatible_product_version_uid
if not UtilClient.is_unset(request.env_type):
query['envType'] = request.env_type
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.product_version_spec_uid):
query['productVersionSpecUID'] = request.product_version_spec_uid
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductEnvironments',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/hosting/products/{OpenApiUtilClient.get_encode_param(uid)}/environments',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductEnvironmentsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_environments(
self,
uid: str,
request: adp_20210720_models.ListProductEnvironmentsRequest,
) -> adp_20210720_models.ListProductEnvironmentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_environments_with_options(uid, request, headers, runtime)
async def list_product_environments_async(
self,
uid: str,
request: adp_20210720_models.ListProductEnvironmentsRequest,
) -> adp_20210720_models.ListProductEnvironmentsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_environments_with_options_async(uid, request, headers, runtime)
def list_product_foundation_references_with_options(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductFoundationReferencesResponse:
"""
@deprecated
@param headers: map
@param runtime: runtime options for this request RuntimeOptions
@return: ListProductFoundationReferencesResponse
Deprecated
"""
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListProductFoundationReferences',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/foundation-references',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductFoundationReferencesResponse(),
self.call_api(params, req, runtime)
)
async def list_product_foundation_references_with_options_async(
self,
uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductFoundationReferencesResponse:
"""
@deprecated
@param headers: map
@param runtime: runtime options for this request RuntimeOptions
@return: ListProductFoundationReferencesResponse
Deprecated
"""
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='ListProductFoundationReferences',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/foundation-references',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductFoundationReferencesResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_foundation_references(
self,
uid: str,
) -> adp_20210720_models.ListProductFoundationReferencesResponse:
"""
@deprecated
@return: ListProductFoundationReferencesResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_foundation_references_with_options(uid, headers, runtime)
async def list_product_foundation_references_async(
self,
uid: str,
) -> adp_20210720_models.ListProductFoundationReferencesResponse:
"""
@deprecated
@return: ListProductFoundationReferencesResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_foundation_references_with_options_async(uid, headers, runtime)
def list_product_instance_configs_with_options(
self,
request: adp_20210720_models.ListProductInstanceConfigsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductInstanceConfigsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.param_type):
query['paramType'] = request.param_type
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductInstanceConfigs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductInstanceConfigsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_instance_configs_with_options_async(
self,
request: adp_20210720_models.ListProductInstanceConfigsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductInstanceConfigsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.environment_uid):
query['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.param_type):
query['paramType'] = request.param_type
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductInstanceConfigs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductInstanceConfigsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_instance_configs(
self,
request: adp_20210720_models.ListProductInstanceConfigsRequest,
) -> adp_20210720_models.ListProductInstanceConfigsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_instance_configs_with_options(request, headers, runtime)
async def list_product_instance_configs_async(
self,
request: adp_20210720_models.ListProductInstanceConfigsRequest,
) -> adp_20210720_models.ListProductInstanceConfigsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_instance_configs_with_options_async(request, headers, runtime)
def list_product_instances_with_options(
self,
tmp_req: adp_20210720_models.ListProductInstancesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductInstancesResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductInstancesShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.env_uid):
query['envUID'] = request.env_uid
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductInstances',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductInstancesResponse(),
self.call_api(params, req, runtime)
)
async def list_product_instances_with_options_async(
self,
tmp_req: adp_20210720_models.ListProductInstancesRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductInstancesResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductInstancesShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.options):
request.options_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.options, 'options', 'json')
query = {}
if not UtilClient.is_unset(request.env_uid):
query['envUID'] = request.env_uid
if not UtilClient.is_unset(request.options_shrink):
query['options'] = request.options_shrink
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.product_version_uid):
query['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductInstances',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductInstancesResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_instances(
self,
request: adp_20210720_models.ListProductInstancesRequest,
) -> adp_20210720_models.ListProductInstancesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_instances_with_options(request, headers, runtime)
async def list_product_instances_async(
self,
request: adp_20210720_models.ListProductInstancesRequest,
) -> adp_20210720_models.ListProductInstancesResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_instances_with_options_async(request, headers, runtime)
def list_product_version_configs_with_options(
self,
uid: str,
request: adp_20210720_models.ListProductVersionConfigsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductVersionConfigsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.config_type):
query['configType'] = request.config_type
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.parameter):
query['parameter'] = request.parameter
if not UtilClient.is_unset(request.scope):
query['scope'] = request.scope
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductVersionConfigs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductVersionConfigsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_version_configs_with_options_async(
self,
uid: str,
request: adp_20210720_models.ListProductVersionConfigsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductVersionConfigsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.config_type):
query['configType'] = request.config_type
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.parameter):
query['parameter'] = request.parameter
if not UtilClient.is_unset(request.scope):
query['scope'] = request.scope
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductVersionConfigs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductVersionConfigsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_version_configs(
self,
uid: str,
request: adp_20210720_models.ListProductVersionConfigsRequest,
) -> adp_20210720_models.ListProductVersionConfigsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_version_configs_with_options(uid, request, headers, runtime)
async def list_product_version_configs_async(
self,
uid: str,
request: adp_20210720_models.ListProductVersionConfigsRequest,
) -> adp_20210720_models.ListProductVersionConfigsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_version_configs_with_options_async(uid, request, headers, runtime)
def list_product_versions_with_options(
self,
tmp_req: adp_20210720_models.ListProductVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductVersionsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductVersionsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
if not UtilClient.is_unset(tmp_req.supported_foundation_types):
request.supported_foundation_types_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.supported_foundation_types, 'supportedFoundationTypes', 'json')
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.product_name):
query['productName'] = request.product_name
if not UtilClient.is_unset(request.product_uid):
query['productUID'] = request.product_uid
if not UtilClient.is_unset(request.released):
query['released'] = request.released
if not UtilClient.is_unset(request.supported_foundation_types_shrink):
query['supportedFoundationTypes'] = request.supported_foundation_types_shrink
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductVersionsResponse(),
self.call_api(params, req, runtime)
)
async def list_product_versions_with_options_async(
self,
tmp_req: adp_20210720_models.ListProductVersionsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductVersionsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListProductVersionsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.platforms):
request.platforms_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.platforms, 'platforms', 'json')
if not UtilClient.is_unset(tmp_req.supported_foundation_types):
request.supported_foundation_types_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.supported_foundation_types, 'supportedFoundationTypes', 'json')
query = {}
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.platforms_shrink):
query['platforms'] = request.platforms_shrink
if not UtilClient.is_unset(request.product_name):
query['productName'] = request.product_name
if not UtilClient.is_unset(request.product_uid):
query['productUID'] = request.product_uid
if not UtilClient.is_unset(request.released):
query['released'] = request.released
if not UtilClient.is_unset(request.supported_foundation_types_shrink):
query['supportedFoundationTypes'] = request.supported_foundation_types_shrink
if not UtilClient.is_unset(request.version):
query['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProductVersions',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductVersionsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_product_versions(
self,
request: adp_20210720_models.ListProductVersionsRequest,
) -> adp_20210720_models.ListProductVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_product_versions_with_options(request, headers, runtime)
async def list_product_versions_async(
self,
request: adp_20210720_models.ListProductVersionsRequest,
) -> adp_20210720_models.ListProductVersionsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_product_versions_with_options_async(request, headers, runtime)
def list_products_with_options(
self,
request: adp_20210720_models.ListProductsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.description):
query['description'] = request.description
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProducts',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductsResponse(),
self.call_api(params, req, runtime)
)
async def list_products_with_options_async(
self,
request: adp_20210720_models.ListProductsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListProductsResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.description):
query['description'] = request.description
if not UtilClient.is_unset(request.fuzzy):
query['fuzzy'] = request.fuzzy
if not UtilClient.is_unset(request.name):
query['name'] = request.name
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListProducts',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListProductsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_products(
self,
request: adp_20210720_models.ListProductsRequest,
) -> adp_20210720_models.ListProductsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_products_with_options(request, headers, runtime)
async def list_products_async(
self,
request: adp_20210720_models.ListProductsRequest,
) -> adp_20210720_models.ListProductsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_products_with_options_async(request, headers, runtime)
def list_workflow_task_logs_with_options(
self,
step_name: str,
task_name: str,
tmp_req: adp_20210720_models.ListWorkflowTaskLogsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListWorkflowTaskLogsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListWorkflowTaskLogsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.filter_values):
request.filter_values_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.filter_values, 'filterValues', 'json')
query = {}
if not UtilClient.is_unset(request.filter_values_shrink):
query['filterValues'] = request.filter_values_shrink
if not UtilClient.is_unset(request.order_type):
query['orderType'] = request.order_type
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.workflow_type):
query['workflowType'] = request.workflow_type
if not UtilClient.is_unset(request.xuid):
query['xuid'] = request.xuid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListWorkflowTaskLogs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/workflows/steps/{OpenApiUtilClient.get_encode_param(step_name)}/tasks/{OpenApiUtilClient.get_encode_param(task_name)}/logs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListWorkflowTaskLogsResponse(),
self.call_api(params, req, runtime)
)
async def list_workflow_task_logs_with_options_async(
self,
step_name: str,
task_name: str,
tmp_req: adp_20210720_models.ListWorkflowTaskLogsRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ListWorkflowTaskLogsResponse:
UtilClient.validate_model(tmp_req)
request = adp_20210720_models.ListWorkflowTaskLogsShrinkRequest()
OpenApiUtilClient.convert(tmp_req, request)
if not UtilClient.is_unset(tmp_req.filter_values):
request.filter_values_shrink = OpenApiUtilClient.array_to_string_with_specified_style(tmp_req.filter_values, 'filterValues', 'json')
query = {}
if not UtilClient.is_unset(request.filter_values_shrink):
query['filterValues'] = request.filter_values_shrink
if not UtilClient.is_unset(request.order_type):
query['orderType'] = request.order_type
if not UtilClient.is_unset(request.page_num):
query['pageNum'] = request.page_num
if not UtilClient.is_unset(request.page_size):
query['pageSize'] = request.page_size
if not UtilClient.is_unset(request.workflow_type):
query['workflowType'] = request.workflow_type
if not UtilClient.is_unset(request.xuid):
query['xuid'] = request.xuid
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query)
)
params = open_api_models.Params(
action='ListWorkflowTaskLogs',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/workflows/steps/{OpenApiUtilClient.get_encode_param(step_name)}/tasks/{OpenApiUtilClient.get_encode_param(task_name)}/logs',
method='GET',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ListWorkflowTaskLogsResponse(),
await self.call_api_async(params, req, runtime)
)
def list_workflow_task_logs(
self,
step_name: str,
task_name: str,
request: adp_20210720_models.ListWorkflowTaskLogsRequest,
) -> adp_20210720_models.ListWorkflowTaskLogsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.list_workflow_task_logs_with_options(step_name, task_name, request, headers, runtime)
async def list_workflow_task_logs_async(
self,
step_name: str,
task_name: str,
request: adp_20210720_models.ListWorkflowTaskLogsRequest,
) -> adp_20210720_models.ListWorkflowTaskLogsResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.list_workflow_task_logs_with_options_async(step_name, task_name, request, headers, runtime)
def put_environment_tunnel_with_options(
self,
uid: str,
request: adp_20210720_models.PutEnvironmentTunnelRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.PutEnvironmentTunnelResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.tunnel_config):
body['tunnelConfig'] = request.tunnel_config
if not UtilClient.is_unset(request.tunnel_type):
body['tunnelType'] = request.tunnel_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='PutEnvironmentTunnel',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.PutEnvironmentTunnelResponse(),
self.call_api(params, req, runtime)
)
async def put_environment_tunnel_with_options_async(
self,
uid: str,
request: adp_20210720_models.PutEnvironmentTunnelRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.PutEnvironmentTunnelResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.tunnel_config):
body['tunnelConfig'] = request.tunnel_config
if not UtilClient.is_unset(request.tunnel_type):
body['tunnelType'] = request.tunnel_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='PutEnvironmentTunnel',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.PutEnvironmentTunnelResponse(),
await self.call_api_async(params, req, runtime)
)
def put_environment_tunnel(
self,
uid: str,
request: adp_20210720_models.PutEnvironmentTunnelRequest,
) -> adp_20210720_models.PutEnvironmentTunnelResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.put_environment_tunnel_with_options(uid, request, headers, runtime)
async def put_environment_tunnel_async(
self,
uid: str,
request: adp_20210720_models.PutEnvironmentTunnelRequest,
) -> adp_20210720_models.PutEnvironmentTunnelResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.put_environment_tunnel_with_options_async(uid, request, headers, runtime)
def put_product_instance_config_with_options(
self,
request: adp_20210720_models.PutProductInstanceConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.PutProductInstanceConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_uid):
body['componentUID'] = request.component_uid
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.config_uid):
body['configUID'] = request.config_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_name):
body['parentComponentName'] = request.parent_component_name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='PutProductInstanceConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.PutProductInstanceConfigResponse(),
self.call_api(params, req, runtime)
)
async def put_product_instance_config_with_options_async(
self,
request: adp_20210720_models.PutProductInstanceConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.PutProductInstanceConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_uid):
body['componentUID'] = request.component_uid
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.config_uid):
body['configUID'] = request.config_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.environment_uid):
body['environmentUID'] = request.environment_uid
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_name):
body['parentComponentName'] = request.parent_component_name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
if not UtilClient.is_unset(request.scope):
body['scope'] = request.scope
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='PutProductInstanceConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-instances/configs',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.PutProductInstanceConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def put_product_instance_config(
self,
request: adp_20210720_models.PutProductInstanceConfigRequest,
) -> adp_20210720_models.PutProductInstanceConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.put_product_instance_config_with_options(request, headers, runtime)
async def put_product_instance_config_async(
self,
request: adp_20210720_models.PutProductInstanceConfigRequest,
) -> adp_20210720_models.PutProductInstanceConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.put_product_instance_config_with_options_async(request, headers, runtime)
def set_environment_foundation_reference_with_options(
self,
uid: str,
foundation_reference_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.SetEnvironmentFoundationReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='SetEnvironmentFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/foundation-references/{OpenApiUtilClient.get_encode_param(foundation_reference_uid)}',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.SetEnvironmentFoundationReferenceResponse(),
self.call_api(params, req, runtime)
)
async def set_environment_foundation_reference_with_options_async(
self,
uid: str,
foundation_reference_uid: str,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.SetEnvironmentFoundationReferenceResponse:
req = open_api_models.OpenApiRequest(
headers=headers
)
params = open_api_models.Params(
action='SetEnvironmentFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/foundation-references/{OpenApiUtilClient.get_encode_param(foundation_reference_uid)}',
method='POST',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.SetEnvironmentFoundationReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def set_environment_foundation_reference(
self,
uid: str,
foundation_reference_uid: str,
) -> adp_20210720_models.SetEnvironmentFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.set_environment_foundation_reference_with_options(uid, foundation_reference_uid, headers, runtime)
async def set_environment_foundation_reference_async(
self,
uid: str,
foundation_reference_uid: str,
) -> adp_20210720_models.SetEnvironmentFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.set_environment_foundation_reference_with_options_async(uid, foundation_reference_uid, headers, runtime)
def update_deliverable_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateDeliverableRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateDeliverableResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation):
body['foundation'] = request.foundation
if not UtilClient.is_unset(request.products):
body['products'] = request.products
if not UtilClient.is_unset(request.status):
body['status'] = request.status
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateDeliverableResponse(),
self.call_api(params, req, runtime)
)
async def update_deliverable_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateDeliverableRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateDeliverableResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation):
body['foundation'] = request.foundation
if not UtilClient.is_unset(request.products):
body['products'] = request.products
if not UtilClient.is_unset(request.status):
body['status'] = request.status
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateDeliverable',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/deliverables/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateDeliverableResponse(),
await self.call_api_async(params, req, runtime)
)
def update_deliverable(
self,
uid: str,
request: adp_20210720_models.UpdateDeliverableRequest,
) -> adp_20210720_models.UpdateDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_deliverable_with_options(uid, request, headers, runtime)
async def update_deliverable_async(
self,
uid: str,
request: adp_20210720_models.UpdateDeliverableRequest,
) -> adp_20210720_models.UpdateDeliverableResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_deliverable_with_options_async(uid, request, headers, runtime)
def update_delivery_instance_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateDeliveryInstanceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.deliverable_config_uid):
body['deliverableConfigUID'] = request.deliverable_config_uid
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.desc):
body['desc'] = request.desc
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateDeliveryInstanceResponse(),
self.call_api(params, req, runtime)
)
async def update_delivery_instance_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateDeliveryInstanceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateDeliveryInstanceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.deliverable_config_uid):
body['deliverableConfigUID'] = request.deliverable_config_uid
if not UtilClient.is_unset(request.deliverable_uid):
body['deliverableUID'] = request.deliverable_uid
if not UtilClient.is_unset(request.desc):
body['desc'] = request.desc
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateDeliveryInstance',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/delivery/delivery-instances/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateDeliveryInstanceResponse(),
await self.call_api_async(params, req, runtime)
)
def update_delivery_instance(
self,
uid: str,
request: adp_20210720_models.UpdateDeliveryInstanceRequest,
) -> adp_20210720_models.UpdateDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_delivery_instance_with_options(uid, request, headers, runtime)
async def update_delivery_instance_async(
self,
uid: str,
request: adp_20210720_models.UpdateDeliveryInstanceRequest,
) -> adp_20210720_models.UpdateDeliveryInstanceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_delivery_instance_with_options_async(uid, request, headers, runtime)
def update_environment_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.advanced_configs):
body['advancedConfigs'] = request.advanced_configs
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.location):
body['location'] = request.location
if not UtilClient.is_unset(request.vendor_config):
body['vendorConfig'] = request.vendor_config
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentResponse(),
self.call_api(params, req, runtime)
)
async def update_environment_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.advanced_configs):
body['advancedConfigs'] = request.advanced_configs
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.location):
body['location'] = request.location
if not UtilClient.is_unset(request.vendor_config):
body['vendorConfig'] = request.vendor_config
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironment',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentResponse(),
await self.call_api_async(params, req, runtime)
)
def update_environment(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentRequest,
) -> adp_20210720_models.UpdateEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_environment_with_options(uid, request, headers, runtime)
async def update_environment_async(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentRequest,
) -> adp_20210720_models.UpdateEnvironmentResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_environment_with_options_async(uid, request, headers, runtime)
def update_environment_node_with_options(
self,
uid: str,
node_uid: str,
request: adp_20210720_models.UpdateEnvironmentNodeRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentNodeResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.application_disk):
body['applicationDisk'] = request.application_disk
if not UtilClient.is_unset(request.etcd_disk):
body['etcdDisk'] = request.etcd_disk
if not UtilClient.is_unset(request.labels):
body['labels'] = request.labels
if not UtilClient.is_unset(request.root_password):
body['rootPassword'] = request.root_password
if not UtilClient.is_unset(request.taints):
body['taints'] = request.taints
if not UtilClient.is_unset(request.trident_system_disk):
body['tridentSystemDisk'] = request.trident_system_disk
if not UtilClient.is_unset(request.trident_system_size_disk):
body['tridentSystemSizeDisk'] = request.trident_system_size_disk
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentNodeResponse(),
self.call_api(params, req, runtime)
)
async def update_environment_node_with_options_async(
self,
uid: str,
node_uid: str,
request: adp_20210720_models.UpdateEnvironmentNodeRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentNodeResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.application_disk):
body['applicationDisk'] = request.application_disk
if not UtilClient.is_unset(request.etcd_disk):
body['etcdDisk'] = request.etcd_disk
if not UtilClient.is_unset(request.labels):
body['labels'] = request.labels
if not UtilClient.is_unset(request.root_password):
body['rootPassword'] = request.root_password
if not UtilClient.is_unset(request.taints):
body['taints'] = request.taints
if not UtilClient.is_unset(request.trident_system_disk):
body['tridentSystemDisk'] = request.trident_system_disk
if not UtilClient.is_unset(request.trident_system_size_disk):
body['tridentSystemSizeDisk'] = request.trident_system_size_disk
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironmentNode',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/nodes/{OpenApiUtilClient.get_encode_param(node_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentNodeResponse(),
await self.call_api_async(params, req, runtime)
)
def update_environment_node(
self,
uid: str,
node_uid: str,
request: adp_20210720_models.UpdateEnvironmentNodeRequest,
) -> adp_20210720_models.UpdateEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_environment_node_with_options(uid, node_uid, request, headers, runtime)
async def update_environment_node_async(
self,
uid: str,
node_uid: str,
request: adp_20210720_models.UpdateEnvironmentNodeRequest,
) -> adp_20210720_models.UpdateEnvironmentNodeResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_environment_node_with_options_async(uid, node_uid, request, headers, runtime)
def update_environment_product_version_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentProductVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.old_product_version_spec_uid):
body['oldProductVersionSpecUID'] = request.old_product_version_spec_uid
if not UtilClient.is_unset(request.old_product_version_uid):
body['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.product_version_spec_uid):
body['productVersionSpecUID'] = request.product_version_spec_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironmentProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def update_environment_product_version_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateEnvironmentProductVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.old_product_version_spec_uid):
body['oldProductVersionSpecUID'] = request.old_product_version_spec_uid
if not UtilClient.is_unset(request.old_product_version_uid):
body['oldProductVersionUID'] = request.old_product_version_uid
if not UtilClient.is_unset(request.product_version_spec_uid):
body['productVersionSpecUID'] = request.product_version_spec_uid
if not UtilClient.is_unset(request.product_version_uid):
body['productVersionUID'] = request.product_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateEnvironmentProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/product-versions',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateEnvironmentProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def update_environment_product_version(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentProductVersionRequest,
) -> adp_20210720_models.UpdateEnvironmentProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_environment_product_version_with_options(uid, request, headers, runtime)
async def update_environment_product_version_async(
self,
uid: str,
request: adp_20210720_models.UpdateEnvironmentProductVersionRequest,
) -> adp_20210720_models.UpdateEnvironmentProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_environment_product_version_with_options_async(uid, request, headers, runtime)
def update_foundation_component_reference_with_options(
self,
uid: str,
component_reference_uid: str,
request: adp_20210720_models.UpdateFoundationComponentReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateFoundationComponentReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_orchestration_values):
body['componentOrchestrationValues'] = request.component_orchestration_values
if not UtilClient.is_unset(request.enable):
body['enable'] = request.enable
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateFoundationComponentReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/components/{OpenApiUtilClient.get_encode_param(component_reference_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateFoundationComponentReferenceResponse(),
self.call_api(params, req, runtime)
)
async def update_foundation_component_reference_with_options_async(
self,
uid: str,
component_reference_uid: str,
request: adp_20210720_models.UpdateFoundationComponentReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateFoundationComponentReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_orchestration_values):
body['componentOrchestrationValues'] = request.component_orchestration_values
if not UtilClient.is_unset(request.enable):
body['enable'] = request.enable
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateFoundationComponentReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}/components/{OpenApiUtilClient.get_encode_param(component_reference_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateFoundationComponentReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def update_foundation_component_reference(
self,
uid: str,
component_reference_uid: str,
request: adp_20210720_models.UpdateFoundationComponentReferenceRequest,
) -> adp_20210720_models.UpdateFoundationComponentReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_foundation_component_reference_with_options(uid, component_reference_uid, request, headers, runtime)
async def update_foundation_component_reference_async(
self,
uid: str,
component_reference_uid: str,
request: adp_20210720_models.UpdateFoundationComponentReferenceRequest,
) -> adp_20210720_models.UpdateFoundationComponentReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_foundation_component_reference_with_options_async(uid, component_reference_uid, request, headers, runtime)
def update_foundation_reference_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateFoundationReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateFoundationReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_config):
body['clusterConfig'] = request.cluster_config
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateFoundationReferenceResponse(),
self.call_api(params, req, runtime)
)
async def update_foundation_reference_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateFoundationReferenceRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateFoundationReferenceResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.cluster_config):
body['clusterConfig'] = request.cluster_config
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateFoundationReference',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/foundation-references/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateFoundationReferenceResponse(),
await self.call_api_async(params, req, runtime)
)
def update_foundation_reference(
self,
uid: str,
request: adp_20210720_models.UpdateFoundationReferenceRequest,
) -> adp_20210720_models.UpdateFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_foundation_reference_with_options(uid, request, headers, runtime)
async def update_foundation_reference_async(
self,
uid: str,
request: adp_20210720_models.UpdateFoundationReferenceRequest,
) -> adp_20210720_models.UpdateFoundationReferenceResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_foundation_reference_with_options_async(uid, request, headers, runtime)
def update_product_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateProductRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.categories):
body['categories'] = request.categories
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.display_name):
body['displayName'] = request.display_name
if not UtilClient.is_unset(request.vendor):
body['vendor'] = request.vendor
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductResponse(),
self.call_api(params, req, runtime)
)
async def update_product_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.categories):
body['categories'] = request.categories
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.display_name):
body['displayName'] = request.display_name
if not UtilClient.is_unset(request.vendor):
body['vendor'] = request.vendor
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProduct',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/products/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductResponse(),
await self.call_api_async(params, req, runtime)
)
def update_product(
self,
uid: str,
request: adp_20210720_models.UpdateProductRequest,
) -> adp_20210720_models.UpdateProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_product_with_options(uid, request, headers, runtime)
async def update_product_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductRequest,
) -> adp_20210720_models.UpdateProductResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_product_with_options_async(uid, request, headers, runtime)
def update_product_component_version_with_options(
self,
uid: str,
relation_uid: str,
request: adp_20210720_models.UpdateProductComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductComponentVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_orchestration_values):
body['componentOrchestrationValues'] = request.component_orchestration_values
if not UtilClient.is_unset(request.component_specification_uid):
body['componentSpecificationUid'] = request.component_specification_uid
if not UtilClient.is_unset(request.component_specification_values):
body['componentSpecificationValues'] = request.component_specification_values
if not UtilClient.is_unset(request.enable):
body['enable'] = request.enable
if not UtilClient.is_unset(request.new_component_version_uid):
body['newComponentVersionUID'] = request.new_component_version_uid
if not UtilClient.is_unset(request.policy):
body['policy'] = request.policy
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
if not UtilClient.is_unset(request.unset_component_version_spec):
body['unsetComponentVersionSpec'] = request.unset_component_version_spec
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductComponentVersionResponse(),
self.call_api(params, req, runtime)
)
async def update_product_component_version_with_options_async(
self,
uid: str,
relation_uid: str,
request: adp_20210720_models.UpdateProductComponentVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductComponentVersionResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_orchestration_values):
body['componentOrchestrationValues'] = request.component_orchestration_values
if not UtilClient.is_unset(request.component_specification_uid):
body['componentSpecificationUid'] = request.component_specification_uid
if not UtilClient.is_unset(request.component_specification_values):
body['componentSpecificationValues'] = request.component_specification_values
if not UtilClient.is_unset(request.enable):
body['enable'] = request.enable
if not UtilClient.is_unset(request.new_component_version_uid):
body['newComponentVersionUID'] = request.new_component_version_uid
if not UtilClient.is_unset(request.policy):
body['policy'] = request.policy
if not UtilClient.is_unset(request.release_name):
body['releaseName'] = request.release_name
if not UtilClient.is_unset(request.unset_component_version_spec):
body['unsetComponentVersionSpec'] = request.unset_component_version_spec
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductComponentVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/relations/{OpenApiUtilClient.get_encode_param(relation_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductComponentVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def update_product_component_version(
self,
uid: str,
relation_uid: str,
request: adp_20210720_models.UpdateProductComponentVersionRequest,
) -> adp_20210720_models.UpdateProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_product_component_version_with_options(uid, relation_uid, request, headers, runtime)
async def update_product_component_version_async(
self,
uid: str,
relation_uid: str,
request: adp_20210720_models.UpdateProductComponentVersionRequest,
) -> adp_20210720_models.UpdateProductComponentVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_product_component_version_with_options_async(uid, relation_uid, request, headers, runtime)
def update_product_foundation_version_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateProductFoundationVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductFoundationVersionResponse:
"""
@deprecated
@param request: UpdateProductFoundationVersionRequest
@param headers: map
@param runtime: runtime options for this request RuntimeOptions
@return: UpdateProductFoundationVersionResponse
Deprecated
"""
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductFoundationVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/foundation',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductFoundationVersionResponse(),
self.call_api(params, req, runtime)
)
async def update_product_foundation_version_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductFoundationVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductFoundationVersionResponse:
"""
@deprecated
@param request: UpdateProductFoundationVersionRequest
@param headers: map
@param runtime: runtime options for this request RuntimeOptions
@return: UpdateProductFoundationVersionResponse
Deprecated
"""
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.foundation_version_uid):
body['foundationVersionUID'] = request.foundation_version_uid
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductFoundationVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/foundation',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductFoundationVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def update_product_foundation_version(
self,
uid: str,
request: adp_20210720_models.UpdateProductFoundationVersionRequest,
) -> adp_20210720_models.UpdateProductFoundationVersionResponse:
"""
@deprecated
@param request: UpdateProductFoundationVersionRequest
@return: UpdateProductFoundationVersionResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_product_foundation_version_with_options(uid, request, headers, runtime)
async def update_product_foundation_version_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductFoundationVersionRequest,
) -> adp_20210720_models.UpdateProductFoundationVersionResponse:
"""
@deprecated
@param request: UpdateProductFoundationVersionRequest
@return: UpdateProductFoundationVersionResponse
Deprecated
"""
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_product_foundation_version_with_options_async(uid, request, headers, runtime)
def update_product_version_with_options(
self,
uid: str,
request: adp_20210720_models.UpdateProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.action):
query['action'] = request.action
body = {}
if not UtilClient.is_unset(request.continuous_integration):
body['continuousIntegration'] = request.continuous_integration
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.entry):
body['entry'] = request.entry
if not UtilClient.is_unset(request.timeout):
body['timeout'] = request.timeout
if not UtilClient.is_unset(request.version):
body['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductVersionResponse(),
self.call_api(params, req, runtime)
)
async def update_product_version_with_options_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductVersionRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductVersionResponse:
UtilClient.validate_model(request)
query = {}
if not UtilClient.is_unset(request.action):
query['action'] = request.action
body = {}
if not UtilClient.is_unset(request.continuous_integration):
body['continuousIntegration'] = request.continuous_integration
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.entry):
body['entry'] = request.entry
if not UtilClient.is_unset(request.timeout):
body['timeout'] = request.timeout
if not UtilClient.is_unset(request.version):
body['version'] = request.version
req = open_api_models.OpenApiRequest(
headers=headers,
query=OpenApiUtilClient.query(query),
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductVersion',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductVersionResponse(),
await self.call_api_async(params, req, runtime)
)
def update_product_version(
self,
uid: str,
request: adp_20210720_models.UpdateProductVersionRequest,
) -> adp_20210720_models.UpdateProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_product_version_with_options(uid, request, headers, runtime)
async def update_product_version_async(
self,
uid: str,
request: adp_20210720_models.UpdateProductVersionRequest,
) -> adp_20210720_models.UpdateProductVersionResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_product_version_with_options_async(uid, request, headers, runtime)
def update_product_version_config_with_options(
self,
uid: str,
config_uid: str,
request: adp_20210720_models.UpdateProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductVersionConfigResponse(),
self.call_api(params, req, runtime)
)
async def update_product_version_config_with_options_async(
self,
uid: str,
config_uid: str,
request: adp_20210720_models.UpdateProductVersionConfigRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.UpdateProductVersionConfigResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.component_version_uid):
body['componentVersionUID'] = request.component_version_uid
if not UtilClient.is_unset(request.description):
body['description'] = request.description
if not UtilClient.is_unset(request.name):
body['name'] = request.name
if not UtilClient.is_unset(request.parent_component_version_uid):
body['parentComponentVersionUID'] = request.parent_component_version_uid
if not UtilClient.is_unset(request.value):
body['value'] = request.value
if not UtilClient.is_unset(request.value_type):
body['valueType'] = request.value_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='UpdateProductVersionConfig',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/product-versions/{OpenApiUtilClient.get_encode_param(uid)}/configs/{OpenApiUtilClient.get_encode_param(config_uid)}',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.UpdateProductVersionConfigResponse(),
await self.call_api_async(params, req, runtime)
)
def update_product_version_config(
self,
uid: str,
config_uid: str,
request: adp_20210720_models.UpdateProductVersionConfigRequest,
) -> adp_20210720_models.UpdateProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.update_product_version_config_with_options(uid, config_uid, request, headers, runtime)
async def update_product_version_config_async(
self,
uid: str,
config_uid: str,
request: adp_20210720_models.UpdateProductVersionConfigRequest,
) -> adp_20210720_models.UpdateProductVersionConfigResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.update_product_version_config_with_options_async(uid, config_uid, request, headers, runtime)
def validate_environment_tunnel_with_options(
self,
uid: str,
request: adp_20210720_models.ValidateEnvironmentTunnelRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ValidateEnvironmentTunnelResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.tunnel_config):
body['tunnelConfig'] = request.tunnel_config
if not UtilClient.is_unset(request.tunnel_type):
body['tunnelType'] = request.tunnel_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='ValidateEnvironmentTunnel',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels/validation',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ValidateEnvironmentTunnelResponse(),
self.call_api(params, req, runtime)
)
async def validate_environment_tunnel_with_options_async(
self,
uid: str,
request: adp_20210720_models.ValidateEnvironmentTunnelRequest,
headers: Dict[str, str],
runtime: util_models.RuntimeOptions,
) -> adp_20210720_models.ValidateEnvironmentTunnelResponse:
UtilClient.validate_model(request)
body = {}
if not UtilClient.is_unset(request.tunnel_config):
body['tunnelConfig'] = request.tunnel_config
if not UtilClient.is_unset(request.tunnel_type):
body['tunnelType'] = request.tunnel_type
req = open_api_models.OpenApiRequest(
headers=headers,
body=OpenApiUtilClient.parse_to_map(body)
)
params = open_api_models.Params(
action='ValidateEnvironmentTunnel',
version='2021-07-20',
protocol='HTTPS',
pathname=f'/api/v2/environments/{OpenApiUtilClient.get_encode_param(uid)}/tunnels/validation',
method='PUT',
auth_type='AK',
style='ROA',
req_body_type='json',
body_type='json'
)
return TeaCore.from_map(
adp_20210720_models.ValidateEnvironmentTunnelResponse(),
await self.call_api_async(params, req, runtime)
)
def validate_environment_tunnel(
self,
uid: str,
request: adp_20210720_models.ValidateEnvironmentTunnelRequest,
) -> adp_20210720_models.ValidateEnvironmentTunnelResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return self.validate_environment_tunnel_with_options(uid, request, headers, runtime)
async def validate_environment_tunnel_async(
self,
uid: str,
request: adp_20210720_models.ValidateEnvironmentTunnelRequest,
) -> adp_20210720_models.ValidateEnvironmentTunnelResponse:
runtime = util_models.RuntimeOptions()
headers = {}
return await self.validate_environment_tunnel_with_options_async(uid, request, headers, runtime)
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
68231ea1fdfc7c7ce7e6f4d578d950648ba1ba6d | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/coverage-big-4579.py | 8c13f6cc0c32208121d23fd4704cad007abaacf3 | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,347 | py | count:int = 0
count2:int = 0
count3:int = 0
count4:int = 0
count5:int = 0
def foo(s: str) -> int:
return len(s)
def foo2(s: str, s2: str) -> int:
return len(s)
def foo3(s: str, s2: str, s3: str) -> int:
return len(s)
def foo4(s: str, s2: str, s3: str, s4: str) -> int:
return len(s)
def foo5(s: str, s2: str, s3: str, s4: str, s5: str) -> int:
return len(s)
class bar(object):
p: bool = True
def baz(self:"bar", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar2(object):
p: bool = True
p2: bool = True
def baz(self:"bar2", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar2", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar3(object):
p: bool = True
p2: bool = True
p3: bool = True
def baz(self:"bar3", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar3", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar3", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar4(object):
p: bool = True
p2: bool = True
p3: bool = True
p4: bool = True
def baz(self:"bar4", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar4", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar4", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz4(self:"bar4", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar5(object):
p: bool = True
p2: bool = True
p3: bool = True
p4: bool = True
p5: bool = True
def baz(self:"bar5", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar5", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar5", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz4(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def $ID(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int], xx5: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
x5:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
y5:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
def qux5(y: int, y2: int, y3: int, y4: int, y5: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
nonlocal x5
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
print(bar().baz([1,2]))
| [
"647530+Virtlink@users.noreply.github.com"
] | 647530+Virtlink@users.noreply.github.com |
eb26144c87b439f5f0f8059de871a2b706ed56c0 | d33cd94fb483f6694f6f1f0848f83d5cc2143faf | /removingelements.py | 832d30578686c0b9ebe77d9bdbf4ce9efbfa9f8c | [] | no_license | kajetan-mazur/isdivide2 | 4bb00f136f5724c05617e806419c192d1ffa0b5e | 170b14cb645fa09d52622d81f801718a6d35d54c | refs/heads/master | 2021-01-19T11:26:17.102939 | 2017-04-25T12:10:04 | 2017-04-25T12:10:04 | 87,967,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 123 | py | list_string = ['flower', 'water', 'earth', 'pot']
# el_to_remove = 'flower'
list_string.remove('flower')
print(list_string) | [
"kajetan@webownia.pl"
] | kajetan@webownia.pl |
81d2d55ca5222f29b7e74ce786cc2e7d5e1986fd | c7fa4d256b39a9254c0ac86199bbd60bce64e948 | /Code/Elasticsearch/ExtractFingerprints.py | 22f1d192942ba6bc9bccc2abbd90648223584238 | [] | no_license | myersjo/Final-Year-Project | 3fd576598e5c448c8c331fe13be97c94adc9d974 | 5c3e1df6decefb337a6eb50792ee4ea59d0db470 | refs/heads/master | 2021-10-28T07:07:02.095025 | 2019-04-22T16:20:36 | 2019-04-22T16:20:36 | 153,266,406 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,005 | py | #!/usr/bin/python
# Elasticsearch version of SameKeys.py
# from https://github.com/sftcd/surveys
import os, sys, argparse, tempfile, gc
import json
import jsonpickle # install via "$ sudo pip install -U jsonpickle"
import time, datetime
from dateutil import parser as dparser # for parsing time from comand line and certs
import pytz # for adding back TZ info to allow comparisons
from elasticsearch import Elasticsearch # install via "$ sudo pip install elasticsearch"
from elasticsearch.helpers import scan, bulk
es = Elasticsearch(timeout=60)
# from https://github.com/sftcd/surveys ...
# locally in $HOME/code/surveys
def_surveydir=os.environ['HOME']+'/code/surveys'
sys.path.insert(0,def_surveydir)
from SurveyFuncs import *
# default values
index="av-records-fresh-geo-ie-20180316"
fp_index="av-fingerprints-20180316"
UPDATE_ELASTICSEARCH=True # Used for testing - if False, data is retrieved from ES, but no inserts/updates are sent
def timestampPrint(message):
print('[{}] {} '.format(datetime.datetime.now(), message))
def newFprintRec():
fprec={}
fprec['ip'] = ""
fprec['fprint'] = ""
fprec['run_date'] = ""
fprec['p22'] = 0
fprec['p25'] = 0
fprec['p110'] = 0
fprec['p143'] = 0
fprec['p443'] = 0
fprec['p587'] = 0
fprec['p993'] = 0
return fprec
def toESDocs(fprecs, index):
docs=[]
for fp in fprecs:
doc={}
doc['_index']=index
doc['_type']="document"
doc['doc']=fprecs[fp]
docs.append(doc)
return docs
# command line arg handling
argparser=argparse.ArgumentParser(description='Scan records for collisions')
argparser.add_argument('-i','--input',
dest='index',
help='Elasticsearch index containing list of IPs')
argparser.add_argument('--fpindex',
dest='fp_index',
help='Elasticsearch fingerprint index')
argparser.add_argument('-p','--ports',
dest='portstring',
help='comma-sep list of ports to scan')
argparser.add_argument('-s','--scandate',
dest='scandatestring',
help='time at which to evaluate certificate validity')
argparser.add_argument('-c','--country',
dest='country',
help='country in which we\'re interested, use XX if you don\'t care, default is IE')
argparser.add_argument('-f','--fps',
dest='fpfile',
help='pre-existing fingerprints file')
args=argparser.parse_args()
# scandate is needed to determine certificate validity, so we support
# the option to now use "now"
if args.scandatestring is None:
scandate=datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
#print >> sys.stderr, "No (or bad) scan time provided, using 'now'"
else:
scandate=dparser.parse(args.scandatestring).replace(tzinfo=pytz.UTC)
print >> sys.stderr, "Scandate: using " + args.scandatestring + "\n"
def_country='IE'
country=def_country
if args.country is not None:
country=args.country
print >>sys.stderr, "Doing a " + country + "run"
if args.index is not None:
index=args.index
if args.fp_index is not None:
fp_index=args.fp_index
# this is an array to hold the set of keys we find
fingerprints=[]
overallcount=0
badcount=0
goodcount=0
# encoder options
jsonpickle.set_encoder_options('json', sort_keys=True, indent=2)
jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=2)
# it can happen that we run out of memory after we've done all of the
# dns stuff, in such a case, it's nice to be able to re-start from the
# fingerprints.json file to save the time of re-doing all those dns
# queries, this branch does that
if args.fpfile is not None:
pass
# TODO: Update
# # read fingerprints from fpfile
# fpf=open(args.fpfile,"r")
# f=getnextfprint(fpf)
# print f
# fpcount=0
# while f:
# fingerprints.append(f)
# fpcount+=1
# if fpcount % 100 == 0:
# print >>sys.stderr, "Read " + str(fpcount) + " fingerprints from " + args.fpfile
# f=getnextfprint(fpf)
# fpf.close()
else:
bads={}
# keep track of how long this is taking per ip
peripaverage=0
if UPDATE_ELASTICSEARCH:
# Disable refresh to stop reindexing until complete
es.indices.put_settings(index=index,
body={ "index.refresh_interval": -1 })
timestampPrint("Disabling ES refresh")
# Generator to get records from ES, 'size' at a time
records = scan(es,
query={"query": {"match_all": {}}},
index=index,
scroll="2m",
size="10")
# with open(infile,'r') as f:
for record in records:
ipstart=time.time()
badrec=False
j_content = record["_source"]["doc"]
somekey=False
thisone=OneFP()
thisone.ip_record=overallcount
thisone.ip=j_content['ip'].strip()
if 'writer' in j_content:
thisone.writer=j_content['writer']
try:
if thisone.writer=="FreshGrab.py":
asn=j_content['asn']
asndec=int(j_content['asndec'])
thisone.asn=asn
thisone.asndec=asndec
# print "Ip: {} ASN: {}".format(thisone.ip, asn)
if country != 'XX' and j_content['country_code'] != country:
badrec=True
print >>sys.stderr, "Bad country for ip",thisone.ip,"location:",j_content['location']['country_code'],"Asked for CC:",country
j_content['wrong_country']=j_content['location']['country_code']
else:
asn=j_content['autonomous_system']['name'].lower()
asndec=int(j_content['autonomous_system']['asn'])
thisone.asn=asn
thisone.asndec=asndec
if country != 'XX' and j_content['location']['country_code'] != country:
badrec=True
print >>sys.stderr, "Bad country for ip",thisone.ip,"location:",j_content['location']['country_code'],"Asked for CC:",country
j_content['wrong_country']=j_content['location']['country_code']
except:
# look that chap up ourselves
mm_inited=False
if not mm_inited:
mm_setup()
mm_inited=True
asninfo=mm_info(thisone.ip)
#print "fixing up asn info",asninfo
thisone.asn=asninfo['asn']
thisone.asndec=asninfo['asndec']
if country != 'XX' and asninfo['cc'] != country:
# just record as baddy if the country-code is (now) wrong?
# mark it so we can revisit later too
print >>sys.stderr, "Bad country for ip",thisone.ip,"asn:",asninfo['cc'],"Asked for CC:",country
j_content['wrong_country']=asninfo['cc']
badrec=True
for pstr in portstrings:
thisone.analysis[pstr]={}
thisone.analysis['nameset']={}
nameset=thisone.analysis['nameset']
try:
# name from reverse DNS
rdnsrec=socket.gethostbyaddr(thisone.ip)
rdns=rdnsrec[0]
#print "FQDN reverse: " + str(rdns)
nameset['rdns']=rdns
except Exception as e:
#print >> sys.stderr, "FQDN reverse exception " + str(e) + " for record:" + thisone.ip
#nameset['rdns']=''
pass
# name from banner
try:
p25=j_content['p25']
if thisone.writer=="FreshGrab.py":
#print p25['data']['banner']
banner=p25['data']['banner']
else:
banner=p25['smtp']['starttls']['banner']
ts=banner.split()
if ts[0]=="220":
banner_fqdn=ts[1]
nameset['banner']=banner_fqdn
elif ts[0].startswith("220-"):
banner_fqdn=ts[0][4:]
nameset['banner']=banner_fqdn
except Exception as e:
#print >> sys.stderr, "FQDN banner exception " + str(e) + " for record:" + str(overallcount) + " ip:" + thisone.ip
nameset['banner']=''
try:
if thisone.writer=="FreshGrab.py":
fp=j_content['p22']['data']['xssh']['key_exchange']['server_host_key']['fingerprint_sha256']
shk=j_content['p22']['data']['xssh']['key_exchange']['server_host_key']
if shk['algorithm']=='ssh-rsa':
thisone.analysis['p22']['rsalen']=shk['rsa_public_key']['length']
else:
thisone.analysis['p22']['alg']=shk['algorithm']
else:
fp=j_content['p22']['ssh']['v2']['server_host_key']['fingerprint_sha256']
shk=j_content['p22']['ssh']['v2']['server_host_key']
if shk['key_algorithm']=='ssh-rsa':
thisone.analysis['p22']['rsalen']=shk['rsa_public_key']['length']
else:
thisone.analysis['p22']['alg']=shk['key_algorithm']
fprint = { "port": 22, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p22 exception " + str(e) + " ip:" + thisone.ip
pass
try:
if thisone.writer=="FreshGrab.py":
tls=j_content['p25']['data']['tls']
cert=tls['server_certificates']['certificate']
else:
tls=j_content['p25']['smtp']['starttls']['tls']
cert=tls['certificate']
fp=cert['parsed']['subject_key_info']['fingerprint_sha256']
get_tls(thisone.writer,'p25',tls,j_content['ip'],thisone.analysis['p25'],scandate)
get_certnames('p25',cert,nameset)
fprint = { "port": 25, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p25 exception for:" + thisone.ip + ":" + str(e)
pass
try:
if thisone.writer=="FreshGrab.py":
cert=j_content['p110']['data']['tls']['server_certificates']['certificate']
fp=j_content['p110']['data']['tls']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
get_tls(thisone.writer,'p25',j_content['p110']['data']['tls'],j_content['ip'],thisone.analysis['p110'],scandate)
else:
fp=j_content['p110']['pop3']['starttls']['tls']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p110']['pop3']['starttls']['tls']['certificate']
get_tls(thisone.writer,'p25',j_content['p110']['pop3']['starttls']['tls'],j_content['ip'],thisone.analysis['p110'],scandate)
get_certnames('p110',cert,nameset)
fprint = { "port": 110, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p110 exception for:" + thisone.ip + ":" + str(e)
pass
try:
if thisone.writer=="FreshGrab.py":
cert=j_content['p143']['data']['tls']['server_certificates']['certificate']
fp=j_content['p143']['data']['tls']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
get_tls(thisone.writer,'p143',j_content['p143']['data']['tls'],j_content['ip'],thisone.analysis['p143'],scandate)
else:
cert=j_content['p143']['pop3']['starttls']['tls']['certificate']
fp=j_content['p143']['imap']['starttls']['tls']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
get_tls(thisone.writer,'p143',j_content['p143']['imap']['starttls']['tls'],j_content['ip'],thisone.analysis['p143'],scandate)
get_certnames('p143',cert,nameset)
fprint = { "port": 143, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p143 exception for:" + thisone.ip + ":" + str(e)
pass
try:
if thisone.writer=="FreshGrab.py":
fp=j_content['p443']['data']['http']['response']['request']['tls_handshake']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p443']['data']['http']['response']['request']['tls_handshake']['server_certificates']['certificate']
get_tls(thisone.writer,'p443',j_content['p443']['data']['http']['response']['request']['tls_handshake'],j_content['ip'],thisone.analysis['p443'],scandate)
else:
fp=j_content['p443']['https']['tls']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p443']['https']['tls']['certificate']
get_tls(thisone.writer,'p443',j_content['p443']['https']['tls'],j_content['ip'],thisone.analysis['p443'],scandate)
get_certnames('p443',cert,nameset)
fprint = { "port": 443, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p443 exception for:" + thisone.ip + ":" + str(e)
pass
try:
if thisone.writer=="FreshGrab.py":
fp=j_content['p587']['data']['tls']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p587']['data']['tls']['server_certificates']['certificate']
get_tls(thisone.writer,'p587',j_content['p587']['data']['tls'],j_content['ip'],thisone.analysis['p587'],scandate)
somekey=True
get_certnames('p587',cert,nameset)
fprint = { "port": 587, "fprint": fp }
thisone.fprints.append(fprint)
else:
# censys.io has no p587 for now
pass
except Exception as e:
#print >> sys.stderr, "p587 exception for:" + thisone.ip + ":" + str(e)
pass
try:
if thisone.writer=="FreshGrab.py":
fp=j_content['p993']['data']['tls']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p993']['data']['tls']['server_certificates']['certificate']
get_tls(thisone.writer,'p993',j_content['p993']['data']['tls'],j_content['ip'],thisone.analysis['p993'],scandate)
else:
fp=j_content['p993']['imaps']['tls']['tls']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']
cert=j_content['p993']['imaps']['tls']['tls']['certificate']['parsed']
get_tls(thisone.writer,'p993',j_content['p993']['imaps']['tls']['tls'],j_content['ip'],thisone.analysis['p993'],scandate)
get_certnames('p993',cert,nameset)
fprint = { "port": 993, "fprint": fp }
thisone.fprints.append(fprint)
somekey=True
except Exception as e:
#print >> sys.stderr, "p993 exception for:" + thisone.ip + ":" + str(e)
pass
besty=[]
nogood=True # assume none are good
tmp={}
# try verify names a bit
for k in nameset:
v=nameset[k]
#print "checking: " + k + " " + v
# see if we can verify the value as matching our give IP
if v != '' and not fqdn_bogon(v):
try:
rip=socket.gethostbyname(v)
if rip == thisone.ip:
besty.append(k)
else:
tmp[k+'-ip']=rip
# some name has an IP, even if not what we expect
nogood=False
except Exception as e:
#oddly, an NXDOMAIN seems to cause an exception, so these happen
#print >> sys.stderr, "Error making DNS query for " + v + " for ip:" + thisone.ip + " " + str(e)
pass
for k in tmp:
nameset[k]=tmp[k]
nameset['allbad']=nogood
nameset['besty']=besty
if not badrec and somekey:
goodcount += 1
# fingerprints.append(thisone)
# Add as nested doc
docid = record['_id']
docindex = record['_index']
data = { "doc": { "fingerprints": thisone } }
encodedData = jsonpickle.encode(data)
# print(encodedData)
# Update doc in ES with fprint data but don't reindex until next refresh
# printOneFP(thisone)
try:
# pass
# seenfps=[]
# fprecs=[]
# for fprint in thisone.fprints:
# if fprint['fprint'] in seenfps:
# i = seenfps.index(fprint['fprint'])
# port = fprint['port']
# fprecs[i][port] = 1
# else:
# fprec = newFprintRec()
# fprecs.append
fprecs={}
for fprint in thisone.fprints:
fp = fprint['fprint']
port = "p{}".format(fprint['port'])
if fp not in fprecs:
fprec = newFprintRec()
fprec['run_date']=args.scandatestring
fprec['fprint']=fp
fprec['ip']=thisone.ip
fprecs[fp] = fprec
fprecs[fp][port] = 1
# for fp in fprecs:
# print(fprecs[fp])
docs = toESDocs(fprecs, fp_index)
# for doc in docs:
# print(doc)
if UPDATE_ELASTICSEARCH:
es.update(index=docindex,
doc_type="document",
id=docid,
body=encodedData,
_source=False,
refresh="false")
bulk(es, docs)
except Exception as e:
timestampPrint("ERROR: {}".format(e))
else:
bads[badcount]=j_content
badcount += 1
overallcount += 1
# update average
ipend=time.time()
thistime=ipend-ipstart
peripaverage=((overallcount*peripaverage)+thistime)/(overallcount+1)
if overallcount % 5 == 0:
print >> sys.stderr, "Reading fingerprints and rdns, did: " + str(overallcount) + \
" most recent ip " + thisone.ip + \
" average time/ip: " + str(peripaverage) \
+ " last time: " + str(thistime)
del j_content
del thisone
if UPDATE_ELASTICSEARCH:
# Enable refresh again
es.indices.put_settings(index=index,
body={ "index.refresh_interval": "60s" })
timestampPrint("Enabling ES refresh")
gc.collect()
# # this gets crapped on each time (for now)
# keyf=open('fingerprints.json', 'w')
# bstr=jsonpickle.encode(fingerprints)
# #bstr=jsonpickle.encode(fingerprints,unpicklable=False)
# keyf.write(bstr)
# del bstr
# keyf.write("\n")
# keyf.close()
# this gets crapped on each time (for now)
# in this case, these are the hosts with no crypto anywhere (except
# maybe on p22)
badf=open('dodgy.json', 'w')
bstr=jsonpickle.encode(bads,unpicklable=False)
badf.write(bstr + '\n')
del bstr
badf.close()
del bads | [
"myersjo@tcd.ie"
] | myersjo@tcd.ie |
ef3f10ffb9fb82da880e30592f7c192f58c36a89 | 2fc65c833223d282bd9867729ad3ed054c0832c2 | /timetable/Section/router.py | 308f412c58640aa5d05ae79329afb640054f1a26 | [] | no_license | libbyandhelen/DB_timetable | 72b744ec332e5c1c3e242df1df6b4373493472ba | 17936821b7064bed2ebb51289e5a9b0e131929d1 | refs/heads/master | 2020-09-21T20:43:55.008545 | 2019-12-12T01:18:48 | 2019-12-12T01:18:48 | 224,921,739 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,304 | py | from Section.views import get_selected_sections_by_user, create_select_section, delete_select_section, \
create_select_section_by_section_id
from base.error import Error
from base.response import error_response
def router_selectsection(request):
"""
/api/usersections
GET: get_selected_sections_by_user
POST: create_select_section
"""
if request.method == "GET":
return get_selected_sections_by_user(request)
elif request.method == "POST":
return create_select_section_by_section_id(request)
# elif request.method == "POST":
# return create_select_section(request)
# elif request.method == "DELETE":
# return delete_section_by_category(request)
elif request.method == "DELETE":
return delete_select_section(request)
else:
return error_response(Error.ERROR_METHOD)
def router_selectsection_id(request, section_id):
"""
/api/usersections/:section_id
DELETE: delete_select_section
POST: create_select_section_by_section_id
"""
if request.method == "DELETE":
return delete_select_section(request, section_id)
elif request.method == "POST":
return create_select_section_by_section_id(request, section_id)
else:
return error_response(Error.ERROR_METHOD) | [
"libbyandhelen@163.com"
] | libbyandhelen@163.com |
65a5e8f29a0c78bacf860b606ec5e621f0688bcd | 2599d93919a1cfd9a030e862d10e40e52d287655 | /project_management_portal/models/.~c9_invoke_f9xkC7.py | 3892df0d6bfd9a2ae01d12345fdf22f8a22f7292 | [] | no_license | chandramoulidupam/my_projects | a6730c44ed2ba7a055d13415067b28ca74f0134b | 111d7753e2cf867d51681ed41a7ea917deb9aecd | refs/heads/master | 2023-09-02T03:38:59.753682 | 2020-06-01T06:20:48 | 2020-06-01T06:20:48 | 267,607,764 | 0 | 0 | null | 2021-11-15T17:51:30 | 2020-05-28T14:11:11 | Python | UTF-8 | Python | false | false | 1,504 | py | from django.contrib.auth.models import AbstractUser
from django.db import models
from project_management_portal.constants.enums import ProjectType
class User(AbstractUser):
name = models.CharField(max_length=50)
profile_pic = models.CharField(max_length=50)
is_admin = models.BooleanField(default=False)
def __str__(self):
return "%s %s" % (self.name, self.profile_pic)
class State(models.Model):
name = models.CharField(max_length=50)
class Transition(models.Model):
transition = models.CharField(max_length=50)
from_state = models.ManyToManyField(State,related_name="transitions")
to_state = models.ManyToManyField(State)
class WorkflowType(models.Model):
name = models.CharField(max_length=200)
states = models.ManyToManyField(State)
transitions = models.ManyToManyField(Transition)
created_at = models.DateTimeField(auto_now=True)
class Project(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
workflow_type = models.ForeignKey(WorkflowType, on_delete=models.CASCADE)
project_type_Choice = ProjectType.get_list_of_tuples()
choices=ProjectType.get_list_of_tuples()
)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator_of_project")
created_at = models.DateTimeField(auto_now=True)
# developers = models.ManyToManyField(User, related_name="developed_by")
def __str__(self):
return self.project_type
| [
"chandramoulidupam@gmail.com"
] | chandramoulidupam@gmail.com |
049c2446d87522af0e88d1b5c128a57f8d91ca95 | 2dde628fbadfe41efdca089239b601067b177270 | /ispectrum/colorpy_wrapper.py | 5b78f41dc8377f6682746de069a6d8054361f64a | [] | no_license | jlustigy/jakely | 7b2e88c39a5bb9b7a6f3c9e16350cdf2a722bbba | 7ddcef774baf98dfc912c379fa869b44e951b167 | refs/heads/master | 2021-06-29T03:06:04.702905 | 2019-11-18T20:49:27 | 2019-11-18T20:49:27 | 53,112,063 | 6 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,964 | py | from colorpy import colormodels, ciexyz
from ..plot import set_figure_colors
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import gridspec
import os
def irgb_string_from_spectrum(wl, spectrum):
"""
Calculates the irgb color given a wavelengh [nm] vs intensity [W/m*m/um]
spectrum in the visible.
"""
# Filter possible nans
ifin = np.isfinite(spectrum)
wl = wl[ifin]
spectrum = spectrum[ifin]
# Run through ColorPy
spec = np.vstack([wl, spectrum]).T
rgb_eye = colormodels.irgb_string_from_rgb (
colormodels.rgb_from_xyz (ciexyz.xyz_from_spectrum (spec)))
return rgb_eye
def make_color_swatch(**kwargs):
"""
Generates a little rectangular swatch of the color given. Note that this
function accepts only keyword arguments for the Rectangle object.
Ex:
swatch = make_color_swatch(color="orange")
"""
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle((0.0, 0.0), 1, 1, **kwargs)
ax.add_patch(rect)
plt.axis('off')
return fig
def plot_response(ax=None, wlmin=350, wlmax=750, **kwargs):
"""
Adds human eye response curves to an axis.
"""
relpath = "../colorvision/eye_response_functions/ciexyz31_1.csv"
fn = os.path.join(os.path.dirname(__file__), relpath)
data = np.genfromtxt(fn, delimiter=',')
wl = data[:,0]
mask = (wl >= wlmin) & (wl <= wlmax)
wl = wl[mask]
x = data[mask,1]
y = data[mask,2]
z = data[mask,3]
yscale = 1.0
# Create new axis if not specified, otherwise add twinx to current figure
if ax is None:
fig = plt.figure(figsize=(12,8))
gs = gridspec.GridSpec(1,1)
ax = plt.subplot(gs[0])
else:
ax = ax.twinx()
ax.set_ylim([0.0,10.0])
ax.axes.get_yaxis().set_visible(False)
# Plot response functions
ax.plot(wl,x, color='white', label=r'x', alpha=1, lw=2.0)
ax.plot(wl,y, color='white', label=r'y', alpha=1, lw=2.0)
ax.plot(wl,z, color='white', label=r'z', alpha=1, lw=2.0)
def rgb_from_wavelength(wl):
"""
Get rgb colors for each wavelength [nm]
"""
num_wl = len(wl)
rgb_colors = np.empty ((num_wl, 3))
for i in range (0, num_wl):
wl_nm = wl[i]
xyz = ciexyz.xyz_from_wavelength (wl_nm)
rgb_colors [i] = colormodels.rgb_from_xyz (xyz)
# scale to make brightest rgb value = 1.0
rgb_max = np.max (rgb_colors)
scaling = 1.0 / rgb_max
rgb_colors *= scaling
return rgb_colors
def plot_spectrum(wl, spectrum,
wlmin=350, wlmax=750,
stellar_spec=None,
show_cie=False,
xtitle="Wavelength [nm]",
ytitle="Intensity",
title="",
**kwargs):
"""
Plots intensity [W/m*m/um] vs wavelength [nm] across the visible, shading the
background above the curve the color the human eye would perceive, and the
entire visible spectrum below the curve. Returns Figure object for saving
and further artistry.
Parameters
----------
wl : array
Wavelength grid [nm]
spectrum : array
Intensity spectrum [W / m^2 / um]
wlmin : float
Minimum wavelength plotted [nm]
wlmax : float
Maximum wavelength plotted [nm]
show_cie : bool
Adds overplotted CIE eye sensitivity curves for reference
xtitle : str
x-axis label
ytitle : str
y-axis label
title : str
Plot title
Returns
-------
matplotlib.figure.Figure
"""
if np.min(wl) > wlmin: wlmin = np.min(wl)
if np.max(wl) < wlmax: wlmax = np.max(wl)
# Mask wl region
mask = (wl >= wlmin) & (wl <= wlmax)
wl = wl[mask]
spectrum = spectrum[mask]
# Filter possible nans
ifin = np.isfinite(spectrum)
wl = wl[ifin]
spectrum = spectrum[ifin]
# Read-in solar spectrum
if stellar_spec is None:
pass
elif stellar_spec == "Sun":
data = np.genfromtxt("spectra/earth_quadrature_radiance_refl.dat", skip_header=8)
wl_solar = data[:,0] * 1000.0 # Convert microns to nm
F_solar = data[:,2]
# Interpolate sun to CMF
F_solar = np.interp(wl, wl_solar, F_solar)
# Multiply Albedo and Flux
spectrum = spectrum * F_solar
else:
print("Given stellar_spec is not included.")
# Convert Flux to photon counts
umnm = 1e-3
hc = 1.986446e-25 # h*c (kg*m**3/s**2)
#spectrum = spectrum * umnm * wl / hc
# Plot spectrum
fig = plt.figure(figsize=(12,8))
gs = gridspec.GridSpec(1,1)
ax1 = plt.subplot(gs[0])
ax1.set_xlim([wlmin, wlmax])
num_wl = len(wl)
#
rgb_colors = rgb_from_wavelength(wl)
#
spec = np.vstack([wl, spectrum]).T
rgb_eye = colormodels.irgb_string_from_rgb (
colormodels.rgb_from_xyz (ciexyz.xyz_from_spectrum (spec)))
# draw color patches (thin vertical lines matching the spectrum curve) in color
for i in range (0, num_wl-1): # skipping the last one here to stay in range
x0 = wl [i]
x1 = wl [i+1]
y0 = spectrum [i]
y1 = spectrum [i+1]
poly_x = [x0, x1, x1, x0]
poly_y = [0.0, 0.0, y1, y0]
color_string = colormodels.irgb_string_from_rgb (rgb_colors[i])
ax1.fill (poly_x, poly_y, color_string, edgecolor=color_string)
# plot intensity as a curve
ax1.plot (
wl, spectrum,
color='k', linewidth=1.0, antialiased=True)
# plot CIE response curves
if show_cie:
plot_response(ax=ax1, wlmin=wlmin, wlmax=wlmax)
ax1.set_xlabel(xtitle)
ax1.set_ylabel(ytitle)
ax1.set_title(title)
ax1.set_xlim([wlmin, wlmax])
# Set plot background color to derived rgb color
#set_figure_colors(fig, foreground="white", background="black")
ax1.patch.set_facecolor(rgb_eye)
return fig
| [
"jlustigy@uw.edu"
] | jlustigy@uw.edu |
210da5e7fcf5b262b8e037957144252589cf0a1c | a632f63d1a99f73d4accd0d200b4780f7b923c4f | /proxy/proxy.py | 780fc24a1d4693ab9f7b9ebee1c6f5e774aa1065 | [] | no_license | jthemee/Hack-Python | b70502837e86b10df9e86aa3386a35e0e1980893 | 91d3d4b1c831a3c1a6da20126bb503e52cff2f45 | refs/heads/master | 2021-01-18T21:17:11.034902 | 2017-03-01T09:22:39 | 2017-03-01T09:22:39 | 39,102,234 | 5 | 8 | null | 2016-04-11T15:21:35 | 2015-07-14T21:51:59 | Python | UTF-8 | Python | false | false | 5,400 | py | import sys
import socket
import threading
# this is a pretty hex dumping function directly taken from
# http://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(src, length=16):
result = []
digits = 4 if isinstance(src, unicode) else 2
for i in xrange(0, len(src), length):
s = src[i:i+length]
hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
result.append( b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text) )
print b'\n'.join(result)
def receive_from(connection):
buffer = ""
# We set a 2 second time out depending on your
# target this may need to be adjusted
connection.settimeout(2)
try:
# keep reading into the buffer until there's no more data
# or we time out
while True:
data = connection.recv(4096)
if not data:
break
buffer += data
except:
pass
return buffer
# modify any requests destined for the remote host
def request_handler(buffer):
# perform packet modifications
return buffer
# modify any responses destined for the local host
def response_handler(buffer):
# perform packet modifications
return buffer
def proxy_handler(client_socket, remote_host, remote_port, receive_first):
# connect to the remote host
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((remote_host,remote_port))
# receive data from the remote end if necessary
if receive_first:
remote_buffer = receive_from(remote_socket)
hexdump(remote_buffer)
# send it to our response handler
remote_buffer = response_handler(remote_buffer)
# if we have data to send to our local client send it
if len(remote_buffer):
print "[<==] Sending %d bytes to localhost." % len(remote_buffer)
client_socket.send(remote_buffer)
# now let's loop and reading from local, send to remote, send to local
# rinse wash repeat
while True:
# read from local host
local_buffer = receive_from(client_socket)
if len(local_buffer):
print "[==>] Received %d bytes from localhost." % len(local_buffer)
hexdump(local_buffer)
# send it to our request handler
local_buffer = request_handler(local_buffer)
# send off the data to the remote host
remote_socket.send(local_buffer)
print "[==>] Sent to remote."
# receive back the response
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print "[<==] Received %d bytes from remote." % len(remote_buffer)
hexdump(remote_buffer)
# send to our response handler
remote_buffer = response_handler(remote_buffer)
# send the response to the local socket
client_socket.send(remote_buffer)
print "[<==] Sent to localhost."
# if no more data on either side close the connections
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print "[*] No more data. Closing connections."
break
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind((local_host,local_port))
except:
print "[!!] Failed to listen on %s:%d" % (local_host,local_port)
print "[!!] Check for other listening sockets or correct permissions."
sys.exit(0)
print "[*] Listening on %s:%d" % (local_host,local_port)
server.listen(5)
while True:
client_socket, addr = server.accept()
# print out the local connection information
print "[==>] Received incoming connection from %s:%d" % (addr[0],addr[1])
# start a thread to talk to the remote host
proxy_thread = threading.Thread(target=proxy_handler,args=(client_socket,remote_host,remote_port,receive_first))
proxy_thread.start()
def main():
# no fancy command line parsing here
if len(sys.argv[1:]) != 5:
print "Usage: ./proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]"
print "Example: ./proxy.py 127.0.0.1 9000 10.12.132.1 9000 True"
sys.exit(0)
# setup local listening parameters
local_host = sys.argv[1]
local_port = int(sys.argv[2])
# setup remote target
remote_host = sys.argv[3]
remote_port = int(sys.argv[4])
# this tells our proxy to connect and receive data
# before sending to the remote host
receive_first = sys.argv[5]
if "True" in receive_first:
receive_first = True
else:
receive_first = False
# now spin up our listening socket
server_loop(local_host,local_port,remote_host,remote_port,receive_first)
main() | [
"jthemee@gmail.com"
] | jthemee@gmail.com |
665871accf3e172f656e0fa932d30ff802625161 | d52aadf33f41edd66997f04d78c9f11e6aa9c22e | /tests/imfusion/build/indexers/conftest.py | 7fcf4fd36d915d28fa45852a842f0a28447b872c | [
"MIT"
] | permissive | sofiaff/imfusion | 3ec3404715e6c9fbca749a551a384f80217d8068 | 796c546802b40ae4aa34e60c6dd308ef4a3c80b1 | refs/heads/master | 2021-07-11T21:56:16.484192 | 2017-05-11T20:50:36 | 2017-05-11T20:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,508 | py | import pytest
from pathlib2 import Path
@pytest.fixture
def data_path():
"""Path to build test data directory."""
return Path(__file__).parent.parent
@pytest.fixture
def refseq_path(data_path):
"""Path to test reference sequence."""
return pytest.helpers.data_path('reference.fa', relative_to=data_path)
@pytest.fixture
def gtf_path(data_path):
"""Path to test reference gtf."""
return pytest.helpers.data_path('reference.gtf', relative_to=data_path)
@pytest.fixture
def transposon_path(data_path):
"""Path to test transposon sequence."""
return pytest.helpers.data_path('transposon.fa', relative_to=data_path)
@pytest.fixture
def features_path(data_path):
"""Path to test transposon features."""
return pytest.helpers.data_path('features.txt', relative_to=data_path)
@pytest.fixture
def build_kws(refseq_path, gtf_path, transposon_path, features_path, tmpdir):
"""Test kws for indexer.build."""
return {
'refseq_path': refseq_path,
'gtf_path': gtf_path,
'transposon_path': transposon_path,
'transposon_features_path': features_path,
'output_dir': Path(str(tmpdir / 'ref'))
}
@pytest.fixture
def cmdline_args():
"""Example command line args."""
return [
'--reference_seq', '/path/to/ref',
'--reference_gtf', '/path/to/gtf',
'--transposon_seq', '/path/to/tr',
'--transposon_features', '/path/to/feat',
'--output_dir', '/path/to/out'
] # yapf:disable
| [
"julianderuiter@gmail.com"
] | julianderuiter@gmail.com |
4fc695ac70d158a6cba3bae5ba199844e1cd2fc5 | 80dbb004883779f51733f5382040f940507e9180 | /youtube/urls.py | 5ade2eef4a72366cff05f9902e55dac1992d6caf | [] | no_license | Shayan-9248/youtube_search | 94824398f498022fb53aa5ca7f08ba6008f70396 | e07d9a2aa0dac0d76675db028c3584583151b31d | refs/heads/master | 2023-03-26T06:07:55.303627 | 2021-03-24T15:21:19 | 2021-03-24T15:21:19 | 350,349,734 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 131 | py | from django.urls import path
from . import views
app_name = 'youtube'
urlpatterns = [
path('', views.index, name='index'),
] | [
"shayan.aimoradii@gmail.com"
] | shayan.aimoradii@gmail.com |
2dc861a7f683325aeac69c4dacf18f63fa19f428 | 03f037d0f6371856ede958f0c9d02771d5402baf | /graphics/VTK-7.0.0/Examples/Infovis/Python/streaming_statistics_pyqt.py | 6f778bc6de891077741ee6e337ac42522a554388 | [
"BSD-3-Clause"
] | permissive | hlzz/dotfiles | b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb | 0591f71230c919c827ba569099eb3b75897e163e | refs/heads/master | 2021-01-10T10:06:31.018179 | 2016-09-27T08:13:18 | 2016-09-27T08:13:18 | 55,040,954 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,739 | py | #!/usr/bin/env python
from __future__ import print_function
from vtk import *
import os.path
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
if not os.path.exists(data_dir):
data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
if not os.path.exists(data_dir):
data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
sqlite_file = data_dir + "temperatures.db"
# I'm sure there's a better way then these global vars
currentRow = 0;
numberOfRows = 1;
done = False;
psuedoStreamingData = vtkProgrammableFilter()
def streamData():
global done
global currentRow
input = psuedoStreamingData.GetInput()
output = psuedoStreamingData.GetOutput()
# Copy just the columns names/types
output.GetRowData().CopyStructure(input.GetRowData())
# Loop through all the input data and grab the next bunch of rows
startRow = currentRow
endRow = startRow + numberOfRows
if (endRow >= input.GetNumberOfRows()):
endRow = input.GetNumberOfRows()
done = True;
print("streaming: ", startRow, "-", endRow)
for i in range(startRow, endRow):
output.InsertNextRow(input.GetRow(i))
currentRow = endRow;
psuedoStreamingData.SetExecuteMethod(streamData)
class Timer(QObject):
def __init__(self, parent=None):
super(Timer, self).__init__(parent)
# Setup the data streaming timer
self.timer = QTimer()
QObject.connect(self.timer, SIGNAL("timeout()"), self.update)
self.timer.start(100)
def update(self):
if (done):
quit();
psuedoStreamingData.Modified() # Is there a way to avoid this?
psuedoStreamingData.GetExecutive().Push()
printStats()
def printStats():
sStats = ss.GetOutputDataObject( 1 )
sPrimary = sStats.GetBlock( 0 )
sDerived = sStats.GetBlock( 1 )
sPrimary.Dump( 15 )
sDerived.Dump( 15 )
if __name__ == "__main__":
""" Main entry point of this python script """
# Set up streaming executive
streamingExec = vtkThreadedStreamingPipeline()
vtkAlgorithm.SetDefaultExecutivePrototype(streamingExec)
streamingExec.FastDelete()
vtkThreadedStreamingPipeline.SetAutoPropagatePush(True)
# Pull the table from the database
databaseToTable = vtkSQLDatabaseTableSource()
databaseToTable.SetURL("sqlite://" + sqlite_file)
databaseToTable.SetQuery("select * from main_tbl")
# Hook up the database to the streaming data filter
psuedoStreamingData.SetInputConnection(databaseToTable.GetOutputPort())
# Calculate offline(non-streaming) descriptive statistics
print("# Calculate offline descriptive statistics:")
ds = vtkDescriptiveStatistics()
ds.SetInputConnection(databaseToTable.GetOutputPort())
ds.AddColumn("Temp1")
ds.AddColumn("Temp2")
ds.Update()
dStats = ds.GetOutputDataObject( 1 )
dPrimary = dStats.GetBlock( 0 )
dDerived = dStats.GetBlock( 1 )
dPrimary.Dump( 15 )
dDerived.Dump( 15 )
# Stats filter to place 'into' the streaming filter
inter = vtkDescriptiveStatistics()
inter.AddColumn("Temp1")
inter.AddColumn("Temp2")
# Calculate online(streaming) descriptive statistics
print("# Calculate online descriptive statistics:")
ss = vtkStreamingStatistics()
ss.SetStatisticsAlgorithm(inter)
ss.SetInputConnection(psuedoStreamingData.GetOutputPort())
# Spin up the timer
app = QApplication(sys.argv)
stream = Timer()
sys.exit(app.exec_())
| [
"shentianweipku@gmail.com"
] | shentianweipku@gmail.com |
9cb36d473a25803272db513f6a0b7e03992d2d38 | 77bed681e9d4327c13e716694b7f3d2fb4009364 | /app/main/__init__.py | 4bf1ffb337d157d241fd5a6b1b6d366d07fdf200 | [] | no_license | nemanja-curcic-dev/online-training-app | 5a30762563485192ec0eae620a90296931215e01 | eb57d9f1acd3b1a16071f23c7400576e14819a2f | refs/heads/master | 2021-10-25T22:57:52.070601 | 2019-04-08T04:02:53 | 2019-04-08T04:02:53 | 105,525,777 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 115 | py | from flask.blueprints import Blueprint
main_blueprint = Blueprint('main_blueprint', __name__)
from . import views | [
"curesr@gmail.com"
] | curesr@gmail.com |
bdaba5660d252a2a76b44267cb85a97ce59aabbf | 081a3c5be292bea814e68ac7072915b22a0a1ebd | /webgl/settings.py | 28476e807deeb5cc480a1a06d19958f055e3159f | [] | no_license | abinabraham/shipweb | 9cb233a8591af70f817852adf5e20f950e6c8040 | f5d376d96292eacab502023ffa1d8197bc506c94 | refs/heads/master | 2021-01-21T22:48:26.272415 | 2017-09-02T05:02:33 | 2017-09-02T05:02:33 | 102,173,801 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,281 | py | """
Django settings for webgl project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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__)))
SUPER_DIR = os.path.abspath(os.path.join(BASE_DIR, os.path.pardir))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6car^j+e#deyel98emo=hp&c#)znd+rr#x_m=@xwj!ko1ou(n&'
# 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',
]
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 = 'webgl.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'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 = 'webgl.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(SUPER_DIR,"static")
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
| [
"abinabrahamcs@gmail.com"
] | abinabrahamcs@gmail.com |
96e010cc6ade90717181601cda9a36024ee05906 | 3c10511acadf8c651c433d6fd03ced9498d5d479 | /21/21.py | c310af95b8a2884d9ade42dad5ff82625e6456aa | [] | no_license | DarkC35/AdventOfCode2020 | d75707c918cd6cf551cbcee2c3b607da2f27c1a6 | 2b0079694917e367b9e8f5271fb5973bb55175a3 | refs/heads/master | 2023-01-23T22:42:08.664703 | 2020-12-12T18:03:17 | 2020-12-12T18:03:17 | 318,242,093 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,771 | py | from timeit import default_timer as timer
def next_board(board):
new_board = [row[:] for row in board]
for row in range(0, len(board)):
for col in range(0, len(board[0])):
if board[row][col] == "L" and count_adjacent_seats(board, row, col) == 0:
new_board[row][col] = "#"
elif board[row][col] == "#" and count_adjacent_seats(board, row, col) >= 4:
new_board[row][col] = "L"
return new_board
def count_adjacent_seats(board, row, col):
count = 0
for x in range(-1, 2):
for y in range(-1, 2):
if not (x == 0 and y == 0) and check_if_occupied(board, row+x, col+y):
count += 1
return count
def check_if_occupied(board, row, col):
if row not in range(0, len(board)):
return False
elif col not in range(0, len(board[0])):
return False
else:
return board[row][col] == "#"
def print_board(board):
for row in board:
for col in row:
print(col, end='')
print()
print()
def count_occupied_seats(board):
count = 0
for row in board:
for col in row:
if col == "#":
count += 1
return count
def check_if_same(board, prev_board):
for row in range(0, len(board)):
if board[row] != prev_board[row]:
return False
return True
start = timer()
board = []
with open("input.txt") as file:
for x in file:
board.append(list(x.strip()))
prev_board = None
while not prev_board or not check_if_same(board, prev_board):
prev_board = [row[:] for row in board]
board = next_board(board)
result = count_occupied_seats(board)
end = timer()
print("Result: ", result)
print("Time (in sec): ", end-start)
| [
"khaunschmied.mmt-m2019@fh-salzburg.ac.at"
] | khaunschmied.mmt-m2019@fh-salzburg.ac.at |
64f97ce5baf232b01e2d738eb174d09a69cc3bcc | 78b3d574423e2b76ab9ca5511cabbccd3a5c4def | /app/tests/a.py | 1ece0d068be8e0f20e4ff5f174b992cb288ff0ba | [] | no_license | zhangmengdream/fisher | 697872bf227f83e33e96242e682a96ef34bb8119 | 7120eb76c959f0b1cd4fb2893531b9f4d954d467 | refs/heads/master | 2022-12-13T17:06:51.794679 | 2019-12-02T08:22:25 | 2019-12-02T08:22:25 | 225,308,479 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 220 | py | # from contextlib import contextmanager
#
# # contextmanager 装饰器
#
#
# def mank_myresource():
# pass
#
#
#
#
kwargs = {1:'a',2:'b',3:'c'}
clauses = [key == value for key, value in kwargs.items()]
print(clauses) | [
"m18715529161@163.com"
] | m18715529161@163.com |
2f217ccdcd79a8d5bb7e6c3d2f7d2ab5c1838d56 | 742f15ee3880306a946df7efee0020e42684b109 | /out/string/python-flask/openapi_server/models/variable_collection.py | 9cfe8be729a4ce32a9dd09c941f50f540d31840e | [] | no_license | potiuk/airflow-api-clients | d0196f80caf6e6f4ecfa6b7c9657f241218168ad | 325ba127f1e9aa808091916d348102844e0aa6c5 | refs/heads/master | 2022-09-14T00:40:28.592508 | 2020-05-31T10:05:42 | 2020-05-31T10:15:55 | 268,128,082 | 0 | 0 | null | 2020-05-30T17:28:04 | 2020-05-30T17:28:03 | null | UTF-8 | Python | false | false | 1,941 | py | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server.models.variable_collection_item import VariableCollectionItem
from openapi_server import util
from openapi_server.models.variable_collection_item import VariableCollectionItem # noqa: E501
class VariableCollection(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(self, variables=None): # noqa: E501
"""VariableCollection - a model defined in OpenAPI
:param variables: The variables of this VariableCollection. # noqa: E501
:type variables: List[VariableCollectionItem]
"""
self.openapi_types = {
'variables': List[VariableCollectionItem]
}
self.attribute_map = {
'variables': 'variables'
}
self._variables = variables
@classmethod
def from_dict(cls, dikt) -> 'VariableCollection':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The VariableCollection of this VariableCollection. # noqa: E501
:rtype: VariableCollection
"""
return util.deserialize_model(dikt, cls)
@property
def variables(self):
"""Gets the variables of this VariableCollection.
:return: The variables of this VariableCollection.
:rtype: List[VariableCollectionItem]
"""
return self._variables
@variables.setter
def variables(self, variables):
"""Sets the variables of this VariableCollection.
:param variables: The variables of this VariableCollection.
:type variables: List[VariableCollectionItem]
"""
self._variables = variables
| [
"kamil.bregula@polidea.com"
] | kamil.bregula@polidea.com |
23f42d702d1da5df927ca90ae08f9306f8083b65 | 8206a8bb162f9ffbe36b87d28bb4bc974de68f48 | /format_print.py | bceca69abb7209f6f0ce7802c3d41c932f6f8ebd | [] | no_license | KaimingWan/Python_Learning | 61e0f260f0061946610198fcf0187d5b7b882078 | 144757d16d92ab76f8a5b64e07beebc4305a454c | refs/heads/master | 2021-01-17T03:50:15.109625 | 2016-01-12T10:46:37 | 2016-01-12T10:46:37 | 39,371,332 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,196 | py | #使用str.format()函数
#使用'{}'占位符
print('I\'m {},{}'.format('Hongten','Welcome to my space!'))
print('#' * 40)
#也可以使用'{0}','{1}'形式的占位符
print('{0},I\'m {1},my E-mail is {2}'.format('Hello','Hongten','hongtenzone@foxmail.com'))
#可以改变占位符的位置
print('{1},I\'m {0},my E-mail is {2}'.format('Hongten','Hello','hongtenzone@foxmail.com'))
print('#' * 40)
#使用'{name}'形式的占位符
print('Hi,{name},{message}'.format(name = 'Tom',message = 'How old are you?'))
print('#' * 40)
#混合使用'{0}','{name}'形式
print('{0},I\'m {1},{message}'.format('Hello','Hongten',message = 'This is a test message!'))
print('#' * 40)
#下面进行格式控制
import math
print('The value of PI is approximately {}.'.format(math.pi))
print('The value of PI is approximately {!r}.'.format(math.pi))
print('The value of PI is approximately {0:.3f}.'.format(math.pi))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print('{0:10} ==> {1:10d}'.format(name, phone))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table)) | [
"344277934@qq.com"
] | 344277934@qq.com |
bc8a787cb384083441ada6219c740bc2df9db940 | aa91abd10252adb014bf031d1d568b5d83872057 | /BCI_framework/library/src/data_analysis/models.py | b67d7a659815c3d89647ecbf7cf3906f1770ca76 | [] | no_license | Alexander-Jing/code_for_UIST | 6a3b288de6c59308727e00cebb39afdb5950517f | dec31229f43149dd2c9d4be2115c6ead7c8a68b3 | refs/heads/main | 2023-05-28T08:29:24.198911 | 2021-06-09T16:40:40 | 2021-06-09T16:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,320 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class LogisticRegression(nn.Module):
def __init__(self, input_dim, num_classes):
super(LogisticRegression, self).__init__()
self.linear = torch.nn.Linear(input_dim, num_classes)
def forward(self, x):
outputs = self.linear(x)
return outputs
class BiRNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes, num_directions = 1, device = 'cpu'):
super(BiRNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.num_classes = num_classes
self.num_directions = num_directions #June17 added
self.device = device
if num_directions == 1:
bidirectional_flag = False
elif num_directions == 2:
bidirectional_flag = True
self.lstm = nn.LSTM(input_size, hidden_size, num_layers,
batch_first=True, bidirectional=bidirectional_flag)
self.dropout1 = nn.Dropout(p=0.2) #inplace: dafualt False
self.fc = nn.Linear(self.hidden_size*self.num_directions, self.num_classes)
def forward(self, x):
out, _ = self.lstm(x)
out = torch.sum(out, dim=1)
out = self.dropout1(out)
# output layer
out = F.log_softmax(self.fc(out), dim=1)
return out
class SimpleRNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes, num_directions = 1, device = 'cpu'):
super(SimpleRNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.num_classes = num_classes
self.num_directions = num_directions #June17 added
self.device = device
if num_directions == 1:
bidirectional_flag = False
elif num_directions == 2:
bidirectional_flag = True
self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True, bidirectional = bidirectional_flag)
self.dropout1 = nn.Dropout(p=0.2) #inplace: dafualt False
self.fc = nn.Linear(self.hidden_size*self.num_directions, self.num_classes)
def forward(self, x):
out, _ = self.rnn(x)
out = torch.sum(out, dim=1)
out = self.dropout1(out)
out = F.log_softmax(self.fc(out), dim=1)
return out
class CNN(nn.Module):
def __init__(self, input_size, conv1d_hidden_size, window_size, window_stride, linear_hidden_size, num_classes):
super(CNN, self).__init__()
self.conv1d_hidden_size = conv1d_hidden_size #hidden_size is the num out_channel for Conv1d
self.input_size = input_size #input_size is the feature size at each time step
self.window_size = window_size #window_size is the kernel size of Conv1d
self.window_stride = window_stride #window_stride is the stride for Conv1d
self.linear_hidden_size = linear_hidden_size
self.num_classes = num_classes
self.conv1d = nn.Conv1d(in_channels = input_size, out_channels = conv1d_hidden_size, kernel_size = window_size, stride = window_stride, padding = 0, padding_mode = 'zeros', dilation = 1, groups = 1, bias = True)
#Default: padding=0, padding_mode='zeros', dilation=1, groups=1, bias=True
self.fc1 = nn.Linear(in_features = conv1d_hidden_size, out_features = linear_hidden_size, bias = True)
self.fc2 = nn.Linear(in_features = linear_hidden_size, out_features = num_classes, bias = True)
self.dropout = nn.Dropout(p=0.2, inplace=False)
def forward(self, x):
conv1d_out = self.conv1d(x.transpose(1,2)) #pytorch conv1d slide from left to right instead of top to down in tf
conv1d_out = torch.sum(conv1d_out, dim = -1)
fc1_out = self.fc1(conv1d_out)
fc1_out = F.relu(fc1_out)
fc1_out = self.dropout(fc1_out)
fc2_out = self.fc2(fc1_out)
logits = F.log_softmax(fc2_out, dim = 1)
return logits
| [
"lwang89@usfca.edu"
] | lwang89@usfca.edu |
29437d33920a0e4eafe897c90482d47aaf488dff | 8e6fff60ed05128beb208e9e529762061cf4aee3 | /GUIapp/tkraise.py | 06d799f633b9880c913f9eb3eb6af8ec46332e76 | [] | no_license | syu-kwsk/python-study | df7f3a9da766bbd675212810b8ddc154bd1fe5f5 | b822820d4b37f58d886afc450f9384f6f69f871f | refs/heads/master | 2020-05-19T11:18:46.137637 | 2019-06-27T13:29:12 | 2019-06-27T13:29:12 | 184,988,355 | 0 | 0 | null | 2019-06-27T16:36:33 | 2019-05-05T06:20:57 | Python | UTF-8 | Python | false | false | 711 | py | from tkinter import *
root = Tk()
def changepage(frame):
frame.tkraise()
root.title("try tkraise()")
root.geometry("1000x600")
top = Frame(root)
label1 = Label(top, text="this is top")
button1 = Button(top, text="change page", command=lambda : changepage(game))
exit1 = Button(top, text="exit", command=lambda: root.quit())
label1.grid()
button1.grid()
exit1.grid()
top.grid(row=0, column=0)
game = Frame(root)
label2 = Label(game, text="this is game")
button2 = Button(game, text="change page", command=lambda : changepage(top))
exit1 = Button(game, text="exit", command=lambda: root.quit())
label2.grid()
button2.grid()
exit1.grid()
game.grid(row=0, column=0)
top.tkraise()
root.mainloop()
| [
"kawasaki.wataru688@mail.kyutech.jp"
] | kawasaki.wataru688@mail.kyutech.jp |
af9e7f873e6f854ab8cec919c976476e7281f61f | e7fb13ed9d22141ed880215911fac2b1342889d4 | /python基础知识/面试题.py | 259e19321040fd1074d075eb1201fa7a1e443b3f | [] | no_license | chenhongwen16/python | 87ca44e20fc40eef836891aed7471a948c21c5ca | dc67e961068ec2895643a4ac4cf5d4066aefa92e | refs/heads/master | 2020-03-24T05:09:56.468989 | 2018-07-28T09:53:57 | 2018-07-28T09:53:57 | 142,477,026 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,643 | py | '''
5.CPython,在命令行下运行Python,就是启动CPython解释器
IPython,IPython是基于CPython之上的一个交互式解释器,也就是说,IPython只是在交互方式上有所增强,但是执行Python代码的功能和CPyhton是完全一样的
PyPy,PyPy是另一个Python解释器,它的目标是执行速度,PyPy采用JIT技术,对Python代码进行动态编译,所以可以显著提高Python代码的执行速度。
Jython,Jython是运行在Java平台上的Python解释器,可以直接把Python代码编译成Java字节码执行。
IronPython,IronPython和Jython类似,只不过IronPython是运行在微软.Net平台上的Python解释器,可以直接把Python代码编译成.Net的字节码。
6.8位等于一字节
7.1 B = 8b (8个bit/ 位) 一个字节(byte)等于8位(bit)
1 kB = 1024 B (kB - kilobajt)
1 MB = 1024 kB (MB - megabajt)
1 GB = 1024 MB (GB - gigabajt)
8.一 代码编排
1 缩进。4个空格的缩进(编辑器都可以完成此功能),不使用Tap,更不能混合使用Tap和空格。
2 每行最大长度79,换行可以使用反斜杠,最好使用圆括号。换行点要在操作符的后边敲回车。
3 类和top-level函数定义之间空两行;类中的方法定义之间空一行;函数内逻辑无关段落之间空一行;其他地方尽量不要再空行。
二 文档编排
1 模块内容的顺序:模块说明和docstring—import—globals&constants—其他定义。其中import部分,又按标准、三方和自己编写顺序依次排放,之间空一行。
2 不要在一句import中多个库,比如import os, sys不推荐。
3 如果采用from XX import XX引用库,可以省略‘module.’,都是可能出现命名冲突,这时就要采用import XX。
三 空格的使用
总体原则,避免不必要的空格。
1 各种右括号前不要加空格。
2 逗号、冒号、分号前不要加空格。
3 函数的左括号前不要加空格。如Func(1)。
4 序列的左括号前不要加空格。如list[2]。
5 操作符左右各加一个空格,不要为了对齐增加空格。
6 函数默认参数使用的赋值符左右省略空格。
7 不要将多句语句写在同一行,尽管使用‘;’允许
9.
10.
11.999
def f(n):
n += 1
f(n)
if __name__ == '__main__':
f(1)
12.
13.
14.机器码(machine code),学名机器语言指令,有时也被称为原生码(Native Code),是电脑的CPU可直接解读的数据。
字节码(Bytecode)是一种包含执行程序、由一序列 op 代码/数据对 组成的二进制文件。字节码是一种中间码,它比机器码更抽象,需要直译器转译后才
能成为机器码的中间代码。
15.c= a if a>1 else b
16.Python3中print为一个函数,必须用括号括起来;Python2中print为class
Python3中input得到的为str;Python2的input的到的为int型,Python2的raw_input得到的为str类型
Python3中/表示真除,%表示取余,//结果取整;Python2中带上小数点/表示真除,%表示取余,//结果取整
17.a,b = b,a
18
19.xrange 用法与 range 完全相同,所不同的是生成的不是一个list对象,而是一个生成器。
20.xreadlines返回一个生成器,来循环操作文件的每一行。
21.‘’ False 0 [] () {}
22.str: split() strip() isalpha() join() count() upper() replace()
list:append() index() pop() reverse() remove() count()
dict:get() items() update() clear()
https://www.cnblogs.com/nianlei/p/5642315.html
23.lambda x : x+x 配合map reduce filter使用
24.语义完整性
25.*args:可以理解为只有一列的表格,长度不固定。
def sum(*args):
count = 0
for i in args:
count += i
print(count)
sum(1,2,3)
**kwargs:可以理解为字典,长度也不固定。
def fun(**kwargs):
for key in kwargs:
print("person's info: %s %s"%(key,kwargs[key]))
fun(chw='27',zch='23')
26.is对比的是数据地址,==比较的是value
27.
28.
29.可变类型: 字典、列表
不可变类型: 字符串、元祖、数字
30. {'k2': [666], 'k1': [666]}
False
{'k2': [666], 'k1': 777}
31.[6,6,6,6]作用域 好好看下
32.
33.def f(x,y):
return x+y
print(reduce(f,[1,2,3,4]))
from functools import reduce
print(reduce(lambda x,y:x+y,[1,2,3,4]))
print(list(map(lambda n:n*2,range(10))))
print(list(filter(lambda x:x>2,range(10))))
34.print('\n'.join(['\t'.join(["%2s*%2s=%2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
35.
36.re.os.time.math.random.sys.Django.pip.pygame.pyMysql.numpy
37.print(re.match('super','superstition').span())
# print(re.match('super','insuperable').span())
print(re.search('super','superstition').span())
print(re.search('super','insuperable').span())
(0,5)
报错
(0,5)
(2,7)
38.String str="abcaxc";
Patter p="ab*c";
贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str,结果就是匹配到:abcaxc(ab*c)。
非贪婪匹配:就是匹配到结果就好,就少的匹配字符。如上面使用模式p匹配字符串str,结果就是匹配到:abc(ab*c)。
39.[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
40.
41.
42.split(',')
43.
44.
45.print(list(map(lambda x:x*x,range(1,11))))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
46.先set在list
47.global
48.logging模块的作用?以及应用场景
49.class Stack(object):
# 初始化栈为空列表
def __init__(self):
self.items = []
# 判断栈是否为空,返回布尔值
def is_empty(self):
return self.items == []
# 返回栈顶元素
def peek(self):
return self.items[len(self.items) - 1]
# 返回栈的大小
def size(self):
return len(self.items)
# 把新的元素堆进栈里面(程序员喜欢把这个过程叫做压栈,入栈,进栈……)
def push(self, item):
self.items.append(item)
# 把栈顶元素丢出去(程序员喜欢把这个过程叫做出栈……)
def pop(self, item):
return self.items.pop()
50.
51.
52.def search(list,target):
high = len(list) - 1
low = 0
while low <= high:
mid = (high + low) // 2
if list[mid] == target:
return mid
elif list[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1
ret = search(list(range(1,1000)),0)
print(ret)
53.
''' | [
"309861722@qq.com"
] | 309861722@qq.com |
bde2d17546e4aff0de68b15ffb0c5f017dea7c68 | e6dab5aa1754ff13755a1f74a28a201681ab7e1c | /.parts/lib/django-1.3/django/conf/locale/zh_CN/formats.py | 00fa8f4a3fd541170626603a495a7c857d6c9a15 | [] | 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 | 101 | py | /home/action/.parts/packages/googleappengine/1.9.4/lib/django-1.3/django/conf/locale/zh_CN/formats.py | [
"ron.y.kagan@gmail.com"
] | ron.y.kagan@gmail.com |
03f14698166026a44a40de67f3f7eae6f6997195 | 380bd0b36a7735fc04ae51e8cf5a94ccfe909b94 | /data_consol/parse_reviews_xml.py | 4fb48b96f9589a1f53ebd48c06a807f9d23ffbbc | [] | no_license | hwright-ucsb/293s-HolyGrail | 17ff389a929f9b3474a01d59d32d233d7bea36dc | c527d5ce947762c8a6e16cc898193f86a802a51f | refs/heads/master | 2021-01-19T21:16:00.565232 | 2017-03-21T22:07:47 | 2017-03-21T22:07:47 | 82,478,665 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,549 | py | import json, re
def removeUnicode(s):
#a mismatch of unicode in hex and usyntax
noUni = s.encode('utf-8')\
.replace("\\x92", "'")\
.replace("\\", '')\
.replace("\xe2\x80\x99", "'")\
.replace("\xc2\xa0", ' ')\
.replace("x93", '"')\
.replace("x94", '"')\
.replace("u2019", "'")\
.replace("u201c", '"')\
.replace("u201d", '"')\
.replace("u2028", "\n")
#for things like that's or she'll
noUni = re.sub(r'([^ ])\?([^ ])', r"\1'\2", noUni)
#for things in quotes like ?Oriental Thai blah..?
noUni = re.sub(r'[ ]\?(.*?)\?[ ]', r' "\1" ', noUni)
#I'm too lazy to figure out which desc thats from but
#I'll assume its supposed to be a ' char
noUni = re.sub('Sage N? Sour OG', "Sage N' Sour OG", noUni)
noUni = noUni.replace("<", "").replace(">", "").replace("&", "and")
return noUni
def writeToFile(raw_data):
global cnt
#for strain_name, reviews in raw_data.iteritems():
reviews=raw_data
for i in range(0, len(reviews)):
strain_name = reviews[i]["strain"]
strain_name = strain_name.replace("-"," ")
if strain_name in strains:
cnt = cnt+1
outfile.write('<doc>\n')
outfile.write('\t<field name="REVIEWID">')
outfile.write(reviews[i]['ID'])
outfile.write('</field>\n')
outfile.write('\t<field name="STRAIN">')
outfile.write(strain_name)
outfile.write('</field>\n')
outfile.write('\t<field name="SOURCE">')
outfile.write("LEAFLY")
outfile.write('</field>\n')
outfile.write('\t<field name="BODY">')
outfile.write(removeUnicode(reviews[i]['content']))
outfile.write('</field>\n')
outfile.write('\t<field name="STARS">')
outfile.write(reviews[i]['stars'])
outfile.write('</field>\n')
outfile.write('\t<field name="DATE">')
outfile.write(str(reviews[i]['date']))
outfile.write('</field>\n')
outfile.write('\t<field name="USER">')
outfile.write(removeUnicode(reviews[i]['user']))
outfile.write('</field>\n')
outfile.write('\t<field name="attributes">')
temp = ""
for attr in reviews[i]['attributes']:
temp = temp +" "+ str(attr)
outfile.write(temp)
outfile.write('</field>\n')
outfile.write('</doc>\n')
raw_data = {}
cnt = 0
strains = set()
outfile = open("reviews_solr-fixed.xml", "w")
strainfile = "unique_strains.txt"
f = open(strainfile,"r")
for strain in f:
strains.add(strain.strip())
outfile.write('<add>\n')
s = "json/leafly-reviews-"
for i in range(0, 14):
t = s + str(i+1) + ".json"
writeToFile(json.load(open(t)))
print("wrote " + t)
outfile.write('</add>')
outfile.close()
print("wrote "+ str(cnt)+" reviews")
| [
"wright@umail.ucsb.edu"
] | wright@umail.ucsb.edu |
a13b993cdc1c27518a585c900f9a698d84ad827c | 9f8779f415719cd77bb119cbfc5ff88d2402d8c0 | /mysite/settings.py | 9c27c4027160161ee262e1d9087d9485123f27ec | [] | no_license | Eluska/djangogirls-workshop | ed433b4bd0fe7fd72c381e2a674737eb2094b97a | 9473535d93f0d273e3274df7ed8126871ff4778e | refs/heads/master | 2021-05-10T21:50:58.283612 | 2018-01-20T16:52:11 | 2018-01-20T16:52:11 | 118,241,114 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,203 | py | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=mkx1l2jc2zth803nwtct(lz)960uooincdvwdow*2b+o7)ish'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
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 = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Bratislava'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
| [
"elena.suranova@seiteq.com"
] | elena.suranova@seiteq.com |
a61b37b10118e7ae82be6f1101c3b31bb4ae21ff | 6bedc9b6041525679bb3605df94c7e7d726ab220 | /priv/jun_seaborn.py | de2a3f8ca0303d316f0f94d175a961b11d5d4e25 | [
"MIT"
] | permissive | zgbjgg/jun | ff2f189763c541eec9db208e45128ff3db22dcb5 | 8a877d4a9c56efb6c9a2e13d25109e9da8dde5de | refs/heads/master | 2021-06-21T22:05:30.692476 | 2020-10-01T03:51:08 | 2020-10-01T03:51:08 | 97,057,283 | 24 | 5 | MIT | 2020-10-01T03:51:09 | 2017-07-12T22:32:04 | Erlang | UTF-8 | Python | false | false | 1,387 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import scipy as sp
import numpy as np
import matplotlib as mpl
import pandas as pd
import sklearn as skl
mpl.use('Agg')
import seaborn as sns
# common helper for dataframe plot using seaborn,
# trying to return a file instead a raw opaque item
def jun_dataframe_plot(df, fn, save='None', keywords=[]):
if ( isinstance(df, pd.core.frame.DataFrame) ):
# clean before any plot
mpl.pyplot.figure()
# make dict from keywords even if empty!
kwargs = dict(keywords)
# get the fun from seaborn directly since we want a dynamic call
fun = getattr(sns, fn)
plot = fun(**kwargs)
if ( plot.__class__.__name__ == 'AxesSubplot' ):
plot_class = 'matplotlib.AxesSubplot'
else:
plot_class = 'seaborn.axisgrid.*'
if save != 'None':
# if figure comes from seaborn use fig, otherwise get_figure
if ( plot_class == 'matplotlib.AxesSubplot' ):
fig = plot.get_figure()
else:
fig = plot.fig
fig.savefig(save, bbox_inches='tight') # save contains path
return plot_class
else:
return (plot_class, plot) # this is correct? because can be confusing with opaque df
else:
return 'error_format_data_frame_invalid'
| [
"zgbjgg@gmail.com"
] | zgbjgg@gmail.com |
a813132444070bf970045b1deee760663a10e810 | 6a0b53a3845bb97e76e9f7cd508d78b600654b95 | /gps.py | 9ea62f840b943d4d917b89ea2eb36a998a3b83e9 | [] | no_license | KTTS18/Hardware_code_TAN | b71199d6553b940b97679f63e51bd9144e087975 | 271f9cf3a067d27bd882bb42c096527bb426f691 | refs/heads/master | 2023-04-16T16:01:28.488859 | 2021-05-04T11:15:58 | 2021-05-04T11:15:58 | 362,198,777 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 994 | py | import serial
import time
import string
import pynmea2
import datetime
import pymongo
MONGO_DETAILS = 'mongodb+srv://TANdb:Tan180704@cluster0.vw9z5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGO_DETAILS)
db = client.myFirstDatabase
try :
while True:
port = "/dev/ttyAMA0"
ser = serial.Serial(port, baudrate=9600, timeout=0.5)
dataout = pynmea2.NMEAStreamReader()
newdata = ser.readline()
if newdata[0:6] == "$GPRMC":
newmsg = pynmea2.parse(newdata)
lat = newmsg.latitude
lng = newmsg.longitude
gps = "Lat = ",float(lat),"and Long = ",float(lng)
print(gps)
now = datetime.datetime.now()
print(now.strftime("Day: %d/%m/%y Time: %H:%M:%S"))
data = {
"lat": float(lat),
"long": float(lng),
"date": now.strftime("Day: %d/%m/%y Time: %H:%M:%S"),
"blind": "61515017"
}
db.location.insert(data)
time.sleep(29)
except KeyboardInterrupt :
print("Force quit..") | [
"Tuksina.007@gmail.com"
] | Tuksina.007@gmail.com |
b37cfcddd38791a19341f6848a7830f447197564 | 09d324aee2522611fc474762d97b734367fa6faa | /kick_start/right.py | 824fb0419f6a0088225d686904f9e85b5699a921 | [] | no_license | garyCC227/python_practice | 96c50d2dc92588793382e71bc81f0f9da15853ec | d1753e2243bd84179ef2e1fefe0ca0b2259c4281 | refs/heads/master | 2022-12-08T22:46:59.622857 | 2019-09-05T08:14:48 | 2019-09-05T08:14:48 | 172,495,990 | 0 | 1 | null | 2022-12-08T06:07:20 | 2019-02-25T11:47:50 | Jupyter Notebook | UTF-8 | Python | false | false | 944 | py | import re
t = int(input())
def has_odd(t):
for i in range(1, t+1):
num = int(input())
if is_existed(num) == False:
print ("Case #{}: {}".format(i, 0))
else:
plus_couter = 0
minus_couter = 0
plus_num = num
minus_num = num
while True:
plus_couter +=1
minus_couter +=1
plus_num+=1
minus_num-=1
if is_existed(plus_num) == False:
break
elif is_existed(minus_num) == False:
break
if plus_num < minus_num:
print("Case #{}: {}".format(i, plus_couter))
else:
print("Case #{}: {}".format(i, minus_couter))
def is_existed(num):
odd = ['1','3','5','7','9']
for e in odd:
if e in str(num):
return True
return False
has_odd(t)
| [
"z5163479@ad.unsw.edu.au"
] | z5163479@ad.unsw.edu.au |
f3bcde6ae30cfb731230794841388499d4d42f42 | 4403600c57fd170aad6bb505e4f14c4b70e63356 | /sensor.py | 3d90ccfcb357c6b8161da75db9832f89fceda02f | [] | no_license | moonclearner/sensor | de4ef554cbc3dadb5fe5e801c55627d9f9340d19 | 0c3ad14375267b135940e8254262b0d054bd472c | refs/heads/master | 2021-01-12T05:11:52.667742 | 2017-01-03T06:38:59 | 2017-01-03T06:38:59 | 77,886,520 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 680 | py | # sensor collection system
from __future__ import unicode_literals
# starting time: 30, December,2016
# author: moonclearner
# -*- coding: utf-8 -*-
from socket import *
from time import ctime
Host = '127.0.0.1'
Port = 21010
BufferSize = 1024
ADDR = (Host,Port)
def server_init():
tcpserversock = socket(AF_INET,SOCK_STREAM)
tcpserversock.bind(ADDR)
tcpserversock.listen(5)
while True:
print "waiting for connection ..."
tcpCliSock, addr =tcpserversock.accept()
print '...connected from:',addr
while True:
data = tcpCliSock.recv(BufferSize)
if not data:
break
tcpCliSock.send('[%s] %s' % (ctime(),data))
tcpCliSock.close()
pass
server_init()
| [
"718857460@qq.com"
] | 718857460@qq.com |
5c3cadcea6b674950e9bd4d54fc622ab03f72053 | b4e22e0dc6d5360534b862792defc59eb8fc436e | /boggleGame.py | 7cb752f5f0afd868e3862359dd13646fd353c2bb | [] | no_license | possibleit/LintCode-Algorithm-question | e4170ef02fbda84f39a0d358cc1b414c682acd38 | d200e8e9a2fde865b9efcf9329abe62eb8d00905 | refs/heads/master | 2020-05-03T02:50:03.218575 | 2019-06-05T14:49:13 | 2019-06-05T14:49:13 | 178,381,158 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,502 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import collections
class TrieNode(object):
def __init__(self,value=0):
self.value = value
self.isword = False
#OrderDict是Dict的子类,可以记录元素添加的顺序,具体见https://docs.python.org/3.6/library/collections.html?highlight=collections#collections.OrderedDict
self.children = collections.OrderDict()
@classmethod
def insert(cls,root, word):
p = root
for c in word:
child = p.children.get(c)
if not child:
child = TrieNode(c)
p.children[c] = child
p = child
p.isword = True
class Solution:
# @param {char[][]} board a list of lists of char
# @param {str[]} words a list of string
# @return {int} an integer
'''
@Author : @LintCode参考答案
@Date : 16:28 2019/4/18
@Description : 描述
给定一个2D矩阵包括 a-z 和字典 dict,找到矩阵上最大的单词集合,这些单词不能在相同的位置重叠。返回最大集合的大小
字典中的单词不重复
可以重复使用字典中的单词
@Example :
Input:
["abc","def","ghi"]
{"abc","defi","gh"}
Output:
3
Explanation:
we can get the largest collection`["abc", "defi", "gh"]`
@Solution :
使用深度优先和回溯的方法,在矩阵上搜索,同时使用前缀树来优化搜索
'''
def boggleGame(self, board, words):
# Write your code here
self.board = board
self.words = words
self.m = len(board)
self.n = len(board[0])
self.results = []
self.temp = []
self.visited = [[False for _ in range(self.n)] for _ in range(self.m)]
self.root = TrieNode()
for word in words:
TrieNode.insert(self.root, word)
self.dfs(0, 0, self.root)
return len(self.results)
def dfs(self, x, y, root):
for i in range(x, self.m):
for j in range(y, self.n):
paths = []
temp = []
self.getAllPaths(i, j, paths, temp, root)
for path in paths:
word = ''
for px, py in path:
word += self.board[px][py]
self.visited[px][py] = True
self.temp.append(word)
if len(self.temp) > len(self.results):
self.results = self.temp[:]
self.dfs(i, j, root)
self.temp.pop()
for px, py in path:
self.visited[px][py] = False
y = 0
def getAllPaths(self, i, j, paths, temp, root):
if i < 0 or i >= self.m or j < 0 or j >= self.n or \
self.board[i][j] not in root.children or \
self.visited[i][j] == True:
return
root = root.children[self.board[i][j]]
if root.isWord:
temp.append((i, j))
paths.append(temp[:])
temp.pop()
return
self.visited[i][j] = True
deltas = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dx, dy in deltas:
newx = i + dx
newy = j + dy
temp.append((i, j))
self.getAllPaths(newx, newy, paths, temp, root)
temp.pop()
self.visited[i][j] = False | [
"2358979326@qq.com"
] | 2358979326@qq.com |
a1920eb17ae8a5d110eec79ba4698965d734274d | fd70357aadb41859afb2d42cc726d597423e6d90 | /aaulan/views/sponsorship.py | 7455b4f8b7bf30c0807dd8116c39eead86d8d6b5 | [
"MIT"
] | permissive | AAULAN/aaulan2.0 | a3f556476e5a33abb4441c4d3dd0491c9bfd7fbb | f0400914fe9e126a2dbf94cbce78cc34f976f3b8 | refs/heads/master | 2020-03-31T01:45:42.485820 | 2019-01-17T20:21:53 | 2019-01-17T20:21:53 | 151,793,970 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 714 | py | from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from ..models.sponsorship import Sponsorship, SponsorshipSerializer
class SponsorshipViewSet(viewsets.ViewSet):
def list(self, request, event_pk=None):
queryset = Sponsorship.objects.filter(event=event_pk)
serializer = SponsorshipSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, event_pk=None, pk=None):
queryset = Sponsorship.objects.filter(event=event_pk)
team = get_object_or_404(queryset, pk=pk)
serializer = SponsorshipSerializer(team)
return Response(serializer.data)
| [
"jacob@jener.dk"
] | jacob@jener.dk |
20ddaf5492fb4c5ccf30b264b6cf8cca8bbfa6ee | 8cd3160bfe2beaf7647cdfc5229cac39ac0c255c | /Prueba2/grafo.py | fba15ac6191b43474f1351ab4807c65e3187b544 | [] | no_license | Lozamded/Paralela | 9168a337cc071f85ab805dd0d2b96a2b5e7caf9b | b0d973cfa1a1ef291671fbccdfee25f21307068b | refs/heads/master | 2021-01-20T14:58:31.769333 | 2017-07-17T22:41:53 | 2017-07-17T22:41:53 | 90,696,175 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,750 | py | def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
texto = "grafo_ejemplo.txt"
archivo = open(texto, "r")
num_lineas = file_len(texto)
i = int(0)
cant_triangulos = int(0);
print "Lista de adyasencia: "
recorrido = ["0","0","0","0"]
lookup = int(0)
comparador = int(0)
num = 0
num2 = 0
revisado = [];
for num,linea in enumerate(archivo,1):
print "linea ",num," ", linea
numero = linea.split(" ")
print "numero ",numero
numero[0] = int(numero[0])
numero[1] = int(numero[1])
if not int(numero[0]) in revisado:
recorrido[0]=int(numero[0])
lookup = int(numero[1])
recorrido[1]=lookup
print "primera vuelta, buscar el ",lookup
archivo.seek(0)
for num2,linea2 in enumerate(archivo,1):
print "primera sublinea ",num2,", ", linea2
numero2 = linea2.split(" ")
print "comparar ", numero2[0]," con ",lookup
if(lookup == int(numero2[0])):
print "encontrado, estoy en el nodo"
print "comparar ", numero2[1]," con ",recorrido[0]," deben ser distintos"
if(int(numero2[1]) != int(recorrido[0])):
print "es distinto, sirve"
recorrido[2] = int(numero2[1])
lookup = recorrido[2]
print "segunda vuelta, buscar el ",lookup
archivo.seek(0)
for num3,linea3 in enumerate(archivo,1):
print"segunda sublinea ", num3, ", ", linea3
numero3 = linea3.split(" ")
if(lookup == int(numero3[0])):
print "encontrado, estoy en el nodo"
if(int(numero3[1]) == int(recorrido[0])):
print "eureka es un triangulo"
cant_triangulos += 1
recorrido[3] = int(numero3[1])
print "recorrido: ",recorrido
revisado.append(recorrido[0])
revisado.append(recorrido[1])
revisado.append(recorrido[2])
revisado.append(recorrido[3])
recorrido[0] = 0;
recorrido[1] = 0;
recorrido[2] = 0;
recorrido[3] = 0;
if num < num_lineas :
archivo.seek(0)
#print "linea ",num," ", linea
#print "numero ", numero
print "revisados ",revisado
archivo.seek(0)
print"cantidad de triangulos ", cant_triangulos
| [
"dhiguerafernandez@gmail.com"
] | dhiguerafernandez@gmail.com |
a831ccd07847fedc4a2a421d53e6d36e4d5ff562 | d3dcb6fdb4c78fdb080a94b3d2790716c8ac5104 | /dq/qm.py | 0fc4f3b72e1d2572a6477269ae98e84ad3ab1b06 | [
"MIT"
] | permissive | shuaigroup/dummy_qm | 7e13c1cb3b1510bd954571f27b72c960202fe4b1 | ddf0a580487e88da584ebb723e9bf920fbc2397e | refs/heads/master | 2020-07-12T03:17:39.516761 | 2019-11-05T05:32:53 | 2019-11-05T05:52:17 | 204,703,197 | 0 | 0 | MIT | 2019-08-30T11:57:25 | 2019-08-27T12:55:40 | Python | UTF-8 | Python | false | false | 120 | py | # -*- coding: utf-8 -*-
def scf(mol_name):
return len(mol_name)
def dft(mol_name):
return len(mol_name) - 2
| [
"liwt31@163.com"
] | liwt31@163.com |
ad2d33429d0c99627e9c18caa875ca3926d8864f | f028c7ca2e4c42505011ac0543cde4a111ee5c74 | /eggs/django_lfs-0.10.2-py2.7.egg/lfs/order/settings.py | deea3ffc34011276d45e862026eca7c9462fbb11 | [] | no_license | yunmengyanjin/website | d625544330c28f072707dcbbc5eb7308a3f4bd9f | 77e9c70687b35fd8b65a7f2d879e0261ae69c00e | refs/heads/master | 2021-04-22T13:10:09.584559 | 2017-05-15T07:39:32 | 2017-05-15T07:39:32 | 56,428,389 | 2 | 16 | null | 2020-10-02T07:41:08 | 2016-04-17T09:18:33 | Python | UTF-8 | Python | false | false | 755 | py | # django imports
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
SUBMITTED = 0
PAID = 1
SENT = 2
CLOSED = 3
CANCELED = 4
PAYMENT_FAILED = 5
PAYMENT_FLAGGED = 6
PREPARED = 7
ORDER_STATES = [
(SUBMITTED, _(u"Submitted")),
(PAID, _(u"Paid")),
(PREPARED, _(u"Prepared")),
(SENT, _(u"Sent")),
(CLOSED, _(u"Closed")),
(CANCELED, _(u"Canceled")),
(PAYMENT_FAILED, _(u"Payment Failed")),
(PAYMENT_FLAGGED, _(u"Payment Flagged")),
]
# use numbers above 20 for custom order states to avoid conflicts if new base states are added to LFS core!
LFS_EXTRA_ORDER_STATES = getattr(settings, 'LFS_EXTRA_ORDER_STATES', [])
if LFS_EXTRA_ORDER_STATES:
ORDER_STATES.extend(LFS_EXTRA_ORDER_STATES) | [
"daniel48@126.com"
] | daniel48@126.com |
fcafb028491856193e3d5ea38edae23be404ff2b | b1599af8f1db3b571a826429a7b93f0c398f6551 | /MinPerimeterRectangel.py | 5c837e8891edc71c9a85c742aab4c8ec40ff5d39 | [] | no_license | jmasramon/codility | 5fe21a6333276792d25a9f4920f94962aa70d837 | f3ce8ccde9da3b139d783daf10f529e5e2bac116 | refs/heads/master | 2020-04-16T17:44:36.340492 | 2017-01-21T19:23:51 | 2017-01-21T19:23:51 | 41,438,883 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,165 | py | __author__ = 'jmasramon'
# N area = a*b
# per = 2(a+b)
# find min perim if area = N
def solution(N):
min_per = (N+1)*2
i=1
while(i*i<N):
if (N%i == 0):
min_per = min(min_per, 2*(i+N/i))
i += 1
if (i*i == N):
min_per = min(min_per, 2*(i+N/i))
return min_per
def seq_all_eq_except_positions(n, exceptions, positions, rest):
orig_n = n
orig_exceps = len(exceptions)
exception_found = False
processed_exceptions = 0
while (n > 0):
exception_found = False
for i in xrange(len(exceptions)):
processed_exceptions += 1
if n == (orig_n - positions[i]):
yield exceptions[i]
del exceptions[i]
del positions[i]
exception_found = True
break
if not exception_found and processed_exceptions == orig_exceps:
yield rest
n -= 1
if __name__ == '__main__':
print 'Start tests..'
assert solution(30) == 22
assert solution(1) == 4
assert solution(2) == 6
assert solution(3) == 8
assert solution(4) == 8
assert solution(25) == 20
| [
"jordi.masramon@gmail.com"
] | jordi.masramon@gmail.com |
64327930a5d8ae9700917472a50c8c1dda60a734 | 5cc4e5a7b0de09f23b9614e3fc48fba9437b5186 | /base.py | 9ec5468085fa2dbeaf16e659ddafe08c3c419b4a | [] | no_license | jaybhagat/rentalsApp | 650926589a74a4bbfc8032a537c37d5ca2ec200a | 29a1123299fd1148565bc81408b343b9ccdbc596 | refs/heads/master | 2022-09-24T18:11:38.003358 | 2020-05-31T00:55:13 | 2020-05-31T00:55:13 | 262,192,139 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,614 | py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Rentals(db.Model):
id = db.Column(db.Integer, primary_key=True)
address = db.Column(db.String(100), unique=False, nullable=False)
price = db.Column(db.Integer, unique=False, nullable=False)
bed = db.Column(db.Integer, unique=False, nullable=True)
bath = db.Column(db.Integer, unique=False, nullable=True)
sqft = db.Column(db.Integer, unique=False, nullable=True)
pet = db.Column(db.Integer, unique=False, nullable=True)
type = db.Column(db.String(50), unique=False, nullable=False)
last_updated = db.Column(db.String(100), unique=False, nullable=False)
contact = db.Column(db.String(250), unique=False, nullable=False)
def __init__(self, address, price, bed, bath, sqft, pet, type, last_updated, contact):
self.address = address
self.price = price
self.bed = bed
self.bath = bath
self.sqft = sqft
self.pet = pet
self.type = type
self.last_updated = last_updated
self.contact = contact
def json(self):
return {'Address': self.address, 'Price': self.price, 'Bed': self.bed, \
'Bath': self.bath, 'Area': self.sqft, 'Pet': self.pet, 'Type': self.type, \
'Last Updated': self.last_updated, 'Contact': self.contact}
@classmethod
def find_by_address(cls, address):
return cls.query.filter_by(address=address).first()
def save_to(self):
db.session.add(self)
db.session.commit()
def delete_(self):
db.session.delete(self)
db.session.commit()
| [
"jay@Jays-MacBook-Pro.local"
] | jay@Jays-MacBook-Pro.local |
a960eef699c4388f843ebc3b90a4abff27eeb1a8 | a6feaaf07b780e5d6277f7fe649c6d88e04a32ac | /project2.py | 3bd53dbb73dffe72f68acf10fa2bdb2daa76c037 | [] | no_license | CN120/Movie_Recomender_WIM | a9a231f71590033fad628bcf24448819a0b87496 | 30365c1d12dcd253235683f318b0f2b906c292b2 | refs/heads/main | 2023-01-03T14:25:25.692042 | 2020-10-29T21:46:27 | 2020-10-29T21:46:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,831 | py | import numpy as np
from math import log
trained = np.loadtxt("./train.txt", dtype=int, delimiter='\t')
print(trained)
test5 = np.loadtxt("test5.txt", dtype=int, delimiter=' ')
test10 = np.loadtxt("test10.txt", dtype=int, delimiter=' ')
test20 = np.loadtxt("test20.txt", dtype=int, delimiter=' ')
testing = None
def buildTesting(test_num):
global testing
testing = np.zeros([100,1000], dtype=int)
if test_num == 5:
test_arr = test5
elif test_num == 10:
test_arr = test10
else:
test_arr = test20
first_item = test_arr[0][0]
for row in test_arr:
testing[row[0]-first_item, row[1]-1] = row[2]
def printNP(arr):
for item in arr:
print(item)
#will modify trained array
def computeIUF():
global trained
m = 200
for col in range(trained.shape[1]):
nz = np.count_nonzero(trained[:,col])
if nz!=0:
trained[:,col] = trained[:,col]* (log(m)-log(nz))
#-------------
#similarities
#-------------
def computeCosSim(user1, user2):
#expects user to be 1 dimmensional ndarray
mask = np.logical_and(user1, user2)
a = user1[mask]
b = user2[mask]
if a.size <=1:
return a.size
else:
return np.sum(a*b)/(np.linalg.norm(a)*np.linalg.norm(b))
def computePearsonSim(user1, user2):
mask = np.logical_and(user1, user2)
a = user1[mask]
b = user2[mask]
if a.size <= 1:
return a.size
else:
avg1 = np.average(a)
avg2 = np.average(b)
a = a-avg1
b = b-avg2
denom = (np.linalg.norm(a)*np.linalg.norm(b))
if denom==0:
return 0
weight = round(np.sum(a*b)/denom, 10)
return weight #modification 2 when commented out
p=2.5
new_weight = weight * (abs(weight)**(p-1))
return new_weight
def computeCosIBCFSim(item1, item2):
s1 = item1.size
s2 = item2.size
if s1>s2:
item1 = item1[:s2]
else:
item2 = item2[:s1]
if s1 <=1:
return s1
else:
avg1 = np.average(item1)
avg2 = np.average(item2)
item1 = item1-avg1
item2 = item2-avg2
denom = (np.linalg.norm(item1)*np.linalg.norm(item2))
if denom==0:
return 0
return round(np.sum(item1*item2)/denom,10)
#-------------
#predictors
#-------------
def predictBasicCosUBCF(userID, movieID, k=None):
neighbors = np.zeros([200,2],dtype=np.float32)
filled = 0
userID = (userID-1)%100
movieID = movieID-1
for row in trained:
if row[movieID]==0:
continue
else:
sim = computeCosSim(row,testing[userID])
if sim>0:
neighbors[filled][0] = sim
neighbors[filled][1] = row[movieID]
filled+=1
sorted_knn = (neighbors[np.argsort(neighbors[:,0])])[::-1]
# printNP(sorted_knn)
if k==None:
knns = sorted_knn[:filled-1] #swapped k for filled-1
else:
knns = sorted_knn[:k] #swapped k for filled-1
numer = np.sum(knns[:,0]*knns[:,1])
denom = np.sum(knns[:,0]) #vertical sum of weights
if denom>0:
prediction = round(numer/denom)
if prediction>5:
return 5
return prediction
else:
return 3
def predictBasicPearsonUBCF(userID, movieID, k=None):
neighbors = np.zeros([200,2],dtype=np.float32)
filled = 0
userID = (userID-1)%100
movieID = movieID-1
for row in trained:
if row[movieID]==0:
continue
else:
sim = computePearsonSim(testing[userID], row) #compare active user with each row/user from trained
if abs(sim)>1:
print(sim)
if sim!=0:
neighbors[filled][0] = sim #first column contains similarity rating
neighbors[filled][1] = row[movieID] #second column contains the ranking given to movie by
filled+=1
sorted_knn = (neighbors[np.argsort(abs(neighbors[:,0]))])[::-1]
# printNP(sorted_knn)
# print("---------------------")
if k==None:
knns = sorted_knn[:filled-1] #swapped k for filled-1
else:
knns = sorted_knn[:k] #swapped k for filled-1
avg_u = np.average(knns[:,1])
numer = np.sum(knns[:,0]*(knns[:,1]-avg_u))
denom = np.sum(abs(knns[:,0])) #vertical sum of weights
ra = np.sum(testing[userID])/np.count_nonzero(testing[userID])
# print(ra)
if denom!=0:
prediction = round(ra+(numer/denom))
if prediction>5:
return 5
if prediction<=0:
return 1
return prediction
else:
return 3
def predictCosIBCF(userID, movieID, k=None):
neighbors = np.zeros([1000,2],dtype=np.float32)
filled = 0
userID = (userID-1)%100
movieID = movieID-1
for i in range(trained.shape[1]):
col = trained[:,i]
if col[userID]==0:
continue
else:
sim = computeCosIBCFSim(col,testing[:,movieID])
if sim>0:
neighbors[filled][0] = sim
neighbors[filled][1] = col[userID]
filled+=1
sorted_knn = (neighbors[np.argsort(neighbors[:,0])])[::-1]
# printNP(sorted_knn)
if k==None:
knns = sorted_knn[:filled-1] #swapped k for filled-1
else:
knns = sorted_knn[:k] #swapped k for filled-1
numer = np.sum(knns[:,0]*knns[:,1])
denom = np.sum(knns[:,0]) #vertical sum of weights
if denom>0:
prediction = round(numer/denom)
if prediction>5:
return 5
return prediction
else:
return 3
def predictCustom(userID, movieID, k=None):
neighbors = np.zeros([200,2],dtype=np.float32)
filled = 0
userID = (userID-1)%100
movieID = movieID-1
for row in trained:
if row[movieID]==0:
continue
else:
sim = computeCosSim(row,testing[userID])
if sim>0:
neighbors[filled][0] = sim
neighbors[filled][1] = row[movieID]
filled+=1
sorted_knn = (neighbors[np.argsort(neighbors[:,0])])[::-1]
# printNP(sorted_knn)
if k==None:
knns = sorted_knn[:filled] #swapped k for filled-1
else:
knns = sorted_knn[:k] #swapped k for filled-1
numer = 0.9 * np.sum(knns[:,0]*knns[:,1]) + (0.1 * (np.sum(trained[:,movieID])/np.count_nonzero(trained[:,movieID])))
denom = np.sum(knns[:,0]) #vertical sum of weights
if denom>0:
prediction = round(numer/denom)
if prediction>5:
return 5
return prediction
else:
return 3
#--------------
#drivers
#--------------
def basicCosUBCF():
global test5, test10, test20
buildTesting(5)
test5 = test5[np.any(test5 == 0, axis=1)]
# printNP(test5)
for row in test5:
row[2] = predictBasicCosUBCF(row[0],row[1])
print(test5)
np.savetxt("result5.txt", test5,fmt='%d', delimiter=' ')
buildTesting(10)
test10 = test10[np.any(test10 == 0, axis=1)]
for row in test10:
row[2] = predictBasicCosUBCF(row[0],row[1])
print(test10)
np.savetxt("result10.txt", test10,fmt='%d', delimiter=' ')
buildTesting(20)
test20 = test20[np.any(test20 == 0, axis=1)]
for row in test20:
row[2] = predictBasicCosUBCF(row[0],row[1])
print(test20)
np.savetxt("result20.txt", test20,fmt='%d', delimiter=' ')
def basicPearsonUBCF():
global test5, test10, test20
# computeIUF() #modification 1 when uncommented (& mod 2 is commented)
buildTesting(5) #sets test
test5 = test5[np.any(test5 == 0, axis=1)]
# printNP(test5)
for row in test5:
row[2] = predictBasicPearsonUBCF(row[0],row[1])
print(test5)
np.savetxt("result5.txt", test5,fmt='%d', delimiter=' ')
buildTesting(10)
test10 = test10[np.any(test10 == 0, axis=1)]
for row in test10:
row[2] = predictBasicPearsonUBCF(row[0],row[1])
print(test10)
np.savetxt("result10.txt", test10,fmt='%d', delimiter=' ')
buildTesting(20)
test20 = test20[np.any(test20 == 0, axis=1)]
for row in test20:
row[2] = predictBasicPearsonUBCF(row[0],row[1])
print(test20)
np.savetxt("result20.txt", test20,fmt='%d', delimiter=' ')
def cosIBCF():
global test5, test10, test20
buildTesting(5)
test5 = test5[np.any(test5 == 0, axis=1)]
# printNP(test5)
for row in test5:
row[2] = predictCosIBCF(row[0],row[1])
print(test5)
np.savetxt("result5.txt", test5,fmt='%d', delimiter=' ')
buildTesting(10)
test10 = test10[np.any(test10 == 0, axis=1)]
for row in test10:
row[2] = predictCosIBCF(row[0],row[1])
print(test10)
np.savetxt("result10.txt", test10,fmt='%d', delimiter=' ')
buildTesting(20)
test20 = test20[np.any(test20 == 0, axis=1)]
for row in test20:
row[2] = predictCosIBCF(row[0],row[1])
print(test20)
np.savetxt("result20.txt", test20,fmt='%d', delimiter=' ')
def custom():
global test5, test10, test20
# computeIUF()
buildTesting(5)
test5 = test5[np.any(test5 == 0, axis=1)]
# printNP(test5)
for row in test5:
row[2] = predictCustom(row[0],row[1])
print(test5)
np.savetxt("result5.txt", test5,fmt='%d', delimiter=' ')
buildTesting(10)
test10 = test10[np.any(test10 == 0, axis=1)]
for row in test10:
row[2] = predictCustom(row[0],row[1])
print(test10)
np.savetxt("result10.txt", test10,fmt='%d', delimiter=' ')
buildTesting(20)
test20 = test20[np.any(test20 == 0, axis=1)]
for row in test20:
row[2] = predictCustom(row[0],row[1])
print(test20)
np.savetxt("result20.txt", test20,fmt='%d', delimiter=' ')
# basicCosUBCF()
# basicPearsonUBCF()
# cosIBCF()
custom() | [
"noreply@github.com"
] | noreply@github.com |
f5106688a14c435c9b722292e4efbf2a86450d65 | 7ca3e3e7cc768524dce8715ac511dededca0548d | /flask/bin/python-config | fcd925df8367b95316b70c08aefbe23f4a79f35d | [] | no_license | Sushantgakhar/microblog | dcd32072a2598cd3d1fbefa6facf31ebf751e333 | cd1c02434a92c8f4f8134ee8b128bcced760a0d7 | refs/heads/master | 2021-01-24T09:18:36.275579 | 2016-11-18T11:27:26 | 2016-11-18T11:27:26 | 69,888,219 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,357 | #!/Users/ishaan/Documents/microblog/flask/bin/python
import sys
import getopt
import sysconfig
valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags',
'ldflags', 'help']
if sys.version_info >= (3, 2):
valid_opts.insert(-1, 'extension-suffix')
valid_opts.append('abiflags')
if sys.version_info >= (3, 3):
valid_opts.append('configdir')
def exit_with_usage(code=1):
sys.stderr.write("Usage: {0} [{1}]\n".format(
sys.argv[0], '|'.join('--'+opt for opt in valid_opts)))
sys.exit(code)
try:
opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
except getopt.error:
exit_with_usage()
if not opts:
exit_with_usage()
pyver = sysconfig.get_config_var('VERSION')
getvar = sysconfig.get_config_var
opt_flags = [flag for (flag, val) in opts]
if '--help' in opt_flags:
exit_with_usage(code=0)
for opt in opt_flags:
if opt == '--prefix':
print(sysconfig.get_config_var('prefix'))
elif opt == '--exec-prefix':
print(sysconfig.get_config_var('exec_prefix'))
elif opt in ('--includes', '--cflags'):
flags = ['-I' + sysconfig.get_path('include'),
'-I' + sysconfig.get_path('platinclude')]
if opt == '--cflags':
flags.extend(getvar('CFLAGS').split())
print(' '.join(flags))
elif opt in ('--libs', '--ldflags'):
abiflags = getattr(sys, 'abiflags', '')
libs = ['-lpython' + pyver + abiflags]
libs += getvar('LIBS').split()
libs += getvar('SYSLIBS').split()
# add the prefix/lib/pythonX.Y/config dir, but only if there is no
# shared library in prefix/lib/.
if opt == '--ldflags':
if not getvar('Py_ENABLE_SHARED'):
libs.insert(0, '-L' + getvar('LIBPL'))
if not getvar('PYTHONFRAMEWORK'):
libs.extend(getvar('LINKFORSHARED').split())
print(' '.join(libs))
elif opt == '--extension-suffix':
ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
if ext_suffix is None:
ext_suffix = sysconfig.get_config_var('SO')
print(ext_suffix)
elif opt == '--abiflags':
if not getattr(sys, 'abiflags', None):
exit_with_usage()
print(sys.abiflags)
elif opt == '--configdir':
print(sysconfig.get_config_var('LIBPL'))
| [
"gakharsushant@gmail.com"
] | gakharsushant@gmail.com | |
3ea4d53a79484f18a2f537cce2b80ff6fb76d9d5 | 2e9f3f35cd239ce59f528c7b3b5e9714f7e5d5a3 | /furnace/kernels/lib_tree_filter/functions/bfs.py | 0c42bda0aebff2c10db5ec40a4cd5d48df3bdd46 | [
"MIT"
] | permissive | CV-IP/TreeFilter-Torch | 8e2bd831060d0fa4e589a56353c2d91a7d4ac87b | 46f36024f4522056fb9a3edf90c94f0a86a1352b | refs/heads/master | 2023-02-04T19:09:32.790909 | 2020-12-16T07:14:41 | 2020-12-16T07:14:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 485 | py | import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
import tree_filter_cuda as _C
class _BFS(Function):
@staticmethod
def forward(ctx, edge_index, max_adj_per_vertex):
sorted_index, sorted_parent, sorted_child =\
_C.bfs_forward(edge_index, max_adj_per_vertex)
return sorted_index, sorted_parent, sorted_child
bfs = _BFS.apply
| [
"stevengrove@stu.xjtu.edu.cn"
] | stevengrove@stu.xjtu.edu.cn |
3305807a13f174ff87ead377d7acd503806033be | a6e4a6f0a73d24a6ba957277899adbd9b84bd594 | /sdk/python/pulumi_azure_native/netapp/v20190601/_inputs.py | 6ac3e38e0fdff20cacdaccca6e8025b52fcd1b8f | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | MisinformedDNA/pulumi-azure-native | 9cbd75306e9c8f92abc25be3f73c113cb93865e9 | de974fd984f7e98649951dbe80b4fc0603d03356 | refs/heads/master | 2023-03-24T22:02:03.842935 | 2021-03-08T21:16:19 | 2021-03-08T21:16:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,825 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from ._enums import *
__all__ = [
'ActiveDirectoryArgs',
'ExportPolicyRuleArgs',
'VolumePropertiesExportPolicyArgs',
]
@pulumi.input_type
class ActiveDirectoryArgs:
def __init__(__self__, *,
active_directory_id: Optional[pulumi.Input[str]] = None,
dns: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
organizational_unit: Optional[pulumi.Input[str]] = None,
password: Optional[pulumi.Input[str]] = None,
smb_server_name: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
username: Optional[pulumi.Input[str]] = None):
"""
Active Directory
:param pulumi.Input[str] active_directory_id: Id of the Active Directory
:param pulumi.Input[str] dns: Comma separated list of DNS server IP addresses for the Active Directory domain
:param pulumi.Input[str] domain: Name of the Active Directory domain
:param pulumi.Input[str] organizational_unit: The Organizational Unit (OU) within the Windows Active Directory
:param pulumi.Input[str] password: Plain text password of Active Directory domain administrator
:param pulumi.Input[str] smb_server_name: NetBIOS name of the SMB server. This name will be registered as a computer account in the AD and used to mount volumes
:param pulumi.Input[str] status: Status of the Active Directory
:param pulumi.Input[str] username: Username of Active Directory domain administrator
"""
if active_directory_id is not None:
pulumi.set(__self__, "active_directory_id", active_directory_id)
if dns is not None:
pulumi.set(__self__, "dns", dns)
if domain is not None:
pulumi.set(__self__, "domain", domain)
if organizational_unit is not None:
pulumi.set(__self__, "organizational_unit", organizational_unit)
if password is not None:
pulumi.set(__self__, "password", password)
if smb_server_name is not None:
pulumi.set(__self__, "smb_server_name", smb_server_name)
if status is not None:
pulumi.set(__self__, "status", status)
if username is not None:
pulumi.set(__self__, "username", username)
@property
@pulumi.getter(name="activeDirectoryId")
def active_directory_id(self) -> Optional[pulumi.Input[str]]:
"""
Id of the Active Directory
"""
return pulumi.get(self, "active_directory_id")
@active_directory_id.setter
def active_directory_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "active_directory_id", value)
@property
@pulumi.getter
def dns(self) -> Optional[pulumi.Input[str]]:
"""
Comma separated list of DNS server IP addresses for the Active Directory domain
"""
return pulumi.get(self, "dns")
@dns.setter
def dns(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "dns", value)
@property
@pulumi.getter
def domain(self) -> Optional[pulumi.Input[str]]:
"""
Name of the Active Directory domain
"""
return pulumi.get(self, "domain")
@domain.setter
def domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "domain", value)
@property
@pulumi.getter(name="organizationalUnit")
def organizational_unit(self) -> Optional[pulumi.Input[str]]:
"""
The Organizational Unit (OU) within the Windows Active Directory
"""
return pulumi.get(self, "organizational_unit")
@organizational_unit.setter
def organizational_unit(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "organizational_unit", value)
@property
@pulumi.getter
def password(self) -> Optional[pulumi.Input[str]]:
"""
Plain text password of Active Directory domain administrator
"""
return pulumi.get(self, "password")
@password.setter
def password(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "password", value)
@property
@pulumi.getter(name="smbServerName")
def smb_server_name(self) -> Optional[pulumi.Input[str]]:
"""
NetBIOS name of the SMB server. This name will be registered as a computer account in the AD and used to mount volumes
"""
return pulumi.get(self, "smb_server_name")
@smb_server_name.setter
def smb_server_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "smb_server_name", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
Status of the Active Directory
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter
def username(self) -> Optional[pulumi.Input[str]]:
"""
Username of Active Directory domain administrator
"""
return pulumi.get(self, "username")
@username.setter
def username(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "username", value)
@pulumi.input_type
class ExportPolicyRuleArgs:
def __init__(__self__, *,
allowed_clients: Optional[pulumi.Input[str]] = None,
cifs: Optional[pulumi.Input[bool]] = None,
nfsv3: Optional[pulumi.Input[bool]] = None,
nfsv4: Optional[pulumi.Input[bool]] = None,
rule_index: Optional[pulumi.Input[int]] = None,
unix_read_only: Optional[pulumi.Input[bool]] = None,
unix_read_write: Optional[pulumi.Input[bool]] = None):
"""
Volume Export Policy Rule
:param pulumi.Input[str] allowed_clients: Client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names
:param pulumi.Input[bool] cifs: Allows CIFS protocol
:param pulumi.Input[bool] nfsv3: Allows NFSv3 protocol
:param pulumi.Input[bool] nfsv4: Deprecated: Will use the NFSv4.1 protocol, please use swagger version 2019-07-01 or later
:param pulumi.Input[int] rule_index: Order index
:param pulumi.Input[bool] unix_read_only: Read only access
:param pulumi.Input[bool] unix_read_write: Read and write access
"""
if allowed_clients is not None:
pulumi.set(__self__, "allowed_clients", allowed_clients)
if cifs is not None:
pulumi.set(__self__, "cifs", cifs)
if nfsv3 is not None:
pulumi.set(__self__, "nfsv3", nfsv3)
if nfsv4 is not None:
pulumi.set(__self__, "nfsv4", nfsv4)
if rule_index is not None:
pulumi.set(__self__, "rule_index", rule_index)
if unix_read_only is not None:
pulumi.set(__self__, "unix_read_only", unix_read_only)
if unix_read_write is not None:
pulumi.set(__self__, "unix_read_write", unix_read_write)
@property
@pulumi.getter(name="allowedClients")
def allowed_clients(self) -> Optional[pulumi.Input[str]]:
"""
Client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names
"""
return pulumi.get(self, "allowed_clients")
@allowed_clients.setter
def allowed_clients(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "allowed_clients", value)
@property
@pulumi.getter
def cifs(self) -> Optional[pulumi.Input[bool]]:
"""
Allows CIFS protocol
"""
return pulumi.get(self, "cifs")
@cifs.setter
def cifs(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "cifs", value)
@property
@pulumi.getter
def nfsv3(self) -> Optional[pulumi.Input[bool]]:
"""
Allows NFSv3 protocol
"""
return pulumi.get(self, "nfsv3")
@nfsv3.setter
def nfsv3(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "nfsv3", value)
@property
@pulumi.getter
def nfsv4(self) -> Optional[pulumi.Input[bool]]:
"""
Deprecated: Will use the NFSv4.1 protocol, please use swagger version 2019-07-01 or later
"""
return pulumi.get(self, "nfsv4")
@nfsv4.setter
def nfsv4(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "nfsv4", value)
@property
@pulumi.getter(name="ruleIndex")
def rule_index(self) -> Optional[pulumi.Input[int]]:
"""
Order index
"""
return pulumi.get(self, "rule_index")
@rule_index.setter
def rule_index(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "rule_index", value)
@property
@pulumi.getter(name="unixReadOnly")
def unix_read_only(self) -> Optional[pulumi.Input[bool]]:
"""
Read only access
"""
return pulumi.get(self, "unix_read_only")
@unix_read_only.setter
def unix_read_only(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "unix_read_only", value)
@property
@pulumi.getter(name="unixReadWrite")
def unix_read_write(self) -> Optional[pulumi.Input[bool]]:
"""
Read and write access
"""
return pulumi.get(self, "unix_read_write")
@unix_read_write.setter
def unix_read_write(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "unix_read_write", value)
@pulumi.input_type
class VolumePropertiesExportPolicyArgs:
def __init__(__self__, *,
rules: Optional[pulumi.Input[Sequence[pulumi.Input['ExportPolicyRuleArgs']]]] = None):
"""
Set of export policy rules
:param pulumi.Input[Sequence[pulumi.Input['ExportPolicyRuleArgs']]] rules: Export policy rule
"""
if rules is not None:
pulumi.set(__self__, "rules", rules)
@property
@pulumi.getter
def rules(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ExportPolicyRuleArgs']]]]:
"""
Export policy rule
"""
return pulumi.get(self, "rules")
@rules.setter
def rules(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ExportPolicyRuleArgs']]]]):
pulumi.set(self, "rules", value)
| [
"noreply@github.com"
] | noreply@github.com |
d416b840d8b75b0bc1afde2953bdda6171b7660d | 745bd131051e8876f725171c7585442afc92d166 | /SenseHat_Letters.py | c9803e5539600d28caec70a28e5dbc62cdcfb0b1 | [] | no_license | toxarisswe/rpi | 5b7027d2cb2fe49243e6130cf3d849bbe8a56644 | 062f4f046521745ddd676ad54ee01ee9f11108b9 | refs/heads/master | 2020-03-27T11:44:46.589470 | 2018-08-29T08:13:34 | 2018-08-29T08:13:34 | 146,505,634 | 0 | 0 | null | 2018-08-28T21:02:06 | 2018-08-28T20:53:23 | null | UTF-8 | Python | false | false | 347 | py | #! /usr/bin/env python
from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
yellow = (255, 255, 0)
sense.show_letter("T", red)
sleep(1)
sense.show_letter("O", blue)
sleep(1)
sense.show_letter("V", green)
sleep(1)
sense.show_letter("E", yellow)
sleep(1)
sense.clear()
| [
"toxaris@hotmail.com"
] | toxaris@hotmail.com |
eb3aaf828529badea89198548156e0978fba4e27 | e825b2f0fde4e24809b224b7eb000ed406065eb3 | /previous/02_main.py | d4210dfbbba78db7861c4c6780ddf5f4cbf47333 | [] | no_license | EricNeid/CodingGame | 0bc2b08324a03f22f8078e0650106bf9d098b80b | 5e4d73582844dec457ac9b375bb2ecde501a0653 | refs/heads/master | 2021-09-20T05:45:56.655900 | 2018-08-04T19:43:31 | 2018-08-04T19:43:31 | 78,210,993 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 677 | py | import sys
import math
# The while loop represents the game.
# Each iteration represents a turn of the game
# where you are given inputs (the heights of the mountains)
# and where you have to print an output (the index of the mountain to fire on)
# The inputs you are given are automatically updated according to your last actions.
# game loop
while True:
max = 0
maxIndex = -1
for i in range(8):
height = int(input())
if height > max:
max = height
maxIndex = i
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
# The index of the mountain to fire on.
print(maxIndex)
| [
"eric.neidhardt@sevenval.com"
] | eric.neidhardt@sevenval.com |
e54795bb281bdf8f85f066736ab758402ee247bb | 8d35b8aa63f3cae4e885e3c081f41235d2a8f61f | /discord/ext/dl/extractor/formula1.py | fe89d221c6f687c2412b0273b350ca3685ae8f59 | [
"MIT"
] | permissive | alexyy802/Texus | 1255f4e54c8d3cc067f0d30daff1cf24932ea0c9 | c282a836f43dfd588d89d5c13f432896aebb540f | refs/heads/master | 2023-09-05T06:14:36.217601 | 2021-11-21T03:39:55 | 2021-11-21T03:39:55 | 429,390,575 | 0 | 0 | MIT | 2021-11-19T09:22:22 | 2021-11-18T10:43:11 | Python | UTF-8 | Python | false | false | 1,020 | py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class Formula1IE(InfoExtractor):
_VALID_URL = (
r"https?://(?:www\.)?formula1\.com/en/latest/video\.[^.]+\.(?P<id>\d+)\.html"
)
_TEST = {
"url": "https://www.formula1.com/en/latest/video.race-highlights-spain-2016.6060988138001.html",
"md5": "be7d3a8c2f804eb2ab2aa5d941c359f8",
"info_dict": {
"id": "6060988138001",
"ext": "mp4",
"title": "Race highlights - Spain 2016",
"timestamp": 1463332814,
"upload_date": "20160515",
"uploader_id": "6057949432001",
},
"add_ie": ["BrightcoveNew"],
}
BRIGHTCOVE_URL_TEMPLATE = "http://players.brightcove.net/6057949432001/S1WMrhjlh_default/index.html?videoId=%s"
def _real_extract(self, url):
bc_id = self._match_id(url)
return self.url_result(
self.BRIGHTCOVE_URL_TEMPLATE % bc_id, "BrightcoveNew", bc_id
)
| [
"noreply@github.com"
] | noreply@github.com |
cf3574e7f1b07fdaf295f9b85a87e7e6aa4fa6a1 | 34bb6071725fb31f50ef7ff147fce5a06a5bb534 | /code/router/handler.py | 131eb17758636f15b29d37e503a366f93725e8eb | [] | no_license | joshmarshall/intro-to-wsgi-presentation-2013 | 6f28612da4fc7225e8ed2081f725ae940821c0d3 | 19bf30410f435a0bb9a101bb2800cac294096931 | refs/heads/master | 2023-08-14T09:39:08.858311 | 2019-01-09T11:45:25 | 2019-01-09T11:45:25 | 164,854,894 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | class Handler(object):
def __init__(self, environ, start_response):
self._environ = environ
self._start_response = start_response
self._response_started = False
self._code = 200
self._message = "OK"
self.headers = {}
def start_response(self, code, status="OK"):
self.headers.setdefault("Content-Length", "application/json")
self._start_response(
"%s %s" % (code, status), list(self.headers.items()))
| [
"catchjosh@gmail.com"
] | catchjosh@gmail.com |
c44a5644d0add67217483c07fda48d223fa18621 | 8c2908b098bd49bf423cb904098773b33229b494 | /MedApp/admin.py | eb656cb96bb956758b596a1a1accc15abadd74d8 | [] | no_license | rasmim/MedApp | d325668866cdd36c748d4ddf61e5d107f8bdc3aa | b1b9330efa104c58eb68636b5cbc48aa4f35f326 | refs/heads/master | 2020-04-05T14:09:10.975174 | 2017-10-20T12:09:49 | 2017-10-20T12:09:49 | 94,787,744 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,667 | py | from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from MedApp.models import CustomUser, Appointment, Patient, Specialization, Diagnostic, Consultation, ConsultationResult
# Register your models here.
class DoctorFilter(admin.SimpleListFilter):
title = 'Doctors'
parameter_name = 'doctor'
def lookups(self, request, model_admin):
doctors = []
qs = CustomUser.objects.filter(groups__in=[1]).distinct()
for c in qs:
doctors.append([c.id, c.get_full_name()])
return doctors
def queryset(self, request, queryset):
if self.value():
return queryset.filter(doctor__id__exact=self.value())
else:
return queryset
class AppointmentAdmin(admin.ModelAdmin):
list_display = ('doctor', 'patient', 'time', 'created_by')
exclude = ('created_by', )
created_by = 'testssds'
list_filter = ['time', DoctorFilter]
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'doctor':
kwargs["queryset"] = CustomUser.objects.filter(groups__in=[1])
return super(AppointmentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
def get_queryset(self, request):
qs = super(AppointmentAdmin, self).get_queryset(request)
if request.user.groups.filter(name='Doctors').exists():
return qs.filter(doctor=request.user)
else:
return qs
class ConsultationaAdmin(admin.ModelAdmin):
list_display = ('doctor', 'patient', 'specialization')
def get_queryset(self, request):
qs = super(ConsultationaAdmin, self).get_queryset(request)
if request.user.groups.filter(name='Doctors').exists():
return qs.filter(doctor=request.user)
else:
return qs
class ConsultationResultAdmin(admin.ModelAdmin):
list_display = ('patient','diagnostic','recipe','image_tag')
actions = ['print_consultation']
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'diagnostic':
specialization_id = Specialization.objects.get(doctor_id=request.user.id)
kwargs["queryset"] = Diagnostic.objects.filter(specilization_id=specialization_id)
return super(ConsultationResultAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
# def print_consultation(request, canvas=None):
# response = HttpResponse(content_type='application/pdf')
# response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
#
# buffer = BytesIO()
#
# # Create the PDF object, using the BytesIO object as its "file."
# p = canvas.Canvas(buffer)
#
# # Draw things on the PDF. Here's where the PDF generation happens.
# # See the ReportLab documentation for the full list of functionality.
# p.drawString(100, 100, "Hello world.")
#
# # Close the PDF object cleanly.
# p.showPage()
# p.save()
#
# # Get the value of the BytesIO buffer and write it to the response.
# pdf = buffer.getvalue()
# buffer.close()
# response.write(pdf)
# return response
class DiagnosticAdmin(admin.ModelAdmin):
list_display = ('name', 'code')
def get_queryset(self, request):
qs = super(DiagnosticAdmin, self).get_queryset(request)
if request.user.groups.filter(name='Doctors').exists():
specialization_id = Specialization.objects.get(doctor_id = request.user.id)
return qs.filter( specilization_id= specialization_id)
else:
return qs
class PatientAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name',)
# list_filter = [DoctorFilter,]
exclude = ['doctor']
search_fields = ('first_name', 'last_name', 'cnp',)
admin.site.register(Diagnostic, DiagnosticAdmin)
admin.site.register(ConsultationResult, ConsultationResultAdmin)
admin.site.register(Appointment, AppointmentAdmin)
admin.site.register(Consultation, ConsultationaAdmin)
admin.site.register(Patient, PatientAdmin)
class UserCreationForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ('email',)
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
class CustomUserAdmin(UserAdmin):
# The forms to add and change user instances
add_form = UserCreationForm
list_display = ("email",)
ordering = ("email",)
# refine the fields
fieldsets = (
(
None, {'fields': ('email', 'password', 'first_name', 'last_name', 'groups', 'last_login', 'user_permissions')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': (
'email', 'password', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active', 'groups',
'last_login', 'user_permissions')}
),
)
search_fields = ('first_name', 'last_name', 'email',)
admin.site.register(CustomUser, CustomUserAdmin)
admin.site.register(Specialization)
# admin.site.register(Diagnostic)
#
# admin.site.register(Consultation)
# admin.site.register(ConsultationResult, FilterByUser)
| [
"mrasmivlad@gmail.com"
] | mrasmivlad@gmail.com |
08c134f6f876b56b29c1de913786e6806a67d98e | 74b12c96a73d464e3ca3241ae83a0b6fe984b913 | /python/tvm/runtime/__init__.py | e0da680a24fc3e555e5824caa81dc414f22c6abf | [
"Apache-2.0",
"BSD-3-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-2-Clause"
] | permissive | masahi/tvm | cf765bb892655f02135e1ce3afde88698f026483 | c400f7e871214451b75f20f4879992becfe5e3a4 | refs/heads/master | 2023-08-22T20:46:25.795382 | 2022-04-13T08:47:10 | 2022-04-13T08:47:10 | 138,661,036 | 4 | 2 | Apache-2.0 | 2021-09-03T20:35:19 | 2018-06-25T23:39:51 | Python | UTF-8 | Python | false | false | 1,454 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""TVM runtime namespace."""
# class exposures
from .packed_func import PackedFunc
from .object import Object
from .object_generic import ObjectGeneric, ObjectTypes
from .ndarray import NDArray, DataType, DataTypeCode, Device
from .module import Module, num_threads
from .profiling import Report
# function exposures
from .object_generic import convert_to_object, convert, const
from .ndarray import device, cpu, cuda, gpu, opencl, cl, vulkan, metal, mtl
from .ndarray import vpi, rocm, ext_dev
from .module import load_module, enabled, system_lib
from .container import String, ShapeTuple
from .params import save_param_dict, load_param_dict
from . import executor
| [
"noreply@github.com"
] | noreply@github.com |
08112369a05666d5f6b11eaf2d0a158f09c0c2f8 | 2a8de1712fb2ae6b3f222b1fa1ced448ee7d95a3 | /dj_anonymizer/utils.py | 86beadeb6c58c9fbc046f8a94b4f894a61eaf7b7 | [
"MIT"
] | permissive | chinskiy/dj_anonymizer | 6e8367a8476d623faa3d49177e011cd0ece4efbf | 0957e34d0d67ca2537bc466d139ea139a8898e7c | refs/heads/master | 2020-03-23T20:34:09.849807 | 2018-10-22T15:14:03 | 2018-10-22T15:14:03 | 142,048,851 | 0 | 0 | MIT | 2018-07-23T17:47:08 | 2018-07-23T17:47:08 | null | UTF-8 | Python | false | false | 424 | py | import os
from dj_anonymizer.conf import settings
def import_if_exist(filename):
"""
Check if file exist in appropriate path and import it
"""
path_to_base_file = os.path.join(
settings.ANONYMIZER_MODEL_DEFINITION_DIR, filename + '.py')
if os.path.isfile(os.path.abspath(path_to_base_file)):
__import__(
settings.ANONYMIZER_MODEL_DEFINITION_DIR + '.' + filename
)
| [
"chinskiy93@gmail.com"
] | chinskiy93@gmail.com |
4c651e654d7a4629ae37b0c69f86348993078c0b | 8d753bb8f19b5b1f526b0688d3cb199b396ed843 | /osp_sai_2.1.8/system/third_party/precompiled/arm64/python/usr/bin/smtpd.py | 88dc01c9dee2f9d29f28fcd5b376d6d926094198 | [] | no_license | bonald/vim_cfg | f166e5ff650db9fa40b564d05dc5103552184db8 | 2fee6115caec25fd040188dda0cb922bfca1a55f | refs/heads/master | 2023-01-23T05:33:00.416311 | 2020-11-19T02:09:18 | 2020-11-19T02:09:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,654 | py | #!/data01/users/sw/shil/my_tmp/osp_sai/arm64/Python-2.7.13_dir/python2_7_13_for_aarch64/../python2_7_13_for_aarch64_out/bin/python2.7
"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call will fail if this program is not run as root (in
which case, use this flag).
--version
-V
Print the version number and exit.
--class classname
-c classname
Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by
default.
--debug
-d
Turn on debugging prints.
--help
-h
Print this message and exit.
Version: %(__version__)s
If localhost is not given then `localhost' is used, and if localport is not
given then 8025 is used. If remotehost is not given then `localhost' is used,
and if remoteport is not given, then 25 is used.
"""
# Overview:
#
# This file implements the minimal SMTP protocol as defined in RFC 821. It
# has a hierarchy of classes which implement the backend functionality for the
# smtpd. A number of classes are provided:
#
# SMTPServer - the base class for the backend. Raises NotImplementedError
# if you try to use it.
#
# DebuggingServer - simply prints each message it receives on stdout.
#
# PureProxy - Proxies all messages to a real smtpd which does final
# delivery. One known problem with this class is that it doesn't handle
# SMTP errors from the backend server at all. This should be fixed
# (contributions are welcome!).
#
# MailmanProxy - An experimental hack to work with GNU Mailman
# <www.list.org>. Using this server as your real incoming smtpd, your
# mailhost will automatically recognize and accept mail destined to Mailman
# lists when those lists are created. Every message not destined for a list
# gets forwarded to a real backend smtpd, as with PureProxy. Again, errors
# are not handled correctly yet.
#
# Please note that this script requires Python 2.0
#
# Author: Barry Warsaw <barry@python.org>
#
# TODO:
#
# - support mailbox delivery
# - alias files
# - ESMTP
# - handle error codes from the backend smtpd
import sys
import os
import errno
import getopt
import time
import socket
import asyncore
import asynchat
__all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"]
program = sys.argv[0]
__version__ = 'Python SMTP proxy version 0.2'
class Devnull:
def write(self, msg): pass
def flush(self): pass
DEBUGSTREAM = Devnull()
NEWLINE = '\n'
EMPTYSTRING = ''
COMMASPACE = ', '
def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals()
if msg:
print >> sys.stderr, msg
sys.exit(code)
class SMTPChannel(asynchat.async_chat):
COMMAND = 0
DATA = 1
def __init__(self, server, conn, addr):
asynchat.async_chat.__init__(self, conn)
self.__server = server
self.__conn = conn
self.__addr = addr
self.__line = []
self.__state = self.COMMAND
self.__greeting = 0
self.__mailfrom = None
self.__rcpttos = []
self.__data = ''
self.__fqdn = socket.getfqdn()
try:
self.__peer = conn.getpeername()
except socket.error, err:
# a race condition may occur if the other end is closing
# before we can get the peername
self.close()
if err[0] != errno.ENOTCONN:
raise
return
print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
self.push('220 %s %s' % (self.__fqdn, __version__))
self.set_terminator('\r\n')
# Overrides base class for convenience
def push(self, msg):
asynchat.async_chat.push(self, msg + '\r\n')
# Implementation of base class abstract method
def collect_incoming_data(self, data):
self.__line.append(data)
# Implementation of base class abstract method
def found_terminator(self):
line = EMPTYSTRING.join(self.__line)
print >> DEBUGSTREAM, 'Data:', repr(line)
self.__line = []
if self.__state == self.COMMAND:
if not line:
self.push('500 Error: bad syntax')
return
method = None
i = line.find(' ')
if i < 0:
command = line.upper()
arg = None
else:
command = line[:i].upper()
arg = line[i+1:].strip()
method = getattr(self, 'smtp_' + command, None)
if not method:
self.push('502 Error: command "%s" not implemented' % command)
return
method(arg)
return
else:
if self.__state != self.DATA:
self.push('451 Internal confusion')
return
# Remove extraneous carriage returns and de-transparency according
# to RFC 821, Section 4.5.2.
data = []
for text in line.split('\r\n'):
if text and text[0] == '.':
data.append(text[1:])
else:
data.append(text)
self.__data = NEWLINE.join(data)
status = self.__server.process_message(self.__peer,
self.__mailfrom,
self.__rcpttos,
self.__data)
self.__rcpttos = []
self.__mailfrom = None
self.__state = self.COMMAND
self.set_terminator('\r\n')
if not status:
self.push('250 Ok')
else:
self.push(status)
# SMTP and ESMTP commands
def smtp_HELO(self, arg):
if not arg:
self.push('501 Syntax: HELO hostname')
return
if self.__greeting:
self.push('503 Duplicate HELO/EHLO')
else:
self.__greeting = arg
self.push('250 %s' % self.__fqdn)
def smtp_NOOP(self, arg):
if arg:
self.push('501 Syntax: NOOP')
else:
self.push('250 Ok')
def smtp_QUIT(self, arg):
# args is ignored
self.push('221 Bye')
self.close_when_done()
# factored
def __getaddr(self, keyword, arg):
address = None
keylen = len(keyword)
if arg[:keylen].upper() == keyword:
address = arg[keylen:].strip()
if not address:
pass
elif address[0] == '<' and address[-1] == '>' and address != '<>':
# Addresses can be in the form <person@dom.com> but watch out
# for null address, e.g. <>
address = address[1:-1]
return address
def smtp_MAIL(self, arg):
print >> DEBUGSTREAM, '===> MAIL', arg
address = self.__getaddr('FROM:', arg) if arg else None
if not address:
self.push('501 Syntax: MAIL FROM:<address>')
return
if self.__mailfrom:
self.push('503 Error: nested MAIL command')
return
self.__mailfrom = address
print >> DEBUGSTREAM, 'sender:', self.__mailfrom
self.push('250 Ok')
def smtp_RCPT(self, arg):
print >> DEBUGSTREAM, '===> RCPT', arg
if not self.__mailfrom:
self.push('503 Error: need MAIL command')
return
address = self.__getaddr('TO:', arg) if arg else None
if not address:
self.push('501 Syntax: RCPT TO: <address>')
return
self.__rcpttos.append(address)
print >> DEBUGSTREAM, 'recips:', self.__rcpttos
self.push('250 Ok')
def smtp_RSET(self, arg):
if arg:
self.push('501 Syntax: RSET')
return
# Resets the sender, recipients, and data, but not the greeting
self.__mailfrom = None
self.__rcpttos = []
self.__data = ''
self.__state = self.COMMAND
self.push('250 Ok')
def smtp_DATA(self, arg):
if not self.__rcpttos:
self.push('503 Error: need RCPT command')
return
if arg:
self.push('501 Syntax: DATA')
return
self.__state = self.DATA
self.set_terminator('\r\n.\r\n')
self.push('354 End data with <CR><LF>.<CR><LF>')
class SMTPServer(asyncore.dispatcher):
def __init__(self, localaddr, remoteaddr):
self._localaddr = localaddr
self._remoteaddr = remoteaddr
asyncore.dispatcher.__init__(self)
try:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# try to re-use a server port if possible
self.set_reuse_addr()
self.bind(localaddr)
self.listen(5)
except:
# cleanup asyncore.socket_map before raising
self.close()
raise
else:
print >> DEBUGSTREAM, \
'%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
self.__class__.__name__, time.ctime(time.time()),
localaddr, remoteaddr)
def handle_accept(self):
pair = self.accept()
if pair is not None:
conn, addr = pair
print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
channel = SMTPChannel(self, conn, addr)
# API for "doing something useful with the message"
def process_message(self, peer, mailfrom, rcpttos, data):
"""Override this abstract method to handle messages from the client.
peer is a tuple containing (ipaddr, port) of the client that made the
socket connection to our smtp port.
mailfrom is the raw address the client claims the message is coming
from.
rcpttos is a list of raw addresses the client wishes to deliver the
message to.
data is a string containing the entire full text of the message,
headers (if supplied) and all. It has been `de-transparencied'
according to RFC 821, Section 4.5.2. In other words, a line
containing a `.' followed by other text has had the leading dot
removed.
This function should return None, for a normal `250 Ok' response;
otherwise it returns the desired response string in RFC 821 format.
"""
raise NotImplementedError
class DebuggingServer(SMTPServer):
# Do something with the gathered message
def process_message(self, peer, mailfrom, rcpttos, data):
inheaders = 1
lines = data.split('\n')
print '---------- MESSAGE FOLLOWS ----------'
for line in lines:
# headers first
if inheaders and not line:
print 'X-Peer:', peer[0]
inheaders = 0
print line
print '------------ END MESSAGE ------------'
class PureProxy(SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
lines = data.split('\n')
# Look for the last header
i = 0
for line in lines:
if not line:
break
i += 1
lines.insert(i, 'X-Peer: %s' % peer[0])
data = NEWLINE.join(lines)
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got some refusals:', refused
def _deliver(self, mailfrom, rcpttos, data):
import smtplib
refused = {}
try:
s = smtplib.SMTP()
s.connect(self._remoteaddr[0], self._remoteaddr[1])
try:
refused = s.sendmail(mailfrom, rcpttos, data)
finally:
s.quit()
except smtplib.SMTPRecipientsRefused, e:
print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
refused = e.recipients
except (socket.error, smtplib.SMTPException), e:
print >> DEBUGSTREAM, 'got', e.__class__
# All recipients were refused. If the exception had an associated
# error code, use it. Otherwise,fake it with a non-triggering
# exception code.
errcode = getattr(e, 'smtp_code', -1)
errmsg = getattr(e, 'smtp_error', 'ignore')
for r in rcpttos:
refused[r] = (errcode, errmsg)
return refused
class MailmanProxy(PureProxy):
def process_message(self, peer, mailfrom, rcpttos, data):
from cStringIO import StringIO
from Mailman import Utils
from Mailman import Message
from Mailman import MailList
# If the message is to a Mailman mailing list, then we'll invoke the
# Mailman script directly, without going through the real smtpd.
# Otherwise we'll forward it to the local proxy for disposition.
listnames = []
for rcpt in rcpttos:
local = rcpt.lower().split('@')[0]
# We allow the following variations on the theme
# listname
# listname-admin
# listname-owner
# listname-request
# listname-join
# listname-leave
parts = local.split('-')
if len(parts) > 2:
continue
listname = parts[0]
if len(parts) == 2:
command = parts[1]
else:
command = ''
if not Utils.list_exists(listname) or command not in (
'', 'admin', 'owner', 'request', 'join', 'leave'):
continue
listnames.append((rcpt, listname, command))
# Remove all list recipients from rcpttos and forward what we're not
# going to take care of ourselves. Linear removal should be fine
# since we don't expect a large number of recipients.
for rcpt, listname, command in listnames:
rcpttos.remove(rcpt)
# If there's any non-list destined recipients left,
print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
if rcpttos:
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got refusals:', refused
# Now deliver directly to the list commands
mlists = {}
s = StringIO(data)
msg = Message.Message(s)
# These headers are required for the proper execution of Mailman. All
# MTAs in existence seem to add these if the original message doesn't
# have them.
if not msg.getheader('from'):
msg['From'] = mailfrom
if not msg.getheader('date'):
msg['Date'] = time.ctime(time.time())
for rcpt, listname, command in listnames:
print >> DEBUGSTREAM, 'sending message to', rcpt
mlist = mlists.get(listname)
if not mlist:
mlist = MailList.MailList(listname, lock=0)
mlists[listname] = mlist
# dispatch on the type of command
if command == '':
# post
msg.Enqueue(mlist, tolist=1)
elif command == 'admin':
msg.Enqueue(mlist, toadmin=1)
elif command == 'owner':
msg.Enqueue(mlist, toowner=1)
elif command == 'request':
msg.Enqueue(mlist, torequest=1)
elif command in ('join', 'leave'):
# TBD: this is a hack!
if command == 'join':
msg['Subject'] = 'subscribe'
else:
msg['Subject'] = 'unsubscribe'
msg.Enqueue(mlist, torequest=1)
class Options:
setuid = 1
classname = 'PureProxy'
def parseargs():
global DEBUGSTREAM
try:
opts, args = getopt.getopt(
sys.argv[1:], 'nVhc:d',
['class=', 'nosetuid', 'version', 'help', 'debug'])
except getopt.error, e:
usage(1, e)
options = Options()
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-V', '--version'):
print >> sys.stderr, __version__
sys.exit(0)
elif opt in ('-n', '--nosetuid'):
options.setuid = 0
elif opt in ('-c', '--class'):
options.classname = arg
elif opt in ('-d', '--debug'):
DEBUGSTREAM = sys.stderr
# parse the rest of the arguments
if len(args) < 1:
localspec = 'localhost:8025'
remotespec = 'localhost:25'
elif len(args) < 2:
localspec = args[0]
remotespec = 'localhost:25'
elif len(args) < 3:
localspec = args[0]
remotespec = args[1]
else:
usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))
# split into host/port pairs
i = localspec.find(':')
if i < 0:
usage(1, 'Bad local spec: %s' % localspec)
options.localhost = localspec[:i]
try:
options.localport = int(localspec[i+1:])
except ValueError:
usage(1, 'Bad local port: %s' % localspec)
i = remotespec.find(':')
if i < 0:
usage(1, 'Bad remote spec: %s' % remotespec)
options.remotehost = remotespec[:i]
try:
options.remoteport = int(remotespec[i+1:])
except ValueError:
usage(1, 'Bad remote port: %s' % remotespec)
return options
if __name__ == '__main__':
options = parseargs()
# Become nobody
classname = options.classname
if "." in classname:
lastdot = classname.rfind(".")
mod = __import__(classname[:lastdot], globals(), locals(), [""])
classname = classname[lastdot+1:]
else:
import __main__ as mod
class_ = getattr(mod, classname)
proxy = class_((options.localhost, options.localport),
(options.remotehost, options.remoteport))
if options.setuid:
try:
import pwd
except ImportError:
print >> sys.stderr, \
'Cannot import module "pwd"; try running with -n option.'
sys.exit(1)
nobody = pwd.getpwnam('nobody')[2]
try:
os.setuid(nobody)
except OSError, e:
if e.errno != errno.EPERM: raise
print >> sys.stderr, \
'Cannot setuid "nobody"; try running with -n option.'
sys.exit(1)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
| [
"zhwwan@gmail.com"
] | zhwwan@gmail.com |
9ae792dadad9708bebb2a5b638f454ccdb0d368b | ab658edbc4f57631185e902bd6cfb68ff10ee020 | /test/server.py | 67aa7b051ce46a191ef718a69d1759ed72546a66 | [
"Apache-2.0"
] | permissive | bigfix/make-prefetch | 4813b8b3db2eb7317440605f4e2932011a8335b4 | 92bfc41a211867508100701f9147b1c1316a669a | refs/heads/master | 2021-01-17T07:05:11.654121 | 2015-11-21T23:25:42 | 2015-11-21T23:25:42 | 17,999,741 | 16 | 11 | Apache-2.0 | 2020-04-11T03:38:33 | 2014-03-22T01:53:36 | Python | UTF-8 | Python | false | false | 664 | py | # This is an HTTP server to respond with 'hodor' to every request. It exists so
# that we can test make-prefetch with different URLs.
import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class HodorHandler(SimpleHTTPRequestHandler):
def do_GET(self):
hodor = 'hodor'
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(hodor)))
self.end_headers()
self.wfile.write(hodor);
self.wfile.close();
return hodor
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('127.0.0.1', 36465), HodorHandler)
httpd.serve_forever()
| [
"briangreenery@gmail.com"
] | briangreenery@gmail.com |
9ff92f262acd0a724cada0eb5e89d9586c474c8d | 394980dffca738f90056550109a4985272430d4d | /app/apis/dbchatter.py | ad2aa20828ea8beceba887d9a040f4f93006e21c | [] | no_license | themailman05/PlaytRate | a068c20444b2baf2269539c9f5f1521f8e89d5e5 | f13d8a9e5e58fa3f1685964f38c7123bca04b7dd | refs/heads/master | 2021-01-21T00:45:32.811105 | 2015-02-23T19:20:59 | 2015-02-23T19:20:59 | 30,440,919 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 854 | py | __author__ = 'liam'
from app import db, models
from sqlalchemy import func
from random import randint
def getTwitterBall(yelpid):
res = models.TwitterBall.query.filter_by(yelpid=yelpid).first()
return res
def getTwitterBallById(id):
res = models.TwitterBall.query.filter_by(id=id).first()
return res
def BallExists(yelpid):
if models.TwitterBall.query.filter_by(yelpid=yelpid).first():
return True
else:
return False
def getNumRows():
rows = db.session.query(models.TwitterBall).count()
return rows
def getRecentEntries(numresults):
entries = getNumRows()
results = set()
for ii in range(entries,entries-numresults,-1):
ball = getTwitterBallById(ii)
results.add(ball)
return results
def main():
print getRecentEntries(5)
if __name__ == "__main__":
main() | [
"themailman05@gmail.com"
] | themailman05@gmail.com |
849420b2a6a39d99fe4c4183abad7cd79874b754 | bc989cab92b0c2edea23f01a123928c897ed1e8c | /AutoML_Web/_app/migrations/0002_customize_auto_search_result.py | f1501dee406dbcc40d07d09f7d7baf7a43970c20 | [] | no_license | dercaft/PCL_AutoML_System | 8a529d434679eabe18fb429d46bdf676c4f23d5b | 39c96bd22947b82a1cbb8a1d13c9e3770ca60fc7 | refs/heads/master | 2023-06-25T02:01:37.921267 | 2021-07-30T13:39:11 | 2021-07-30T13:39:11 | 301,154,625 | 1 | 0 | null | 2020-11-10T03:00:28 | 2020-10-04T14:54:51 | JavaScript | UTF-8 | Python | false | false | 410 | py | # Generated by Django 3.1.2 on 2021-07-22 15:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='customize_auto_search',
name='result',
field=models.CharField(default='./result.txt', max_length=512),
),
]
| [
"wuyuhang2073@gmail.com"
] | wuyuhang2073@gmail.com |
98ce853f8b3869397a10ff8b9bf030bba94d59b7 | 45a3e1f7c069945cfa0ecf8b36569de27d8d9599 | /auctions/migrations/0013_auto_20210309_1115.py | 597280645a49ea5dc69c4ab4533ecedb091fca20 | [] | no_license | Parker-Sullins/commerce | 8d53a3ac82cd88826186d39b31f3648ae53546b7 | 72c6f3a8fee052cab3323e2b2e26bd4980cc469a | refs/heads/master | 2023-03-20T07:05:43.181011 | 2021-03-10T03:23:56 | 2021-03-10T03:23:56 | 342,736,958 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 785 | py | # Generated by Django 3.1.7 on 2021-03-09 17:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auctions', '0012_auto_20210309_1102'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='listing_id',
),
migrations.AddField(
model_name='comment',
name='listing',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='auctions.listing'),
),
migrations.AlterField(
model_name='comment',
name='comment_content',
field=models.CharField(max_length=150),
),
]
| [
"parker.rsullins@gmail.com"
] | parker.rsullins@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.