blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
494dae4a3988c4df9e2050a66813f04888212319 | 81c27135219230d6329e3154711ebcf121df6158 | /Old/lesson12/poissonblending.py | ed8ec4ac22eaa46308534ed23b0848ffe2c8b662 | [
"MIT"
] | permissive | jsjtxietian/Computational-Photography | 021ebda89d5cbf3e178dbe8b7d393cf2f577d99d | f3b9e772da174b49efc2a46e1e73be276950759d | refs/heads/master | 2020-06-16T17:31:26.654834 | 2020-03-13T05:08:51 | 2020-03-13T05:08:51 | 195,651,346 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,771 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import scipy.sparse
import PIL.Image
import pyamg
# pre-process the mask array so that uint64 types from opencv.imread can be adapted
def prepare_mask(mask):
if type(mask[0][0]) is np.ndarray:
result = np.ndarray((mask.shape[0], mask.shape[1]), dtype=np.uint8)
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
if sum(mask[i][j]) > 0:
result[i][j] = 1
else:
result[i][j] = 0
mask = result
return mask
def blend(img_target, img_source, img_mask, offset=(0, 0)):
# compute regions to be blended
region_source = (
max(-offset[0], 0),
max(-offset[1], 0),
min(img_target.shape[0]-offset[0], img_source.shape[0]),
min(img_target.shape[1]-offset[1], img_source.shape[1]))
region_target = (
max(offset[0], 0),
max(offset[1], 0),
min(img_target.shape[0], img_source.shape[0]+offset[0]),
min(img_target.shape[1], img_source.shape[1]+offset[1]))
region_size = (region_source[2]-region_source[0], region_source[3]-region_source[1])
# clip and normalize mask image
img_mask = img_mask[region_source[0]:region_source[2], region_source[1]:region_source[3]]
img_mask = prepare_mask(img_mask)
img_mask[img_mask==0] = False
img_mask[img_mask!=False] = True
# create coefficient matrix
A = scipy.sparse.identity(np.prod(region_size), format='lil')
for y in range(region_size[0]):
for x in range(region_size[1]):
if img_mask[y,x]:
index = x+y*region_size[1]
A[index, index] = 4
if index+1 < np.prod(region_size):
A[index, index+1] = -1
if index-1 >= 0:
A[index, index-1] = -1
if index+region_size[1] < np.prod(region_size):
A[index, index+region_size[1]] = -1
if index-region_size[1] >= 0:
A[index, index-region_size[1]] = -1
A = A.tocsr()
# create poisson matrix for b
P = pyamg.gallery.poisson(img_mask.shape)
# for each layer (ex. RGB)
for num_layer in range(img_target.shape[2]):
# get subimages
t = img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer]
s = img_source[region_source[0]:region_source[2], region_source[1]:region_source[3],num_layer]
t = t.flatten()
s = s.flatten()
# create b
b = P * s
for y in range(region_size[0]):
for x in range(region_size[1]):
if not img_mask[y,x]:
index = x+y*region_size[1]
b[index] = t[index]
# solve Ax = b
x = pyamg.solve(A,b,verb=False,tol=1e-10)
# assign x to target image
x = np.reshape(x, region_size)
x[x>255] = 255
x[x<0] = 0
x = np.array(x, img_target.dtype)
img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer] = x
return img_target
def test():
img_mask = np.asarray(PIL.Image.open('./testimages/test1_mask.png'))
img_mask.flags.writeable = True
img_source = np.asarray(PIL.Image.open('./testimages/test1_src.png'))
img_source.flags.writeable = True
img_target = np.asarray(PIL.Image.open('./testimages/test1_target.png'))
img_target.flags.writeable = True
img_ret = blend(img_target, img_source, img_mask, offset=(40,-30))
img_ret = PIL.Image.fromarray(np.uint8(img_ret))
img_ret.save('./testimages/test1_ret.png')
if __name__ == '__main__':
test()
| [
"jsjtxietian@outlook.com"
] | jsjtxietian@outlook.com |
34c75ed85b11695edf53feaa3236244bd3fefc44 | ac5e52a3fc52dde58d208746cddabef2e378119e | /exps-sblp-obt/sblp_ut=3.5_rd=1_rw=0.06_rn=4_u=0.075-0.325_p=harmonic-2/sched=RUN_trial=4/params.py | f2962918ddc7d0f6fada37b1a1592dedf23cce8d | [] | no_license | ricardobtxr/experiment-scripts | 1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1 | 7bcebff7ac2f2822423f211f1162cd017a18babb | refs/heads/master | 2023-04-09T02:37:41.466794 | 2021-04-25T03:27:16 | 2021-04-25T03:27:16 | 358,926,457 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 247 | py | {'cpus': 4,
'duration': 30,
'final_util': '3.668690',
'max_util': '3.5',
'periods': 'harmonic-2',
'release_master': False,
'res_distr': '1',
'res_nmb': '4',
'res_weight': '0.06',
'scheduler': 'RUN',
'trial': 4,
'utils': 'uni-medium-3'}
| [
"ricardo.btxr@gmail.com"
] | ricardo.btxr@gmail.com |
31476fc290a0b30f6609e362098fdcb213ef2fcf | 510a39b432b5f197b05545de6436c99cd6c8e93b | /HW11.py | e16a797654c6eb0ffccbae4bdd507e5d4df96aea | [] | no_license | bolanderc/MAE5510TA | fe7cb34805325f128e9e0a499186befc9fc8eb7a | ade01f6105fc82bedca501389098057d5c64e184 | refs/heads/master | 2020-04-26T06:48:00.171110 | 2019-04-09T17:11:04 | 2019-04-09T17:11:04 | 173,376,702 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,638 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 10:09:58 2019
@author: christian
"""
import numpy as np
import scipy.linalg
from eig_vec_norm import normalize_evec
import warnings
warnings.filterwarnings('ignore')
def matprint(mat, fmt="g"):
col_maxes = [max([len(("{:"+fmt+"}").format(x)) for x in col]) for col in mat.T]
for x in mat:
for i, y in enumerate(x):
print(("{:"+str(col_maxes[i])+fmt+"}").format(y), end=" ")
print("")
def HW8_3():
rho = 0.0023769
g = 32.17
theta_o = 0.0
Sw = 185
bw = 33
W = 2800
Vo = 180
CDo = 0.05
Ixxb = 1000
Iyyb = 3000
Izzb = 3500
Ixzb = 30
CLa = 4.4
CDa = 0.35
Cma = -0.68
CLahat = 1.6
Cmahat = -4.35
CYb = -0.56
Clb = -0.075
Cnb = 0.07
CDq = 0.
CLq = 3.8
Cmq = -9.95
CYp = 0.
Clp = -0.410
Cnp = -0.0575
CYr = 0.24
Clr = 0.105
Cnr = -0.125
W_g = W/g
cw = Sw/bw
Cg = rho*Sw*cw/(4*W_g)
Cy = rho*Sw*cw*cw*cw/(8.*Iyyb)
Rgx = g*cw/(2.*Vo*Vo)
CLo = W*np.cos(theta_o)/(0.5*rho*Vo*Vo*Sw)
Rzahat = Cg*-CLahat
Rmahat = Cy*Cmahat
Rxmu = Cg*2.*-CDo
Rzmu = -Cg*2.*CLo
Rmmu = 0.0
Rxa = Cg*(CLo - CDa)
Rza = Cg*(-CLa - CDo)
Rma = Cy*Cma
Rxq = -Cg*CDq
Rzq = -Cg*CLq
Rmq = Cy*Cmq
Ct = np.cos(theta_o)
St = np.sin(theta_o)
A = np.array([[Rxmu, Rxa, Rxq, 0., 0., -Rgx*Ct],
[Rzmu, Rza, (1 + Rzq), 0., 0., -Rgx*St],
[Rmmu, Rma, Rmq, 0., 0., 0.],
[Ct, St, 0., 0., 0., -St],
[-St, Ct, 0., 0., 0., -Ct],
[0., 0., 1., 0., 0., 0.]])
B = np.array([[1., 0., 0., 0., 0., 0.],
[0., (1. - Rzahat), 0., 0., 0., 0.],
[0., -Rmahat, 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])
eigvals, eigvecs = scipy.linalg.eig(A, B)
eigv_norm = normalize_evec(eigvecs)
for i in range(len(eigvecs)):
print('eig_' + str(i + 1) + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
print('vec = (%7.6f + %7.6fj)' % (eigvecs[0, i].real,
eigvecs[0, i].imag))
print(' (%7.6f + %7.6fj)' % (eigvecs[1, i].real,
eigvecs[1, i].imag))
print(' (%7.6f + %7.6fj)' % (eigvecs[2, i].real,
eigvecs[2, i].imag))
print(' (%7.6f + %7.6fj)' % (eigvecs[3, i].real,
eigvecs[3, i].imag))
print(' (%7.6f + %7.6fj)' % (eigvecs[4, i].real,
eigvecs[4, i].imag))
print(' (%7.6f + %7.6fj)' % (eigvecs[5, i].real,
eigvecs[5, i].imag))
print('vec_norm = (%7.6f + %7.6fj)' % (eigv_norm[i, 0].real,
eigv_norm[i, 0].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 1].real,
eigv_norm[i, 1].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 2].real,
eigv_norm[i, 2].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 3].real,
eigv_norm[i, 3].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 4].real,
eigv_norm[i, 4].imag))
print(' (%7.6f + %7.6fj)\n' % (eigv_norm[i, 5].real,
eigv_norm[i, 5].imag))
def HW8_4():
Ct = np.cos(0.)
St = np.sin(0.)
cw = 28.
Vo = 660.
Rgx = 0.00103
Rxmuhat = 0.
Rzmuhat = 0.
Rmmuhat = 0.
Rxahat = 0.
Rzahat = -0.00239
Rmahat = -0.00201
Rxmu = -0.000206
Rzmu = -0.00288
Rmmu = 0.
Rxa = 0.000354
Rza = -0.00960
Rma = -0.000512
Rxq = 0.
Rzq = -0.0102
Rmq = -0.00857
A = np.array([[Rxmu, Rxa, Rxq, 0., 0., -Rgx*Ct],
[Rzmu, Rza, (1 + Rzq), 0., 0., -Rgx*St],
[Rmmu, Rma, Rmq, 0., 0., 0.],
[Ct, St, 0., 0., 0., -St],
[-St, Ct, 0., 0., 0., -Ct],
[0., 0., 1., 0., 0., 0.]])
B = np.array([[1., 0., 0., 0., 0., 0.],
[0., (1. - Rzahat), 0., 0., 0., 0.],
[0., -Rmahat, 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])
eigvals, eigvecs = scipy.linalg.eig(A, B)
eigv_norm = normalize_evec(eigvecs)
sp = np.argmax(np.absolute(eigvals))
for i in range(len(eigvals)):
if eigvals[i].real == 0.0 and eigvals[i].imag == 0.0:
print("Rigid-body Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
elif np.round(eigvals[i].real, decimals=6) == np.round(eigvals[sp].real, decimals=6):
print("Short-period Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
dampingtime = np.log(0.01)*cw/(eigvals[i].real*2.*Vo)
period = 2.*np.pi*cw/(np.abs(eigvals[i].imag)*2.*Vo)
print("99 %% damping time = %3.2f sec" % (dampingtime))
print("period = %3.2f sec" % (period))
else:
print("Long-period (Phugoid) Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
dampingtime = np.log(0.01)*cw/(eigvals[i].real*2.*Vo)
period = 2.*np.pi*cw/(np.abs(eigvals[i].imag)*2.*Vo)
print("99 %% damping time = %3.2f sec" % (dampingtime))
print("period = %3.2f sec" % (period))
print(u"\u03C7" + ' = (%7.6f + %7.6fj)' % (eigv_norm[i, 0].real,
eigv_norm[i, 0].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 1].real,
eigv_norm[i, 1].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 2].real,
eigv_norm[i, 2].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 3].real,
eigv_norm[i, 3].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 4].real,
eigv_norm[i, 4].imag))
print(' (%7.6f + %7.6fj)\n' % (eigv_norm[i, 5].real,
eigv_norm[i, 5].imag))
def HW9_1():
Sw = 5500
bw = 196
cw = 28
xbw = 0.
W = 636600
CLa = 5.5
CLwa = 4.67
Sh = 1300
xbh = -100
lwt = 55
CLha = 3.5
Cma = -1.26
rho = 0.00089068
Vo = 660
M = 0.663
CLw = 0.597
RAw = 6.98
Klp = 0.79
RTw = 0.286
Sv = 875
xbv = -96
zbv = -23
CLvB = 3.3
CYB = -0.89
ClB = -0.144
CnB = 0.182
Ixxb = 1.836e7
Izzb = 4.954e7
Ixzb = 7.33e5
etav = 1.
g = 32.2
theta_o = 0.
CYp = 0
Clp = -Klp*CLwa/8
Cnp = -(1. - 3.*Klp*CLwa/(np.pi*RAw))*CLw/8.
CYr = -etav*2.*Sv*xbv*CLvB/(Sw*bw)
Clr = (1. - 3.*Klp*CLwa/(np.pi*RAw))*CLw/4. + etav*2.*Sv*xbv*zbv*CLvB/(Sw*bw*bw)
Cnr = -etav*2.*Sv*xbv*xbv*CLvB/(Sw*bw*bw)
ixz = Ixzb/Ixxb
izx = Ixzb/Izzb
Rgy = g*bw/(2.*Vo*Vo)
Cm = rho*Sw*bw/(4.*W/g)
Cx = rho*Sw*bw*bw*bw/(8.*Ixxb)
Cz = rho*Sw*bw*bw*bw/(8.*Izzb)
RyB = Cm*CYB
RlB = Cx*ClB
RnB = Cz*CnB
Ryp = Cm*CYp
Rlp = Cx*Clp
Rnp = Cz*Cnp
Ryr = Cm*CYr
Rlr = Cx*Clr
Rnr = Cz*Cnr
A = np.array([[RyB, Ryp, (Ryr - 1), 0., Rgy*np.cos(theta_o), 0.,],
[RlB, Rlp, Rlr, 0., 0., 0.,],
[RnB, Rnp, Rnr, 0., 0., 0.,],
[1., 0., 0., 0., 0., np.cos(theta_o)],
[0., 1., np.tan(theta_o), 0., 0., 0.],
[0., 0., (1./np.cos(theta_o)), 0., 0., 0.]])
B = np.array([[1., 0., 0., 0., 0., 0.],
[0., 1., -ixz, 0., 0., 0.],
[0., -izx, 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])
eigvals, eigvecs = scipy.linalg.eig(A, B)
matprint(B)
eigv_norm = normalize_evec(eigvecs)
sp = np.argmax(abs(eigvals.real))
rigid = []
dutch = []
for i in range(len(eigvals)):
if eigvals[i].real == 0.0 and eigvals[i].imag == 0.0:
rigid.append(i)
elif eigvals[i].imag != 0.0:
dutch.append(i)
elif np.round(eigvals[i].real, decimals=6) == np.round(eigvals[sp].real, decimals=6):
roll = i
else:
spiral = i
for i in range(len(eigvals)):
if i in rigid:
print("Rigid-body Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
elif i == roll:
print("Roll Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[roll]*eigvals[spiral])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[roll] + eigvals[spiral])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
elif i in dutch:
print("Dutch Roll Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[dutch[0]]*eigvals[dutch[1]])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wd = 2.*Vo*np.abs(eigvals[i].imag)/bw
period = 2.*np.pi/wd
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[dutch[0]] + eigvals[dutch[1]])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_d" + " = %7.6f rad/sec" % wd)
print("period = %7.6f" % period)
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
else:
print("Spiral Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[roll]*eigvals[spiral])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[roll] + eigvals[spiral])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
print(u"\u03C7" + ' = (%7.6f + %7.6fj)' % (eigv_norm[i, 0].real,
eigv_norm[i, 0].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 1].real,
eigv_norm[i, 1].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 2].real,
eigv_norm[i, 2].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 3].real,
eigv_norm[i, 3].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 4].real,
eigv_norm[i, 4].imag))
print(' (%7.6f + %7.6fj)\n' % (eigv_norm[i, 5].real,
eigv_norm[i, 5].imag))
rollamp = np.absolute(eigv_norm[roll, :])
spiralamp = np.absolute(eigv_norm[spiral, :])
dutchamp = np.absolute(eigv_norm[dutch[0], :])
dutchphase = np.arctan2(eigv_norm[dutch[0], :].imag, eigv_norm[dutch[0], :].real)*180/np.pi
print('Eigenvector\tRoll Mode\tSpiral Mode\t\tDutch Roll')
print('Component\tAmplitude\tAmplitude\tAmplitude\tPhase')
print('----------------------------------------------------------------------')
symbols = [u"\u0392", "p", "r", u"\u03BEy", u"\u03D5", u"\u03C8"]
for i in range(len(rollamp)):
print(' ' + u"\u0394" + '%s\t\t%7.6f\t%7.6f\t%7.6f %4.2f\u00B0' % (symbols[i],
rollamp[i],
spiralamp[i],
dutchamp[i],
dutchphase[i]))
def HWEx9_2_1():
Sw = 185
bw = 33
W = 2800
Vo = 180
CDo = 0.05
Ixxb = 1000
Iyyb = 3000
Izzb = 3500
Ixzb = 30
CLa = 4.4
CDa = 0.35
Cma = -0.68
CLahat = 1.6
Cmahat = -4.35
CYb = -0.56
Clb = -0.075
Cnb = 0.07
CDq = 0.
CLq = 3.8
Cmq = -9.95
CYp = 0.
Clp = -0.41
Cnp = -0.0575
CYr = 0.24
Clr = 0.105
Cnr = -0.125
ixz = Ixzb/Ixxb
izx = Ixzb/Izzb
Cm = 0.041679
Cx = 1.975306
Cz = 0.564373
RyB = Cm*CYb
RlB = Cx*Clb
RnB = Cz*Cnb
Ryp = Cm*CYp
Rlp = Cx*Clp
Rnp = Cz*Cnp
Ryr = Cm*CYr
Rlr = Cx*Clr
Rnr = Cz*Cnr
Rgy = 0.0164
theta_o = 0.0
A = np.array([[RyB, Ryp, (Ryr - 1), 0., Rgy*np.cos(theta_o), 0.,],
[RlB, Rlp, Rlr, 0., 0., 0.,],
[RnB, Rnp, Rnr, 0., 0., 0.,],
[1., 0., 0., 0., 0., np.cos(theta_o)],
[0., 1., np.tan(theta_o), 0., 0., 0.],
[0., 0., (1./np.cos(theta_o)), 0., 0., 0.]])
B = np.array([[1., 0., 0., 0., 0., 0.],
[0., 1., -ixz, 0., 0., 0.],
[0., -izx, 1., 0., 0., 0.],
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]])
eigvals, eigvecs = scipy.linalg.eig(A, B)
eigv_norm = normalize_evec(eigvecs)
sp = np.argmax(abs(eigvals.real))
rigid = []
dutch = []
for i in range(len(eigvals)):
if eigvals[i].real == 0.0 and eigvals[i].imag == 0.0:
rigid.append(i)
elif eigvals[i].imag != 0.0:
dutch.append(i)
elif np.round(eigvals[i].real, decimals=6) == np.round(eigvals[sp].real, decimals=6):
roll = i
else:
spiral = i
for i in range(len(eigvals)):
if i in rigid:
print("Rigid-body Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
elif i == roll:
print("Roll Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[roll]*eigvals[spiral])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[roll] + eigvals[spiral])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
elif i in dutch:
print("Dutch Roll Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[dutch[0]]*eigvals[dutch[1]])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wd = 2.*Vo*np.abs(eigvals[i].imag)/bw
period = 2.*np.pi/wd
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[dutch[0]] + eigvals[dutch[1]])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_d" + " = %7.6f rad/sec" % wd)
print("period = %7.6f" % period)
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
else:
print("Spiral Mode")
print("----------------")
print(u"\u03BB" + ' = (%7.6f + %7.6fj)' % (eigvals[i].real,
eigvals[i].imag))
sqrtmult = np.sqrt(eigvals[roll]*eigvals[spiral])
sigma = -eigvals[i].real*2.*Vo/bw
dampingtime = np.log(0.01)/-sigma
wn = 2.*Vo*sqrtmult/bw
damp_ratio = -1.*(eigvals[roll] + eigvals[spiral])/(2.*sqrtmult)
print(u"\u03C3" + " = %7.6f sec^-1" % (sigma))
print("99 %% damping time = %3.2f sec" % (dampingtime))
print(u"\u03C9_n" + " = %7.6f rad/sec" % wn)
print(u"\u03B6" + " = %7.6f" % damp_ratio)
print(u"\u03C7" + ' = (%7.6f + %7.6fj)' % (eigv_norm[i, 0].real,
eigv_norm[i, 0].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 1].real,
eigv_norm[i, 1].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 2].real,
eigv_norm[i, 2].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 3].real,
eigv_norm[i, 3].imag))
print(' (%7.6f + %7.6fj)' % (eigv_norm[i, 4].real,
eigv_norm[i, 4].imag))
print(' (%7.6f + %7.6fj)\n' % (eigv_norm[i, 5].real,
eigv_norm[i, 5].imag))
rollamp = np.absolute(eigv_norm[roll, :])
spiralamp = np.absolute(eigv_norm[spiral, :])
dutchamp = np.absolute(eigv_norm[dutch[0], :])
dutchphase = np.arctan2(eigv_norm[dutch[0], :].imag, eigv_norm[dutch[0], :].real)*180/np.pi
print('Eigenvector\tRoll Mode\tSpiral Mode\t\tDutch Roll')
print('Component\tAmplitude\tAmplitude\tAmplitude\tPhase')
print('----------------------------------------------------------------------')
symbols = [u"\u0392", "p", "r", u"\u03BEy", u"\u03D5", u"\u03C8"]
for i in range(len(rollamp)):
print(' ' + u"\u0394" + '%s\t\t%7.6f\t%7.6f\t%7.6f %4.2f\u00B0' % (symbols[i],
rollamp[i],
spiralamp[i],
dutchamp[i],
dutchphase[i]))
print("\n8.3 (1.0 pts)")
print("-------------------------")
HW8_3()
print("\n8.4 (3.0 pts)")
print("-------------------------")
HW8_4()
print("\n9.1 (3.0 pts)")
print("-------------------------")
HW9_1()
print("\nExample 9.2.1 (1.0 pts)")
print("-------------------------")
HWEx9_2_1()
#8.3 (/1) :
#8.4 (/3) :
#8.40 (/2) :
#9.1 (/3) :
#Ex. 9.2.1 (/1) :
#Total (/10) :
| [
"christianrbolander@gmail.com"
] | christianrbolander@gmail.com |
cb5caad5545db7b3223f337a9365ad9bfa9a4851 | 42f7dec4a971d33c533681a28c11d1e681553112 | /hst_analysis.py | 453c9e9fe4ff976651afa5561d7a184ea96350e6 | [] | no_license | ivanokhotnikov/moohst | 69e49878fbb1fde4c403f496aa4222baedfeaa23 | 3d6621a1fe776ea534f3f774b611a09140a8e9a4 | refs/heads/master | 2023-06-28T23:12:02.831837 | 2021-07-30T09:22:43 | 2021-07-30T09:22:43 | 369,152,752 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 39,190 | py | import os
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
import plotly.figure_factory as ff
from io import BytesIO
from joblib import dump, load
from hst.hst import HST
from hst.regressor import Regressor
from sklearn.model_selection import KFold, train_test_split, cross_validate
def set_defaults(analysis_type):
"""Assigns the default values of oil, its parameters and initial design parameters to initialize the HST, to plot its efficiency map and to conduct other calculations.
Paramters
---
analysis_type: str, 'sizing', 'performance', 'map' or 'comparison
A string flag defining a type of callation to customize.
"""
if analysis_type == 'sizing':
max_swash_angle = 18
pistons = 9
return max_swash_angle, pistons
if analysis_type == 'performance':
input_speed = 2160
pressure_charge = 25
pressure_discharge = 475
return input_speed, pressure_charge, pressure_discharge
if analysis_type == 'map':
max_speed = 2500
max_pressure = 500
max_power = 580
gear_ratio = 0.8
return max_speed, max_pressure, max_power, gear_ratio
if analysis_type == 'comparison':
displ_1 = 350
displ_2 = 330
speed = 2160
pressure = 475
oil_temp = 100
return displ_1, displ_2, speed, pressure, oil_temp
def fit_catalogues(data_in):
"""
Fits the custom Regressor model to the catalogue data. Each modelis cross_validated with the metrics being saved in the model's properties.
Parameters:
---
data_in: pd.DataFrame
Catalogue data
Returns:
---
models: dict
Dictionary of the fitted models. Keys: 'pump_mass', 'pump_speed', 'motor_mass', 'motor_speed'. Values: Regressor objects
"""
models = {}
if not os.path.exists('models'):
os.mkdir('models')
for machine_type in ('pump', 'motor'):
for data_type in ('speed', 'mass'):
data = data_in[data_in['type'] == f'{machine_type.capitalize()}']
model = Regressor(machine_type=machine_type, data_type=data_type)
x_full = data['displacement'].to_numpy(dtype='float64')
y_full = data[data_type].to_numpy(dtype='float64')
x_train, x_test, y_train, y_test = train_test_split(x_full,
y_full,
test_size=0.2,
random_state=0)
strat_k_fold = KFold(n_splits=5, shuffle=True, random_state=42)
cv_results = cross_validate(
model,
x_train,
y_train,
cv=strat_k_fold,
scoring=['neg_root_mean_squared_error', 'r2'],
return_estimator=True,
n_jobs=-1,
verbose=0)
model.r2_ = np.mean([k for k in cv_results['test_r2']])
model.cv_rmse_ = -np.mean(
[k for k in cv_results['test_neg_root_mean_squared_error']])
model.cv_r2std_ = np.std([k for k in cv_results['test_r2']])
model.cv_rmsestd_ = np.std(
[k for k in cv_results['test_neg_root_mean_squared_error']])
model.coefs_ = np.mean([k.coefs_ for k in cv_results['estimator']],
axis=0)
model.test_rmse_, model.test_r2_ = model.eval(x_test, y_test)
model.fitted_ = True
dump(model,
os.path.join('models', f'{machine_type}_{data_type}.joblib'))
models['_'.join((machine_type, data_type))] = model
return models
def load_catalogues(github=False):
"""
Load and returns the regression models as well as the catalogue data.
Parameters:
---
github: bool, default False
A flag to read the catalogues from the github repository if set to True and there is no local `models` folder containing fir models. If github=False and the `models` folder contains nothing, `fir_catalogues` is performed.
Returns:
---
models: dict
Dictionary of four regression models with te following keys: 'pump_mass', 'pump_speed', 'motor_mass', 'motor_speed'
data: pd.DataFrame
Catalogues data
"""
models = {}
data = pd.read_csv(
'https://raw.githubusercontent.com/ivanokhotnikov/effmap_demo/master/data/data.csv',
index_col='#')
if os.path.exists('.\\models') and len(os.listdir('.\\models')):
for file in os.listdir('.\\models'):
models[file[:-7]] = load(os.path.join(os.getcwd(), 'models', file))
elif github:
for machine_type in ('pump', 'motor'):
for data_type in ('mass', 'speed'):
link = f'https://github.com/ivanokhotnikov/effmap_demo/blob/master/models/{machine_type}_{data_type}.joblib?raw=true'
mfile = BytesIO(requests.get(link).content)
models['_'.join((machine_type, data_type))] = load(mfile)
else:
models = fit_catalogues(data)
return models, data
def plot_catalogue_data(models,
data_in,
show_figure=False,
save_figure=False,
format='pdf'):
for i in models:
model = models[i]
data_type = model.data_type
machine_type = model.machine_type
data = data_in[data_in['type'] == f'{machine_type.capitalize()}']
x = data['displacement'].to_numpy(dtype='float64')
x_cont = np.linspace(.2 * np.amin(x), 1.2 * np.amax(x), num=100)
sns.set_style('ticks', {
'spines.linewidth': .25,
})
sns.set_palette('Set1',
n_colors=len(data['manufacturer'].unique()),
desat=.9)
plot = sns.JointGrid(
x='displacement',
y=data_type,
data=data,
hue='manufacturer',
)
plot.plot_joint(sns.scatterplot, edgecolor='.2', linewidth=.5)
plot.plot_marginals(sns.kdeplot, fill=True)
if data_type == 'speed':
plot.ax_joint.set_ylabel(f'{machine_type.capitalize()} speed, rpm')
plot.ax_marg_y.set_ylim(500, 5000)
if data_type == 'mass':
plot.ax_joint.set_ylabel(f'{machine_type.capitalize()} mass, kg')
if machine_type == 'pump': plot.ax_marg_y.set_ylim(0, 700)
if machine_type == 'motor': plot.ax_marg_y.set_ylim(0, 500)
plot.ax_joint.set_xlabel(
f'{machine_type.capitalize()} displacement, cc/rev')
plot.ax_marg_x.set_xlim(0, 900)
for l in zip(('Fit + RMSE', 'Fit', 'Fit - RMSE'),
(+model.test_rmse_, 0, -model.test_rmse_),
('crimson', 'gold', 'seagreen')):
plot.ax_joint.plot(
x_cont,
model.predict(x_cont) + l[1],
color=l[2],
linestyle='--',
label=f'{l[0]}',
linewidth=1,
)
plot.ax_joint.legend()
if show_figure:
plt.show()
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
plot.savefig(f'images/{machine_type}_{data_type}.{format}')
plt.clf()
plt.close('all')
def plot_catalogue_data_plotly(models,
data_in,
show_figure=False,
save_figure=False,
format='pdf'):
for i in models:
model = models[i]
data_type = model.data_type
machine_type = model.machine_type
data = data_in[data_in['type'] == f'{machine_type.capitalize()}']
x = data['displacement'].to_numpy(dtype='float64')
x_cont = np.linspace(.2 * np.amin(x), 1.2 * np.amax(x), num=100)
fig_scatter = go.Figure()
for l in zip(('Fit + SD', 'Fit', 'Fit - SD'),
(+model.test_rmse_, 0, -model.test_rmse_),
('--r', '--y', '--g')):
fig_scatter.add_scatter(
x=x_cont,
y=model.predict(x) + l[1],
name=l[0],
color=l[2],
)
for idx, k in enumerate(data['manufacturer'].unique()):
fig_scatter.add_scatter(
x=data['displacement'][data['manufacturer'] == k],
y=data[data_type][data['manufacturer'] == k],
mode='markers',
name=k,
marker_symbol=idx,
marker=dict(size=7, line=dict(color='black', width=.5)),
)
fig_scatter.update_xaxes(
title_text=f'{machine_type.capitalize()} displacement, cc/rev',
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
range=[0, round(1.1 * max(data['displacement']), -2)],
)
fig_scatter.update_yaxes(
title_text=f'{machine_type.capitalize()} {data_type}, rpm'
if data_type == 'speed' else
f'{machine_type.capitalize()} {data_type}, kg',
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
range=[0, round(1.2 * max(data[data_type]), -2)]
if data_type == 'mass' else [
round(.7 * min(data[data_type]), -2),
round(1.2 * max(data[data_type]), -2)
],
)
fig_scatter.update_layout(
# title=f'Catalogue data for {machine_type} {data_type}',
template='none',
width=700,
height=600,
showlegend=True,
legend=dict(orientation='v',
x=.99 if data_type == 'speed' else .01,
y=1,
xanchor='right' if data_type == 'speed' else 'left',
yanchor='top'),
font=dict(size=14, color='black'),
)
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
fig_scatter.write_image(
f'images/{machine_type}_{data_type}.{format}')
if show_figure:
fig_scatter.show()
def plot_histograms(models,
data_in,
show_figure=True,
save_figure=False,
format='pdf'):
sns.set_style('ticks', {
'palette': 'Set1',
'spines.linewidth': .25,
})
for data_type in ('speed', 'mass'):
for machine_type in ('pump', 'motor'):
ind = data_in.index[data_in['type'] ==
f'{machine_type.capitalize()}']
predictions = models[f'{machine_type}_{data_type}'].predict(
data_in.loc[ind, 'displacement'])
data_in.loc[ind, f'{data_type}_residuals'] = data_in.loc[
ind, data_type] - predictions
plot_originals = sns.histplot(
data=data_in,
x=data_type,
kde=True,
hue='type',
element='step',
)
sns.despine()
plot_originals.legend_.set_title(None)
if data_type == 'speed': plt.xlabel('Speed, rpm')
if data_type == 'mass': plt.xlabel('Mass, kg')
if show_figure: plt.show()
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
plt.savefig(f'images/hist_originals_{data_type}.{format}')
plt.clf()
plot_originals.cla()
plot_residuals = sns.histplot(
data=data_in,
x=f'{data_type}_residuals',
kde=True,
hue='type',
element='step',
)
sns.despine()
plot_residuals.legend_.set_title(None)
if data_type == 'speed': plt.xlabel('Speed residual, rpm')
if data_type == 'mass': plt.xlabel('Mass residual, kg')
if show_figure: plt.show()
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
plt.savefig(f'images/hist_residuals_{data_type}.{format}')
plt.clf()
plt.close('all')
def plot_histograms_plotly(models,
data_in,
show_figure=True,
save_figure=False,
format='pdf'):
for data_type in ('speed', 'mass'):
fig_hist_original = go.Figure()
fig_hist_residuals = go.Figure()
for machine_type in ('pump', 'motor'):
fig_hist_original.add_trace(
go.Histogram(
x=data_in[data_in['type'] ==
f'{machine_type.capitalize()}']
[data_type].to_numpy(dtype='float64'),
name=f'{machine_type.capitalize()}',
xbins=dict(size=100 if data_type == 'speed' else 10),
opacity=0.75,
# histnorm='probability density',
))
fig_hist_residuals.add_trace(
go.Histogram(
x=data_in[data_in['type'] ==
f'{machine_type.capitalize()}']
[data_type].to_numpy(dtype='float64') -
models[f'{machine_type}_{data_type}'].predict(
data_in[data_in['type'] ==
f'{machine_type.capitalize()}']
['displacement'].to_numpy(dtype='float64')),
name=f'{machine_type.capitalize()}',
xbins=dict(size=100 if data_type == 'speed' else 10),
opacity=0.75,
# histnorm='probability density',
))
fig_hist_original.update_layout(
# title=f'Distribution of the original {data_type} data',
width=700,
height=600,
template='none',
barmode='overlay',
xaxis=dict(
title=f'{data_type.capitalize()}, rpm' if data_type
== 'speed' else f'{data_type.capitalize()}, kg',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
yaxis=dict(
title=f'Count',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
showlegend=True,
legend=dict(orientation='v',
x=.99,
y=1,
xanchor='right',
yanchor='top'),
font=dict(size=14, color='black'),
)
fig_hist_residuals.update_layout(
# title=f'Distribution of the residuals of the {data_type} data',
width=700,
height=600,
template='none',
barmode='overlay',
xaxis=dict(
title=f'{data_type.capitalize()} models residuals, rpm'
if data_type == 'speed' else
f'{data_type.capitalize()} models residuals, kg',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
yaxis=dict(
title=f'Frequency',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
showlegend=True,
legend=dict(orientation='v',
x=.99,
y=1,
xanchor='right',
yanchor='top'),
font=dict(size=14, color='black'),
)
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
fig_hist_original.write_image(
f'images/hist_originals_{data_type}.{format}')
fig_hist_residuals.write_image(
f'images/hist_residuals_{data_type}.{format}')
if show_figure:
fig_hist_original.show()
fig_hist_residuals.show()
def plot_distributions_plotly(models,
data_in,
show_figure=True,
save_figure=False,
format='pdf'):
for data_type in ('speed', 'mass'):
print_data_originals = []
print_data_residuals = []
for machine_type in ('pump', 'motor'):
print_data_originals.append(
data_in[data_in['type'] == f'{machine_type.capitalize()}']
[data_type].to_numpy(dtype='float64'))
print_data_residuals.append(
data_in[data_in['type'] == f'{machine_type.capitalize()}']
[data_type].to_numpy(dtype='float64') -
models[f'{machine_type}_{data_type}'].predict(
data_in[data_in['type'] == f'{machine_type.capitalize()}']
['displacement'].to_numpy(dtype='float64')))
fig_dist_originals = ff.create_distplot(
print_data_originals,
['Pump', 'Motor'],
show_hist=True,
bin_size=100 if data_type == 'speed' else 10,
show_rug=False,
)
fig_dist_originals.update_layout(
# title=f'Distribution of the original {data_type} data',
width=700,
height=600,
template='none',
xaxis=dict(
title=f'{data_type.capitalize()}, rpm'
if data_type == 'speed' else f'{data_type.capitalize()}, kg',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
linewidth=0.25,
gridwidth=0.25,
mirror='all',
),
yaxis=dict(
title=f'Probability density',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
showlegend=True,
legend=dict(orientation='v',
x=.99,
y=1,
xanchor='right',
yanchor='top'),
font=dict(size=14, color='black'))
fig_dist_residuals = ff.create_distplot(
print_data_residuals,
['Pump', 'Motor'],
show_hist=True,
bin_size=100 if data_type == 'speed' else 10,
show_rug=False,
)
fig_dist_residuals.update_layout(
# title=f'Distribution of the residuals of the {data_type} data',
width=700,
height=600,
template='none',
xaxis=dict(
title=f'{data_type.capitalize()} models residuals, rpm'
if data_type == 'speed' else
f'{data_type.capitalize()} models residuals, kg',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
yaxis=dict(
title=f'Probability density',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
),
showlegend=True,
legend=dict(orientation='v',
x=.99,
y=1,
xanchor='right',
yanchor='top'),
font=dict(size=14, color='black'))
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
fig_dist_originals.write_image(
f'images/dist_originals_{data_type}.{format}')
fig_dist_residuals.write_image(
f'images/dist_residuals_{data_type}.{format}')
if show_figure:
fig_dist_originals.show()
fig_dist_residuals.show()
def plot_validation(show_figure=False, save_figure=False, format='pdf'):
data = pd.read_csv(
'https://raw.githubusercontent.com/ivanokhotnikov/effmap_demo/master/data/test_data.csv'
)
data.dropna(
subset=['Forward Speed', 'Reverse Speed', 'Volumetric at 1780RPM'],
inplace=True)
data['Reverse Speed'] = data['Reverse Speed'].astype(np.float64)
data['Volumetric at 1780RPM'] = data['Volumetric at 1780RPM'].map(
lambda x: float(x[:-1]))
data.loc[data['Reverse Speed'] == 568.0, 'Reverse Speed'] = 1568.0
data.loc[data['Volumetric at 1780RPM'] == 60.1,
'Volumetric at 1780RPM'] = round(
(1571 / 1780 + 1568 / 1780) / 2 * 100, ndigits=1)
speeds = data[['Forward Speed', 'Reverse Speed']].astype(float)
speeds = speeds.stack()
vol_eff = speeds / 1780 * 1e2
piston_max = 1.1653 * 25.4 * 1e-3
piston_min = 1.1650 * 25.4 * 1e-3
bore_max = 1.1677 * 25.4 * 1e-3
bore_min = 1.1671 * 25.4 * 1e-3
rad_clearance_max = (bore_max - piston_min) / 2
rad_clearance_min = (bore_min - piston_max) / 2
benchmark = HST(swash=15, oil='SAE 30', oil_temp=60)
benchmark.compute_sizes(displ=196,
k1=.7155,
k2=.9017,
k3=.47,
k4=.9348,
k5=.9068)
benchmark.load_oil()
eff_min = benchmark.compute_eff(speed_pump=1780,
pressure_discharge=207,
pressure_charge=14,
h1=29e-6,
h2=29e-6,
h3=rad_clearance_max)[0]
eff_max = benchmark.compute_eff(speed_pump=1780,
pressure_discharge=207,
pressure_charge=14,
h1=29e-6,
h2=29e-6,
h3=rad_clearance_min)[0]
eff_midrange = benchmark.compute_eff(speed_pump=1780,
pressure_discharge=207,
pressure_charge=14,
h1=29e-6,
h2=29e-6,
h3=np.mean((rad_clearance_min,
rad_clearance_max)))[0]
sns.set_style('ticks', {
'spines.linewidth': .25,
})
sns.set_palette('Set1')
plot = sns.histplot(
data=vol_eff,
kde=True,
element='step',
label='Test data',
color='steelblue',
)
sns.despine()
plot.axes.axvline(
eff_max['hst']['volumetric'],
label=
f"Prediction at min clearance, {round(eff_max['hst']['volumetric'], 2)}%",
linestyle=':',
color='crimson',
linewidth=1,
)
plot.axes.axvline(
eff_min['hst']['volumetric'],
label=
f"Prediction at max clearance, {round(eff_min['hst']['volumetric'], 2)}%",
linestyle=':',
color='seagreen',
linewidth=1,
)
plot.axes.axvline(
eff_midrange['hst']['volumetric'],
label=
f"Prediction at midrange clearance, {round(eff_midrange['hst']['volumetric'], 2)}%",
linestyle=':',
color='royalblue',
linewidth=1,
)
plot.axes.axvline(
vol_eff.mean(),
label=f"Test mean, {round(vol_eff.mean(), 2)}%",
linestyle='--',
color='steelblue',
linewidth=1,
)
plot.axes.axvline(
vol_eff.mean() + vol_eff.std(),
label=f"Test mean + SD, {round(vol_eff.mean() + vol_eff.std(),2)}%",
linestyle='--',
color='darkorange',
linewidth=1,
)
plot.axes.axvline(
vol_eff.mean() - vol_eff.std(),
label=f"Test mean - SD, {round(vol_eff.mean() - vol_eff.std(),2)}%",
color='slateblue',
linestyle='--',
linewidth=1,
)
plt.xlim(86, 92)
plt.ylim(0, 90)
plt.xlabel('HST volumetric efficiency, %')
plt.legend(loc='upper right', fontsize='x-small')
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
plt.savefig(f'images/validation.{format}')
if show_figure: plt.show()
plt.clf()
plt.close('all')
def plot_validation_plotly(show_figure=False, save_figure=False, format='pdf'):
"""Performs validation of the efficiency model by computing the volumetric efficiency of the benchmark HST, for which the test data is available containing results of measurements of the input/output speeds, and comparing the computed efficiency with the test data.
"""
data = pd.read_csv(
'https://raw.githubusercontent.com/ivanokhotnikov/effmap_demo/master/data/test_data.csv'
)
data.dropna(
subset=['Forward Speed', 'Reverse Speed', 'Volumetric at 1780RPM'],
inplace=True)
speeds = data[['Forward Speed', 'Reverse Speed']].astype(float)
speeds = speeds.stack()
vol_eff = speeds / 1780 * 1e2
piston_max = 1.1653 * 25.4 * 1e-3
piston_min = 1.1650 * 25.4 * 1e-3
bore_max = 1.1677 * 25.4 * 1e-3
bore_min = 1.1671 * 25.4 * 1e-3
rad_clearance_max = (bore_max - piston_min) / 2
rad_clearance_min = (bore_min - piston_max) / 2
benchmark = HST(swash=15, oil='SAE 30', oil_temp=60)
benchmark.compute_sizes(displ=196,
k1=.7155,
k2=.9017,
k3=.47,
k4=.9348,
k5=.9068)
benchmark.load_oil()
eff_min = benchmark.compute_eff(speed_pump=1780,
pressure_discharge=207,
pressure_charge=14,
h3=rad_clearance_max)[0]
eff_max = benchmark.compute_eff(speed_pump=1780,
pressure_discharge=207,
pressure_charge=14,
h3=rad_clearance_min)[0]
fig = ff.create_distplot(
[vol_eff],
[
f"Test data. Mean = {round(vol_eff.mean(),2)}%, SD = {round(vol_eff.std(),2)}%"
],
show_hist=True,
bin_size=.3,
show_rug=False,
)
fig.add_scatter(
x=[eff_max['hst']['volumetric'], eff_max['hst']['volumetric']],
y=[0, .6],
mode='lines',
name=
f"Prediction at min clearance, {round(eff_max['hst']['volumetric'],2)}%",
line=dict(width=1.5, ),
)
fig.add_scatter(
x=[eff_min['hst']['volumetric'], eff_min['hst']['volumetric']],
y=[0, .6],
mode='lines',
name=
f"Prediction at max clearance, {round(eff_min['hst']['volumetric'],2)}%",
line=dict(width=1.5, ),
)
fig.add_scatter(
x=[vol_eff.mean(), vol_eff.mean()],
y=[0, .6],
mode='lines',
name=f"Test mean, {round(vol_eff.mean(),2)}%",
line=dict(width=1.5, dash='dash'),
)
fig.add_scatter(
x=[vol_eff.mean() + vol_eff.std(),
vol_eff.mean() + vol_eff.std()],
y=[0, .6],
mode='lines',
name='Test mean + SD',
line=dict(width=1.5, dash='dash'),
)
fig.add_scatter(
x=[vol_eff.mean() - vol_eff.std(),
vol_eff.mean() - vol_eff.std()],
y=[0, .6],
mode='lines',
name='Test mean - SD',
line=dict(width=1.5, dash='dash'),
)
fig.update_layout(
# title=
# f'Sample of {len(vol_eff)} measurements of the {benchmark.displ} cc/rev HST with {benchmark.oil} at {benchmark.oil_temp}C',
template='none',
width=1000,
height=600,
xaxis=dict(
title='HST volumetric efficiency, %',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
range=[84, 94],
dtick=2,
mirror='all',
),
yaxis=dict(
title='Probability density',
showline=True,
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
range=[0, .6],
mirror='all',
),
showlegend=True,
legend_orientation='v',
legend=dict(x=1.05, y=1, xanchor='left', yanchor='top'),
font=dict(size=14, color='black'))
if save_figure:
if not os.path.exists('images'): os.mkdir('images')
fig.write_image(f'images/validation.{format}')
if show_figure: fig.show()
def plot_hst_comparison(displ_1,
displ_2,
speed,
pressure,
temp,
show_figure=True,
save_figure=False,
format='pdf'):
"""
Prints a bar plot to compare total efficiencies of two HSTs.
Parameters:
---
displ_1, displ_2: float
Displacements of the HSTs to be comapred
speed, pressure, temp, charge: floats
Operational parameters for the comparison
"""
effs_1, effs_2 = [], []
motor_pows_1, motor_pows_2 = [], []
pump_pows_1, pump_pows_2 = [], []
oils = ('SAE 15W40', 'SAE 10W40', 'SAE 10W60', 'SAE 5W40', 'SAE 0W30',
'SAE 30')
hst_1, hst_2 = HST(oil_temp=temp), HST(oil_temp=temp)
hst_1.compute_sizes(displ_1)
hst_2.compute_sizes(displ_2)
for oil in oils:
hst_1.oil, hst_2.oil = oil, oil
hst_1.load_oil()
hst_2.load_oil()
eff_1 = hst_1.compute_eff(speed, pressure)[0]
eff_2 = hst_2.compute_eff(speed, pressure)[0]
effs_1.append(eff_1['hst']['total'])
effs_2.append(eff_2['hst']['total'])
motor_pows_1.append(hst_1.performance['motor']['power'])
motor_pows_2.append(hst_2.performance['motor']['power'])
pump_pows_1.append(hst_1.performance['pump']['power'])
pump_pows_2.append(hst_2.performance['pump']['power'])
fig_eff = go.Figure()
fig_eff.add_trace(
go.Bar(
x=oils,
y=effs_1,
text=[f'{eff:.2f}' for eff in effs_1],
textposition='auto',
name=f'{displ_1} cc/rev',
marker_color='steelblue',
))
fig_eff.add_trace(
go.Bar(x=oils,
y=effs_2,
text=[f'{eff:.2f}' for eff in effs_2],
textposition='auto',
name=f'{displ_2} cc/rev',
marker_color='indianred'))
fig_eff.update_layout(
# title=
# f'Total efficiency of {displ_1} and {displ_2} cc/rev HSTs at {speed} rpm, {pressure} bar, {temp}C oil',
yaxis=dict(
title='Total HST efficiency, %',
range=[50, 90],
),
template='none',
showlegend=True,
legend_orientation='h',
width=800,
height=500,
font=dict(size=14),
)
fig_pow = go.Figure()
fig_pow.add_trace(
go.Bar(
x=oils,
y=pump_pows_1,
text=[f'{pow:.2f}' for pow in pump_pows_1],
textposition='auto',
name=f'{displ_1} cc/rev in',
marker_color='steelblue',
))
fig_pow.add_trace(
go.Bar(
x=oils,
y=motor_pows_1,
text=[f'{pow:.2f}' for pow in motor_pows_1],
textposition='auto',
name=f'{displ_1} cc/rev out',
marker_color='lightblue',
))
fig_pow.add_trace(
go.Bar(
x=oils,
y=pump_pows_2,
text=[f'{pow:.2f}' for pow in pump_pows_2],
textposition='auto',
name=f'{displ_2} cc/rev in',
marker_color='indianred',
))
fig_pow.add_trace(
go.Bar(x=oils,
y=motor_pows_2,
text=[f'{pow:.2f}' for pow in motor_pows_2],
textposition='auto',
name=f'{displ_2} cc/rev out',
marker_color='pink'))
fig_pow.update_layout(
# title=
# f'Power balance of {displ_1} and {displ_2} cc/rev HSTs at {speed} rpm, {pressure} bar, {temp}C oil',
yaxis=dict(title='Power, kW', ),
template='none',
showlegend=True,
legend_orientation='h',
width=900,
height=600,
font=dict(size=14, color='black'),
)
if save_figure:
if not os.path.exists('images'):
os.mkdir('images')
fig_eff.write_image(f'images/hst_eff_comparison.{format}')
fig_pow.write_image(f'images/hst_power_comparison.{format}')
if show_figure:
fig_eff.show()
fig_pow.show()
def plot_engines_comparison(hst1,
hst4,
show_figure=True,
save_figure=False,
format='pdf'):
engine_1 = hst1.load_engines()['engine_1']
engine_4 = hst4.load_engines()['engine_4']
fig_comparison = go.Figure()
fig_comparison.add_scatter(
x=engine_4['speed'],
y=engine_4['torque'],
name='Engine 4',
mode='lines+markers',
marker=dict(size=3),
line=dict(color='indianred', width=1.5),
)
fig_comparison.add_scatter(
x=engine_1['speed'],
y=engine_1['torque'],
name='Engine 1',
mode='lines+markers',
marker=dict(size=3),
line=dict(color='steelblue', width=1.5),
)
fig_comparison.update_xaxes(
title_text=f'Engine speed, rpm',
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
)
fig_comparison.update_yaxes(
title_text=f'Engine torque, Nm',
linecolor='black',
showgrid=True,
gridcolor='LightGray',
gridwidth=0.25,
linewidth=0.25,
mirror='all',
)
fig_comparison.update_layout(
# title=f'Engines comparison',
template='none',
width=900,
height=600,
showlegend=True,
font=dict(size=14, color='black'),
)
if save_figure:
if not os.path.exists('images'):
os.mkdir('images')
fig_comparison.write_image(f'images/engines_comparison.{format}')
if show_figure:
fig_comparison.show()
def eff_temp(hst, show_figure=True, save_figure=False, format='pdf'):
from scipy.interpolate import interp1d
effs = []
hst.oil = 'SAE 15W40'
temps = range(0, 110, 10)
for temp in temps:
hst.oil_temp = temp
hst.load_oil()
eff, perf = hst.compute_eff(speed_pump=2025, pressure_discharge=472)
effs.append(eff['hst']['total'])
sns.set_style('ticks', {
'spines.linewidth': .25,
})
sns.set_palette('Set1')
plt.scatter(temps, effs, c='steelblue')
f2 = interp1d(temps, effs, kind='cubic')
x = np.linspace(0, 100)
sns.despine()
plt.plot(x, f2(x), color='steelblue')
plt.legend(['Interpolation', 'Data'], loc='best')
plt.xlabel('Oil temperature, deg C')
plt.ylabel('HSU total efficiency, %')
if save_figure:
if not os.path.exists('images'):
os.mkdir('images')
plt.savefig(f'images/eff_temp.{format}')
if show_figure:
plt.show()
def print_to_moohst(show=True, save=False):
if show:
shows = True
saves = False
elif save:
shows = False
saves = True
#* Catalogue data
models, data = load_catalogues()
plot_catalogue_data(
models,
data,
show_figure=shows,
save_figure=saves,
)
plot_histograms(
models,
data,
show_figure=shows,
save_figure=saves,
)
#* Validation
plot_validation(show_figure=shows, save_figure=saves)
#* HST initialization
hst = HST(*set_defaults('sizing'))
hst.compute_sizes(displ=500)
hst.compute_speed_limit(models['pump_speed'])
#* Oil setting
hst.oil = 'SAE 15W40'
hst.oil_temp = 100
hst.load_oil()
hst.plot_oil(show_figure=shows, save_figure=saves)
#* Maps preparation
input_speed, pressure_charge, pressure_discharge = set_defaults(
'performance')
max_speed, max_pressure, hst.max_power_input, hst.input_gear_ratio = set_defaults(
'map')
hst.engine = None
#* Maps plotting
hst.plot_eff_map(
max_speed,
max_pressure,
pressure_charge=pressure_charge,
show_figure=shows,
save_figure=saves,
)
hst.plot_power_map(
max_speed,
max_pressure,
pressure_charge=pressure_charge,
show_figure=shows,
save_figure=saves,
)
eff_temp(hst, save_figure=save, show_figure=show)
#* Comparisons
# engine_1 = HST(440, engine='engine_1')
# engine_4 = HST(350,
# engine='engine_4',
# max_power_input=580,
# input_gear_ratio=.8)
# plot_engines_comparison(engine_1,
# engine_4,
# show_figure=shows,
# save_figure=saves,
# format='pdf')
# plot_hst_comparison(*set_defaults('comparison'),
# show_figure=shows,
# save_figure=saves,
# format='pdf')
if __name__ == '__main__':
print_to_moohst(show=True, save=False) | [
"ivan.okhotnikov@outlook.com"
] | ivan.okhotnikov@outlook.com |
7e76a758ca334284f2cf95c5c441f5885ed5dc8f | 413df3b2d56f3296803d4af3e973251c8ff1eab0 | /CSC-8311 .py | 36afeb3b1bc6e2bce1cab98220953d1d31e8030b | [] | no_license | cedali/csc-8311 | 8348b6efbf48665cf0d74f5426eb1d41d5c2cf74 | 2e943dce8c8b7e9956acce617509009881db6145 | refs/heads/master | 2021-04-06T02:38:33.914711 | 2018-03-09T13:41:49 | 2018-03-09T13:41:49 | 124,539,335 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,285 | py | import Bio
import sys
import os
import random
import unittest
from Bio import Entrez
from Bio import ExPASy
from Bio import SeqIO
from Bio import SwissProt
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_rna, generic_dna, generic_protein
from Bio.Alphabet import IUPAC
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO
from collections import Counter
import matplotlib as mp1
import re
from numpy import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import math
#creating DNA class and defining DNA characteristics of the DNA
class DNA:
def __init__(self, filename, start=3):
self.type = "DNA"
self.header = ""
self.genomeseq = ""
self.genome_seq_len=0
self.start = 3
self.direction(start)
self.read_FASTA(filename)
def read_FASTA(self,filename):
with open(filename) as f:
fast = f.read()
for genome in fast.split(">")[1:]:
self.header, self.genomeseq = genome.splitlines()[0], "".join(genome.splitlines()[1:])
self.genome_seq_len = len(self.genomeseq)
#print(self.genomeseq)
def direction(self, start):
if start == 3:
self.start, self.finish = 3, 5
elif start == 5:
self.start, self.finish = 5, 3
def c_gc_skewness(self, piece_seq_len=50):
# counts = Counter(genomeseq)
list = [0]
for i in range(0, self.genome_seq_len, piece_seq_len):
genome = self.genomeseq[i:i + piece_seq_len]
counts_Genome = Counter(genome)
G, C = counts_Genome["G"], counts_Genome["C"]
try:
sGC = (G - C) / (G + C)
except ZeroDivisionError:
sGC = 0
# print("sGC:",sGC,"last value",list[-1])
# print(genome," number of G= ",G," number of C = ",C,"gc shift: ",sGC)
liste.append((list[-1] + sGC))
# print(genome,"number of G= ",G," number of C= ",C,"gc shift: ",sGC)
plt.plot(range(0, len(list)), list)
plt.show()
def c_at_skewness(self, piece_seq_len=50):
# counts = Counter(genomeseq)
list = [0]
for i in range(0, self.genome_seq_len, piece_seq_len):
genome = self.genomeseq[i:i + piece_seq_len]
countsGenome = Counter(genome)
A, T = countsGenome["A"], countsGenome["T"]
try:
sAT = (A - T) / (A + T)
except ZeroDivisionError:
sAT = 0
# print("sGC:",sGC,"son eleman",list[-1])
# print(genome," number of G= ",G," number of C= ",C,"gc shift: ",sGC)
liste.append((liste[-1] + sAT))
# print(genome," number of G= ",G," number of C = ",C,"gc shift: ",sGC)
plt.plot(range(0, len(list)), list)
plt.show()
#it will be demonstrated as a 3D graph
def Zcurved(self):
listx, listy, listz = [], [], []
A, T, G, C = 0, 0, 0, 0
# count=0
for i in self.genomeseq:
if i == "A":
A = A + 1
elif i == "T":
T = T + 1
elif i == "G":
G = G + 1
elif i == "C":
C = C + 1
"""count=count+1
if count==10:
break"""
listx.append((A + G) - (C + T))
listy.append((A + C) - (G + T))
listz.append((A + T) - (G + C))
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(listx, listy, listz)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.legend()
plt.show()
# print("number of A : {}\nT : {}\nG : {}\nC : {}".format(A,T,G,C))
# print(listx)
def Point(self):
pass
def gene_entropi(sequence):
counts=Counter(sequence)
A,T,G,C=counts["A"],counts["T"],counts["G"],counts["C"]
print(A,T,G,C)
try:
A = (A/len(sequence))*(math.log(2,(A/len(sequence)/(1/4))))
T = (T/len(sequence))*(math.log(2,(T/len(sequence)/(1/4))))
G = (G/len(sequence))*(math.log(2,(G/len(sequence)/(1/4))))
C = (C/len(sequence))*(math.log(2,(C/len(sequence)/(1/4))))
except ZeroDivisionError:
A = 0
G = 0
T = 0
C = 0
gene = A + T
print(gene)
def sequencealignment(align1,aling2):
matris=zeros((len(aling1)+1,len(align2)+1))
count = 0
for i in range(0,len(align2)+1):
matris[0][i] = count
count = count - 2
count = 0
for i in range(0,len(align1)+1):
matris[i][0] = count
count = count - 2
for i in matris:
print(i)
verticalAxis = ["X"]
horizontalAxis = ["X"]
for i in align1:
verticalAxis.append(i)
for i in align2:
horizontalAxis.append(i)
print(horizontalAxis)
gap=-2
match=5
Mismatch=-5
#print(len(verticalAxis))
for i in range(1,len(horizontalAxis)):
for j in range(1,len(verticalAxis)):
if verticalAxis[j] == horizontalAxis[i]:
#print("this are: ",verticalAxis[j]," ",horizontalAxis[i])
matris[j][i] = matris[j-1][i-1] + 5
else:
leftTop = matris[j-1][i-1] + Mismatch
top = matris[j-1][i] + gap
left = matris[j][i-1] + gap
if leftTop>top and leftTop>left:
matris[j][i] = leftTop
elif top>leftTop and top>left:
matris[j][i] = top
else:
matris[j][i] = left
for i in matris:
print(i)
print(Bio.__version__) | [
"noreply@github.com"
] | noreply@github.com |
00f943af87cab6ec48e99ae5cf97813d61755732 | 3f0c1a0066e5b72ba70a60399fb6a6abc138a810 | /SBC/settings.py | 3655d9b193823d7880073c8a640be28fba1c346f | [] | no_license | calosh/Buscador_Semantico | facce482e95d4acd8082d2249134688f8e529842 | 88e827b4730263a2c4e040654ab97fea71f2f343 | refs/heads/master | 2020-03-20T16:22:42.960238 | 2018-07-23T05:08:01 | 2018-07-23T05:08:01 | 137,537,611 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,190 | py | """
Django settings for SBC project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'kp67(75yu-62#&&1+*(#z7pj6be()^k%i9d4^f_5!%9g!a23yt'
# 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',
'app',
]
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 = 'SBC.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SBC.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
] | [
"carlitoshxt@gmail.com"
] | carlitoshxt@gmail.com |
94709ea9fdd3f5b965a753f366702dbec38c259a | c0c6b41523d8f8071c88d4320d9040a6d1d2e3f4 | /problem1 | 80d2761714d5ce30c6ac12310c7fc42a98b8b028 | [] | no_license | GLAU-TND/python-programming-assignment-2-Manish-021 | 952cf9bd8a4f953074595f7c7d164541eba94443 | 782bdef864fadac653e500d03498de6c92c56382 | refs/heads/master | 2021-01-09T11:43:22.749103 | 2020-02-24T11:42:25 | 2020-02-24T11:42:25 | 242,287,538 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 225 | t=eval(input())
b=[min(t)]
a=min(t)[-1]
t.remove(min(t))
for i in t:
for j in t:
if a==j[0] and j[-1]!=b[0][0]:
b.append(j)
a=j[-1]
t.remove(j)
break
b=b+t
print(b)
| [
"noreply@github.com"
] | noreply@github.com | |
f4229b522cdf325535b9c5a91bec75d3119678ce | 5ce97eb386e04ef5e8f7de1b94725648fbba89b0 | /proj4-gu-nt-proj4-2-sub/util/layers.py | d880bdb5edee6b40509488ecfd5df6f368b74e69 | [] | no_license | Chenyb/CS61C | 5716a29feabddeb2df28b76a3ef1df42424990f9 | 3deeaf0c452745be12fa71d611e30dc655484932 | refs/heads/master | 2016-08-13T02:07:03.536235 | 2015-12-25T06:29:21 | 2015-12-25T06:29:21 | 48,569,125 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,609 | py | import numpy as np
#from im2col import *
from im2col_c import *
def linear_forward(X, A, b):
"""
Input:
- X: [N * M] -> N data of size M
- A: [M * K] -> M weights for K classes
- b: [1 * K] -> bias
Output:
- X * A + b: [N * K]
"""
return np.dot(X.reshape(X.shape[0], -1), A) + b
def linear_backward(df, X, A):
"""
Input:
- df: [N * K] -> gradient on the upstream function 'f'
- X: [N * M] -> N data of size M
- A: [M * K] -> M weights for K classes
Output:
- dX: [N * M] -> gradient on X
- dA: [M * K] -> gradient on A
- db: [K * 1] -> gradient on b
"""
# gradient on X: dL/dX = dL/df * df/dX = dL/df * A.T: [N * M]
dX = np.dot(df, A.T).reshape(X.shape)
# gradient on A: dL/dA = dL/df * df/dA = X.T * dL/df: [M * K]
dA = np.dot(X.T, df)
# gradient on b: dL/db = dL/df * df/db = [sum_n(dL_n/df_k)]: [K * 1]
db = np.sum(df, axis=0)
return dX, dA, db
def ReLU_forward(f):
"""
Input:
- f: [N * K] -> scores for K classes of N data
Output:
- max(0, f): [N * K]
"""
return np.maximum(0, f)
def ReLU_backward(df, g):
"""
Input:
- df: [N * K] -> gradient on the upstream function 'f'
- g: [N * K] -> output of LeRU_forward
Output:
- [if (g_nk <= 0) 0 else df_nk]: [N * K]
"""
g_ = g.reshape(df.shape)
df[g_ <= 0] = 0
return df.reshape(g.shape)
def softmax_loss(f, Y):
"""
* Coumputes the loss and its gradient for softmax classification
Input:
- f: [N * K] -> scores of N images for K classes
- Y: [N * 1] -> labels of N images (range(0, K))
Output:
- L: softmax loss
- df: gradient of L on f
"""
N = f.shape[0]
# probs: [p_nk = exp(f_k_n) / sum(exp(f_j_n))]: [N * K]
p = np.exp(f - np.max(f, axis=1, keepdims=True))
p /= np.sum(p, axis=1, keepdims=True)
# loss: sum_n(-log(p_ny)) / N, where p_ny = prob of the image n's label
L = np.sum(-np.log(p[np.arange(N), Y])) / N
# dL_n/df_k = p_k - delta_Y_n_k, where delta_Y_n_k = if (Y[n] == k) 1 else 0
# gradient of L on f: dL/df = [dL_n/df_k / N]: [N * K]
df = p.copy()
df[np.arange(N), Y] -= 1
df /= N
return L, df
def conv_forward(X, A, b, S, P):
"""
Input:
- X: [N * D * H * W] -> N image data of size D * H * W
- A: [K * D * F * F] -> K filters of size D * F * F
- b: [K * 1] -> bias
- S: stride of convolution (integer)
- P: size of zero padding (integer)
Output:
- f: [N * K * H_ * W_] -> activation maps, where
- H_ = (H - F + 2P)/S + 1
- W_ = (W - F + 2P)/S + 1
- X_col: [(D * F * F) * (H_ * W_ * N)] -> column stretched images
"""
N, _, H, W = X.shape
K, D, F, _ = A.shape
assert (H - F + 2*P) % S == 0, 'wrong convolution params'
assert (W - F + 2*P) % S == 0, 'wrong convolution params'
H_ = (H - F + 2*P) / S + 1
W_ = (W - F + 2*P) / S + 1
# compute X_col: [(D * F * F) * (H_ * W_ * N)]
X_col = im2col_forward(X, F, F, S, P)
# compute f = A * X_col_ + b: [K * (H_ * W_) * N] -> [N * K * (H_ * W_)]
f = np.dot(A.reshape(K, -1), X_col) + b
f = f.reshape(K, H_, W_, N).transpose(3,0,1,2)
return f, X_col
def conv_backward(df, X, X_col, A, S, P):
"""
Input:
- df: [N * K * H_ * W_] -> gradient on the upstream function 'f'
- X: [N * D * H * W] -> image
- X_col: [(D * F * F) * (H_ * W_ * N)] -> column strecthed images
- A: [K * D * F * F] -> K filters of size D * F1 * F2
- S: stride of convolution (integer)
- P: size of zero padding (integer)
Output:
- dX: [N * D * H * W] -> gradient on X
- dA: [K * D * F * F] -> gradient on A
- db: [K * 1] -> gradient on b
"""
N, K, W_, H_ = df.shape
_, D, F, _ = A.shape
# dL/dX_col = dL/df * df/dX_col = A * df_ : [(N * H_ * W_) * (D * F * F)]
dX_col = np.dot(A.reshape(K, -1).T, df.transpose(1,2,3,0).reshape(K, -1))
# dL/dX : [N * D * H * W]
dX = im2col_backward(dX_col, X.shape, F, F, S, P)
# dL/dA = dL/df * df/dA = X_col_ * df_ : [K * (D * F * F)]
dA = np.dot(X_col, df.transpose(2,3,0,1).reshape(-1, K))
# dL/db = sum(dL/df): [K * 1]
db = np.sum(df, axis=(0, 2, 3)).reshape(K, 1)
return dX, dA, db
def max_pool_forward(X, F, S):
"""
Input:
- X: [N * D * H * W] -> N image data of size D * H * W
- F: size of pooling
- S: stride of pooling
Output:
- f: [N * D * H_ * W_] -> pooled maps, where
- H_ = (H - F)/S + 1
- W_ = (W - F)/S + 1
- X_idx: [(H_ * W_ * N * D) * 1] -> indices for X_col
"""
N, D, H, W = X.shape
assert (H - F) % S == 0, 'wrong pooling params'
assert (W - F) % S == 0, 'wrong pooling params'
H_ = (H - F) / S + 1
W_ = (W - F) / S + 1
# compute X_col : [(F * F) * (H_ * W_ * N * D)]
X_col = im2col_forward(X.reshape(N*D, 1, H, W), F, F, S, 0)
# compute X_idx : [(H_ * W_ * N * D)]
X_idx = np.argmax(X_col, axis=0)
# compute f: [N * D * H_ * W_]
f = X_col[X_idx, np.arange(X_col.shape[1])].reshape(H_,W_,N,D).transpose(2,3,0,1)
return f, X_idx
def max_pool_backward(df, X, X_idx, F, S):
"""
Input:
- df: [ N * D * H_ * W_ ] -> gradient on the upstream function 'f'
- X: [ N * D * H * W ] -> images
- X_idx: [(N * D * H_ * W_)] -> indice from column strecthed image
- F: size of pooling
- S: stride of pooling
Output:
- dX: [N * D * H * W] -> gradient on X
"""
N, D, H_, W_ = df.shape
_, _, H, W = X.shape
# dX_col : [(F * F) * (H_ * W_ * N * D)]
dX_col = np.zeros((F*F, H_*W_*N*D))
dX_col[X_idx, np.arange(dX_col.shape[1])] = df.transpose(2,3,0,1).flatten()
# dX : [N * D * H * W]
dX = im2col_backward(dX_col, (N*D, 1, H, W), F, F, S, 0).reshape(X.shape)
return dX
| [
"chenyb@berkeley.edu"
] | chenyb@berkeley.edu |
81008224cac8591b4f00dcd38bf9b8e5cc34dc27 | 30ec40dd6a81dbee73e7f14c144e20495960e565 | /kubernetes/client/models/v1beta1_http_ingress_rule_value.py | 9653f80f26ca995284fb6ca79ec30368e71cd13e | [
"Apache-2.0"
] | permissive | jonathan-kosgei/client-python | ae5a46968bcee19a3c62e1cefe227131ac9e7200 | 4729e6865d810824cafa312b4d06dfdb2d4cdb54 | refs/heads/master | 2021-01-20T14:59:10.435626 | 2017-05-08T16:55:51 | 2017-05-08T16:55:51 | 90,700,132 | 1 | 0 | null | 2017-05-09T03:50:42 | 2017-05-09T03:50:42 | null | UTF-8 | Python | false | false | 3,300 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1HTTPIngressRuleValue(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, paths=None):
"""
V1beta1HTTPIngressRuleValue - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'paths': 'list[V1beta1HTTPIngressPath]'
}
self.attribute_map = {
'paths': 'paths'
}
self._paths = paths
@property
def paths(self):
"""
Gets the paths of this V1beta1HTTPIngressRuleValue.
A collection of paths that map requests to backends.
:return: The paths of this V1beta1HTTPIngressRuleValue.
:rtype: list[V1beta1HTTPIngressPath]
"""
return self._paths
@paths.setter
def paths(self, paths):
"""
Sets the paths of this V1beta1HTTPIngressRuleValue.
A collection of paths that map requests to backends.
:param paths: The paths of this V1beta1HTTPIngressRuleValue.
:type: list[V1beta1HTTPIngressPath]
"""
if paths is None:
raise ValueError("Invalid value for `paths`, must not be `None`")
self._paths = paths
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1beta1HTTPIngressRuleValue):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"mehdy@google.com"
] | mehdy@google.com |
5fc066834916a8dbb349035d834ab8ffcd3415d5 | c3483984a4782be6097e4753de3cb545ae00039b | /geneticTest/unitTestingExample/unitTesting/test_Employee.py | e00ef30b7b7dd17f737f32a405b4966559a25522 | [] | no_license | nghiemphan93/machineLearning | 67c3f60f317a0c753b465751113511baaefd1184 | 36d214b27c68d399f5494b5ec9b28fee74d57f7f | refs/heads/master | 2020-03-28T02:20:11.843154 | 2020-02-03T14:18:39 | 2020-02-03T14:18:39 | 147,563,336 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,536 | py | import unittest
from geneticTest.unitTestingExample.stuffToTest.Employee import Employee
class TestEmployee(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('setupClass')
@classmethod
def tearDownClass(cls):
print('teardownClass')
def setUp(self):
print('setUp')
self.emp_1 = Employee('Corey', 'Schafer', 50000)
self.emp_2 = Employee('Sue', 'Smith', 60000)
def tearDown(self):
print('tearDown\n')
def test_email(self):
print('test_email')
self.assertEqual(self.emp_1.email, 'Corey.Schafer@email.com')
self.assertEqual(self.emp_2.email, 'Sue.Smith@email.com')
self.emp_1.first = 'John'
self.emp_2.first = 'Jane'
self.assertEqual(self.emp_1.email, 'John.Schafer@email.com')
self.assertEqual(self.emp_2.email, 'Jane.Smith@email.com')
def test_fullname(self):
print('test_fullname')
self.assertEqual(self.emp_1.fullname, 'Corey Schafer')
self.assertEqual(self.emp_2.fullname, 'Sue Smith')
self.emp_1.first = 'John'
self.emp_2.first = 'Jane'
self.assertEqual(self.emp_1.fullname, 'John Schafer')
self.assertEqual(self.emp_2.fullname, 'Jane Smith')
def test_apply_raise(self):
print('test_apply_raise')
self.emp_1.apply_raise()
self.emp_2.apply_raise()
self.assertEqual(self.emp_1.pay, 52500)
self.assertEqual(self.emp_2.pay, 63000)
if __name__ == '__main__':
unittest.main() | [
"nghiemphan93@gmail.com"
] | nghiemphan93@gmail.com |
f49600817eab6414b04ca5c1b5d27b1d41bf832c | 44dec6a793a8478a3e5a3a80a72f0c0a743b3df9 | /big_data/test/api.py | 84bc1a290b9c9160999288fae77c8542bb10eba5 | [] | no_license | liying1993/my_practice | f6599fd68bc32581c2217d2a834192adbf4a9712 | f4c34738f2129e631f3e0094ab7bfa5abedb7e10 | refs/heads/master | 2021-01-22T13:03:17.278770 | 2018-02-24T09:00:10 | 2018-02-24T09:00:10 | 102,332,602 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,111 | py | from ..blockchain import app
import unittest
import json
from pprint import pprint
from io import StringIO
class TestApi(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def request_get(self, uri):
print("GET {}".format(uri))
headers = {"Content-Type": "application/json"}
self.request = self.app.get(
uri,
headers=headers)
try:
pprint(json.loads(self.request.data.decode("utf-8")))
except json.JSONDecodeError:
print("{}".format(self.request.data.decode("utf-8")))
def request_post(self, uri, data):
print("POST {}".format(uri))
headers = {"Content-Type": "application/json"}
self.request = self.app.post(
uri,
headers=headers,
input_stream=StringIO(json.dumps(data)))
print(self.request._status)
print(self.request.headers)
try:
pprint(json.loads(self.request.data.decode("utf-8")))
except json.JSONDecodeError:
print("{}".format(self.request.data.decode("utf-8"))) | [
"2071127345@qq.com"
] | 2071127345@qq.com |
ce60cb9577e898f6ef22820e4ca9b8dd62031b01 | 82b60d856c46ef1ec060293d85cee555406f5845 | /app/DATOS_LISTOS/datosRegistrosCHEKOK.py | b641547e9a8bb784e23289973702bbdc602d7c51 | [] | no_license | lagossully/AyudaConFlask | 5292e82b7f9da1a26a2628cd69caf4930c06b0aa | e047111d27bdb67b497e6cc38bb8fd8ee56b8224 | refs/heads/master | 2020-04-10T02:29:06.513919 | 2018-12-06T22:38:00 | 2018-12-06T22:38:00 | 160,745,434 | 0 | 0 | null | 2018-12-06T23:30:15 | 2018-12-06T23:30:14 | null | UTF-8 | Python | false | false | 1,700 | py | from random import choice, random, randint, randrange
from configuraciones import *
import psycopg2
conn = psycopg2.connect("dbname=%s user=%s password=%s"%(database,user,passwd))
cur = conn.cursor()
sql="""select id_sensor from sensores;"""
cur.execute(sql)
posts = cur.fetchall()
sql="""select patente from autos;"""
cur.execute(sql)
posts2 = cur.fetchall()
c=1
for t in posts2:
fecha=43438
for x in range(10):
hour=choice(('12:','13:','15:','16:'))
for w in range(20,60):
last=hour
hour+=str(w)
for y in posts:
if y[0] == 1:
data=randrange(80,160,5)
if y[0] == 2:
data=randrange(70,180,2)
if y[0] == 3:
data=randrange(130, 280,5)
if y[0] == 4:
data=randrange(10,37,1)
if y[0] == 5:
data=randrange(30,80,10)
if y[0] == 6:
data=randrange(12,15,1)
if y[0] == 7:
data=randrange(60, 150, 10)
if y[0] == 8:
data=randrange(50,120,5)
sql="""insert INTO registros VALUES"""
sql=sql+("({},'{}','{}',{});".format(c,
hour,
fecha,
data))
cur.execute(sql)
sql2="""insert INTO mediciones VALUES"""
sql2=sql2+("({},{},'{}');".format(c,
y[0],
t[0]))
cur.execute(sql2)
c+=1
hour=last
fecha+=1
conn.commit()
cur.close()
conn.close()
| [
"180206779@Docencia.udp.cl"
] | 180206779@Docencia.udp.cl |
b71cf501c6e9e920c344c180785088347c9eea05 | 398de9098811c7712b18f8e314340ce93aa86839 | /id2date.py | 7fc4502cd5258ae680b5604cba9dd53e78ba1f70 | [] | no_license | NiMaZi/thesis | 0c2ce8bced070d010838bae80f844a46bb1a798c | 15dc1aeca941f8feec4c283cd7436983ba982871 | refs/heads/master | 2020-03-18T13:19:52.711331 | 2018-07-09T12:11:08 | 2018-07-09T12:11:08 | 134,776,324 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,288 | py | import os
import sys
import csv
import json
import boto3
import numpy as np
homedir=os.environ['HOME']
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
es=Elasticsearch(['localhost:9200'])
s3 = boto3.resource("s3")
mybucket=s3.Bucket("workspace.scitodate.com")
s3key=sys.argv[1]
id2date={}
for i in range(0,15000):
try:
mybucket.download_file("yalun/"+s3key+"/abs"+str(i)+".txt",homedir+"/temp/tmptxt"+s3key+".txt")
except:
continue
f=open(homedir+"/temp/tmptxt"+s3key+".txt",'r',encoding='utf-8')
abstract=f.read().split(",")[0]
f.close()
results=scan(es,
query={
"query": {
"bool": {
"must": [{"match_phrase": {"abstract": abstract}}]
}
}
},
size=1
)
for n,result in enumerate(results):
if n>10:
break
if abstract in result['_source']['abstract']:
try:
id2date[i]=result['_source']['date']
except:
break
f=open(homedir+"/temp/id2date"+s3key+".json",'w')
json.dump(id2date,f)
f.close()
f=open(homedir+"/temp/id2date"+s3key+".json",'rb')
d=f.read()
f.close()
mybucket.put_object(Body=d,Key="yalun/"+s3key+"/id2date.json") | [
"zhengyl940425@gmail.com"
] | zhengyl940425@gmail.com |
9586e05b891e5809a3bb66a07ef851d098c5abc0 | 6e366c25bfab97691589d85512e5b7b515f5bb32 | /codingDOJO_python_stack/django/django_intro/dash/dash_app/migrations/0001_initial.py | f5480e8d6b33d5a9a2238458ed8fe94460945a2c | [] | no_license | Sota1218/codingDojo-in-Seattle | 09bcae69ffec934b6498ed378c7c6922728a11b5 | c1f5d9b8e0d8a12607784786d6351fed9e98b377 | refs/heads/master | 2022-12-04T17:13:39.298423 | 2020-08-06T09:41:02 | 2020-08-06T09:41:02 | 285,524,490 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 918 | py | # Generated by Django 2.2 on 2019-12-13 18:04
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('login_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Trip',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('dest', models.CharField(max_length=225)),
('start_date', models.DateField()),
('end_date', models.DateField()),
('plan', models.CharField(max_length=225)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.ManyToManyField(related_name='trips', to='login_app.User')),
],
),
]
| [
"sotayoshihiro@USERnoMacBook-Air.local"
] | sotayoshihiro@USERnoMacBook-Air.local |
96f0e08ae2ac25053eeb6b7f10974a41dfad3381 | 03b03bee341f784f05f39e4abff1e1fc9e49624f | /Programming-Fundamentals-using-Python/Day-3/Exercises/Exercise-15.py | a950d0d4f2319532e79e566b6c87b3fa407f7446 | [] | no_license | Incertam7/Infosys-InfyTQ | 3051d6ccf6ff300f6d209659fd771171ba50db23 | 57d55e9d3fb7bb08efe5dc0f536c08d24f6ff3fb | refs/heads/master | 2021-05-28T19:34:58.124849 | 2020-07-07T00:43:32 | 2020-07-07T00:43:32 | 254,277,511 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 377 | py | #PF-Exer-15
def find_sum_of_digits(number):
sum_of_digits = 0
#Write your logic here
while number > 0:
remainder = number % 10
sum_of_digits += remainder
number //= 10
return sum_of_digits
#Provide different values for number and test your program
sum_of_digits=find_sum_of_digits(123)
print("Sum of digits:", sum_of_digits)
| [
"noreply@github.com"
] | noreply@github.com |
63d41c42f8f87f62095b5bc99fda6d77e3eb4288 | 59788643fcce655a3a15ad0d3c91401a63e525d9 | /home/models.py | f925cf6580cdcd1ae6f9a202aa595fe40ca9a4ba | [] | no_license | crowdbotics-apps/element-28308 | f39132662eb2e433d44e3c570ae539d9feae3db0 | 018966b7d47c9e2f9b1bb33c018d1a9b7a3b3b42 | refs/heads/master | 2023-06-06T09:31:10.513777 | 2021-06-29T20:33:03 | 2021-06-29T20:33:03 | 381,465,888 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 276 | py | from django.conf import settings
from django.db import models
class CustomText(models.Model):
"Generated Model"
chart = models.URLField(
null=True,
blank=True,
)
class HomePage(models.Model):
"Generated Model"
body = models.TextField()
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
68722f7023aea120420746a38e0ac5ed4af46825 | a9ed3f674134423fcd816865b1501167daeb0d45 | /bucketcloner/backends/swift.py | 2148d44ed8d2d00cfa5786abe54b54133f66fdc2 | [] | no_license | camptocamp/docker-bucket-cloner | 5862332041c1df4df74063015e1abcd7b6edc5f2 | 9c3c69488d342ec94c3f0647816410063ffab593 | refs/heads/master | 2022-07-30T17:12:44.266122 | 2021-07-29T15:54:35 | 2021-07-29T15:54:35 | 151,561,378 | 0 | 1 | null | 2022-07-15T11:46:37 | 2018-10-04T11:29:58 | Python | UTF-8 | Python | false | false | 315 | py | import swiftclient
class Swift(object):
def __init__(self, **kwargs):
self.client = swiftclient.client.Connection(**kwargs)
def list_buckets(self):
buckets = []
for container in self.client.get_container("")[1]:
buckets.append(container['name'])
return buckets
| [
"leo.depriester@camptocamp.com"
] | leo.depriester@camptocamp.com |
6f781fbb34a0effb575b1359355f0db2026e382d | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5658571765186560_1/Python/dnutsch/problem_d.py | ec9d645f24bcbab7bf09cb17d6dd1abaea92f717 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 1,111 | py | #!/usr/bin/python
f = open('D-large.in','r');
out = open('D-large.out','w');
T = int(f.readline().strip())
for t in range(T):
X,R,C = [int(x) for x in f.readline().strip().split(' ')]
#print "x {}, r {}, c {}".format(X,R,C)
mx = max(R,C)
mn = min (R,C)
richard_wins = False
if (R*C) % X != 0:
richard_wins = True
if X >=7:
richard_wins = True # can make a donut
elif X > mx:
# maybe win by bisection, assume so
richard_wins = True
elif X == mx:
# maybe can bisect in minor dimension
if X >= 4 and X >= mn + (mn -1):
richard_wins = True
else:
#can't win by bisection, try squaring
if X >= 4 and mn < 2:
richard_wins = True
if X >= 9 and mn < 3:
richard_wins = True
if X >= 16 and mn < 4:
richard_wins = True
max_angle = 1+((X-1) // 2)
if max_angle > mn:
richard_wins = True
line = "Case #{}: {}".format(t+1, "RICHARD" if richard_wins else "GABRIEL")
print line
out.write(line+"\n")
f.close()
out.close()
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
f6888edf9775c1a80bafa07e0227f6ecfade3494 | 2406425d12f96b81fca3f735f034f4375e44d567 | /app/views.py | 1e664fcdaaeb853fb0730dca8c445a32105e7b5f | [] | no_license | BodleyAlton/info3180-lab2 | 94dad3b54182e2afc1a6e99590bb7300bec70c10 | c509c5882744fa0a8b20e92a5d2abe2a813b3f4f | refs/heads/master | 2020-12-31T00:11:30.576229 | 2017-02-03T14:16:25 | 2017-02-03T14:16:25 | 80,547,339 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,772 | py | """
Flask Documentation: http://flask.pocoo.org/docs/
Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/
Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/
This file creates your application.
"""
from app import app
from flask import render_template, request, redirect, url_for
import time
###
# Routing for your application.
###
@app.route('/')
def home():
"""Render website's home page."""
return render_template('home.html')
@app.route('/about/')
def about():
"""Render the website's about page."""
return render_template('about.html', name="Mary Jane")
@app.route('/profile/')
def profile():
"""Render the website's profile page"""
return render_template('profile.html',name="Aladin Suprester", uname="ASupra",
ID="100934857",gender="Male", pos="Expert Time Waster",age="28",date=timeinfo())
def timeinfo():
now= time.strftime("%c")
return "Today's date is " + time.strftime("%a %d %b %Y")
###
# The functions below should be applicable to all Flask apps.
###
@app.route('/<file_name>.txt')
def send_text_file(file_name):
"""Send your static text file."""
file_dot_text = file_name + '.txt'
return app.send_static_file(file_dot_text)
@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=600'
return response
@app.errorhandler(404)
def page_not_found(error):
"""Custom 404 page."""
return render_template('404.html'), 404
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0",port="8080") | [
"altonbodley@gmail.com"
] | altonbodley@gmail.com |
e818c37d9b6bd51c5ded62760f60d10e5ab3e5b7 | f1e69fceca699492a0b3be02c05e5acb0588712e | /src/config.py | b3e8b55022af6dac4184bda4903c1ca6283d4195 | [
"MIT"
] | permissive | choobinejad/data-analytics-workshop | 207488dbdc24f2964f01a0f1145dd9576995695c | 56efeb483cb5c34e9efc2e0f389b6f2de2ea93ac | refs/heads/master | 2020-12-30T08:26:43.025004 | 2020-02-07T16:50:58 | 2020-02-07T16:50:58 | 238,927,894 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py | import json
es_cloud_id = 'ml-workshop-shared:dXMtZWFzdDQuZ2NwLmVsYXN0aWMtY2xvdWQuY29tJGUxZDNjMmE1NDcwMzRkNzg5NTc3MmIzYzkzNGM3ZGU0JGUxZjY5N2JiYWRjYzRhMDFhMzM0MTlhNzgzNTA1MDMy'
es_user = 'elastic'
es_password = 'EvFqdXnuNSEirNnRm8RD9veG'
| [
"jeremy.m.woodworth@gmail.com"
] | jeremy.m.woodworth@gmail.com |
1beef113b1accc85341f2933f32d80839e029de5 | 1496fd578daaf13bebccd68057c455b74481b8de | /week3/oddTuples.py | 51bd390f843f0f573961b7f11200d940a4670f98 | [] | no_license | leahfrye/MITx-6.00.1x | 274c58a6d7ca4c64dbd1bda5c2f102012f4a4f17 | 41e26ded3606b83b21998777ff32cf862e2b7f1d | refs/heads/master | 2021-09-03T14:43:04.654759 | 2018-01-09T21:43:45 | 2018-01-09T21:43:45 | 115,056,698 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 302 | py | # Takes a tuple as an input and returns a new tuple, where every other element of the input
def oddTuples(aTup):
oddTups = ()
count = 0
for x in aTup:
if count % 2 == 0:
oddTups += (x,)
count += 1
print(oddTups)
oddTuples((4, 5, 18, 10, 7, 1, 8, 15, 4, 8)) | [
"lefrye@nps.edu"
] | lefrye@nps.edu |
ba017f14c0775d89dbd53d36c4176b80e4cefe64 | 1ab51f22ba8c43323e37b5cbf7125b0d00f15a56 | /manage.py | 97d85a3dc6f7aeed122d2357fdbae6305d22497c | [
"MIT"
] | permissive | tailorv/neighbourshood | 424b65707b04630389045a0471dc9710b6d63dcb | f9470ba1f9bb8c995d0b8ae93e90316285226026 | refs/heads/main | 2023-08-21T07:55:08.371636 | 2021-11-02T07:19:39 | 2021-11-02T07:19:39 | 423,046,460 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 670 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'area51_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"maxwellmuthomijr@gmail.com"
] | maxwellmuthomijr@gmail.com |
b2350463d670e71f629110e647c1fb932056883f | 2f186ab7c3bea7a588176e1322728ea6c46a09f3 | /env/lib/python2.7/site-packages/telegram/message.py | 32f8fe45bd8a9cdaf46cc792446e9b4760779827 | [] | no_license | spbisya/voiceRecognition | b486167a0544b6b0a78c607a6c85dab95f1df36c | 3453f00336511bbdace4a46377b25a26595e0917 | refs/heads/master | 2021-05-03T12:28:34.639732 | 2016-10-06T06:34:35 | 2016-10-06T06:34:35 | 70,119,371 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 18,828 | py | #!/usr/bin/env python
# pylint: disable=R0902,R0912,R0913
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Message."""
import sys
from datetime import datetime
from time import mktime
from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize, Sticker, TelegramObject,
User, Video, Voice, Venue, MessageEntity)
class Message(TelegramObject):
"""This object represents a Telegram Message.
Note:
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
message_id (int):
from_user (:class:`telegram.User`):
date (:class:`datetime.datetime`):
forward_from (:class:`telegram.User`):
forward_from_chat (:class:`telegram.Chat`):
forward_date (:class:`datetime.datetime`):
reply_to_message (:class:`telegram.Message`):
edit_date (:class:`datetime.datetime`):
text (str):
audio (:class:`telegram.Audio`):
document (:class:`telegram.Document`):
photo (List[:class:`telegram.PhotoSize`]):
sticker (:class:`telegram.Sticker`):
video (:class:`telegram.Video`):
voice (:class:`telegram.Voice`):
caption (str):
contact (:class:`telegram.Contact`):
location (:class:`telegram.Location`):
new_chat_member (:class:`telegram.User`):
left_chat_member (:class:`telegram.User`):
new_chat_title (str):
new_chat_photo (List[:class:`telegram.PhotoSize`]):
delete_chat_photo (bool):
group_chat_created (bool):
supergroup_chat_created (bool):
migrate_to_chat_id (int):
migrate_from_chat_id (int):
channel_chat_created (bool):
Deprecated: 4.0
new_chat_participant (:class:`telegram.User`): Use `new_chat_member`
instead.
left_chat_participant (:class:`telegram.User`): Use `left_chat_member`
instead.
Args:
message_id (int):
from_user (:class:`telegram.User`):
date (:class:`datetime.datetime`):
chat (:class:`telegram.Chat`):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
forward_from (Optional[:class:`telegram.User`]):
forward_from_chat (:class:`telegram.Chat`):
forward_date (Optional[:class:`datetime.datetime`]):
reply_to_message (Optional[:class:`telegram.Message`]):
edit_date (Optional[:class:`datetime.datetime`]):
text (Optional[str]):
audio (Optional[:class:`telegram.Audio`]):
document (Optional[:class:`telegram.Document`]):
photo (Optional[List[:class:`telegram.PhotoSize`]]):
sticker (Optional[:class:`telegram.Sticker`]):
video (Optional[:class:`telegram.Video`]):
voice (Optional[:class:`telegram.Voice`]):
caption (Optional[str]):
contact (Optional[:class:`telegram.Contact`]):
location (Optional[:class:`telegram.Location`]):
new_chat_member (Optional[:class:`telegram.User`]):
left_chat_member (Optional[:class:`telegram.User`]):
new_chat_title (Optional[str]):
new_chat_photo (Optional[List[:class:`telegram.PhotoSize`]):
delete_chat_photo (Optional[bool]):
group_chat_created (Optional[bool]):
supergroup_chat_created (Optional[bool]):
migrate_to_chat_id (Optional[int]):
migrate_from_chat_id (Optional[int]):
channel_chat_created (Optional[bool]):
bot (Optional[Bot]): The Bot to use for instance methods
"""
def __init__(self, message_id, from_user, date, chat, bot=None, **kwargs):
# Required
self.message_id = int(message_id)
self.from_user = from_user
self.date = date
self.chat = chat
# Optionals
self.forward_from = kwargs.get('forward_from')
self.forward_from_chat = kwargs.get('forward_from_chat')
self.forward_date = kwargs.get('forward_date')
self.reply_to_message = kwargs.get('reply_to_message')
self.edit_date = kwargs.get('edit_date')
self.text = kwargs.get('text', '')
self.entities = kwargs.get('entities', list())
self.audio = kwargs.get('audio')
self.document = kwargs.get('document')
self.photo = kwargs.get('photo')
self.sticker = kwargs.get('sticker')
self.video = kwargs.get('video')
self.voice = kwargs.get('voice')
self.caption = kwargs.get('caption', '')
self.contact = kwargs.get('contact')
self.location = kwargs.get('location')
self.venue = kwargs.get('venue')
self.new_chat_member = kwargs.get('new_chat_member')
self.left_chat_member = kwargs.get('left_chat_member')
self.new_chat_title = kwargs.get('new_chat_title', '')
self.new_chat_photo = kwargs.get('new_chat_photo')
self.delete_chat_photo = bool(kwargs.get('delete_chat_photo', False))
self.group_chat_created = bool(kwargs.get('group_chat_created', False))
self.supergroup_chat_created = bool(kwargs.get('supergroup_chat_created', False))
self.migrate_to_chat_id = int(kwargs.get('migrate_to_chat_id', 0))
self.migrate_from_chat_id = int(kwargs.get('migrate_from_chat_id', 0))
self.channel_chat_created = bool(kwargs.get('channel_chat_created', False))
self.pinned_message = kwargs.get('pinned_message')
self.bot = bot
@property
def chat_id(self):
"""int: Short for :attr:`Message.chat.id`"""
return self.chat.id
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.Message:
"""
if not data:
return None
data['from_user'] = User.de_json(data.get('from'), bot)
data['date'] = datetime.fromtimestamp(data['date'])
data['chat'] = Chat.de_json(data.get('chat'), bot)
data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
data['forward_from'] = User.de_json(data.get('forward_from'), bot)
data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
data['edit_date'] = Message._fromtimestamp(data.get('edit_date'))
data['audio'] = Audio.de_json(data.get('audio'), bot)
data['document'] = Document.de_json(data.get('document'), bot)
data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
data['video'] = Video.de_json(data.get('video'), bot)
data['voice'] = Voice.de_json(data.get('voice'), bot)
data['contact'] = Contact.de_json(data.get('contact'), bot)
data['location'] = Location.de_json(data.get('location'), bot)
data['venue'] = Venue.de_json(data.get('venue'), bot)
data['new_chat_member'] = User.de_json(data.get('new_chat_member'), bot)
data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
return Message(bot=bot, **data)
def __getitem__(self, item):
if item in self.__dict__.keys():
return self.__dict__[item]
elif item == 'chat_id':
return self.chat.id
def to_dict(self):
"""
Returns:
dict:
"""
data = super(Message, self).to_dict()
# Required
data['from'] = data.pop('from_user', None)
data['date'] = self._totimestamp(self.date)
# Optionals
if self.forward_date:
data['forward_date'] = self._totimestamp(self.forward_date)
if self.edit_date:
data['edit_date'] = self._totimestamp(self.edit_date)
if self.photo:
data['photo'] = [p.to_dict() for p in self.photo]
if self.entities:
data['entities'] = [e.to_dict() for e in self.entities]
if self.new_chat_photo:
data['new_chat_photo'] = [p.to_dict() for p in self.new_chat_photo]
return data
@staticmethod
def _fromtimestamp(unixtime):
"""
Args:
unixtime (int):
Returns:
datetime.datetime:
"""
if not unixtime:
return None
return datetime.fromtimestamp(unixtime)
@staticmethod
def _totimestamp(dt_obj):
"""
Args:
dt_obj (:class:`datetime.datetime`):
Returns:
int:
"""
if not dt_obj:
return None
try:
# Python 3.3+
return int(dt_obj.timestamp())
except AttributeError:
# Python 3 (< 3.3) and Python 2
return int(mktime(dt_obj.timetuple()))
def _quote(self, kwargs):
"""Modify kwargs for replying with or without quoting"""
if 'reply_to_message_id' in kwargs:
if 'quote' in kwargs:
del kwargs['quote']
elif 'quote' in kwargs:
if kwargs['quote']:
kwargs['reply_to_message_id'] = self.message_id
del kwargs['quote']
else:
if self.chat.type != Chat.PRIVATE:
kwargs['reply_to_message_id'] = self.message_id
def reply_text(self, *args, **kwargs):
"""
Shortcut for ``bot.sendMessage(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the message is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendMessage(self.chat_id, *args, **kwargs)
def reply_photo(self, *args, **kwargs):
"""
Shortcut for ``bot.sendPhoto(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the photo is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendPhoto(self.chat_id, *args, **kwargs)
def reply_audio(self, *args, **kwargs):
"""
Shortcut for ``bot.sendAudio(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the audio is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendAudio(self.chat_id, *args, **kwargs)
def reply_document(self, *args, **kwargs):
"""
Shortcut for ``bot.sendDocument(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the document is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendDocument(self.chat_id, *args, **kwargs)
def reply_sticker(self, *args, **kwargs):
"""
Shortcut for ``bot.sendSticker(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the sticker is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendSticker(self.chat_id, *args, **kwargs)
def reply_video(self, *args, **kwargs):
"""
Shortcut for ``bot.sendVideo(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the video is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendVideo(self.chat_id, *args, **kwargs)
def reply_voice(self, *args, **kwargs):
"""
Shortcut for ``bot.sendVoice(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the voice is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendVoice(self.chat_id, *args, **kwargs)
def reply_location(self, *args, **kwargs):
"""
Shortcut for ``bot.sendLocation(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the location is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendLocation(self.chat_id, *args, **kwargs)
def reply_venue(self, *args, **kwargs):
"""
Shortcut for ``bot.sendVenue(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the venue is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendVenue(self.chat_id, *args, **kwargs)
def reply_contact(self, *args, **kwargs):
"""
Shortcut for ``bot.sendContact(update.message.chat_id, *args, **kwargs)``
Keyword Args:
quote (Optional[bool]): If set to ``True``, the contact is sent as an actual reply to
this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
"""
self._quote(kwargs)
return self.bot.sendContact(self.chat_id, *args, **kwargs)
def forward(self, chat_id, disable_notification=False):
"""Shortcut for
bot.forwardMessage(chat_id=chat_id,
from_chat_id=update.message.chat_id,
disable_notification=disable_notification,
message_id=update.message.message_id)
"""
return self.bot.forwardMessage(
chat_id=chat_id,
from_chat_id=self.chat_id,
disable_notification=disable_notification,
message_id=self.message_id)
def parse_entity(self, entity):
"""
Returns the text from a given :class:`telegram.MessageEntity`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don't handle automatically.
(That is, you can't just slice ``Message.text`` with the offset and length.)
Args:
entity (MessageEntity): The entity to extract the text from. It must be an entity that
belongs to this message.
Returns:
str: The text of the given entity
"""
# Is it a narrow build, if so we don't need to convert
if sys.maxunicode == 0xffff:
return self.text[entity.offset:entity.offset + entity.length]
else:
entity_text = self.text.encode('utf-16-le')
entity_text = entity_text[entity.offset * 2:(entity.offset + entity.length) * 2]
return entity_text.decode('utf-16-le')
def parse_entities(self, types=None):
"""
Returns a ``dict`` that maps :class:`telegram.MessageEntity` to ``str``.
It contains entities from this message filtered by their ``type`` attribute as the key, and
the text that each entity belongs to as the value of the ``dict``.
Note:
This method should always be used instead of the ``entities`` attribute, since it
calculates the correct substring from the message text based on UTF-16 codepoints.
See ``get_entity_text`` for more info.
Args:
types (Optional[list]): List of ``MessageEntity`` types as strings. If the ``type``
attribute of an entity is contained in this list, it will be returned.
Defaults to a list of all types. All types can be found as constants in
:class:`telegram.MessageEntity`.
Returns:
dict[:class:`telegram.MessageEntity`, ``str``]: A dictionary of entities mapped to the
text that belongs to them, calculated based on UTF-16 codepoints.
"""
if types is None:
types = MessageEntity.ALL_TYPES
return {entity: self.parse_entity(entity)
for entity in self.entities if entity.type in types}
| [
"wtcute.info@gmail.com"
] | wtcute.info@gmail.com |
2d16bab98905c63b9c5ab6e5049a4e550331c47d | f76ed16c49b1ec80fb006ad68243c57d238dde7f | /coins.py | 4a974d08a08a0ecb03542fc6fbaf0df5128bd16c | [] | no_license | club-de-programacion-competitiva/soluciones | 978ad054a6a40e811ea97581b2908cd882e713e5 | 2532c6accd04f26af33079989aebc1fcd91d9c95 | refs/heads/master | 2020-12-24T03:07:48.706138 | 2020-01-31T22:04:14 | 2020-01-31T22:04:14 | 237,360,936 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 712 | py | # Alternativa: crear un diccionrio que guarde cada resultado,
# y en cada iteración verificar si el valor ya existe, para evitar un ciclo infinito
# Este método es muy tardado, con el diccionario es más eficiente
def convert(gold):
if (int(gold / 2) + int(gold / 3) + int(gold / 4)) <= gold:
return gold
elif (int(gold / 2) + int(gold / 3) + int(gold / 4)) > gold:
return (convert((int(gold / 2)) + convert(int(gold / 3)) + convert(int(gold / 4))))
#return max(gold, convert((int(gold / 2)) + convert(int(gold / 3)) + convert(int(gold / 4))))
nums = []
for i in range(10):
try:
num = int(input())
except:
break
print(convert(num))
| [
"noreply@github.com"
] | noreply@github.com |
b3a796f6f6e1d72469e523177fe6e9c9ac1fb9ff | 94d5ef47d3244950a0308c754e0aa55dca6f2a0e | /migrations/versions/53e2ad0d34e3_added_produce_id_to_breed_table_instead.py | 977835fba4e07675a127bd13b29394f31d921a8f | [] | no_license | MUMT-IT/mis2018 | 9cbc7191cdc1bcd7e0c2de1e0586d8bd7b26002e | 69fabc0b16abfeba44173caa93d4f63fa79033fd | refs/heads/master | 2023-08-31T16:00:51.717449 | 2023-08-31T11:30:13 | 2023-08-31T11:30:13 | 115,810,883 | 5 | 5 | null | 2023-09-14T10:08:35 | 2017-12-30T17:06:00 | HTML | UTF-8 | Python | false | false | 1,288 | py | """added produce_id to breed table instead
Revision ID: 53e2ad0d34e3
Revises: e4f15449eb31
Create Date: 2018-02-03 22:51:38.297350
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '53e2ad0d34e3'
down_revision = 'e4f15449eb31'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('food_produce_breeds', sa.Column('produce_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'food_produce_breeds', 'food_produces', ['produce_id'], ['id'])
op.drop_constraint(u'food_produces_produce_breed_id_fkey', 'food_produces', type_='foreignkey')
op.drop_column('food_produces', 'produce_breed_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('food_produces', sa.Column('produce_breed_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.create_foreign_key(u'food_produces_produce_breed_id_fkey', 'food_produces', 'food_produce_breeds', ['produce_breed_id'], ['id'])
op.drop_constraint(None, 'food_produce_breeds', type_='foreignkey')
op.drop_column('food_produce_breeds', 'produce_id')
# ### end Alembic commands ###
| [
"likit.pre@mahidol.edu"
] | likit.pre@mahidol.edu |
56e2ea0cf73544e8dbe4bf9a62cade699f0cd4f7 | 353e6685be6737a828b8770d4d71e389ca2853b9 | /0x11-python-network_1/5-hbtn_header.py | b7a195a4f570bbc400e36cfd7ab5c6a16a190e72 | [] | no_license | adebudev/holbertonschool-higher_level_programming | 912af3f7caab3197beb062b5389f5b464b2ed177 | cb0510ed0b6d7b7c43d0fd6949139b62e2bdede7 | refs/heads/master | 2022-12-18T17:40:28.539558 | 2020-09-25T04:29:45 | 2020-09-25T04:29:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 290 | py | #!/usr/bin/python3
"""Request value X-Request-Id with requests Module"""
import requests
import sys
if __name__ == '__main__':
"""displays the value of the variable X-Request-Id"""
url = sys.argv[1]
R = 'X-Request-Id'
req = requests.get(url)
print(req.headers.get(R))
| [
"delaasuncionbuelvasadrian@gmail.com"
] | delaasuncionbuelvasadrian@gmail.com |
e771e784f52c0bbf8c8a589dd857b97d356428d2 | 52950b2783a7aebf23689c9c5397cf381d0dde7d | /oss/xbob.paper.tpami2013-1.0.0/xbob/paper/tpami2013/scripts/plda_enroll.py | a841b4daaa17533308371045ad00b2a7443841c6 | [] | no_license | zhouyong64/academiccoder | 9b4a8f9555b99dc364a0c0e4157faa582b542e90 | 5415a43889a18795fb98960ff7700dbcdd5138df | refs/heads/master | 2020-05-17T11:46:15.143345 | 2017-12-05T06:57:14 | 2017-12-05T06:57:14 | 29,723,245 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,209 | py | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Laurent El Shafey <Laurent.El-Shafey@idiap.ch>
# Wed Aug 21 16:56:36 CEST 2013
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import imp
import argparse
from .. import plda, utils
def main():
"""Enroll PLDA models"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-c', '--config-file', metavar='FILE', type=str,
dest='config_file', default='xbob/paper/tpami2013/config_multipie.py', help='Filename of the configuration file to use to run the script on the grid (defaults to "%(default)s")')
parser.add_argument('-g', '--group', metavar='LIST', type=str, nargs='+',
dest='group', default=['dev','eval'], help='Database group (\'dev\' or \'eval\') for which to retrieve models.')
parser.add_argument('--output-dir', metavar='FILE', type=str,
dest='output_dir', default='output', help='The base output directory for everything (models, scores, etc.).')
parser.add_argument('--features-dir', metavar='STR', type=str,
dest='features_dir', default=None, help='The directory where the features are stored. \
It will overwrite the value in the configuration file if any. \
Default is the value in the configuration file, that is prepended by the given output directory and the protocol.')
parser.add_argument('--plda-dir', metavar='STR', type=str,
dest='plda_dir', default=None, help='The subdirectory where the PLDA data are stored. \
It will overwrite the value in the configuration file if any. \
Default is the value in the configuration file. It is appended to the given output directory and the protocol.')
parser.add_argument('--plda-model-filename', metavar='STR', type=str,
dest='plda_model_filename', default=None, help='The (relative) filename of the PLDABase model. \
It will overwrite the value in the configuration file if any. Default is the value in the configuration file. \
It is then appended to the given output directory, the protocol and the plda directory.')
parser.add_argument('-p', '--protocol', metavar='STR', type=str,
dest='protocol', default=None, help='The protocol of the database to consider. \
It will overwrite the value in the configuration file if any. Default is the value in the configuration file.')
parser.add_argument('-f', '--force', dest='force', action='store_true',
default=False, help='Force to erase former data if already exist')
parser.add_argument('--grid', dest='grid', action='store_true',
default=False, help='It is currently not possible to paralellize this script, and hence useless for the time being.')
args = parser.parse_args()
# Loads the configuration
config = imp.load_source('config', args.config_file)
# Update command line options if required
if args.protocol: protocol = args.protocol
else: protocol = config.protocol
# Directories containing the features and the PCA model
if args.features_dir: features_dir = args.features_dir
else: features_dir = os.path.join(args.output_dir, protocol, config.features_dir)
if args.plda_dir: plda_dir_ = args.plda_dir
else: plda_dir_ = config.plda_dir
if args.plda_model_filename: plda_model_filename_ = args.plda_model_filename
else: plda_model_filename_ = config.model_filename
plda_model_filename = os.path.join(args.output_dir, protocol, plda_dir_, plda_model_filename_)
if utils.check_string(args.group): groups = [args.group]
else: groups = args.group
# (sorted) list of models
models_ids = sorted(config.db.model_ids(protocol=protocol, groups=groups))
# Loads the PLDABase
pldabase = plda.load_base_model(plda_model_filename)
# Enrolls all the client models
print("Enrolling PLDA models...")
for model_id in models_ids:
# Path to the model
model_path = os.path.join(args.output_dir, protocol, plda_dir_, config.models_dir, str(model_id) + ".hdf5")
# Removes old file if required
if args.force:
print("Removing old PLDA model.")
utils.erase_if_exists(model_path)
if os.path.exists(model_path):
print("PLDA model already exists.")
else:
# List of enrollment filenames
enroll_files = config.db.objects(protocol=protocol, model_ids=(model_id,), purposes='enrol')
# Loads enrollment files
data = utils.load_data(enroll_files, features_dir, config.features_ext)
# Enrolls
machine = plda.enroll_model(data, pldabase)
# Saves the machine
utils.save_machine(machine, model_path)
if __name__ == "__main__":
main()
| [
"snowalvie@gmail.com"
] | snowalvie@gmail.com |
98ae303820c7197f7a53af3c15c75266fb7f3b88 | a9eb3084b4841c208b00b967d955324a4d43f082 | /maintenance/scripts/idr0079_csv_to_table_on_project.py | 7c425ccdf06dc091c4f1c6c75c5ab608cf086fd1 | [] | no_license | ome/training-scripts | cd520a0a50ea834d662692206c17dedb8a8d4381 | 6f6866b21be4cbf48cafe2756899a21b4764b47e | refs/heads/master | 2023-06-22T14:30:21.184573 | 2022-12-05T18:51:08 | 2022-12-05T18:51:08 | 127,337,041 | 6 | 13 | null | 2023-06-15T14:45:04 | 2018-03-29T19:17:49 | Python | UTF-8 | Python | false | false | 5,242 | py | #!/usr/bin/env python
import pandas
import csv
import mimetypes
import os
import omero.clients
import omero.cli
import omero
from omero_metadata.populate import ParsingContext
from omero.util.metadata_utils import NSBULKANNOTATIONSRAW
project_name = "idr0079-hartmann-lateralline/experimentA"
# NB: Need to checkout https://github.com/IDR/idr0079-hartmann-lateralline
# and run this from in idr0079-hartmann-lateralline directory OR update
# tables_path to point to that repo.
tables_path = "./experimentA/idr0079_experimentA_extracted_measurements/%s/"
# Lots of tsv files to choose from...
# e.g. Tissue Frame Of Reference Primary Component Analysis measured:
# tables_path += "%s_shape_TFOR_pca_measured.tsv"
# e.g. Other Measurements:
tables_path += "%s_other_measurements.tsv"
def get_omero_col_type(col_name):
"""Returns s for string, d for double, l for long/int"""
if "Name" in col_name:
return "s"
return "d"
def populate_metadata(project, dict_data):
csv_columns = list(dict_data[0].keys())
# Dataset Name, Image Name, PC...
csv_columns.sort()
# header s,s,d,d,d,...
col_types = [get_omero_col_type(name) for name in csv_columns]
header = f"# header {','.join(col_types)}\n"
print('header', header)
csv_file = "other_measurements_summaries.csv"
print("writing to", csv_file)
with open(csv_file, 'w') as csvfile:
# header s,s,d,l,s
csvfile.write(header)
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data:
writer.writerow(data)
# Links the csv file to the project and parses it to create OMERO.table
mt = mimetypes.guess_type(csv_file, strict=False)[0]
fileann = conn.createFileAnnfromLocalFile(
csv_file, mimetype=mt, ns=NSBULKANNOTATIONSRAW
)
fileid = fileann.getFile().getId()
project.linkAnnotation(fileann)
client = project._conn.c
ctx = ParsingContext(
client, project._obj, fileid=fileid, file=csv_file, allow_nan=True
)
ctx.parse()
def process_image(image):
# Read csv for each image
image_name = image.name
table_pth = tables_path % (image_name, image_name)
print('table_pth', table_pth)
df = pandas.read_csv(table_pth, delimiter="\t")
cols = ["Source Name",
"Cell ID",
"Centroids RAW X",
"Centroids RAW Y",
"Centroids RAW Z",
"Centroids TFOR X",
"Centroids TFOR Y",
"Centroids TFOR Z",
"Longest Extension",
"Major Axis Length",
"Major/Medium Axis Eccentricity",
"Major/Minor Axis Eccentricity",
"Medium Axis Length",
"Medium/Minor Axis Eccentricity",
"Minor Axis Length",
"Orientation along X",
"Orientation along Y",
"Orientation along Z",
"Roundness (Smoothness)",
"Sphericity",
"Surface Area",
"Volume",
"X Axis Length",
"Y Axis Length",
"Y/X Aspect Ratio",
"Z Axis Length",
"Z/X Aspect Ratio",
"Z/Y Aspect Ratio"]
summary = df.describe()
data = {'count': summary['Cell ID']['count']}
# get: RAW_Y_Range, RAW_X_Range, RAW_Z_Range
for dim in ['X', 'Y', 'Z']:
min_val = summary[f'Centroids RAW {dim}']['min']
max_val = summary[f'Centroids RAW {dim}']['max']
data[f'RAW_{dim}_Range'] = max_val - min_val
min_tfor = summary[f'Centroids TFOR {dim}']['min']
max_tfor = summary[f'Centroids TFOR {dim}']['max']
data[f'TFOR_{dim}_Range'] = max_tfor - min_tfor
# Mean_Sphericity, Mean_Volume, Mean_Z_Axis_Length, Mean_X_Axis_Length
for col_name in ['Sphericity', 'Volume', 'X Axis Length', 'Y Axis Length', 'Z Axis Length']:
value = summary[col_name]['mean']
data[f'Mean_{col_name}'.replace(' ', '_')] = value
# For PC .tsf
# columns are named "PC 1", "PC 2" etc...
# for pc_id in range(1,4):
# for stat in ['count', 'mean', 'min', 'max', 'std']:
# # No spaces in OMERO.table col names!
# omero_table_colname = f"PC{pc_id}_{stat}"
# value = summary[f'PC {pc_id}'][stat]
# data[omero_table_colname] = value
return data
def main(conn):
project = conn.getObject("Project", attributes={"name": project_name})
print("Project", project.id)
conn.SERVICE_OPTS.setOmeroGroup(project.getDetails().group.id.val)
data_rows = []
# For each Image in Project, open the local CSV and summarise to one row
for dataset in project.listChildren():
for image in dataset.listChildren():
# ignore _seg images etc.
if '_' in image.name:
continue
dict_data = process_image(image)
dict_data['Dataset Name'] = dataset.name
dict_data['Image Name'] = image.name
data_rows.append(dict_data)
populate_metadata(project, data_rows)
# Usage:
# cd idr0079-hartmann-lateralline
# python scripts/csv_to_table_on_project.py
if __name__ == "__main__":
with omero.cli.cli_login() as c:
conn = omero.gateway.BlitzGateway(client_obj=c.get_client())
main(conn)
conn.close()
| [
"w.moore@dundee.ac.uk"
] | w.moore@dundee.ac.uk |
65b9c52ec1d9f80e900be3aaf4e02cf9ea349b1c | 9775ca99e222ec2cf7aa071b68954ee750f4b58a | /0x09-python-everything_is_object/100-magic_string.py | bc304a2f8dc85450f6f897c63025222c9cd30a42 | [] | no_license | humeinstein/holbertonschool-higher_level_programming | f7363a129cc5e2787207ab898c984b5866cbe7de | 01ba467964d7585ee95b7e0d76e7ae6bbdf61358 | refs/heads/master | 2020-07-22T20:25:21.868028 | 2020-02-13T23:08:49 | 2020-02-13T23:08:49 | 207,317,556 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 113 | py | #!/usr/bin/python3
def magic_string(new_list=[]):
new_list += ["Holberton"]
return ", ".join(new_list) | [
"humeincreations@gmail.com"
] | humeincreations@gmail.com |
3124b674fa821716127a4d34ee60d1afc948da96 | 7000895fad6f4c23084122ef27b3292d5e57df9f | /src/xrd/crypto/Qryptonight.py | 1475f988d07b1c8d0513eab0742c2dab0685602f | [
"MIT"
] | permissive | jack3343/xrd-core | 1302cefe2a231895a53fcef73e558cdbc1196884 | 48a6d890d62485c627060b017eadf85602268caf | refs/heads/master | 2022-12-15T07:36:16.618507 | 2020-08-27T09:21:36 | 2020-08-27T09:21:36 | 290,652,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,140 | py | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from xrd.core import config
from xrd.core.Singleton import Singleton
from xrd.crypto.Qryptonight7 import Qryptonight7
from xrd.crypto.QRandomX import QRandomX
class Qryptonight(object, metaclass=Singleton):
def __init__(self):
self.lock = threading.Lock()
self._qryptonight_7 = Qryptonight7()
self._qrandom_x = QRandomX()
def get_qn(self, block_number):
if block_number < config.dev.hard_fork_heights[0]:
return self._qryptonight_7
else:
return self._qrandom_x
def get_seed_height(self, block_number):
return self._qrandom_x.get_seed_height(block_number)
def hash(self, block_number, seed_height, seed_hash, blob):
with self.lock:
if block_number < config.dev.hard_fork_heights[0]:
return bytes(self._qryptonight_7.hash(blob))
else:
return bytes(self._qrandom_x.hash(block_number, seed_height, seed_hash, blob))
| [
"70303530+jack3343@users.noreply.github.com"
] | 70303530+jack3343@users.noreply.github.com |
950e5209c58dd48953f9e0b2d9ea73aa3c6f81dc | 0b344fa1202824ac1b312115c9d85467dd0b2b50 | /neutron/plugins/embrane/l2base/openvswitch/__init__.py | 1fac4725b72223216d141bfcf4e5a24cc93df883 | [
"Apache-2.0"
] | permissive | netscaler/neutron | 78f075633462eb6135032a82caf831a7e10b27da | 1a17ee8b19c5440e1300426b5190de10750398e9 | refs/heads/master | 2020-06-04T01:26:12.859765 | 2013-10-17T06:58:30 | 2013-10-17T06:58:30 | 13,155,825 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 714 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Embrane, 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.
#
# @author: Ivar Lazzaro, Embrane, Inc.
| [
"ivar@embrane.com"
] | ivar@embrane.com |
a305b3406bd25b2530b5c1818128b7efcc88a902 | 29ff793f23f77297b635fdbcde8cce3a182d9b0c | /craigslist_webscraping/items.py | 61b641d8893df2781ce81f3255698a2d0d111fae | [] | no_license | Kiwibp/NYC-DSA-Bootcamp--Web-Scraping | 2212b617427bde8c670adf53558b2f9ba4aab693 | 8ab2cf2f1d130c4167bff122924a082382e27d68 | refs/heads/master | 2020-03-19T17:32:45.899251 | 2018-07-10T16:08:34 | 2018-07-10T16:08:34 | 136,765,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class CraigslistWebscrapingItem(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field()
location = scrapy.Field()
date = scrapy.Field()
| [
"keenanburkepitts@keenans-mbp.home"
] | keenanburkepitts@keenans-mbp.home |
a795f19f8bf50240b8403bd4eee3481113f2d309 | 2c42b9c205768f6e2746ad5452097869f7fe7245 | /config.py | 8c75e3b9b219af63949fca706001051ed505e7d4 | [] | no_license | roquesantos-cronapp/flask-mega-tutorial | 36847126e283036e5c7ae5a1cb5bbde3eac813fc | b3df35c9780a3ef5de49eb9e94bbeeb464799b55 | refs/heads/master | 2020-04-05T08:03:21.913155 | 2018-11-08T11:58:45 | 2018-11-08T11:58:45 | 156,699,564 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 674 | py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
POSTS_PER_PAGE = 25
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
ADMINS = ['roque.santos@cronapp.io']
LANGUAGES = ['en', 'es'] | [
"roque.santos@cronapp.io"
] | roque.santos@cronapp.io |
48d6846699beba2a700f52ae82f3116ffef4551e | a1855d3b65d538f7520c629f4d43819792b7d872 | /twitterbot.py | 905a9fae4814e2545bbf0db73ee0581198d8b0ec | [
"MIT"
] | permissive | gabriel-marchal/Twitter-InternetSpeed-Bot-Kolbi | 07ecd3e516782ca5a604650faa741e911fb6abf5 | 4329c210c6bc529dd917c5c73d29ff2cf975349b | refs/heads/master | 2022-12-08T17:11:36.874668 | 2020-09-01T23:19:33 | 2020-09-01T23:19:33 | 291,552,841 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,283 | py | from TwitterAPI import TwitterAPI
import speedtest
import sched
import time
import os
from dotenv import load_dotenv
load_dotenv()
### CONFIG VARIABLES ###
consumer_key = os.getenv("consumer_key")
consumer_secret = os.getenv("consumer_secret")
access_token_key = os.getenv("access_token_key")
access_token_secret = os.getenv("access_token_secret")
advertised_download = 50 #in Mbps
advertised_upload = 10 #in Mbps
running_interval = 450 #in seconds
#########################
api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
def check_speeds():
speedtester = speedtest.Speedtest()
# returned as bits, converted to megabits
download_speed = int(speedtester.download() / 1000000)
upload_speed = int(speedtester.upload() / 1000000)
print("Download Speed: " + str(download_speed) + "Mbps")
print("Upload Speed: " + str(upload_speed) + "Mbps")
# # Uncomment code to create triaged messaging
# thresholds = {'first':0.8, 'second':0.5}
# messages = {'first':'[enter polite message]', 'second': '[enter stern message]'}
# if download_speed < advertised_download * thresholds['first'] or upload_speed < advertised_upload * thresholds['first']:
# tweet = messages['first']
# api.request("statuses/update", {"status": tweet})
# elif download_speed < advertised_download * thresholds['second'] or upload_speed < advertised_upload * thresholds['second']:
# tweet = messages['second']
# api.request("statuses/update", {"status": tweet})
# If using triaged messaging, above, then comment out the conditional block, below.
if download_speed < advertised_download * 0.75:
tweet = "@kolbi_cr su internet es una basura! Por que me llegan solamente " + str(download_speed) + " en vez de los " + str(advertised_download) + "Mbps que me cobran? Arreglen su servicio.."
api.request("statuses/update", {"status": tweet})
print("Tweet sent:\n" + tweet)
print("\n")
else:
print("Speeds OK, no tweet")
print("\n")
scheduler = sched.scheduler(time.time, time.sleep)
def periodic_check(scheduler, interval, action, arguments=()):
scheduler.enter(interval, 1, periodic_check, (scheduler, interval, action, arguments))
action()
periodic_check(scheduler, running_interval, check_speeds)
scheduler.run() | [
"gmarchal1@ucenfotec.ac.cr"
] | gmarchal1@ucenfotec.ac.cr |
d3407c1815d554881ce33812bf3dfc89430fe36f | 2521e6427a7668d8cc91eabb368a5cf0eb7310f9 | /Cap18-Extras/09_dimensionar.py | 5872547aa4d77143e41c6c59a3c7fd24ab1da260 | [] | no_license | frclasso/turma3_Python1_2018 | 4a7bc0ba0eb538100400c15fc5c5b3ac1eeb7e50 | 47cd3aaa6828458b7f5164a8bce717bb8dd83a7c | refs/heads/master | 2020-04-06T16:18:00.889198 | 2019-06-10T15:11:32 | 2019-06-10T15:11:32 | 157,614,408 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 284 | py | #!/usr/bin/env python3
import openpyxl
wb = openpyxl.Workbook()
#print(wb.sheetnames)
sheet = wb.active
sheet['A1'] = 'Tall row'
sheet['B2'] = 'Wide column'
sheet.row_dimensions[1].height = 70
sheet.column_dimensions['B'].widht = 50
wb.save('dimensions.xlsx')
print('Feito...') | [
"frcalsso@yahoo.com.br"
] | frcalsso@yahoo.com.br |
1bb77fc8dacaeb560a91eefb770e6455bfb58186 | add0bb7a309ea346614d7f560a24e653d3d0ff67 | /Python多线程/多线程.py | 141bbbb34bec2b4895f11d7847ae4c8244b89526 | [] | no_license | 1572903465/PythonProjects | 935aff08d5b3d3f146393764a856369061513d36 | 73576080174f72ea1df9b36d201cf3949419041b | refs/heads/master | 2023-06-10T15:50:49.178112 | 2021-07-05T15:42:53 | 2021-07-05T15:42:53 | 301,328,267 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 801 | py | import time
import threading
#GIL是解释器用于同步线程的一种机制
#它使得任何时刻仅有一个线程在执行 (就算你是多核处理器也一样)
#使用GIL的解释器只允许同一时间执行一个线程
#常见的使用GIL的解释器有 CPython 与 Ruby MRI
#如果你用JPython没有GIL锁
#CPU 多线程
def start():#单纯计算 消耗CPU资源 没有实际意义
data = 0
for _ in range(10000000):#连续加
data += 1
return
if __name__ == "__main__":
time_data = time.time()
ts = {}
for i in range(10):
t = threading.Thread(target = start)#target参数填函数名 不要用括号
t.start()
ts[i] = t #全新的线程
for i in range(10):
ts[i].join()
print(time.time() - time_data) | [
"1572903465@qq.com"
] | 1572903465@qq.com |
5878577c9ecb22d9196dd6cc719dd160f8576408 | 8908b41e3911d1ebeaefc2154ee99d254b1609f5 | /astar.py | 2b544a677092992d4c9e33f1b5a147cef7ec5cf8 | [] | no_license | multikulti/Saper | ff607509defa52b301d32e80fdef5fadef9911b8 | 3eb9c3bce783853275f358edbeb72f3d2c82a911 | refs/heads/master | 2021-01-11T00:45:07.556711 | 2017-01-16T15:31:54 | 2017-01-16T15:31:54 | 70,495,327 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,950 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
""" generic A-Star path searching algorithm """
import sys
from abc import ABCMeta, abstractmethod
class AStar:
@abstractmethod
def heuristic_cost_estimate(self, start, goal):
"""computes the estimated (rough) distance between two random nodes, this method must be implemented in a subclass"""
raise NotImplementedException
@abstractmethod
def distance_between(self, n1, n2):
"""gives the real distance between two adjacent nodes n1 and n2 (i.e n2 belongs to the list of n1's neighbors), this method must be implemented in a subclass"""
raise NotImplementedException
@abstractmethod
def neighbors(self, node):
"""for a given node, returns (or yields) the list of its neighbors. this method must be implemented in a subclass"""
raise NotImplementedException
def _yield_path(self, came_from, last):
yield last
current = came_from[last]
while True:
yield current
if current in came_from:
current = came_from[current]
else:
break
def _reconstruct_path(self, came_from, last):
return list(reversed([p for p in self._yield_path(came_from, last)]))
def astar(self, start, goal):
"""applies the a-star path searching algorithm in order to find a route between a 'start' node and a 'root' node"""
closedset = set([]) # The set of nodes already evaluated.
# The set of tentative nodes to be evaluated, initially containing the
# start node
openset = set([start])
came_from = {} # The map of navigated nodes.
g_score = {}
g_score[start] = 0 # Cost from start along best known path.
# Estimated total cost from start to goal through y.
f_score = {}
f_score[start] = self.heuristic_cost_estimate(start, goal)
while len(openset) > 0:
# the node in openset having the lowest f_score[] value
current = min(f_score, key=f_score.get)
if current == goal:
return self._reconstruct_path(came_from, goal)
openset.discard(current) # remove current from openset
del f_score[current]
closedset.add(current) # add current to closedset
for neighbor in self.neighbors(current):
if neighbor in closedset:
continue
tentative_g_score = g_score[current] + self.distance_between(current, neighbor)
if (neighbor not in openset) or (tentative_g_score < g_score[neighbor]):
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + self.heuristic_cost_estimate(neighbor, goal)
openset.add(neighbor)
return None
__all__ = ['AStar']
| [
"mateusz.ziolkovski@gmail.com"
] | mateusz.ziolkovski@gmail.com |
9eea2ab6a50a9be9c909a9e2de1e8ad63cbdbe62 | 13228839374753871bb6e2f5af291e0824bf79bf | /build.py | da67e52466557fae12e57999c3f8baac9bd3c8eb | [] | no_license | theirix/conan-libssh2 | a1fc6a615ca5f933a6352926e365db395a832b4c | 965b2f107460594d3e0321ba27cddcaeb7cf3d65 | refs/heads/release/1.8.0 | 2021-01-11T14:17:50.297665 | 2017-01-17T15:38:16 | 2017-01-17T15:38:16 | 81,315,824 | 0 | 1 | null | 2017-02-08T10:08:10 | 2017-02-08T10:08:09 | null | UTF-8 | Python | false | false | 207 | py | from conan.packager import ConanMultiPackager
if __name__ == "__main__":
builder = ConanMultiPackager()
builder.add_common_builds(shared_option_name="libssh2:shared", pure_c=True)
builder.run()
| [
"a.kucher@avantize.com"
] | a.kucher@avantize.com |
88fca4c4dac79c79690eba654d20db9b00f37a69 | afe096d0d4b6112b0a098790c2feb5c4f919f968 | /load_configure.py | 47b2b4b0e180d517b21b2213b4b72b10a56bac67 | [
"MIT"
] | permissive | tjandy/ExcelToCode | 0e964f00b745b1610b0e439217fecf64336ea242 | fa5a89e367e83c1273fe6122eed68af1ff9ff911 | refs/heads/master | 2021-01-18T08:29:23.653598 | 2017-08-06T08:15:08 | 2017-08-06T08:15:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,968 | py | # -*- coding: utf-8 -*-
import os
import sys
import imp
import xlsconfig
from util import resolve_path
######################################################################
### 加载配置文件。cfg_file是python格式的文件。
######################################################################
def load_configure(cfg_file, option):
cfg_file = os.path.abspath(cfg_file)
print "load configure file", cfg_file
if not os.path.exists(cfg_file):
raise RuntimeError, "配置文件不存在: %s" % cfg_file
cfg = imp.load_source("custom_configure", cfg_file)
for k, v in cfg.__dict__.iteritems():
if k.startswith('_'): continue
setattr(xlsconfig, k, v)
file_path = os.path.dirname(cfg_file)
xlsconfig.CONFIG_PATH = file_path
xlsconfig.pre_init_method(xlsconfig)
safe_parse_path(option, "project", "PROJECT_PATH")
safe_parse_path(option, "input", "INPUT_PATH")
safe_parse_path(option, "output", "OUTPUT_PATH")
safe_parse_path(option, "temp", "TEMP_PATH")
safe_parse_path(option, "converter", "CONVERTER_PATH")
for k in xlsconfig.DEPENDENCIES.keys():
path = xlsconfig.DEPENDENCIES[k]
xlsconfig.DEPENDENCIES[k] = resolve_path(path)
# 所有已知的配置中,名字叫'file_path'的路径,会自动转义
resolve_path_in_config(xlsconfig.CODE_GENERATORS)
resolve_path_in_config(xlsconfig.DATA_WRITERS)
resolve_path_in_config(xlsconfig.POSTPROCESSORS)
# 加载完毕回调
xlsconfig.post_init_method(xlsconfig)
return
# 解析并转义路径
# option中的路径参数优先于配置文件中的参数
def safe_parse_path(option, option_key, cfg_key):
path = getattr(option, option_key, None)
if path is None:
path = getattr(xlsconfig, cfg_key)
path = resolve_path(path)
setattr(xlsconfig, cfg_key, path)
# 转义所有后缀为'_path'的变量
def resolve_path_in_config(config):
for info in config:
keys = info.keys()
for k in keys:
if k.endswith("_path"):
info[k] = resolve_path(info[k])
return
| [
"you_lan_hai@foxmail.com"
] | you_lan_hai@foxmail.com |
7a1483ba083193f24b9231a2dbfa18ffc09c84aa | 43321ac13d178656a69b5aeb2eb3aaee5ac31153 | /PyBank/main.py | 875afef90ba2d4efac8ff5b983d3c5c38753f8d6 | [] | no_license | Daltonjfield/Python-Challange | 5fc50905ec5821cdd31038f9a84535ee4f914500 | 8ad1a984845a4c80f704a8d9e61b8f56850e0234 | refs/heads/master | 2022-12-20T02:27:23.714697 | 2020-10-02T23:08:54 | 2020-10-02T23:08:54 | 299,745,456 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,600 | py | # Dependencies
import os
import csv
# Variables
months = []
profit_loss_changes = []
total_months = 0
net_total_pl = 0
original_month_pl = 0
current_month_pl = 0
profit_loss_change = 0
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
for row in csvreader:
print(row)
# Calculate total numbers of months included in the dataset
total_months += 1
# Calculate Net total amount of "Profit/Losses" over the entire period
current_month_pl = int(row[1])
net_total_pl += current_month_pl
if (total_months == 1):
original_month_pl = current_month_pl
continue
else:
profit_loss_change = current_month_pl - original_month_pl
months.append(row[0])
profit_loss_changes.append(profit_loss_change)
original_month_pl = current_month_pl
# Calculate the average of the changes in "Profit/Losses" over the entire period
sum_pl = sum(profit_loss_changes)
avg_pl = round(sum_pl/(total_months - 1), 2)
# Calculate the greatest increase in in profits (date and amount) over the entire period
greatest_increase = max(profit_loss_changes)
increase_index = profit_loss_changes.index(greatest_increase)
best_month = months[increase_index]
# Calculate the greatest decrease in in profits (date and amount) over the entire period
greatest_decrease = min(profit_loss_changes)
decrease_index = profit_loss_changes.index(greatest_decrease)
worst_month = months[decrease_index]
print("Financial Analysis")
print("----------------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${net_total_pl}")
print(f"Average Change: ${avg_pl}")
print(f"Greatest Increase in Profits: {best_month} (${greatest_increase})")
print(f"Greatest Decrease in Losses: {worst_month} (${greatest_decrease})")
output_path = os.path.join("Analysis","financial_analysis.txt")
with open(output_path, "w") as outfile:
outfile.write("Financial Analysis\n")
outfile.write("-------------------\n")
outfile.write(f"Total Months : {total_months}\n")
outfile.write(f"Total: ${net_total_pl}\n")
outfile.write(f"Average Change: ${avg_pl}\n")
outfile.write(f"Greatest Increase in Profits: {best_month} (${greatest_increase})\n")
outfile.write(f"Greatest Decrease in Losses: {worst_month} (${greatest_decrease}\n") | [
"daltonfield@Daltons-MacBook-Pro.local"
] | daltonfield@Daltons-MacBook-Pro.local |
8a9f2c084e5fbff4425c903743db38ff3e08f6e7 | e7d1e06b5686f87280db292863b34ce0ea530d94 | /src/examples/func_local.py | 151515b33e59143e74c36eb6b6361a128c4ad393 | [] | no_license | tobereborn/byte-of-python2 | 4e9abdb3c513f8b5aa3955873b7468ddb60c8883 | c7e06be6f246dc6292780d59de0806b19c086943 | refs/heads/master | 2021-01-12T04:25:00.536489 | 2017-02-07T02:06:23 | 2017-02-07T02:06:23 | 77,606,492 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 213 | py | #!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on Dec 31, 2016
@author: weizhen
'''
def func(x):
print 'Local x is', x
x = 2
print 'Change local x to', x
x = 50
func(x)
print 'x is still', x
| [
"none"
] | none |
f2934ceaf7b1d80f3dbef566c84a049199ad5a6a | af4a73729eed23d505276cf4d43130ccdd4bb532 | /lambda.py | b0a1f71bb9c8e2d2866f8ce25e42cc73187f5f0e | [] | no_license | chetanoli2012/Python-Class-Codes | 413c1064d8b31e49cd7eba7c12928cb4e16a4dae | 843ab1656c69f97b3c8b4a72f7ad4021e90f36ce | refs/heads/master | 2020-03-12T07:49:13.000796 | 2018-04-21T21:50:08 | 2018-04-21T21:50:08 | 130,514,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 64 | py | items = [1,2,3,4,5]
l = list(map(lambda x:x**2, items))
print(l) | [
"chetanoli2012@gmail.com"
] | chetanoli2012@gmail.com |
5d17c50bdd48e6c41bda269ba92d577eb1e79b42 | b9648b18534941232fc15fa0a851548a0930fc4b | /user_input.py | a2db26a060da02d5005ad13899ba8eed36b0a5fe | [] | no_license | csmyth215/shape_project | 0eda3e70ef90d6a5bb647663ee1cf7c08043c437 | 371a47326c962695d8b87c4efcfd9cfae3e328c3 | refs/heads/master | 2023-08-20T17:25:08.207906 | 2020-06-27T15:58:25 | 2020-06-27T15:58:53 | 250,755,121 | 1 | 0 | null | 2021-09-22T19:20:41 | 2020-03-28T09:20:21 | Python | UTF-8 | Python | false | false | 17,146 | py | import sys
from two_dimensional_shapes import *
from three_dimensional_shapes import *
# Currently lacking final input option to ask the user if they would like to run the program again.
# Need to restructure code to separate user input from calculations,
# and group calculations common to several shapes.
# Need to write automated tests to identify calculation or programming errors.
def get_radius(item):
item = str(item)
print(f"Tell me the radius of the {item}: ")
validation_pending = True
while validation_pending == True:
rad = input()
try:
rad = int(rad)
if rad > 0:
validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
rad = float(rad)
if rad > 0:
validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value.")
return(float(rad))
def get_quad_properties(quad):
# requires wording alignment
quad = str(quad)
print(f"Tell me the length and perpendicular height of {quad}: ")
length_validation_pending = True
perph_validation_pending = True
while length_validation_pending == True:
leng = input("Length: ")
try:
leng = int(leng)
if leng > 0:
length_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
leng = float(leng)
if leng > 0:
length_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value.")
while perph_validation_pending == True:
perph = input("Perpendicular height: ")
try:
perph = int(perph)
if perph > 0:
perph_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
perph = float(perph)
if perph > 0:
perph_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value greater than 0.")
print("How many pairs of parallel side does your shape have - 1 or 2?")
parallel_varification_pending = True
while parallel_varification_pending == True:
parallel_pairs = input()
try:
parallel_pairs = int(parallel_pairs)
if parallel_pairs > 0 and parallel_pairs <= 2:
parallel_varification_pending = False
else:
print("Please enter '1' or '2'.")
except ValueError:
print("Please enter '1' or '2'.")
if parallel_pairs == 2:
print(f"What is the smallest interior angle in your shape (in degrees)?")
angle_validation_pending = True
while angle_validation_pending == True:
angle = input()
try:
angle = int(angle)
if angle > 0 and angle <= 90:
angle_validation_pending = False
else:
print("Please enter a numerical value greater than 0 and less than or equal to 90.")
except:
try:
angle = float(angle)
if angle > 0 and angle <= 90:
angle_validation_pending = False
else:
print("Please enter a numerical value greater than 0 and less than or equal to 90.")
except ValueError:
print("Please enter a numerical value greater than 0 and less than or equal to 90.")
properties = (leng, perph, angle)
properties_ints = []
for i in properties:
properties_ints.append(int(i))
return properties_ints
else:
print("The shape metric calculator doesn't work with trapezia just yet, sorry!")
def determine_triangle_knowledge():
print("What triangle metrics do you already know?")
triangle_combinations = {1: "Base and perpendicular height", 2: "All three sides", 3: "Neither 1 nor 2"}
for x, y in triangle_combinations.items():
print(x,".", y)
validation_pending = True
while validation_pending == True:
known_combo = input()
try:
known_combo = int(known_combo)
if known_combo == 1:
validation_pending = False
return get_bh()
elif known_combo == 2:
validation_pending = False
return get_abc()
elif known_combo == 3:
validation_pending = False
print("The calculator needs that minimum knowledge for now, sorry!")
else:
print("Please enter '1', '2', or '3'.")
except ValueError as ex:
print("Please enter '1', '2', or '3'.")
print("Debug!:", ex)
def get_bh():
print("Tell me the base and perpendicular height of your triangle: ")
base_validation_pending = True
perph_validation_pending = True
while base_validation_pending == True:
base = input("Base: ")
try:
base = int(base)
if base > 0:
base_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
base = float(base)
if base > 0:
base_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value.")
while perph_validation_pending == True:
perph = input("Perpendicular height: ")
try:
perph = int(perph)
if perph > 0:
perph_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
perph = float(perph)
if perph > 0:
perph_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value greater than 0.")
bh = []
base = float(base)
ph = float(perph)
bh.append(base)
bh.append(perph)
return bh
def get_abc():
print("Tell me the lengths of the three sides of your triangle: ")
abc_validation_pending = True
while abc_validation_pending == True:
abc = []
a = input("Length a: ")
abc.append(a)
b = input("Length b: ")
abc.append(b)
c = input("Length c: ")
abc.append(c)
count = 0
for x in abc:
try:
x = int(x)
if x > 0:
count += 1
else:
print("Please enter numerical values greater than 0.")
except:
try:
x = float(x)
if x > 0:
count += 1
else:
print("Please enter numerical values greater than 0.")
except ValueError:
print("Please enter numerical values greater than 0.")
abcfloats = []
a = float(a)
b = float(b)
c = float(c)
abcfloats.append(a)
abcfloats.append(b)
abcfloats.append(c)
if a + b > c and b + c > a and a + c > b and count == 3:
abc_validation_pending = False
else:
print("Your three lengths do not make a valid triangle. Please try again.")
return abcfloats
def determine_prism_type():
print("What shape is the base of your prism?")
prisms = {1: "Quadrilateral", 2: "Triangle", 3: "Other"}
for x, y in prisms.items():
print(x,".", y)
validation_pending = True
while validation_pending == True:
prism = input()
try:
prism = int(prism)
if prism == 1:
validation_pending = False
this_prism_properties = (1, get_quad_properties("one prism face"))
return this_prism_properties
elif prism == 2:
validation_pending = False
print("Thinking of the triangular face of your prism...")
this_prism_properties = (2, determine_triangle_knowledge())
return this_prism_properties
elif prism == 3:
validation_pending = False
print("The calculator isn't built for prisms with so many size yet, sorry!")
else:
print("Please enter '1', '2', or '3'.")
except ValueError as ex:
print("Please enter '1', '2', or '3'.")
print("Debug!:", ex)
def determine_depth(shape):
print(f"Tell me the depth of your {shape}: ")
validation_pending = True
while validation_pending == True:
depth = input("Depth: ")
try:
depth = int(depth)
if depth > 0:
length_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except:
try:
depth = float(depth)
if depth > 0:
length_validation_pending = False
else:
print("Please enter a numerical value greater than 0.")
except ValueError:
print("Please enter a numerical value.")
return(float(depth))
def size_two_dimensional_shape():
two_dimensional_inventory = {1: 'Circle', 2: 'Quadrilateral', 3: 'Triangle', 4: 'Other'}
for x, y in two_dimensional_inventory.items():
print(x,".", y)
validation_pending = True
while validation_pending == True:
shape_number = input()
try:
shape_number = int(shape_number)
except ValueError:
pass
if shape_number == 1:
validation_pending = False
this_radius = get_radius("circle")
my_circle = Circle(this_radius)
print(f"Your circle has radius", this_radius, "units, perimeter",
'{0:.2f}'.format(my_circle.get_perimeter()), "units and area",
'{0:.2f}'.format(my_circle.get_area()), "square units")
elif shape_number == 2:
validation_pending = False
this_quad = get_quad_properties("your quadrilateral")
my_quad = Quadrilateral(this_quad[0], this_quad[1], this_quad[2])
print("Your shape has length", this_quad[0], "units,
perpendicular height", this_quad[1], "units, perimeter",
'{0:.2f}'.format(my_quad.get_perimeter()), "units and area",
'{0:.2f}'.format(my_quad.get_area()), "square units")
elif shape_number == 3:
validation_pending = False
properties = determine_triangle_knowledge()
if properties is None:
print("Aborting program for now (insufficient knowledge).")
sys.exit()
if len(properties) == 3:
# abc known
my_tri = Triangle(properties[1], a=properties[0], c=properties[2])
print("Your triangle has lengths", properties[0],",", properties[1],
"and", properties[2], "units, perimeter", '{0:.2f}'.format(my_tri.get_perimeter()),
"units and area", '{0:.2f}'.format(my_tri.get_area()), "square units")
elif len(properties) == 2:
# base and height known
my_tri = Triangle(properties[0], ph=properties[1])
print("Your triangle has base", properties[0], "units, perpendicular height",
properties[1], "units, perimeter", '{0:.2f}'.format(my_tri.get_perimeter()),
"units and area", '{0:.2f}'.format(my_tri.get_area()), "square units")
else:
print("Error encountered. Contact administrator.")
elif shape_number == 4:
validation_pending = False
print("Other shapes will be coming soon.")
else:
print("Please enter either '1', '2' '3' or '4'.")
def size_three_dimensional_shape():
three_dimensional_inventory = {1: 'Sphere', 2: 'Prism', 3: 'Cylinder', 4: 'Other'}
for x, y in three_dimensional_inventory.items():
print(x,".", y)
validation_pending = True
while validation_pending == True:
shape_number = input()
try:
shape_number = int(shape_number)
except ValueError:
pass
if shape_number == 1:
validation_pending = False
this_radius = get_radius("sphere")
my_sphere = Sphere(this_radius)
print(f"Your sphere has radius", this_radius,
", surface area", '{0:.2f}'.format(my_sphere.get_surface_area()),
"square units and volume", '{0:.2f}'.format(my_sphere.get_volume()), "cubic units.")
elif shape_number == 2:
validation_pending = False
properties = determine_prism_type()
if properties[1] is None:
print("Aborting program for now (insufficient knowledge).")
sys.exit()
d = determine_depth("prism")
if properties[0] == 1:
my_quad_prism = QuadPrism(properties[1][0], properties[1][1], d)
print(f"Your prism has surface area",
'{0:.2f}'.format(my_quad_prism.get_surface_area()),
"square units and volume", '{0:.2f}'.format(my_quad_prism.get_volume()), "cubic units.")
elif properties[0] == 2:
if len(properties[1]) == 3:
# abc known
my_tri_prism = TriangularPrism(properties[1][1], d, a=properties[1][0], c=properties[1][2])
print("Your prism has surface area",
'{0:.2f}'.format(my_tri_prism.get_surface_area()),
"square units and volume", '{0:.2f}'.format(my_tri_prism.get_volume()), "cubic units.")
elif len(properties[1]) == 2:
# base and height known
my_tri_prism = TriangularPrism(properties[1][0], d, ph=properties[1][1])
print("Your prism has surface area",
'{0:.2f}'.format(my_tri_prism.get_surface_area()),
"square units and volume",
'{0:.2f}'.format(my_tri_prism.get_volume()), "cubic units.")
else:
print("Error encountered. Contact administrator.")
elif shape_number == 3:
validation_pending = False
this_radius = get_radius("circular face")
d = determine_depth("cylinder")
my_cylinder = Cylinder(this_radius, d)
print(f"Your cylinder has radius", this_radius,
", depth", d,
", surface area", '{0:.2f}'.format(my_cylinder.get_surface_area()),
"square units and volume", '{0:.2f}'.format(my_cylinder.get_volume()), "cubic units.")
elif shape_number == 4:
validation_pending = False
print("Other shapes will be coming soon.")
else:
print("Please enter either '1', '2' '3' or '4'.")
def determine_dimension_track():
dimension_list = {1: 'Two dimensions', 2: 'Three dimensions'}
print("Welcome to the shape metric calculator. \nHow many dimensions does your shape have?")
for x, y in dimension_list.items():
print(x,".", y)
validation_pending = True
while validation_pending == True:
dimension_count = (input())
try:
dimension_count = int(dimension_count)
except ValueError:
pass
if dimension_count in dimension_list.keys():
validation_pending = False
print(f"\nWhich category does your {dimension_list[dimension_count][:-1].lower()}al shape best fit into?")
if dimension_count == 2:
size_two_dimensional_shape()
elif dimension_count == 3:
size_three_dimensional_shape()
else:
print("Please enter either '2' or '3'.")
determine_dimension_track() | [
"chloe.smyth57@gmail.com"
] | chloe.smyth57@gmail.com |
43e861e7d858bf8ffe54f59165a8d442ab349855 | acf3014cfb4c5b0b11db58e5a187096af7db66a3 | /jj4.py | fdd4a02ef427fc0940ca45462e07d3146812b19e | [] | no_license | abbeeda/ggbo | 9d9083e4f7366359c6d35d9f838c5b7c31c85ad7 | 48ffb0a130757c814d4048c6bebaa6963e3ca0f9 | refs/heads/master | 2020-08-10T17:09:34.884494 | 2019-10-18T13:29:22 | 2019-10-18T13:29:22 | 214,382,898 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 314 | py | <<<<<<< HEAD
a=int(input(""))
b=int(input(""))
c=int(input(""))
if a>b:
d=a
else:
d=b
if d>c:
print(d)
else:
print(c)
=======
a=int(input(""))
b=int(input(""))
c=int(input(""))
if a>b:
d=a
else:
d=b
if d>c:
print(d)
else:
print(c)
>>>>>>> c4107b7d195ae20fa506d622edecf008161c987b
| [
"2897254827@qq.com"
] | 2897254827@qq.com |
21fcc91bb92c203b5014998e5f7a4e1735e9186d | a7c33b1d260d96756dc12290da93cc02e4263f39 | /project6/website/articles/admin.py | 8b6005bf51ca7496e714508c2573cba3d836192b | [] | no_license | FosDos/udemy-django-projects | fed711a313891a162c19d1283a3e685cf4ee2007 | acb86f610fd4564d93901f2277321d1173a5cafc | refs/heads/master | 2022-12-03T03:56:29.725235 | 2020-08-27T13:34:24 | 2020-08-27T13:34:24 | 290,474,351 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 122 | py | from django.contrib import admin
# Register your models here.
from .models import Article;
admin.site.register(Article); | [
"fosterclarksonwilliams@gmail.com"
] | fosterclarksonwilliams@gmail.com |
aeb1d9e97840a831a2788c0ea0ccb002728935fd | 2b7d422e78c188923158a2a0780a99eca960e746 | /opt/ros/melodic/lib/python2.7/dist-packages/control_msgs/msg/_JointTrajectoryGoal.py | 5daffbc8743dfc8aad30e794c9f3e0535a86a395 | [] | no_license | sroberti/VREP-Sandbox | 4fd6839cd85ac01aa0f2617b5d6e28440451b913 | 44f7d42494654357b6524aefeb79d7e30599c01d | refs/heads/master | 2022-12-24T14:56:10.155484 | 2019-04-18T15:11:54 | 2019-04-18T15:11:54 | 180,481,713 | 0 | 1 | null | 2022-12-14T18:05:19 | 2019-04-10T02:00:14 | C++ | UTF-8 | Python | false | false | 13,159 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from control_msgs/JointTrajectoryGoal.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import trajectory_msgs.msg
import genpy
import std_msgs.msg
class JointTrajectoryGoal(genpy.Message):
_md5sum = "2a0eff76c870e8595636c2a562ca298e"
_type = "control_msgs/JointTrajectoryGoal"
_has_header = False #flag to mark the presence of a Header object
_full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
trajectory_msgs/JointTrajectory trajectory
================================================================================
MSG: trajectory_msgs/JointTrajectory
Header header
string[] joint_names
JointTrajectoryPoint[] points
================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
string frame_id
================================================================================
MSG: trajectory_msgs/JointTrajectoryPoint
# Each trajectory point specifies either positions[, velocities[, accelerations]]
# or positions[, effort] for the trajectory to be executed.
# All specified values are in the same order as the joint names in JointTrajectory.msg
float64[] positions
float64[] velocities
float64[] accelerations
float64[] effort
duration time_from_start
"""
__slots__ = ['trajectory']
_slot_types = ['trajectory_msgs/JointTrajectory']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
trajectory
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(JointTrajectoryGoal, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.trajectory is None:
self.trajectory = trajectory_msgs.msg.JointTrajectory()
else:
self.trajectory = trajectory_msgs.msg.JointTrajectory()
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_get_struct_3I().pack(_x.trajectory.header.seq, _x.trajectory.header.stamp.secs, _x.trajectory.header.stamp.nsecs))
_x = self.trajectory.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.pack('<I%ss'%length, length, _x))
length = len(self.trajectory.joint_names)
buff.write(_struct_I.pack(length))
for val1 in self.trajectory.joint_names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.pack('<I%ss'%length, length, val1))
length = len(self.trajectory.points)
buff.write(_struct_I.pack(length))
for val1 in self.trajectory.points:
length = len(val1.positions)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(struct.pack(pattern, *val1.positions))
length = len(val1.velocities)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(struct.pack(pattern, *val1.velocities))
length = len(val1.accelerations)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(struct.pack(pattern, *val1.accelerations))
length = len(val1.effort)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(struct.pack(pattern, *val1.effort))
_v1 = val1.time_from_start
_x = _v1
buff.write(_get_struct_2i().pack(_x.secs, _x.nsecs))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
if self.trajectory is None:
self.trajectory = trajectory_msgs.msg.JointTrajectory()
end = 0
_x = self
start = end
end += 12
(_x.trajectory.header.seq, _x.trajectory.header.stamp.secs, _x.trajectory.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.trajectory.header.frame_id = str[start:end].decode('utf-8')
else:
self.trajectory.header.frame_id = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.trajectory.joint_names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8')
else:
val1 = str[start:end]
self.trajectory.joint_names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.trajectory.points = []
for i in range(0, length):
val1 = trajectory_msgs.msg.JointTrajectoryPoint()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.positions = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.velocities = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.accelerations = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.effort = struct.unpack(pattern, str[start:end])
_v2 = val1.time_from_start
_x = _v2
start = end
end += 8
(_x.secs, _x.nsecs,) = _get_struct_2i().unpack(str[start:end])
self.trajectory.points.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_get_struct_3I().pack(_x.trajectory.header.seq, _x.trajectory.header.stamp.secs, _x.trajectory.header.stamp.nsecs))
_x = self.trajectory.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.pack('<I%ss'%length, length, _x))
length = len(self.trajectory.joint_names)
buff.write(_struct_I.pack(length))
for val1 in self.trajectory.joint_names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.pack('<I%ss'%length, length, val1))
length = len(self.trajectory.points)
buff.write(_struct_I.pack(length))
for val1 in self.trajectory.points:
length = len(val1.positions)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(val1.positions.tostring())
length = len(val1.velocities)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(val1.velocities.tostring())
length = len(val1.accelerations)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(val1.accelerations.tostring())
length = len(val1.effort)
buff.write(_struct_I.pack(length))
pattern = '<%sd'%length
buff.write(val1.effort.tostring())
_v3 = val1.time_from_start
_x = _v3
buff.write(_get_struct_2i().pack(_x.secs, _x.nsecs))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.trajectory is None:
self.trajectory = trajectory_msgs.msg.JointTrajectory()
end = 0
_x = self
start = end
end += 12
(_x.trajectory.header.seq, _x.trajectory.header.stamp.secs, _x.trajectory.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.trajectory.header.frame_id = str[start:end].decode('utf-8')
else:
self.trajectory.header.frame_id = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.trajectory.joint_names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8')
else:
val1 = str[start:end]
self.trajectory.joint_names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.trajectory.points = []
for i in range(0, length):
val1 = trajectory_msgs.msg.JointTrajectoryPoint()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.positions = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.velocities = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.accelerations = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
val1.effort = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
_v4 = val1.time_from_start
_x = _v4
start = end
end += 8
(_x.secs, _x.nsecs,) = _get_struct_2i().unpack(str[start:end])
self.trajectory.points.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_3I = None
def _get_struct_3I():
global _struct_3I
if _struct_3I is None:
_struct_3I = struct.Struct("<3I")
return _struct_3I
_struct_2i = None
def _get_struct_2i():
global _struct_2i
if _struct_2i is None:
_struct_2i = struct.Struct("<2i")
return _struct_2i
| [
"samuel.p.roberti@gmail.com"
] | samuel.p.roberti@gmail.com |
f04925d7a0bf63c4b38d98c0cb08f71f17cc7b9c | 347699fbc16144e45ec9ffb4fbdb01e19cc69329 | /cough2.py | 0187d44d66b5d0a074e7763a7e4e9445b57ae747 | [] | no_license | kevindsteeleii/CS50-Python_Intro_to_CS | e7793f82d0530cd2f22f5b9fae1af0afd9b9ab36 | 6dea7245a27fe540ec9aa2fc878e7b876c4533ef | refs/heads/master | 2020-04-20T14:15:06.223633 | 2019-02-03T00:36:15 | 2019-02-03T00:36:15 | 168,892,517 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 101 | py | # has no special name
def main():
cough()
def cough():
print(3* "cough\n")
main()
# cough() | [
"github email address"
] | github email address |
3f780797cdf8d2ecfe9ac9b581a417acfd3754c6 | e46a845d9b5653ae2955c5623c0add0029b909b7 | /Categorize_new_member.py | 627853591110e8ed2d831ac1c7bf0b83357f51ee | [] | no_license | AdnCodez/Codewars | 89ea2aa3cb51e9d2429a0f406c1c03b2d36b5060 | 475556a413693b83ddfeb45a2257310de5e8d200 | refs/heads/master | 2020-03-24T04:59:40.087827 | 2018-07-31T16:16:15 | 2018-07-31T16:16:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 365 | py | # 7 kyu / Categorize New Member
# Details
# https://www.codewars.com/kata/categorize-new-member
def open_or_senior(data):
result = []
for i in data:
if i[0] >= 55 and i[1] > 7:
result.append("Senior")
else:
result.append("Open")
return result
print(open_or_senior([[4, 22], [55, 21], [19, -2], [104, 20]]))
| [
"adnan.7.habbat@gmail.com"
] | adnan.7.habbat@gmail.com |
327e422e523dcf388394fefb4bfc1f9ea1a87a16 | f63792e5e3a388d8c87f47c0dcffaafb6569f52c | /concat_csv.py | ec182ed84da26f0c3ea7055af0412658d743eb15 | [] | no_license | geomajor56/bct-leaflet | 16efde69da1a48a99e5801d9f9d6b12f4d69775b | acbc46d80e7a45041eeaebd05698572b229590bf | refs/heads/master | 2020-04-23T04:33:49.738386 | 2014-12-10T22:08:48 | 2014-12-10T22:08:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 394 | py | __author__ = 'mas'
import csv
with open('/home/mas/gis-data/bct/bmw_assessor_2014.csv', 'r') as csvinput:
with open('/home/mas/gis-data/bct/bmw_csv_new.csv', 'w') as csvoutput:
dest = csv.writer(csvoutput, lineterminator='\n')
source = csv.reader(csvinput)
for row in source:
result = row[:3] + [row[1] + row[2]]
dest.writerow(result)
| [
"geomajor56@gmail.com"
] | geomajor56@gmail.com |
aa46ed9e8ed2ac5ed218ebcd394bc3a96ec3aa34 | 24e3ed40be3cb6241c6d5ceca14d99d9de68e975 | /join.py | 72b0bfac453a9f785f296ae02b8074b56b9df7be | [] | no_license | mrlz/SpotifyMusicBrainz | 25396667bb3c14d323a0f1e81ada51955a2be131 | ea195d2c757fc05608675fcd310068e5e963e44c | refs/heads/main | 2023-02-27T15:34:35.307113 | 2021-02-09T04:08:11 | 2021-02-09T04:08:11 | 337,286,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,315 | py | import csv
from multiprocessing import Pool
import time
def create_rows(arg):
row = arg[0]
extension_rows = arg[1]
ans = []
ans.append(row[0].replace(',', ''))
ans.append(row[1].replace(',', ''))
ans.append(row[2].replace(',', ''))
ans.append(row[3].replace(',', ''))
ans.append(row[4].replace(',', ''))
ans.append(row[5].replace(',', ''))
ans.append(row[6].replace(',', ''))
ans.append("NONE")
ans.append("NONE")
for row2 in extension_rows:
if row2:
country = "NONE"
begin = "NONE"
breaking = 0
if (row[2].lower() in row2[0].lower() and row[1].lower() in row2[1].lower()):
if (len(row2) > 4):
begin = row2[4]
if (len(row2) > 3):
country = row2[3]
breaking = 1
if(breaking == 1):
ans[7] = country
ans[8] = begin
return ans
pool = Pool(processes = 4)
print("Loading files")
with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
tuples = list(reader)
tuples = tuples[1:len(tuples)]
i = 0
# tuples = tuples[0:100] #DELETE THIS ONE
with open('artist_country_full_clean.csv', 'r') as csvfile2:
reader2 = csv.reader(csvfile2)
tuples2 = list(reader2)
tuples2 = tuples2[2:len(tuples2)]
with open('extended_spotify_data.csv', 'w') as csvfile3:
fieldnames = ['Position', 'Track Name', 'Artist', 'Streams', 'URL', 'Date', 'Region', 'Country', 'Begin_area']
writer = csv.DictWriter(csvfile3, fieldnames = fieldnames)
writer.writeheader()
arguments = []
for row in tuples:
if row:
arguments.append([row,tuples2])
print("Computing rows")
start = time.time()
results = pool.map(create_rows, arguments)
end = time.time()
print("Took", end-start)
print("Writing rows")
for res in results:
# print(res)
writer.writerow({'Position': res[0], 'Track Name': res[1], 'Artist': res[2], 'Streams': res[3], 'URL': res[4], 'Date': res[5], 'Region': res[6], 'Country': res[7], 'Begin_area': res[8]})
| [
"sunshinewaker77@hotmail.com"
] | sunshinewaker77@hotmail.com |
ef519f43e5db8098082fdc741d5dc58fddc8d738 | faaf8af02a069919c4d553ff8e944bee8ccad806 | /Python para Zumbis/10.py | a7024a383dac48975c403a327f54b7e1cbbd090f | [] | no_license | marcioandrews/Estudos_Python | 5fe10993fc0ebc5a75d8a04687bc55cae7bd9fda | 07bf0683114132c726ed22c5d1c1be8ed7fc7fb2 | refs/heads/master | 2022-11-20T21:18:57.529507 | 2020-07-13T16:29:03 | 2020-07-13T16:29:03 | 279,171,877 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 179 | py | qc = int (input ('Quantidade de cigarros fumados por dia '))
af = int (input ('Anos fumando '))
totala = af * 365
totalc = qc * totala
total = totalc / 1440
print (f'{total:.2f}') | [
"47893016+marcioandrews@users.noreply.github.com"
] | 47893016+marcioandrews@users.noreply.github.com |
918e565d89ad445a30f28a4fbffff08134023528 | a5201b3a9d2a93d612d93d1ad5f8627eccdbb626 | /ScoreRank/wsgi.py | 778b9f2f9f7476d98b4b62f0c05d11a121fdc281 | [] | no_license | xuzizheng1/ScoreRank | 26bf39c81c074f033b6e98e311e2276e50d66317 | 1c003218b7ce2afd999c74b5088f0ff459651bdf | refs/heads/master | 2023-07-17T13:21:33.456149 | 2021-09-06T17:12:52 | 2021-09-06T17:12:52 | 259,191,498 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 395 | py | """
WSGI config for ScoreRank 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', 'ScoreRank.settings')
application = get_wsgi_application()
| [
"815203041@qq.com"
] | 815203041@qq.com |
1e88f7e22cd7e897109c553ce40fd696c2ea995a | 10d495c139f6556d27f8dfe34c4ee348b1803b64 | /src/snowflake/connector/auth/default.py | 87f6f6214d583b32c8bdc7c8032d941e9b860bb1 | [
"Apache-2.0",
"MIT"
] | permissive | snowflakedb/snowflake-connector-python | a5544f53d68a7a8d9be80ddf6e3cd34412610e8b | da1ae4ed1e940e4210348c59c9c660ebaa78fc2e | refs/heads/main | 2023-09-01T19:50:39.864458 | 2023-08-31T20:06:56 | 2023-08-31T20:06:56 | 62,262,074 | 492 | 494 | Apache-2.0 | 2023-09-14T10:02:00 | 2016-06-29T22:29:53 | Python | UTF-8 | Python | false | false | 1,016 | py | #!/usr/bin/env python
#
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
#
from __future__ import annotations
from typing import Any
from .by_plugin import AuthByPlugin, AuthType
class AuthByDefault(AuthByPlugin):
"""Default username and password authenticator."""
@property
def type_(self) -> AuthType:
return AuthType.DEFAULT
@property
def assertion_content(self) -> str:
return "*********"
def __init__(self, password: str) -> None:
"""Initializes an instance with a password."""
super().__init__()
self._password: str | None = password
def reset_secrets(self) -> None:
self._password = None
def prepare(self, **kwargs: Any) -> None:
pass
def reauthenticate(self, **kwargs: Any) -> dict[str, bool]:
return {"success": False}
def update_body(self, body: dict[Any, Any]) -> None:
"""Sets the password if available."""
body["data"]["PASSWORD"] = self._password
| [
"noreply@github.com"
] | noreply@github.com |
e216c2feeb68eba1c8976b72040c3a84d2b3c578 | e2ba1e3d001902e50f1dc9a63baf2a8abcac3ed8 | /InnerEye-DataQuality/InnerEyeDataQuality/datasets/nih_cxr.py | 91776355375965f599295af3453238326df7cff1 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | RobinMarshall55/InnerEye-DeepLearning | 81f52e7429f942e8c9845958d5b586e19e14e351 | 8495a2eec3903957e3e81f81a0d2ad842d41dfe2 | refs/heads/main | 2023-08-15T19:46:38.017713 | 2021-10-22T14:13:56 | 2021-10-22T14:13:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,929 | py | # ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
import logging
from pathlib import Path
from typing import Callable, List, Optional, Tuple, Dict, Union
import PIL
from PIL import Image
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
NIH_TOTAL_SIZE = 112120
class NIHCXR(Dataset):
def __init__(self,
data_directory: str,
use_training_split: bool,
seed: int = 1234,
shuffle: bool = True,
transform: Optional[Callable] = None,
num_samples: int = None,
return_index: bool = True) -> None:
"""
Class for the full NIH ChestXray Dataset (112k images)
:param data_directory: the directory containing all training images from the dataset as well as the
Data_Entry_2017.csv file containing the dataset labels.
:param use_training_split: whether to return the training or the test split of the dataset.
:param seed: random seed to use for dataset creation
:param shuffle: whether to shuffle the dataset prior to spliting between validation and training
:param transform: a preprocessing function that takes a PIL image as input and returns a tensor
:param num_samples: number of the samples to return (has to been smaller than the dataset split)
"""
self.data_directory = Path(data_directory)
if not self.data_directory.exists():
logging.error(
f"The data directory {self.data_directory} does not exist. Make sure to download the NIH data "
f"first.The dataset can on the main page"
"https://www.kaggle.com/nih-chest-xrays/data. Make sure all images are placed directly under the "
"data_directory folder. Make sure you downloaded the Data_Entry_2017.csv file to this directory as"
"well.")
self.train = use_training_split
self.seed = seed
self.random_state = np.random.RandomState(seed)
self.dataset_dataframe = pd.read_csv(self.data_directory / "Data_Entry_2017.csv")
self.dataset_dataframe["pneumonia_like"] = self.dataset_dataframe["Finding Labels"].apply(
lambda x: x.split("|")).apply(lambda x: "pneumonia" in x.lower()
or "infiltration" in x.lower()
or "consolidation" in x.lower())
self.transforms = transform
orig_labels = self.dataset_dataframe.pneumonia_like.values.astype(np.int64)
subjects_ids = self.dataset_dataframe["Image Index"].values
is_train_ids = self.dataset_dataframe["train"].values
self.num_classes = 2
self.indices = np.where(is_train_ids)[0] if use_training_split else np.where(~is_train_ids)[0]
self.indices = self.random_state.permutation(self.indices) \
if shuffle else self.indices
# ------------- Select subset of current split ------------- #
if num_samples is not None:
assert 0 < num_samples <= len(self.indices)
self.indices = self.indices[:num_samples]
self.subject_ids = subjects_ids[self.indices]
self.orig_labels = orig_labels[self.indices].reshape(-1)
self.targets = self.orig_labels
# Identify case ids for ambiguous and clear label noise cases
self.ambiguity_metric_args: Dict = dict()
dataset_type = "TRAIN" if use_training_split else "VAL"
logging.info(f"Proportion of positive labels - {dataset_type}: {np.mean(self.targets)}")
logging.info(f"Number samples - {dataset_type}: {self.targets.shape[0]}")
self.return_index = return_index
def __getitem__(self, index: int) -> Union[Tuple[int, PIL.Image.Image, int], Tuple[PIL.Image.Image, int]]:
"""
:param index: The index of the sample to be fetched
:return: The image and label tensors
"""
subject_id = self.subject_ids[index]
filename = self.data_directory / f"{subject_id}"
target = self.targets[index]
scan_image = Image.open(filename).convert("L")
if self.transforms is not None:
scan_image = self.transforms(scan_image)
if self.return_index:
return index, scan_image, int(target)
return scan_image, int(target)
def __len__(self) -> int:
"""
:return: The size of the dataset
"""
return len(self.indices)
def get_label_names(self) -> List[str]:
return ["NotPneunomiaLike", "PneunomiaLike"]
| [
"noreply@github.com"
] | noreply@github.com |
809c00156fa6bd32d5801f9d9428c87659126e75 | 23570a56058230282b47dfdeee21ce197dea6b09 | /quiz5.py | 8be733aaec7c8d38b5e4f627afbf0617b6817dea | [] | no_license | heejin99/Python | 1c2c0b384bf64d46719ad53d220830c74321886e | 42d095f9d63be1f817f931bc348fc7f5f68ee742 | refs/heads/master | 2023-07-06T11:12:12.690425 | 2021-08-09T14:05:55 | 2021-08-09T14:05:55 | 334,972,290 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 592 | py | # Coca 서비스 이용 택시 기사님(50명)
# 조건 1 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수
# 조건 2 소요시간 5분~15분 사이의 승객만 매칭
from random import *
cnt = 0 # 총 탑승 승객 수
for person in range(1, 51):
time = randrange(5, 51)
if 5 <= time <= 15: # 매칭 성공
print("[O] {0}번째 손님 (소요시간 : {1}분)".format(person, time))
cnt+=1
else: # 매칭 실패
print("[ ] {0}번째 손님 (소요시간 : {1}분)".format(person, time))
print("총 탑승 승객 : {0} 분".format(cnt)) | [
"wkdgmlwls30@naver.com"
] | wkdgmlwls30@naver.com |
485638e90767c3729c2e58115078a84fba15158a | e57763d1c8e282997f1f8a735459bc026d9a9d58 | /W03D01/32_multiplicationtable.py | e2c8ea628841349707cb08199aad9485cccfbc63 | [] | no_license | santosh-srm/srm-pylearn | 86612733e17ccdedf0d48b8ec9517a7ebfcee096 | 18f74adc16e03e535bd19118628366a36a46131b | refs/heads/main | 2023-03-01T12:38:11.327635 | 2021-02-06T06:33:47 | 2021-02-06T06:33:47 | 321,044,226 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 708 | py | """Print a multiplication table."""
def main():
"""Printing Multiplication Table"""
print_table(2)
print_table(7)
print_table(13)
def print_table(n):
"""Print nth Multiplication Table"""
print(f"Table {n}")
for i in range(1, 11):
print(f'{n} * {i} = {n*i}')
print("\n")
main()
""" Output
Table 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Table 7
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Table 13
13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130
"""
| [
"santoshrao.m@gmail.com"
] | santoshrao.m@gmail.com |
7d6d2fd0654513d92a796442f5ef4e517a284778 | 1695f950570ee24e4bbd1c00f247b1047e092804 | /foodcomputer/management/commands/_build_handler.py | b90410539cb73c0420b12fd41f70446ffce1f038 | [] | no_license | econforte/MavFC2018 | 436c4b4de7260ef0d3d1edc73f478e7a42a1bb8c | d6f1e5a01512297b5283d790daf06bdf602dc3e8 | refs/heads/master | 2020-03-12T03:31:06.036731 | 2018-05-02T02:22:11 | 2018-05-02T02:22:11 | 130,426,041 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,587 | py | from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.authtoken.models import Token
from experiment.models import *
from foodcomputer.models import *
class DataBuilder(object):
def clear_tables(self):
day_num = Day.objects.all().delete()[0]
device_num = DeviceType.objects.all().delete()[0]
return day_num, device_num
def build_days(self):
Day(id=1, name='Monday').save()
Day(id=2, name='Tuesday').save()
Day(id=3, name='Wednesday').save()
Day(id=4, name='Thursday').save()
Day(id=5, name='Friday').save()
Day(id=6, name='Saturday').save()
Day(id=7, name='Sunday').save()
return True
def build_data_types(self):
DataType(id=1, name='Boolean', descr='True/False represented by a 1 or a 0').save()
DataType(id=2, name='Float', descr='decimal number').save()
return True
def build_unit_types(self):
UnitType(id=1, name='Degrees Celsius', abbr='C', descr='Conversion of Celsius to Fahrenheit: F = C * 9/5 + 32 Measurement of Temperature.', min_limit=-5, max_limit=40).save()
UnitType(id=2, name='On/Off', abbr='1/0', descr='Describes if something is turned on or off.', min_limit=0, max_limit=1).save()
UnitType(id=3, name='pH', abbr='pH', descr='It\'s just pH.', min_limit=0, max_limit=14).save()
UnitType(id=4, name='Electrical Conductivity', abbr='EC', descr='Amount of electrolytes in the water.', min_limit=0, max_limit=10).save()
UnitType(id=5, name='Luminous Intensity', abbr='CD', descr='Luminous Intensity is the "photometric quantity" as lumens per steradian (lm/sr). '
'It is abbreviated as CD here to represent candela, another name for Luminous Intensity.', min_limit=0, max_limit=10000).save()
UnitType(id=6, name='Wavelength', abbr='WAVE', descr='Measured in nanometers (nm), wavelength in the food computer sense usually '
'refers to the PAR sensor, which measures photosynthesis.', min_limit=0, max_limit=300).save()
UnitType(id=7, name='Absolute Humidity', abbr='AH', descr='AH is the mass of the water vapor divided by the net volume of both the air and the vapor.', min_limit=0, max_limit=100).save()
UnitType(id=8, name='Parts Per Million', abbr='PPM', descr='Number of particles of interest divided by total number of particles. '
'If refering to CO2, it is the number of CO2 molecules divided by the '
'number of all molecules, in any given volume of the air. '
'It may also refer to solid or liquid proportions.', min_limit=0, max_limit=100).save()
return True
def build_device_types(self):
DeviceType(name='pH Sensor', model_id='SWPH 1', unit_type_id=3, data_type_id=1, is_controller=False, bio_threshold=0.4).save()
DeviceType(name='EC Sensor', model_id='SWEC 1', unit_type_id=4, data_type_id=1, is_controller=False, bio_threshold=0.9).save()
DeviceType(name='Water Thermometer', model_id='SWTM 1', unit_type_id=1, data_type_id=1, is_controller=False, bio_threshold=2).save()
DeviceType(name='Light Intensity', model_id='SLIN 1', unit_type_id=5, data_type_id=1, is_controller=False, bio_threshold=1).save()
DeviceType(name='Photosynthetically Active Radiation Sensor', model_id='SLPA 1', unit_type_id=6, data_type_id=1, is_controller=False, bio_threshold=15).save()
DeviceType(name='Air Thermometer', model_id='SATM 1', unit_type_id=1, data_type_id=1, is_controller=False, bio_threshold=2).save()
DeviceType(name='Humidity Sensor', model_id='SAHU 1', unit_type_id=7, data_type_id=1, is_controller=False, bio_threshold=0.6).save()
DeviceType(name='CO2 Sensor', model_id='SACO 1', unit_type_id=8, data_type_id=1, is_controller=False, bio_threshold=1).save()
DeviceType(name='Shell', model_id='SGSO 1', unit_type_id=2, data_type_id=2, is_controller=False, bio_threshold=0).save()
DeviceType(name='Window', model_id='SGWO 1', unit_type_id=2, data_type_id=2, is_controller=False, bio_threshold=0).save()
DeviceType(name='Air Conditioner', model_id='AAAC 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Humidity P', model_id='AAHU 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Ventilation', model_id='AAVE 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Circulation', model_id='AACR 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='MB Light', model_id='ALMI 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='RGB Growth Light Red', model_id='ARGB 2', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='LED Grow Light left', model_id='ALPN 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Air Pump', model_id='AAAP 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Heater', model_id='AAHE 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='Water Pump', model_id='WP', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='LED Grow Light right', model_id='ALPN 2', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='RGB Growth Light Green', model_id='ARGB 1', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
DeviceType(name='RGB Growth Light Blue', model_id='ARGB 3', unit_type_id=2, data_type_id=2, is_controller=True, bio_threshold=0).save()
return True
def build_fc_user(self):
try:
user = User.objects.get(username='genericFCuser')
except ObjectDoesNotExist:
user = User.objects.create_user(username='genericFCuser', password='tempPW-asddsa123321')
user.is_active=True
token = Token.objects.get_or_create(user=user)
user.set_password(token[0].key)
user.save()
return token[0].key | [
"cbane@unomaha.edu"
] | cbane@unomaha.edu |
a9adbd9757605899cfcc24ab62f85a0506576082 | 9923e30eb99716bfc179ba2bb789dcddc28f45e6 | /apimatic/python_generic_lib/Samsara+API-Python/samsaraapi/models/tag_1.py | c430f1f458ea4d2ca686481440b43d895aaab5a2 | [
"MIT"
] | permissive | silverspace/samsara-sdks | cefcd61458ed3c3753ac5e6bf767229dd8df9485 | c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa | refs/heads/master | 2020-04-25T13:16:59.137551 | 2019-03-01T05:49:05 | 2019-03-01T05:49:05 | 172,804,041 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,770 | py | # -*- coding: utf-8 -*-
"""
samsaraapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Tag1(object):
"""Implementation of the 'Tag1' model.
TODO: type model description here.
Attributes:
id (long|int): The ID of this tag.
name (string): Name of this tag.
parent_tag_id (long|int): The ID of this tag.
"""
# Create a mapping from Model property names to API property names
_names = {
"id":'id',
"name":'name',
"parent_tag_id":'parentTagId'
}
def __init__(self,
id=None,
name=None,
parent_tag_id=None):
"""Constructor for the Tag1 class"""
# Initialize members of the class
self.id = id
self.name = name
self.parent_tag_id = parent_tag_id
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
id = dictionary.get('id')
name = dictionary.get('name')
parent_tag_id = dictionary.get('parentTagId')
# Return an object of this model
return cls(id,
name,
parent_tag_id)
| [
"greg@samsara.com"
] | greg@samsara.com |
846a6757276db72f19c0eee1d8c7a5baab55122d | 05470f817fdb223bc1c9697032723489229c2f58 | /py/generate_password.py | 11d03b8ec50621f66bae0b3fb7fc924428ef14e9 | [
"MIT"
] | permissive | christophfranke/continuous-integration-tools | 14460892f36214b75e9029eac4ff09101dbeee80 | eeb77a624303f5b5971ea7110a8352ff72feb312 | refs/heads/master | 2021-01-09T06:47:55.417229 | 2017-02-02T10:42:36 | 2017-02-02T10:42:36 | 81,100,932 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 280 | py | from modules import engine
from modules import out
from modules import run
@engine.prepare_and_clean
def execute():
out.log("generating password...")
run.local('openssl rand -base64 15')
def help():
out.log("Creates a strong random 20 characters password.", 'help') | [
"franke@ragusescheer.de"
] | franke@ragusescheer.de |
db99422319b1f8551b4d4246f83114cc4c4e37bb | 97892ab999d98171e2583cbaa4ca5bfc9c9fd701 | /deploy/ansible/roles/iroha/add_peers_and_notaries.py | 52fd95ef42f22a8fc0fd0b57b0289d33c86d85bd | [
"Apache-2.0"
] | permissive | d3ledger/notary | efeb38bd60d41e63e4e4dd819e249c08f03e8ffa | 0e719a1a8fcdce23933df68749028befe40cbc50 | refs/heads/master | 2021-06-03T02:36:54.545268 | 2019-10-10T09:00:32 | 2019-10-10T09:00:32 | 129,921,969 | 17 | 6 | Apache-2.0 | 2020-02-18T13:10:37 | 2018-04-17T15:01:56 | Kotlin | UTF-8 | Python | false | false | 2,791 | py | #!/usr/env/python3
import base64
import csv
import json
import os
import sys
'''
host;port;priv_key_hex_encoded;pub_key_hex_encoded
'''
class Peer:
def __init__(self, host, port, priv_key, pub_key):
self.host = host
self.port = port
self.priv_key = priv_key
self.pub_key = pub_key
def __str__(self):
return "{}\n{}\n{}\n{}\n".format(
self.host,
self.port,
self.priv_key,
self.pub_key
)
def parse_peers(peers_csv_fp):
peers = []
with open(peers_csv_fp) as csvfile:
peersreader = csv.reader(csvfile, delimiter=';')
for peer in peersreader:
peers.append(Peer(peer[0], peer[1], peer[2], peer[3]))
return peers
def mfilter(cmd):
if not ("setAccountDetail" in cmd.keys()):
return True
if cmd["setAccountDetail"]["accountId"] == "notaries@notary":
return False
return True
def genesis_add_peers(peers_list, genesis_block_fp):
genesis_dict = json.loads(open(genesis_block_fp, "r").read())
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'] = filter(
lambda c: not c.get('addPeer'),
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'])
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'] = filter(
mfilter,
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'])
for p in peers_list:
p_add_command = {
"addPeer": {"peer": {"address": "%s:%s" % (p.host, '10001'), "peerKey": hex_to_b64(p.pub_key)}}}
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'].append(p_add_command)
p_add_command = {
"setAccountDetail": {
"accountId": "notaries@notary",
"key": p.pub_key,
"value": "http://{}:20000".format(p.host)
}
}
genesis_dict['payload']['transactions'][0]['payload']['reducedPayload']['commands'].append(p_add_command)
with open(genesis_block_fp, 'w') as genesis_json:
json.dump(genesis_dict, genesis_json, indent=4)
def hex_to_b64(hex_string):
hex_string = base64.b64encode(bytearray.fromhex(hex_string))
return hex_string.decode('utf-8')
def make_keys(peers):
for i, p in enumerate(peers):
with open('node%s.priv' % i, 'w+') as priv_key_file:
priv_key_file.write(p.priv_key)
with open('node%s.pub' % i, 'w+') as pub_key_file:
pub_key_file.write(p.pub_key)
if __name__ == "__main__":
os.chdir("files")
peers_csv = sys.argv[1]
peers = parse_peers(peers_csv)
genesis_add_peers(peers, "genesis.block")
| [
"noreply@github.com"
] | noreply@github.com |
22e0f4ddf70d8a6df31ef25ad3c9523dd8105a3a | ac89e5d51d0d15ffdecfde25985c28a2af9c2e43 | /test/test_match_alliance.py | 931bc1a9d817c762a45d35d742fc1774fbbb67f5 | [] | no_license | TBA-API/tba-api-client-python | 20dc4a634be32926054ffc4c52b94027ee40ac7d | 4f6ded8fb4bf8f7896891a9aa778ce15a2ef720b | refs/heads/master | 2021-07-15T16:36:32.234217 | 2020-05-07T00:20:43 | 2020-05-07T00:20:43 | 134,112,743 | 4 | 8 | null | 2019-07-01T03:14:12 | 2018-05-20T02:13:45 | Python | UTF-8 | Python | false | false | 1,191 | py | # coding: utf-8
"""
The Blue Alliance API v3
# Overview Information and statistics about FIRST Robotics Competition teams and events. # Authentication All endpoints require an Auth Key to be passed in the header `X-TBA-Auth-Key`. If you do not have an auth key yet, you can obtain one from your [Account Page](/account). A `User-Agent` header may need to be set to prevent a 403 Unauthorized error. # noqa: E501
The version of the OpenAPI document: 3.04.1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import tbaapiv3client
from tbaapiv3client.models.match_alliance import MatchAlliance # noqa: E501
from tbaapiv3client.rest import ApiException
class TestMatchAlliance(unittest.TestCase):
"""MatchAlliance unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testMatchAlliance(self):
"""Test MatchAlliance"""
# FIXME: construct object with mandatory attributes with example values
# model = tbaapiv3client.models.match_alliance.MatchAlliance() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"travis@example.org"
] | travis@example.org |
4c53a074db5d4ab4401ea1f0ffb6bd3abb60f510 | 5a255386f62477a7d51c2e7ce02e6e4d88892eeb | /src/M09_第一胎VS第二胎.py | c0a94f1ccf35362666ae87b5630dfa0c30ca1b71 | [] | no_license | SuperLatte/Statistics_PyOJ_Competition | af8bc5c54028a174f7cdd9c3106f444f6dc5955c | 553c07cdeb94dfb028ae96406cb7e4ae0f026097 | refs/heads/master | 2020-12-31T05:57:16.075427 | 2015-06-30T09:13:20 | 2015-06-30T09:13:20 | 37,768,306 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,522 | py | #-*- coding:utf-8 -*-
# 描述:
#
# 仍然利用NSFG数据(url为http://112.124.1.3:8050/getData/101),但这次我们想验证第一胎婴儿是否更倾向于更早或更晚出生而较少准时出生的假设,因此需要利用卡方检验计算出其卡方值chisq及推翻假设的p值。
# 试写函数solve计算卡方值chisq及p值
# 输入:
#
# 调查样本数据,格式为{“status”:"ok","data":[[1, 1, 39, 1, 141, 1, 33.16, 6448.271111704751], [1, 2, 39, 1, 126, 2, 39.25, 6448.271111704751], ...]}
#
# 输出:
#
# [chisq,p]
#
# 注意:
#
# (1)婴儿第几周出生数据由于被调查人选填错误等原因出现了一些不合理数据,比如错填了月份(5<prglength<=10),其他错填(prglength<=5, 10<prglength<=25, prglength>=49),对于错填月份的情况,将月份*4.33作为其周数,对于其他错填情况则舍弃此条数据
#
# (2)一般认为,如果婴儿在第37周或更早出生,那就是提前出生;准时出生则是在第38周到第40周;而延后出生则是在41周或更晚
import urllib
import json
from scipy.stats import chi2 as C
class Solution:
def solve(self):
html = self.getHtml('http://112.124.1.3:8050/getData/101')
data = json.loads(html)["data"]
T1 = []
T2 = []
for i in range(len(data)):
a = data[i][2]
if ((a<=5) | (a>=49) | ((a>10)&(a<=25))):
continue
if ((a<=10)&(a>5)):
a = 4.33*a
if (data[i][5] == 1):
T1.append(a)
T2.append(a)
n1 = len(T1)
n2 = len(T2)
a1=0
b1=0
d1=0
for i in T1:
if (i < 38):
a1 = a1 + 1
elif i>=41:
d1 = d1 +1
else:
b1 = b1 + 1
a2=0
b2=0
d2=0
for i in T2:
if (i < 38):
a2 = a2 + 1
elif i>=41:
d2 = d2 +1
else:
b2 = b2 + 1
t1 = float(a2)*n1/n2
t2 = float(b2)*n1/n2
c2 = float(a1**2)/(n1*float(a2)/n2)+float(b1**2)/(n1*float(b2)/n2)+float(d1**2)/(n1*float(d2)/n2)-n1
p = C.sf(c2,2)
return [c2,p]
def getHtml(self, url):
page = urllib.urlopen(url)
html = page.read()
return html
if __name__=='__main__':
solution = Solution()
print solution.solve() | [
"arkie01@163.com"
] | arkie01@163.com |
9349bd74ff31deab5e9122b86f3ac15dc12aa5e5 | 096863b26bead89e229fb439c7c1eda1cd3d2cd8 | /tests/test_public.py | a383e680e25cdc4896e0b23f5298614dd1480c60 | [
"ISC"
] | permissive | euri10/pykraken | 57a37788d4544487bc0d68fffea38361cd805cb7 | 04e2797723579aee48706533357e7fa17004bb28 | refs/heads/master | 2021-01-17T16:57:07.118143 | 2016-05-30T13:12:33 | 2016-05-30T13:12:33 | 59,895,343 | 6 | 1 | ISC | 2019-10-01T18:13:29 | 2016-05-28T13:15:42 | Python | UTF-8 | Python | false | false | 2,138 | py | import time
import pykraken
import pytest
from pykraken.config import PROXY, API_KEY, PRIVATE_KEY
def test_no_api_key():
with pytest.raises(Exception):
client = pykraken.Client()
def test_server_time():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
utcnow = time.time()
t = client.kpublic_time()
# t_compare = datetime.strptime(t[1], '%a, %d %b %y %H:%M:%S +0000')
t_compare = t[0]
print("t_compare: {} utcnow: {}".format(t_compare, utcnow))
delta = t_compare - utcnow
assert abs(delta)<= 10
def test_assets_asset_parameter():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_assets(asset=['XETH'])
assert u'XETH' in t.keys()
def test_assets_aclass_parameter():
with pytest.raises(pykraken.exceptions.BadParamterError):
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_assets(aclass='mouahahah bad parameter')
def test_assetpairs():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_assetpairs()
# TODO: find a better test
assert 'XXBTZUSD' in t.keys()
def test_ticker():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_ticker(pair=['XETHXXBT'])
print(t)
assert 'XETHXXBT' in t.keys()
def test_OHLC():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_ohlc(pair=['XETHXXBT'])
print(t)
assert 'XETHXXBT' in t.keys()
def test_depth():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_depth(pair=['XETHXXBT'])
print(t)
assert 'XETHXXBT' in t.keys()
def test_trades():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_trades(pair=['XETHXXBT'])
print(t)
assert 'XETHXXBT' in t.keys()
def test_spread():
client = pykraken.Client(API_KEY, PRIVATE_KEY, requests_kwargs=PROXY)
t = client.kpublic_spread(pair=['XETHXXBT'])
print(t)
assert 'XETHXXBT' in t.keys()
| [
"benoit.barthelet@gmail.com"
] | benoit.barthelet@gmail.com |
d5a7791ef5d1a16c2f4cfdbc78846c44437f2ad5 | 33327721233dbab4f95226aca5ebf52ec5782ae3 | /ModelInheritance/urls.py | 184bf47cbd9fed6d95c6e1cf7d0f6a88f774f9c9 | [] | no_license | priyankaonly1/ModelInheritance | 0b45e515cb1f9751f76b9639d1aab78369a861f9 | 078dfd24428c8f64ab66da421a1e4afc94b5c14c | refs/heads/main | 2023-07-05T11:55:17.489648 | 2021-09-03T18:56:22 | 2021-09-03T18:56:22 | 402,871,149 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 809 | py | """ModelInheritance URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from school import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
]
| [
"priyankabiswasonly1@gmail.com"
] | priyankabiswasonly1@gmail.com |
5725565c8233d54c532088ebda905dca10d51e65 | 9b64f0f04707a3a18968fd8f8a3ace718cd597bc | /huaweicloud-sdk-servicestage/huaweicloudsdkservicestage/v2/model/create_o_auth_request.py | 6759129234f47c48a4eb8652297aba7bde7df202 | [
"Apache-2.0"
] | permissive | jaminGH/huaweicloud-sdk-python-v3 | eeecb3fb0f3396a475995df36d17095038615fba | 83ee0e4543c6b74eb0898079c3d8dd1c52c3e16b | refs/heads/master | 2023-06-18T11:49:13.958677 | 2021-07-16T07:57:47 | 2021-07-16T07:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,107 | py | # coding: utf-8
import re
import six
class CreateOAuthRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'repo_type': 'str',
'tag': 'str',
'body': 'OAuth'
}
attribute_map = {
'repo_type': 'repo_type',
'tag': 'tag',
'body': 'body'
}
def __init__(self, repo_type=None, tag=None, body=None):
"""CreateOAuthRequest - a model defined in huaweicloud sdk"""
self._repo_type = None
self._tag = None
self._body = None
self.discriminator = None
self.repo_type = repo_type
if tag is not None:
self.tag = tag
if body is not None:
self.body = body
@property
def repo_type(self):
"""Gets the repo_type of this CreateOAuthRequest.
仓库类型。 支持OAuth授权的仓库类型有:github、gitlab、gitee、bitbucket。
:return: The repo_type of this CreateOAuthRequest.
:rtype: str
"""
return self._repo_type
@repo_type.setter
def repo_type(self, repo_type):
"""Sets the repo_type of this CreateOAuthRequest.
仓库类型。 支持OAuth授权的仓库类型有:github、gitlab、gitee、bitbucket。
:param repo_type: The repo_type of this CreateOAuthRequest.
:type: str
"""
self._repo_type = repo_type
@property
def tag(self):
"""Gets the tag of this CreateOAuthRequest.
站点标签。 比如国际站的,?tag=intl。 默认为空。
:return: The tag of this CreateOAuthRequest.
:rtype: str
"""
return self._tag
@tag.setter
def tag(self, tag):
"""Sets the tag of this CreateOAuthRequest.
站点标签。 比如国际站的,?tag=intl。 默认为空。
:param tag: The tag of this CreateOAuthRequest.
:type: str
"""
self._tag = tag
@property
def body(self):
"""Gets the body of this CreateOAuthRequest.
:return: The body of this CreateOAuthRequest.
:rtype: OAuth
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this CreateOAuthRequest.
:param body: The body of this CreateOAuthRequest.
:type: OAuth
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
import simplejson as json
return json.dumps(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CreateOAuthRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
e0f1d63c7f12b3730b39b47399da4f32770a8c76 | 4e062e841e7371722f3b4321e14ebbd04d1299a6 | /rl3/a2c/a2c.py | 7f3719ffbb3ce3290135b493bc57b947dd10a3e7 | [
"Apache-2.0"
] | permissive | viclen/machine_learning_examples_v2 | 1e767e033efae2e337d7c456f2bd23746ccc4f73 | d47d572629899efe23bb26edffedfd464c0f77e4 | refs/heads/master | 2022-11-26T19:26:11.330565 | 2020-08-04T23:06:17 | 2020-08-04T23:06:17 | 285,119,617 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,871 | py | # https://deeplearningcourses.com/c/cutting-edge-artificial-intelligence
import time
import joblib
import numpy as np
import tensorflow as tf
import os
tf.compat.v1.disable_eager_execution()
def set_global_seeds(i):
tf.compat.v1.set_random_seed(i)
np.random.seed(i)
def cat_entropy(logits):
a0 = logits - tf.reduce_max(input_tensor=logits, axis=1, keepdims=True)
ea0 = tf.exp(a0)
z0 = tf.reduce_sum(input_tensor=ea0, axis=1, keepdims=True)
p0 = ea0 / z0
return tf.reduce_sum(input_tensor=p0 * (tf.math.log(z0) - a0), axis=1)
def find_trainable_variables(key):
with tf.compat.v1.variable_scope(key):
return tf.compat.v1.trainable_variables()
def discount_with_dones(rewards, dones, gamma):
discounted = []
r = 0
for reward, done in zip(rewards[::-1], dones[::-1]):
r = reward + gamma * r * (1. - done) # fixed off by one bug
discounted.append(r)
return discounted[::-1]
class Agent:
def __init__(self, Network, ob_space, ac_space, nenvs, nsteps, nstack,
ent_coef=0.01, vf_coef=0.5, max_grad_norm=0.5, lr=7e-4,
alpha=0.99, epsilon=1e-5, total_timesteps=int(80e6)):
config = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=nenvs,
inter_op_parallelism_threads=nenvs)
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
nbatch = nenvs * nsteps
A = tf.compat.v1.placeholder(tf.int32, [nbatch])
ADV = tf.compat.v1.placeholder(tf.float32, [nbatch])
R = tf.compat.v1.placeholder(tf.float32, [nbatch])
LR = tf.compat.v1.placeholder(tf.float32, [])
step_model = Network(sess, ob_space, ac_space, nenvs, 1, nstack, reuse=False)
train_model = Network(sess, ob_space, ac_space, nenvs, nsteps, nstack, reuse=True)
neglogpac = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=train_model.pi, labels=A)
pg_loss = tf.reduce_mean(input_tensor=ADV * neglogpac)
vf_loss = tf.reduce_mean(input_tensor=tf.math.squared_difference(tf.squeeze(train_model.vf), R) / 2.0)
entropy = tf.reduce_mean(input_tensor=cat_entropy(train_model.pi))
loss = pg_loss - entropy * ent_coef + vf_loss * vf_coef
params = find_trainable_variables("model")
grads = tf.gradients(ys=loss, xs=params)
if max_grad_norm is not None:
grads, grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)
grads_and_params = list(zip(grads, params))
trainer = tf.compat.v1.train.RMSPropOptimizer(learning_rate=LR, decay=alpha, epsilon=epsilon)
_train = trainer.apply_gradients(grads_and_params)
def train(states, rewards, actions, values):
advs = rewards - values
feed_dict = {train_model.X: states, A: actions, ADV: advs, R: rewards, LR: lr}
policy_loss, value_loss, policy_entropy, _ = sess.run(
[pg_loss, vf_loss, entropy, _train],
feed_dict
)
return policy_loss, value_loss, policy_entropy
def save(save_path):
ps = sess.run(params)
joblib.dump(ps, save_path)
def load(load_path):
loaded_params = joblib.load(load_path)
restores = []
for p, loaded_p in zip(params, loaded_params):
restores.append(p.assign(loaded_p))
ps = sess.run(restores)
self.train = train
self.train_model = train_model
self.step_model = step_model
self.step = step_model.step
self.value = step_model.value
self.save = save
self.load = load
tf.compat.v1.global_variables_initializer().run(session=sess)
class Runner:
def __init__(self, env, agent, nsteps=5, nstack=4, gamma=0.99):
self.env = env
self.agent = agent
nh, nw, nc = env.observation_space.shape
nenv = env.num_envs
self.batch_ob_shape = (nenv * nsteps, nh, nw, nc * nstack)
self.state = np.zeros((nenv, nh, nw, nc * nstack), dtype=np.uint8)
self.nc = nc
obs = env.reset()
self.update_state(obs)
self.gamma = gamma
self.nsteps = nsteps
self.dones = [False for _ in range(nenv)]
self.total_rewards = [] # store all workers' total rewards
self.real_total_rewards = []
def update_state(self, obs):
# Do frame-stacking here instead of the FrameStack wrapper to reduce IPC overhead
self.state = np.roll(self.state, shift=-self.nc, axis=3)
self.state[:, :, :, -self.nc:] = obs
def run(self):
mb_states, mb_rewards, mb_actions, mb_values, mb_dones = [], [], [], [], []
for n in range(self.nsteps):
actions, values = self.agent.step(self.state)
mb_states.append(np.copy(self.state))
mb_actions.append(actions)
mb_values.append(values)
mb_dones.append(self.dones)
obs, rewards, dones, infos = self.env.step(actions)
for done, info in zip(dones, infos):
if done:
self.total_rewards.append(info['reward'])
if info['total_reward'] != -1:
self.real_total_rewards.append(info['total_reward'])
self.dones = dones
for n, done in enumerate(dones):
if done:
self.state[n] = self.state[n] * 0
self.update_state(obs)
mb_rewards.append(rewards)
mb_dones.append(self.dones)
# batch of steps to batch of rollouts
mb_states = np.asarray(mb_states, dtype=np.uint8).swapaxes(1, 0).reshape(self.batch_ob_shape)
mb_rewards = np.asarray(mb_rewards, dtype=np.float32).swapaxes(1, 0)
mb_actions = np.asarray(mb_actions, dtype=np.int32).swapaxes(1, 0)
mb_values = np.asarray(mb_values, dtype=np.float32).swapaxes(1, 0)
mb_dones = np.asarray(mb_dones, dtype=np.bool).swapaxes(1, 0)
mb_dones = mb_dones[:, 1:]
last_values = self.agent.value(self.state).tolist()
# discount/bootstrap off value fn
for n, (rewards, dones, value) in enumerate(zip(mb_rewards, mb_dones, last_values)):
rewards = rewards.tolist()
dones = dones.tolist()
if dones[-1] == 0:
rewards = discount_with_dones(rewards + [value], dones + [0], self.gamma)[:-1]
else:
rewards = discount_with_dones(rewards, dones, self.gamma)
mb_rewards[n] = rewards
mb_rewards = mb_rewards.flatten()
mb_actions = mb_actions.flatten()
mb_values = mb_values.flatten()
return mb_states, mb_rewards, mb_actions, mb_values
def learn(network, env, seed, new_session=True, nsteps=5, nstack=4, total_timesteps=int(80e6),
vf_coef=0.5, ent_coef=0.01, max_grad_norm=0.5, lr=7e-4,
epsilon=1e-5, alpha=0.99, gamma=0.99, log_interval=1000):
tf.compat.v1.reset_default_graph()
set_global_seeds(seed)
nenvs = env.num_envs
env_id = env.env_id
save_name = os.path.join('models', env_id + '.save')
ob_space = env.observation_space
ac_space = env.action_space
agent = Agent(Network=network, ob_space=ob_space, ac_space=ac_space, nenvs=nenvs,
nsteps=nsteps, nstack=nstack,
ent_coef=ent_coef, vf_coef=vf_coef,
max_grad_norm=max_grad_norm,
lr=lr, alpha=alpha, epsilon=epsilon, total_timesteps=total_timesteps)
if os.path.exists(save_name):
agent.load(save_name)
runner = Runner(env, agent, nsteps=nsteps, nstack=nstack, gamma=gamma)
nbatch = nenvs * nsteps
tstart = time.time()
for update in range(1, total_timesteps // nbatch + 1):
states, rewards, actions, values = runner.run()
policy_loss, value_loss, policy_entropy = agent.train(
states, rewards, actions, values)
nseconds = time.time() - tstart
fps = int((update * nbatch) / nseconds)
if update % log_interval == 0 or update == 1:
print(' - - - - - - - ')
print("nupdates", update)
print("total_timesteps", update * nbatch)
print("fps", fps)
print("policy_entropy", float(policy_entropy))
print("value_loss", float(value_loss))
# total reward
r = runner.total_rewards[-100:] # get last 100
tr = runner.real_total_rewards[-100:]
if len(r) == 100:
print("avg reward (last 100):", np.mean(r))
if len(tr) == 100:
print("avg total reward (last 100):", np.mean(tr))
print("max (last 100):", np.max(tr))
agent.save(save_name)
env.close()
agent.save(save_name)
| [
"victorpbi5@hotmail.com"
] | victorpbi5@hotmail.com |
40c50ea403143a68cd76529a6eca254fecf33e09 | 17bbb6a93ac2689e3b573c6a76d245c3de4c7d34 | /controlapp/apps.py | b9af50e257656146060bb43c2943c1e9e71f610d | [] | no_license | luma1103/proyectozona | d18297aeee5f2beb311b2ffa949f8a63a2f52f5c | ed5cfce95b48a7ef9b30040aafee0ecd40295caf | refs/heads/master | 2021-08-07T08:24:56.152860 | 2017-11-07T22:17:24 | 2017-11-07T22:17:24 | 109,874,181 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 160 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ControlappConfig(AppConfig):
name = 'controlapp'
| [
"lumamor1103@gmail.com"
] | lumamor1103@gmail.com |
8f152a314ef63e887d0f8e569075306ee1396908 | 4ae3b27a1d782ae43bc786c841cafb3ace212d55 | /Test_Slen/Pytest_proj/01/Scripts/rst2latex.py | 61137b0e6f44ef69c8780b8663fadf71a62bbb4b | [] | no_license | bopopescu/Py_projects | c9084efa5aa02fd9ff6ed8ac5c7872fedcf53e32 | a2fe4f198e3ca4026cf2e3e429ac09707d5a19de | refs/heads/master | 2022-09-29T20:50:57.354678 | 2020-04-28T05:23:14 | 2020-04-28T05:23:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 844 | py | #!c:\users\jsun\documents\py_projects\pytest_proj\01\scripts\python.exe
# $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing LaTeX.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline
description = ('Generates LaTeX documents from standalone reStructuredText '
'sources. '
'Reads from <source> (default is stdin) and writes to '
'<destination> (default is stdout). See '
'<http://docutils.sourceforge.net/docs/user/latex.html> for '
'the full reference.')
publish_cmdline(writer_name='latex', description=description)
| [
"sunusd@yahoo.com"
] | sunusd@yahoo.com |
1c40fabd6acb0b56b897d13eb7ee86d5ac64e604 | 876c0fcfcc6201ab36e3eefe61feac5053acd642 | /q3helper/fraction.py | 636e1d0f79ac3f1db7edc107c0a1cb5ce52d9ca8 | [] | no_license | mbusc1/Python-Projects | 10ca8b6c229681007ff9af84fcdf6b964213deff | 0d28b8f3f1d82fdce958172b84a06c384c0d5d7b | refs/heads/master | 2021-01-09T04:27:57.604419 | 2020-02-21T23:17:03 | 2020-02-21T23:17:03 | 242,245,375 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,874 | py | from goody import irange
from goody import type_as_str
import math
class Fraction:
# Call as Fraction._gcd(...); no self parameter
# Helper method computes the Greatest Common Divisor of x and y
@staticmethod
def _gcd(x : int, y : int) -> int:
assert x >= 0 and y >= 0, 'Fraction._gcd: x('+str(x)+') and y('+str(y)+') must be >= 0'
while y != 0:
x, y = y, x % y
return x
# Returns a string that is the decimal representation of a Fraction, with
# decimal_places digitst appearing after the decimal points.
# For example: if x = Fraction(23,8), then x(5) returns '2.75000'
def __call__(self, decimal_places):
answer = ''
num = self.num
denom = self.denom
# handle negative values
if num < 0:
num, answer = -num, '-'
# handle integer part
if num >= denom:
answer += str(num//denom)
num = num - num//denom*denom
# handle decimal part
answer += '.'+str(num*10**decimal_places//denom)
return answer
@staticmethod
# Call as Fraction._validate_arithmetic(..); with no self parameter
# Helper method raises exception with appropriate message if type(v) is not
# in the set of types t; the message includes the values of the strings
# op (operator), lt (left type) and rt (right type)
# An example call (from my __add__ method), which checks whether the type of
# right is a Fraction or int is...
# Fraction._validate_arithmetic(right, {Fraction,int},'+','Fraction',type_as_str(right))
def _validate_arithmetic(v, t : set, op : str, lt : str, rt : str):
if type(v) not in t:
raise TypeError('unsupported operand type(s) for '+op+
': \''+lt+'\' and \''+rt+'\'')
@staticmethod
# Call as Fraction._validate_relational(..); with no self parameter
# Helper method raises exception with appropriate message if type(v) is not
# in the set of types t; the message includes the values of the strings
# op (operator), and rt (right type)
def _validate_relational(v, t : set, op : str, rt : str):
if type(v) not in t:
raise TypeError('unorderable types: '+
'Fraction() '+op+' '+rt+'()')
def __init__(self,num=0,denom=1):
#check for 0
if num == 0 and denom != 1:
self.num = num
self.denom = 1
return None
if denom == 0:
raise AssertionError('Cannot divide by 0 for a fraction')
# verify input data type is integer
if (type(num) is not int) or (type(denom) is not int):
raise AssertionError('Arguments must be 1-2 integers')
return None
#verify postivie numerator
if denom > 0 and num < 0:
gcd = self._gcd(-num,denom)
self.num = int(num/gcd)
self.denom = int(denom/gcd)
return None
if denom < 0 and num < 0:
num = -num
denom = -denom
gcd = self._gcd(num,denom)
self.num = int(num/gcd)
self.denom = int(denom/gcd)
return None
#fix negative denom
if num > 0 and denom < 0:
num = -num
denom = -denom
gcd = self._gcd(-num,denom)
self.num = int(num/gcd)
self.denom = int(denom/gcd)
return None
# assign regular variables
gcd = self._gcd(num,denom)
self.num = int(num/gcd)
self.denom = int(denom/gcd)
return None
def __repr__(self):
return 'Fraction('+str(self.num)+','+str(self.denom)+')'
def __str__(self):
return str(self.num)+'/'+str(self.denom)
def __bool__(self):
if self.num == 0 and self.denom == 1:
return False
else:
return True
def __getitem__(self,i):
if type(i) is int:
if i == 0:
return self.num
elif i == 1:
return self.denom
else:
raise TypeError('Indavild index integer')
elif type(i) is str:
if i == '':
raise TypeError('Index must be a number or non-empty string representing numerator or denominator')
elif str.find(i,'numerator'[0:len(i)]) >= 0:
return self.num
elif str.find(i,'denominator'[0:len(i)]) >= 0:
return self.denom
else:
raise TypeError('Indavild index string')
else:
raise TypeError('Index must be a number or non-empty string representing numerator or denominator')
def __pos__(self):
return Fraction(self.num,self.denom)
def __neg__(self):
return Fraction(-self.num,self.denom)
def __abs__(self):
return Fraction(abs(self.num),(self.denom))
def __add__(self,right):
Fraction._validate_arithmetic(right, {Fraction,int},'+','Fraction',type_as_str(right))
if type(right) is int:
return Fraction(self.num+(right*self.denom),self.denom)
if type(right) is Fraction:
gcd = min(self.denom,right.denom)
return Fraction(self.num*right.denom+right.num*self.denom,int((self.denom*right.denom+right.denom*self.denom)/ gcd))
def __radd__(self,left):
Fraction._validate_arithmetic(left, {Fraction,int},'+','Fraction',type_as_str(left))
if type(left) is int:
return Fraction(self.num+(left*self.denom),self.denom)
if type(left) is Fraction:
gcd = min(self.denom,left.denom)
return Fraction(self.num*left.denom+left.num*self.denom,int((self.denom*left.denom+left.denom*self.denom)/ gcd))
def __sub__(self,right):
Fraction._validate_arithmetic(right, {Fraction,int},'-','Fraction',type_as_str(right))
if type(right) is int:
return Fraction(self.num-(right*self.denom),self.denom)
if type(right) is Fraction:
gcd = min(self.denom,right.denom)
return Fraction(self.num*right.denom-right.num*self.denom,int((self.denom*right.denom+right.denom*self.denom)/ gcd))
def __rsub__(self,left):
Fraction._validate_arithmetic(left, {Fraction,int},'-','Fraction',type_as_str(left))
if type(left) is int:
return Fraction(-self.num+(left*self.denom),self.denom)
if type(left) is Fraction:
gcd = min(self.denom,left.denom)
return Fraction(-self.num*left.denom+left.num*self.denom,int((self.denom*left.denom+left.denom*self.denom)/ gcd))
def __mul__(self,right):
Fraction._validate_arithmetic(right, {Fraction,int},'*','Fraction',type_as_str(right))
if type(right) is Fraction:
return Fraction(self.num*right.num,self.denom*right.denom)
elif type(right) is int:
return Fraction(self.num*right,self.denom)
def __rmul__(self,left):
Fraction._validate_arithmetic(left, {Fraction,int},'*','Fraction',type_as_str(left))
if type(left) is Fraction:
return Fraction(self.num*left.num,self.denom*left.denom)
elif type(left) is int:
return Fraction(self.num*left,self.denom)
def __truediv__(self,right):
pass
def __rtruediv__(self,left):
pass
def __pow__(self,right):
pass
def __eq__(self,right):
pass
def __lt__(self,right):
pass
def __gt__(self,right):
pass
# Uncomment this method when you are ready to write/test it
# If this is pass, then no attributes will be set!
#def __setattr__(self,name,value):
# pass
##############################
# Newton: pi = 6*arcsin(1/2); see the arcsin series at http://mathforum.org/library/drmath/view/54137.html
# Check your results at http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
# also see http://www.numberworld.org/misc_runs/pi-5t/details.html
def compute_pi(n):
def prod(r):
answer = 1
for i in r:
answer *= i
return answer
answer = Fraction(1,2)
x = Fraction(1,2)
for i in irange(1,n):
big = 2*i+1
answer += Fraction(prod(range(1,big,2)),prod(range(2,big,2)))*x**big/big
return 6*answer
if __name__ == '__main__':
# Put in simple tests for Fraction before allowing driver to run
print()
import driver
driver.default_file_name = 'bscq31F19.txt'
# driver.default_show_traceback= True
# driver.default_show_exception= True
# driver.default_show_exception_message= True
driver.driver()
| [
"pianobuscemi@gmail.com"
] | pianobuscemi@gmail.com |
740e29f1caaa4ec8c3bdc4ff19d6221706c40e2e | aac4c14380fe5f8f6acd287bd30aa47ebcf955fa | /codes/eda.py | b21648467689cfdeff6d079b2b7461ecee12717a | [] | no_license | matheus695p/nox-and-co-emissions | 13fa2e2e5e8d5b7555702b1facf90625bdcf522e | 60e0acc4e96d1b0e0455898c8881a68ae6691bdd | refs/heads/main | 2023-04-15T07:32:44.314993 | 2021-04-16T16:02:44 | 2021-04-16T16:02:44 | 356,569,249 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,244 | py | import warnings
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from src.config_cnn import arguments_parser
from src.visualizations import (pairplot_sns, pairgrid_plot, violinplot,
kernel_density_estimation)
warnings.filterwarnings("ignore")
sns.set(font_scale=1.5)
plt.style.use('dark_background')
# variables
args = arguments_parser()
path = "data/featured/"
file = "featured_data.csv"
# lectura del dataframe
df = pd.read_csv(path+file)
df["year"] = df["year"].apply(int)
# features
feature_cols = ['at', 'ap', 'ah', 'afdp', 'gtep', 'tit', 'tat', 'tey', 'cdp']
# target col
target_cols = ["co", "nox"]
# datos de training
train_df = df[(df["year"] >= 2011) & (df["year"] <= 2013)]
train_df.drop(columns="year", inplace=True)
# datos de testing
test_df = df[df["year"] >= 2014]
test_df.drop(columns="year", inplace=True)
# solo los targets
targets_train = train_df[target_cols]
targets_test = test_df[target_cols]
# solo los features
feature_train = train_df[feature_cols]
feature_test = test_df[feature_cols]
# PAIRPLOTS
# pairplot targets
pairplot_sns(targets_train, name="Entrenamiento")
pairplot_sns(targets_test, name="Testeo")
# pairplot features
pairplot_sns(feature_train, name="Train")
pairplot_sns(feature_test, name="Test")
# PAIRGRIDS
# pairgrids targets
pairgrid_plot(targets_train, name="Entrenamiento")
pairgrid_plot(targets_test, name="Testeo")
# DISTRIBUCIONES targets
for col in target_cols:
print("Distribuciones de la columna:", col)
# Violin plot de la distribución
violinplot(targets_train, col, name="Entrenamiento")
violinplot(targets_test, col, name="Testeo")
# Kernel estimación
kernel_density_estimation(targets_train, col, name="Entrenamiento")
kernel_density_estimation(targets_test, col, name="Testeo")
# DISTRIBUCIONES features
for col in feature_cols:
print("Distribuciones de la columna:", col)
# Violin plot de la distribución
# violinplot(feature_train, col, name="Entrenamiento")
# violinplot(feature_test, col, name="Testeo")
# Kernel estimación
kernel_density_estimation(feature_train, col, name="Entrenamiento")
kernel_density_estimation(feature_test, col, name="Testeo")
| [
"mateu_695p@hotmail.com"
] | mateu_695p@hotmail.com |
d1863f2c464a35789ea292a393febaade2777322 | d7b86b837c7602dcf08bc3e26ccb38fd9f87a96c | /sampleproject/bot/telegrambot.py | 43bf22205ce8cdff391ae693d37ce75be5c0c3a2 | [] | no_license | ahmadfah1612/django-telegrambot | 897270548ee9fc29c6d66ad1ca5fd17db33444cf | 5ca49c0b3c460558865a5781144353009c1f4611 | refs/heads/master | 2021-06-11T04:55:54.505704 | 2017-04-08T11:01:56 | 2017-04-08T11:01:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,472 | py | # -*- coding: utf-8 -*-
# Example code for telegrambot.py module
from telegram.ext import CommandHandler, MessageHandler, Filters
from django_telegrambot.apps import DjangoTelegramBot
import logging
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')
def help(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')
def echo(bot, update):
update.message.reply_text(update.message.text)
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def main():
logger.info("Loading handlers for telegram bot")
# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
| [
"peleccom@gmail.com"
] | peleccom@gmail.com |
0d5e9383532263b64a998555e321058c1dca6a7a | aecb87b877e41244d0f17957874c7648a99d5406 | /shuffle.py | 31a07b2d1abb6c1f58e2da6f8efedc951e819210 | [] | no_license | RobbeDP/spotify-shuffler | 2795c8e406c0cf936fdc834fef0b9dc2fc6cecd0 | ff43159301ef50a47826414b99181ecfc3b1dc3b | refs/heads/master | 2022-12-06T01:20:18.969241 | 2022-11-24T13:34:33 | 2022-11-24T13:34:33 | 181,222,304 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,470 | py | import sys
import os
import spotipy
import spotipy.util as util
import random
limit = 100
scope = 'playlist-modify-public'
if len(sys.argv) > 2:
username = sys.argv[1]
playlist_uri = sys.argv[2]
else:
print(f"Usage: {sys.argv[0]} username playlist_uri")
sys.exit()
try:
token = util.prompt_for_user_token(username, scope)
except AttributeError:
os.remove(f".cache-{username}")
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
playlist_uri_list = playlist_uri.split(':')
user = playlist_uri_list[2]
playlist_id = playlist_uri_list[4]
playlist = sp.user_playlist(user, playlist_id, fields=['name', 'tracks'])
playlist_name = f"{playlist['name']} - SHUFFLED"
new_playlist = sp.user_playlist_create(username, playlist_name)
track_uris = []
offset = 0
while True:
items = sp.user_playlist_tracks(user=user, playlist_id=playlist_id, limit=limit, offset=offset)['items']
for item in items:
track_uris.append(item['track']['uri'])
offset += limit
if len(items) != limit:
break
random.shuffle(track_uris)
offset = 0
while True:
to_add = track_uris[offset:offset+limit]
sp.user_playlist_add_tracks(username, new_playlist['id'], to_add)
offset += limit
if len(to_add) != limit:
break
else:
print(f"Couldn't get token for {username}")
| [
"Robbe.DeProft@ugent.be"
] | Robbe.DeProft@ugent.be |
7840d987b36c9fc865a9c33ba48aef4d748b4d5c | 7c6d2749585529a83ac9238d1ed03415ac754660 | /Ex31.py | 37f3a62d72345c3b7acbd909be32865104d83a50 | [] | no_license | Caffeine-addict7410/Pythonwork | c7006daf87926c432a2311ebfb49ff0bb8179cc8 | b7d55a71d98354527507c477ce596d00e591447e | refs/heads/master | 2020-05-01T17:07:42.118331 | 2019-06-11T14:48:43 | 2019-06-11T14:48:43 | 177,591,833 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,178 | py | print("""You enter a dark room with two doors.
Do you go through door #1 or door #2?""")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake.")
print("What do you do?")
print("1. Take the cake")
print("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print("The bear eats your face off. GOOD JOB!")
elif bear == "2":
print("The bear eats your legs off.Good job!")
else:
print(f"Well,doing {bear} is probably better.")
print("The bear flees")
elif door == "2":
print("you stare into the endless adyss at cthulhu's retina")
print("1. Blueberries")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies")
insanity = input("> ")
if insanity == "1" or insanity == "2":
print("Your body survives powered by a mind of jello.")
print("Good job!!")
else:
print("The insanity rots your eyes into a pool of muck.")
print("Game over! :(")
else:
print("You stumble around and fall on a knife and die.")
print("Game Over :(") | [
"student.138059@worcesterschools.net"
] | student.138059@worcesterschools.net |
f1f5c53ef79d2ea290f04a92dfee8f7ca47e5392 | 8d4f064973b5f21ed06cd06e9853b3fba78e027b | /PYTHON/stack.py | f3d3d4b98d68db2819b33d34e1e91cbc76bacfe7 | [] | no_license | abby2407/Data_Structures-and-Algorithms | f824fe4c9b37c6136251e8b8e14f4ff58297f2c7 | 5a04a518b2dd26df270004d00e4b9454206a06c0 | refs/heads/master | 2022-09-21T02:19:52.594624 | 2020-06-01T06:41:15 | 2020-06-01T06:41:15 | 265,739,975 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,796 | py |
# ---------------stack using simple list ----------------------
class Stack():
def __init__(self):
self.stack = list()
def push(self,item):
self.stack.append(item)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
return None
def peek(self):
if len(self.stack) > 0:
return self.stack[len(self.stack) - 1]
else:
return None
def __str__(self):
return str(self.stack)
my_stack = Stack()
my_stack.push(5)
my_stack.push(10)
my_stack.push(15)
print(my_stack)
print(my_stack.pop())
print(my_stack.peek())
print(my_stack)
#-----------------*--------------------*------------------*-----------
# stack using Singly Linked List
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Stack1:
def __init__(self):
self.head = None
def isempty(self):
if self.head == None:
return True
else:
return False
def push(self,data):
if self.head == None:
self.head = Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
def pop(self):
if self.isempty():
return None
else:
poppedNode = self.head
self.head = self.head.next
poppedNode.next = None
return poppedNode.data
def peek(self):
if self.isempty():
return None
else:
return self.head.data
MyStack = Stack1()
MyStack.push(2)
MyStack.push(4)
MyStack.push(6)
MyStack.pop()
print(MyStack)
| [
"noreply@github.com"
] | noreply@github.com |
2dfc7daffcdc6cd0db366b294cdcc40bb150459f | d89545958e45d11e462966ad4ce02e68b049b23b | /pochta/pochta_main/models.py | 2847b7d9aff6d846cc49f1f81f59d2454fe3f2ba | [] | no_license | foxgroup-2020/pochta-address | 283c3cfcbcff4aec28fe3e317dc1489ed903be76 | 9d8e97544168198391353671600f292dea99d040 | refs/heads/main | 2023-01-13T04:36:00.707414 | 2020-11-15T04:39:49 | 2020-11-15T04:39:49 | 312,629,660 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,181 | py | from django.db import models
from django.contrib.auth.models import User
import os
class FileParse(models.Model):
date_upload = models.DateTimeField('Дата загрузки', auto_now=True)
file_path = models.FileField('Файл', upload_to='docs/')
current_record = models.IntegerField('Текущая запись', default=0, editable=False)
all_record = models.IntegerField('Всего записей', default=0, editable=False)
result = models.BooleanField('Результат', default=False)
def state(self):
if self.all_record != 0:
return (self.current_record*100) // self.all_record
else:
return 0
def filename(self):
return os.path.basename(self.file_path.name)
class FileResult(models.Model):
source_addr = models.CharField('Исходный адрес', max_length=300)
source_index = models.CharField('Исходный индекс', max_length=6, blank=True)
get_addr = models.CharField('Полученный адрес', max_length=300)
state = models.IntegerField('Статус', default=0)
not_recognize = models.CharField('Полученный адрес', max_length=5, blank=True)
accuracy = models.CharField('Код точности', max_length=3, blank=True)
time_answer = models.IntegerField('Время ответа', default=0, blank=True)
field_index = models.CharField('Индекс', max_length=6, blank=True)
field_C = models.CharField('Страна', max_length=100, blank=True)
field_R = models.CharField('Регион', max_length=100, blank=True)
field_A = models.CharField('Район', max_length=100, blank=True)
field_P = models.CharField('Населенный пункт', max_length=100, blank=True)
field_T = models.CharField('Внутригородская территория', max_length=100, blank=True)
field_S = models.CharField('Улично-дорожные элементы', max_length=100, blank=True)
field_N = models.IntegerField('Номер дома', default=0, blank=True)
field_NL = models.CharField('Литера', max_length=2, blank=True)
field_D = models.CharField('Дробь', max_length=2, blank=True)
field_E = models.IntegerField('Корпус', default=0, blank=True)
field_B = models.IntegerField('Строение', default=0, blank=True)
field_F = models.IntegerField('Помещение', default=0, blank=True)
field_BOX = models.IntegerField('Абонентский ящик', default=0, blank=True)
ident_low = models.CharField('Идентификатор нижнего уровня', max_length=50, blank=True)
latitude = models.CharField('Широта',max_length=10, blank=True)
longtitude = models.CharField('Долгота',max_length=10, blank=True)
num_dest_post = models.IntegerField('Номер участка', default=0, blank=True)
file_source = models.ForeignKey(FileParse, on_delete=models.CASCADE, blank=True)
class Billing(models.Model):
date_req = models.DateField(auto_now=True)
file = models.ForeignKey(FileParse, on_delete=models.Model)
count_req = models.IntegerField(default=0)
| [
"ruslan.gzn@gmail.com"
] | ruslan.gzn@gmail.com |
3a9e6f26eb3c504ecdcee462cc4ca6fa202c7bab | 6cea35ad90d80191d4a088685d9192fb43f39ee2 | /example/chat/packetType.py | 5dbf972f5cf124ee971ab18468593b1abec8bdc5 | [] | no_license | realtime-system/pysage | de48f538cae24caf08829d9311dfe64e2856c7be | 6aef3a6f3c68ae8622f921254ee3815cd5cade07 | refs/heads/master | 2016-09-06T09:38:46.088683 | 2011-11-09T23:20:06 | 2011-11-09T23:20:06 | 24,540,925 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 766 | py | from pysage import *
class rcvChatMessage(Message):
'''regular chat Message'''
properties = ['nick', 'msg']
types = ['p','p']
packet_type = 101
class conMessage(Message):
'''client connect to server and send nickName'''
properties = ['nick']
types = ['p']
packet_type = 102
class srvConMessage(Message):
'''server send connection data to clients'''
properties = ['id','nick']
types = ['i', 'p']
packet_type = 103
class errMessage(Message):
'''error Messages sending id of error'''
properties = ['err']
types = ['i']
packet_type = 104
class inputMsg(Message):
'''client input Messages'''
properties = ['msg']
types = ['p']
packet_type = 105 | [
"afanolovcic@gmail.com@1fa98330-223e-0410-ac30-ad2a981e1070"
] | afanolovcic@gmail.com@1fa98330-223e-0410-ac30-ad2a981e1070 |
9baf84a3f128fbdc8787947c099b5f83b777bbc7 | 1285703d35b5a37734e40121cd660e9c1a73b076 | /aizu_online_judge/tree/7_d_solution.py | 70efa80577b60594e3d0ffb0dedc8489925e85a8 | [] | no_license | takin6/algorithm-practice | 21826c711f57131108168775f08e4e13d07a3b38 | f4098bea2085a77d11c29e1593b3cc3f579c24aa | refs/heads/master | 2022-11-30T09:40:58.083766 | 2020-08-07T22:07:46 | 2020-08-07T22:07:46 | 283,609,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 985 | py | class Node():
def __init__(self, parent = -1, left = -1, right = -1):
self.parent = parent
self.left = left
self.right = right
def postorder(ns, i, post):
if ns[i].left != -1:
postorder(ns, ns[i].left, post)
if ns[i].right != -1:
postorder(ns, ns[i].right, post)
post.append(str(i + 1))
def poio_node(ns, po, io):
p = po[0]
i = io.index(p)
if i != 0:
ns[p].left = po[1]
ns[po[1]].parent = p
poio_node(ns, po[1:i + 1], io[:i])
if i != len(io) -1:
ns[p].right = po[i + 1]
ns[po[1 + i]].parent = p
poio_node(ns, po[i + 1:], io[i + 1:])
def min1(n):
return n - 1
n = int(input())
po = list(map(int, input().split()))
io = list(map(int, input().split()))
po = list(map(min1, po))
io = list(map(min1, io))
ns = [Node() for i in range(n)]
poio_node(ns, po, io)
post = []
postorder(ns, po[0], post)
print(" ".join(post)) | [
"takayukiinoue116@gmail.com"
] | takayukiinoue116@gmail.com |
02701f9e865c9dad1ce5b494c6801ac7563a11fa | cc5e889e5cfb063651f3e2d103a22a64f1870959 | /nova-13.0.0/nova/virt/libvirt/driver.py | 58dd46d7e508bce5058c0f970bb66273658b1f6c | [
"Apache-2.0"
] | permissive | bopopescu/pro-nova | d7e3a17f884c09548d424b17a59f2dcfcb2bb16e | 7632e83030d7358b7eb8f45918d504d267047cd9 | refs/heads/master | 2022-11-23T14:51:12.343826 | 2017-03-02T15:00:02 | 2017-03-02T15:00:02 | 282,099,365 | 0 | 0 | null | 2020-07-24T02:06:02 | 2020-07-24T02:06:02 | null | UTF-8 | Python | false | false | 363,563 | py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
"""
A connection to a hypervisor through libvirt.
Supports KVM, LXC, QEMU, UML, XEN and Parallels.
"""
import collections
import contextlib
import errno
import functools
import glob
import itertools
import mmap
import operator
import os
import shutil
import tempfile
import time
import uuid
import eventlet
from eventlet import greenthread
from eventlet import tpool
from lxml import etree
from os_brick.initiator import connector
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_service import loopingcall
from oslo_utils import excutils
from oslo_utils import fileutils
from oslo_utils import importutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units
import six
from six.moves import range
from nova.api.metadata import base as instance_metadata
from nova import block_device
from nova.compute import arch
from nova.compute import hv_type
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_mode
from nova.image import glance
import nova.conf
from nova.console import serial as serial_console
from nova.console import type as ctype
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova import image
from nova.network import model as network_model
from nova import objects
from nova.objects import fields
from nova.objects import migrate_data as migrate_data_obj
from nova.pci import manager as pci_manager
from nova.pci import utils as pci_utils
from nova import utils
from nova import version
from nova.virt import block_device as driver_block_device
from nova.virt import configdrive
from nova.virt import diagnostics
from nova.virt.disk import api as disk
from nova.virt.disk.vfs import guestfs
from nova.virt import driver
from nova.virt import firewall
from nova.virt import hardware
from nova.virt.image import model as imgmodel
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import firewall as libvirt_firewall
from nova.virt.libvirt import guest as libvirt_guest
from nova.virt.libvirt import host
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import imagecache
from nova.virt.libvirt import instancejobtracker
from nova.virt.libvirt.storage import dmcrypt
from nova.virt.libvirt.storage import lvm
from nova.virt.libvirt.storage import rbd_utils
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt.libvirt import vif as libvirt_vif
from nova.virt.libvirt.volume import remotefs
from nova.virt import netutils
from nova.virt import watchdog_actions
from nova import volume
from nova.volume import encryptors
libvirt = None
uefi_logged = False
LOG = logging.getLogger(__name__)
# Downtime period in milliseconds
LIVE_MIGRATION_DOWNTIME_MIN = 100
# Step count
LIVE_MIGRATION_DOWNTIME_STEPS_MIN = 3
# Delay in seconds
LIVE_MIGRATION_DOWNTIME_DELAY_MIN = 10
libvirt_opts = [
cfg.StrOpt('rescue_image_id',
help='Rescue ami image. This will not be used if an image id '
'is provided by the user.'),
cfg.StrOpt('rescue_kernel_id',
help='Rescue aki image'),
cfg.StrOpt('rescue_ramdisk_id',
help='Rescue ari image'),
cfg.StrOpt('virt_type',
default='kvm',
choices=('kvm', 'lxc', 'qemu', 'uml', 'xen', 'parallels'),
help='Libvirt domain type'),
cfg.StrOpt('connection_uri',
default='',
help='Override the default libvirt URI '
'(which is dependent on virt_type)'),
cfg.BoolOpt('inject_password',
default=False,
help='Inject the admin password at boot time, '
'without an agent.'),
cfg.BoolOpt('inject_key',
default=False,
help='Inject the ssh public key at boot time'),
cfg.IntOpt('inject_partition',
default=-2,
help='The partition to inject to : '
'-2 => disable, -1 => inspect (libguestfs only), '
'0 => not partitioned, >0 => partition number'),
cfg.BoolOpt('use_usb_tablet',
default=True,
help='Sync virtual and real mouse cursors in Windows VMs'),
cfg.StrOpt('live_migration_inbound_addr',
help='Live migration target ip or hostname '
'(if this option is set to None, which is the default, '
'the hostname of the migration target '
'compute node will be used)'),
cfg.StrOpt('live_migration_uri',
help='Override the default libvirt live migration target URI '
'(which is dependent on virt_type) '
'(any included "%s" is replaced with '
'the migration target hostname)'),
cfg.StrOpt('live_migration_flag',
default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER, '
'VIR_MIGRATE_LIVE, VIR_MIGRATE_TUNNELLED',
help='Migration flags to be set for live migration',
deprecated_for_removal=True,
deprecated_reason='The correct live migration flags can be '
'inferred from the new '
'live_migration_tunnelled config option. '
'live_migration_flag will be removed to '
'avoid potential misconfiguration.'),
cfg.StrOpt('block_migration_flag',
default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER, '
'VIR_MIGRATE_LIVE, VIR_MIGRATE_TUNNELLED, '
'VIR_MIGRATE_NON_SHARED_INC',
help='Migration flags to be set for block migration',
deprecated_for_removal=True,
deprecated_reason='The correct block migration flags can be '
'inferred from the new '
'live_migration_tunnelled config option. '
'block_migration_flag will be removed to '
'avoid potential misconfiguration.'),
cfg.BoolOpt('live_migration_tunnelled',
help='Whether to use tunnelled migration, where migration '
'data is transported over the libvirtd connection. If '
'True, we use the VIR_MIGRATE_TUNNELLED migration flag, '
'avoiding the need to configure the network to allow '
'direct hypervisor to hypervisor communication. If '
'False, use the native transport. If not set, Nova '
'will choose a sensible default based on, for example '
'the availability of native encryption support in the '
'hypervisor.'),
cfg.IntOpt('live_migration_bandwidth',
default=0,
help='Maximum bandwidth(in MiB/s) to be used during migration. '
'If set to 0, will choose a suitable default. Some '
'hypervisors do not support this feature and will return '
'an error if bandwidth is not 0. Please refer to the '
'libvirt documentation for further details'),
cfg.IntOpt('live_migration_downtime',
default=500,
help='Maximum permitted downtime, in milliseconds, for live '
'migration switchover. Will be rounded up to a minimum '
'of %dms. Use a large value if guest liveness is '
'unimportant.' % LIVE_MIGRATION_DOWNTIME_MIN),
cfg.IntOpt('live_migration_downtime_steps',
default=10,
help='Number of incremental steps to reach max downtime value. '
'Will be rounded up to a minimum of %d steps' %
LIVE_MIGRATION_DOWNTIME_STEPS_MIN),
cfg.IntOpt('live_migration_downtime_delay',
default=75,
help='Time to wait, in seconds, between each step increase '
'of the migration downtime. Minimum delay is %d seconds. '
'Value is per GiB of guest RAM + disk to be transferred, '
'with lower bound of a minimum of 2 GiB per device' %
LIVE_MIGRATION_DOWNTIME_DELAY_MIN),
cfg.IntOpt('live_migration_completion_timeout',
default=800,
help='Time to wait, in seconds, for migration to successfully '
'complete transferring data before aborting the '
'operation. Value is per GiB of guest RAM + disk to be '
'transferred, with lower bound of a minimum of 2 GiB. '
'Should usually be larger than downtime delay * downtime '
'steps. Set to 0 to disable timeouts.'),
cfg.IntOpt('live_migration_progress_timeout',
default=150,
help='Time to wait, in seconds, for migration to make forward '
'progress in transferring data before aborting the '
'operation. Set to 0 to disable timeouts.'),
cfg.StrOpt('snapshot_image_format',
choices=('raw', 'qcow2', 'vmdk', 'vdi'),
help='Snapshot image format. Defaults to same as source image'),
cfg.StrOpt('disk_prefix',
help='Override the default disk prefix for the devices attached'
' to a server, which is dependent on virt_type. '
'(valid options are: sd, xvd, uvd, vd)'),
cfg.IntOpt('wait_soft_reboot_seconds',
default=120,
help='Number of seconds to wait for instance to shut down after'
' soft reboot request is made. We fall back to hard reboot'
' if instance does not shutdown within this window.'),
cfg.StrOpt('cpu_mode',
choices=('host-model', 'host-passthrough', 'custom', 'none'),
help='Set to "host-model" to clone the host CPU feature flags; '
'to "host-passthrough" to use the host CPU model exactly; '
'to "custom" to use a named CPU model; '
'to "none" to not set any CPU model. '
'If virt_type="kvm|qemu", it will default to '
'"host-model", otherwise it will default to "none"'),
cfg.StrOpt('cpu_model',
help='Set to a named libvirt CPU model (see names listed '
'in /usr/share/libvirt/cpu_map.xml). Only has effect if '
'cpu_mode="custom" and virt_type="kvm|qemu"'),
cfg.StrOpt('snapshots_directory',
default='$instances_path/snapshots',
help='Location where libvirt driver will store snapshots '
'before uploading them to image service'),
cfg.StrOpt('xen_hvmloader_path',
default='/usr/lib/xen/boot/hvmloader',
help='Location where the Xen hvmloader is kept'),
cfg.ListOpt('disk_cachemodes',
default=[],
help='Specific cachemodes to use for different disk types '
'e.g: file=directsync,block=none'),
cfg.StrOpt('rng_dev_path',
help='A path to a device that will be used as source of '
'entropy on the host. Permitted options are: '
'/dev/random or /dev/hwrng'),
cfg.ListOpt('hw_machine_type',
help='For qemu or KVM guests, set this option to specify '
'a default machine type per host architecture. '
'You can find a list of supported machine types '
'in your environment by checking the output of '
'the "virsh capabilities"command. The format of the '
'value for this config option is host-arch=machine-type. '
'For example: x86_64=machinetype1,armv7l=machinetype2'),
cfg.StrOpt('sysinfo_serial',
default='auto',
choices=('none', 'os', 'hardware', 'auto'),
help='The data source used to the populate the host "serial" '
'UUID exposed to guest in the virtual BIOS.'),
cfg.IntOpt('mem_stats_period_seconds',
default=10,
help='A number of seconds to memory usage statistics period. '
'Zero or negative value mean to disable memory usage '
'statistics.'),
cfg.ListOpt('uid_maps',
default=[],
help='List of uid targets and ranges.'
'Syntax is guest-uid:host-uid:count'
'Maximum of 5 allowed.'),
cfg.ListOpt('gid_maps',
default=[],
help='List of guid targets and ranges.'
'Syntax is guest-gid:host-gid:count'
'Maximum of 5 allowed.'),
cfg.IntOpt('realtime_scheduler_priority',
default=1,
help='In a realtime host context vCPUs for guest will run in '
'that scheduling priority. Priority depends on the host '
'kernel (usually 1-99)'),
cfg.StrOpt('backup_path',
default="/var/lib/nova/instances/backup",
help='where backup are stored on disk (string value)'),
]
CONF = nova.conf.CONF
CONF.register_opts(libvirt_opts, 'libvirt')
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('enabled', 'nova.compute.api',
group='ephemeral_storage_encryption')
CONF.import_opt('cipher', 'nova.compute.api',
group='ephemeral_storage_encryption')
CONF.import_opt('key_size', 'nova.compute.api',
group='ephemeral_storage_encryption')
CONF.import_opt('live_migration_retry_count', 'nova.compute.manager')
CONF.import_opt('server_proxyclient_address', 'nova.spice', group='spice')
CONF.import_opt('vcpu_pin_set', 'nova.conf.virt')
CONF.import_opt('hw_disk_discard', 'nova.virt.libvirt.imagebackend',
group='libvirt')
CONF.import_group('workarounds', 'nova.utils')
CONF.import_opt('iscsi_use_multipath', 'nova.virt.libvirt.volume.iscsi',
group='libvirt')
DEFAULT_FIREWALL_DRIVER = "%s.%s" % (
libvirt_firewall.__name__,
libvirt_firewall.IptablesFirewallDriver.__name__)
DEFAULT_UEFI_LOADER_PATH = {
"x86_64": "/usr/share/OVMF/OVMF_CODE.fd",
"aarch64": "/usr/share/AAVMF/AAVMF_CODE.fd"
}
MAX_CONSOLE_BYTES = 100 * units.Ki
# The libvirt driver will prefix any disable reason codes with this string.
DISABLE_PREFIX = 'AUTO: '
# Disable reason for the service which was enabled or disabled without reason
DISABLE_REASON_UNDEFINED = None
# Guest config console string
CONSOLE = "console=tty0 console=ttyS0"
GuestNumaConfig = collections.namedtuple(
'GuestNumaConfig', ['cpuset', 'cputune', 'numaconfig', 'numatune'])
libvirt_volume_drivers = [
'iscsi=nova.virt.libvirt.volume.iscsi.LibvirtISCSIVolumeDriver',
'iser=nova.virt.libvirt.volume.iser.LibvirtISERVolumeDriver',
'local=nova.virt.libvirt.volume.volume.LibvirtVolumeDriver',
'fake=nova.virt.libvirt.volume.volume.LibvirtFakeVolumeDriver',
'rbd=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver',
'sheepdog=nova.virt.libvirt.volume.net.LibvirtNetVolumeDriver',
'nfs=nova.virt.libvirt.volume.nfs.LibvirtNFSVolumeDriver',
'smbfs=nova.virt.libvirt.volume.smbfs.LibvirtSMBFSVolumeDriver',
'aoe=nova.virt.libvirt.volume.aoe.LibvirtAOEVolumeDriver',
'glusterfs='
'nova.virt.libvirt.volume.glusterfs.LibvirtGlusterfsVolumeDriver',
'fibre_channel='
'nova.virt.libvirt.volume.fibrechannel.'
'LibvirtFibreChannelVolumeDriver',
'scality=nova.virt.libvirt.volume.scality.LibvirtScalityVolumeDriver',
'ocfs2=nova.virt.libvirt.volume.ocfs2.LibvirtOcfs2VolumeDriver',
'gpfs=nova.virt.libvirt.volume.gpfs.LibvirtGPFSVolumeDriver',
'quobyte=nova.virt.libvirt.volume.quobyte.LibvirtQuobyteVolumeDriver',
'hgst=nova.virt.libvirt.volume.hgst.LibvirtHGSTVolumeDriver',
'scaleio=nova.virt.libvirt.volume.scaleio.LibvirtScaleIOVolumeDriver',
'disco=nova.virt.libvirt.volume.disco.LibvirtDISCOVolumeDriver',
]
def patch_tpool_proxy():
"""eventlet.tpool.Proxy doesn't work with old-style class in __str__()
or __repr__() calls. See bug #962840 for details.
We perform a monkey patch to replace those two instance methods.
"""
def str_method(self):
return str(self._obj)
def repr_method(self):
return repr(self._obj)
tpool.Proxy.__str__ = str_method
tpool.Proxy.__repr__ = repr_method
patch_tpool_proxy()
# For information about when MIN_LIBVIRT_VERSION and
# NEXT_MIN_LIBVIRT_VERSION can be changed, consult
#
# https://wiki.openstack.org/wiki/LibvirtDistroSupportMatrix
#
# Currently this is effectively the min version for i686/x86_64
# + KVM/QEMU, as other architectures/hypervisors require newer
# versions. Over time, this will become a common min version
# for all architectures/hypervisors, as this value rises to
# meet them.
MIN_LIBVIRT_VERSION = (0, 10, 2)
# TODO(berrange): Re-evaluate this at start of each release cycle
# to decide if we want to plan a future min version bump.
# MIN_LIBVIRT_VERSION can be updated to match this after
# NEXT_MIN_LIBVIRT_VERSION has been at a higher value for
# one cycle
NEXT_MIN_LIBVIRT_VERSION = (1, 2, 1)
# When the above version matches/exceeds this version
# delete it & corresponding code using it
MIN_LIBVIRT_DEVICE_CALLBACK_VERSION = (1, 1, 1)
# Live snapshot requirements
MIN_LIBVIRT_LIVESNAPSHOT_VERSION = (1, 0, 0)
MIN_QEMU_LIVESNAPSHOT_VERSION = (1, 3, 0)
# BlockJobInfo management requirement
MIN_LIBVIRT_BLOCKJOBINFO_VERSION = (1, 1, 1)
# Relative block commit & rebase (feature is detected,
# this version is only used for messaging)
MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION = (1, 2, 7)
# Libvirt version 1.2.17 is required for successfull block live migration
# of vm booted from image with attached devices
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION = (1, 2, 17)
# libvirt discard feature
MIN_LIBVIRT_DISCARD_VERSION = (1, 0, 6)
MIN_QEMU_DISCARD_VERSION = (1, 6, 0)
# While earlier versions could support NUMA reporting and
# NUMA placement, not until 1.2.7 was there the ability
# to pin guest nodes to host nodes, so mandate that. Without
# this the scheduler cannot make guaranteed decisions, as the
# guest placement may not match what was requested
MIN_LIBVIRT_NUMA_VERSION = (1, 2, 7)
# PowerPC based hosts that support NUMA using libvirt
MIN_LIBVIRT_NUMA_VERSION_PPC = (1, 2, 19)
# Versions of libvirt with known NUMA topology issues
# See bug #1449028
BAD_LIBVIRT_NUMA_VERSIONS = [(1, 2, 9, 2)]
# While earlier versions could support hugepage backed
# guests, not until 1.2.8 was there the ability to request
# a particular huge page size. Without this the scheduler
# cannot make guaranteed decisions, as the huge page size
# used by the guest may not match what was requested
MIN_LIBVIRT_HUGEPAGE_VERSION = (1, 2, 8)
# Versions of libvirt with broken cpu pinning support. This excludes
# versions of libvirt with broken NUMA support since pinning needs
# NUMA
# See bug #1438226
BAD_LIBVIRT_CPU_POLICY_VERSIONS = [(1, 2, 10)]
# qemu 2.1 introduces support for pinning memory on host
# NUMA nodes, along with the ability to specify hugepage
# sizes per guest NUMA node
MIN_QEMU_NUMA_HUGEPAGE_VERSION = (2, 1, 0)
# fsFreeze/fsThaw requirement
MIN_LIBVIRT_FSFREEZE_VERSION = (1, 2, 5)
# UEFI booting support
MIN_LIBVIRT_UEFI_VERSION = (1, 2, 9)
# Hyper-V paravirtualized time source
MIN_LIBVIRT_HYPERV_TIMER_VERSION = (1, 2, 2)
MIN_QEMU_HYPERV_TIMER_VERSION = (2, 0, 0)
MIN_LIBVIRT_HYPERV_FEATURE_VERSION = (1, 0, 0)
MIN_LIBVIRT_HYPERV_FEATURE_EXTRA_VERSION = (1, 1, 0)
MIN_QEMU_HYPERV_FEATURE_VERSION = (1, 1, 0)
# parallels driver support
MIN_LIBVIRT_PARALLELS_VERSION = (1, 2, 12)
# Ability to set the user guest password with Qemu
MIN_LIBVIRT_SET_ADMIN_PASSWD = (1, 2, 16)
# s/390 & s/390x architectures with KVM
MIN_LIBVIRT_KVM_S390_VERSION = (1, 2, 13)
MIN_QEMU_S390_VERSION = (2, 3, 0)
# libvirt < 1.3 reported virt_functions capability
# only when VFs are enabled.
# libvirt 1.3 fix f391889f4e942e22b9ef8ecca492de05106ce41e
MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION = (1, 3, 0)
# ppc64/ppc64le architectures with KVM
# NOTE(rfolco): Same levels for Libvirt/Qemu on Big Endian and Little
# Endian giving the nuance around guest vs host architectures
MIN_LIBVIRT_KVM_PPC64_VERSION = (1, 2, 12)
MIN_QEMU_PPC64_VERSION = (2, 1, 0)
# Names of the types that do not get compressed during migration
NO_COMPRESSION_TYPES = ('qcow2',)
# realtime suppport
MIN_LIBVIRT_REALTIME_VERSION = (1, 2, 13)
MIN_LIBVIRT_OTHER_ARCH = {arch.S390: MIN_LIBVIRT_KVM_S390_VERSION,
arch.S390X: MIN_LIBVIRT_KVM_S390_VERSION,
arch.PPC: MIN_LIBVIRT_KVM_PPC64_VERSION,
arch.PPC64: MIN_LIBVIRT_KVM_PPC64_VERSION,
arch.PPC64LE: MIN_LIBVIRT_KVM_PPC64_VERSION,
}
MIN_QEMU_OTHER_ARCH = {arch.S390: MIN_QEMU_S390_VERSION,
arch.S390X: MIN_QEMU_S390_VERSION,
arch.PPC: MIN_QEMU_PPC64_VERSION,
arch.PPC64: MIN_QEMU_PPC64_VERSION,
arch.PPC64LE: MIN_QEMU_PPC64_VERSION,
}
class LibvirtDriver(driver.ComputeDriver):
capabilities = {
"has_imagecache": True,
"supports_recreate": True,
"supports_migrate_to_same_host": False
}
def __init__(self, virtapi, read_only=False):
super(LibvirtDriver, self).__init__(virtapi)
global libvirt
if libvirt is None:
libvirt = importutils.import_module('libvirt')
self._host = host.Host(self._uri(), read_only,
lifecycle_event_handler=self.emit_event,
conn_event_handler=self._handle_conn_event)
self._initiator = None
self._fc_wwnns = None
self._fc_wwpns = None
self._caps = None
self.firewall_driver = firewall.load_driver(
DEFAULT_FIREWALL_DRIVER,
host=self._host)
self.vif_driver = libvirt_vif.LibvirtGenericVIFDriver()
self.volume_drivers = driver.driver_dict_from_config(
self._get_volume_drivers(), self)
self._disk_cachemode = None
self.image_cache_manager = imagecache.ImageCacheManager()
self.image_backend = imagebackend.Backend(CONF.use_cow_images)
self.disk_cachemodes = {}
self.valid_cachemodes = ["default",
"none",
"writethrough",
"writeback",
"directsync",
"unsafe",
]
self._conn_supports_start_paused = CONF.libvirt.virt_type in ('kvm',
'qemu')
for mode_str in CONF.libvirt.disk_cachemodes:
disk_type, sep, cache_mode = mode_str.partition('=')
if cache_mode not in self.valid_cachemodes:
LOG.warn(_LW('Invalid cachemode %(cache_mode)s specified '
'for disk type %(disk_type)s.'),
{'cache_mode': cache_mode, 'disk_type': disk_type})
continue
self.disk_cachemodes[disk_type] = cache_mode
self._volume_api = volume.API()
self._image_api = image.API()
sysinfo_serial_funcs = {
'none': lambda: None,
'hardware': self._get_host_sysinfo_serial_hardware,
'os': self._get_host_sysinfo_serial_os,
'auto': self._get_host_sysinfo_serial_auto,
}
self._sysinfo_serial_func = sysinfo_serial_funcs.get(
CONF.libvirt.sysinfo_serial)
self.job_tracker = instancejobtracker.InstanceJobTracker()
self._remotefs = remotefs.RemoteFilesystem()
self._live_migration_flags = self._block_migration_flags = None
def _get_volume_drivers(self):
return libvirt_volume_drivers
@property
def disk_cachemode(self):
if self._disk_cachemode is None:
# We prefer 'none' for consistent performance, host crash
# safety & migration correctness by avoiding host page cache.
# Some filesystems (eg GlusterFS via FUSE) don't support
# O_DIRECT though. For those we fallback to 'writethrough'
# which gives host crash safety, and is safe for migration
# provided the filesystem is cache coherent (cluster filesystems
# typically are, but things like NFS are not).
self._disk_cachemode = "none"
if not self._supports_direct_io(CONF.instances_path):
self._disk_cachemode = "writethrough"
return self._disk_cachemode
def _set_cache_mode(self, conf):
"""Set cache mode on LibvirtConfigGuestDisk object."""
try:
source_type = conf.source_type
driver_cache = conf.driver_cache
except AttributeError:
return
cache_mode = self.disk_cachemodes.get(source_type,
driver_cache)
conf.driver_cache = cache_mode
def _do_quality_warnings(self):
"""Warn about untested driver configurations.
This will log a warning message about untested driver or host arch
configurations to indicate to administrators that the quality is
unknown. Currently, only qemu or kvm on intel 32- or 64-bit systems
is tested upstream.
"""
caps = self._host.get_capabilities()
hostarch = caps.host.cpu.arch
if (CONF.libvirt.virt_type not in ('qemu', 'kvm') or
hostarch not in (arch.I686, arch.X86_64)):
LOG.warn(_LW('The libvirt driver is not tested on '
'%(type)s/%(arch)s by the OpenStack project and '
'thus its quality can not be ensured. For more '
'information, see: https://wiki.openstack.org/wiki/'
'HypervisorSupportMatrix'),
{'type': CONF.libvirt.virt_type, 'arch': hostarch})
def _handle_conn_event(self, enabled, reason):
LOG.info(_LI("Connection event '%(enabled)d' reason '%(reason)s'"),
{'enabled': enabled, 'reason': reason})
self._set_host_enabled(enabled, reason)
def _version_to_string(self, version):
return '.'.join([str(x) for x in version])
def init_host(self, host):
self._host.initialize()
self._do_quality_warnings()
self._parse_migration_flags()
if (CONF.libvirt.virt_type == 'lxc' and
not (CONF.libvirt.uid_maps and CONF.libvirt.gid_maps)):
LOG.warn(_LW("Running libvirt-lxc without user namespaces is "
"dangerous. Containers spawned by Nova will be run "
"as the host's root user. It is highly suggested "
"that user namespaces be used in a public or "
"multi-tenant environment."))
# Stop libguestfs using KVM unless we're also configured
# to use this. This solves problem where people need to
# stop Nova use of KVM because nested-virt is broken
if CONF.libvirt.virt_type != "kvm":
guestfs.force_tcg()
if not self._host.has_min_version(MIN_LIBVIRT_VERSION):
raise exception.NovaException(
_('Nova requires libvirt version %s or greater.') %
self._version_to_string(MIN_LIBVIRT_VERSION))
if (CONF.libvirt.virt_type == 'parallels' and
not self._host.has_min_version(MIN_LIBVIRT_PARALLELS_VERSION)):
raise exception.NovaException(
_('Running Nova with parallels virt_type requires '
'libvirt version %s') %
self._version_to_string(MIN_LIBVIRT_PARALLELS_VERSION))
# Give the cloud admin a heads up if we are intending to
# change the MIN_LIBVIRT_VERSION in the next release.
if not self._host.has_min_version(NEXT_MIN_LIBVIRT_VERSION):
LOG.warning(_LW('Running Nova with a libvirt version less than '
'%(version)s is deprecated. The required minimum '
'version of libvirt will be raised to %(version)s '
'in the next release.'),
{'version': self._version_to_string(
NEXT_MIN_LIBVIRT_VERSION)})
kvm_arch = arch.from_host()
if (CONF.libvirt.virt_type in ('kvm', 'qemu') and
kvm_arch in MIN_LIBVIRT_OTHER_ARCH and
not self._host.has_min_version(
MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch),
MIN_QEMU_OTHER_ARCH.get(kvm_arch))):
raise exception.NovaException(
_('Running Nova with qemu/kvm virt_type on %(arch)s '
'requires libvirt version %(libvirt_ver)s and '
'qemu version %(qemu_ver)s, or greater') %
{'arch': kvm_arch,
'libvirt_ver': self._version_to_string(
MIN_LIBVIRT_OTHER_ARCH.get(kvm_arch)),
'qemu_ver': self._version_to_string(
MIN_QEMU_OTHER_ARCH.get(kvm_arch))})
def _check_required_migration_flags(self, migration_flags, config_name):
if CONF.libvirt.virt_type == 'xen':
if (migration_flags & libvirt.VIR_MIGRATE_PEER2PEER) != 0:
LOG.warning(_LW('Removing the VIR_MIGRATE_PEER2PEER flag from '
'%(config_name)s because peer-to-peer '
'migrations are not supported by the "xen" '
'virt type'),
{'config_name': config_name})
migration_flags &= ~libvirt.VIR_MIGRATE_PEER2PEER
else:
if (migration_flags & libvirt.VIR_MIGRATE_PEER2PEER) == 0:
LOG.warning(_LW('Adding the VIR_MIGRATE_PEER2PEER flag to '
'%(config_name)s because direct migrations '
'are not supported by the %(virt_type)s '
'virt type'),
{'config_name': config_name,
'virt_type': CONF.libvirt.virt_type})
migration_flags |= libvirt.VIR_MIGRATE_PEER2PEER
if (migration_flags & libvirt.VIR_MIGRATE_UNDEFINE_SOURCE) == 0:
LOG.warning(_LW('Adding the VIR_MIGRATE_UNDEFINE_SOURCE flag to '
'%(config_name)s because, without it, migrated '
'VMs will remain defined on the source host'),
{'config_name': config_name})
migration_flags |= libvirt.VIR_MIGRATE_UNDEFINE_SOURCE
if (migration_flags & libvirt.VIR_MIGRATE_PERSIST_DEST) != 0:
LOG.warning(_LW('Removing the VIR_MIGRATE_PERSIST_DEST flag from '
'%(config_name)s as Nova ensures the VM is '
'persisted on the destination host'),
{'config_name': config_name})
migration_flags &= ~libvirt.VIR_MIGRATE_PERSIST_DEST
return migration_flags
def _check_block_migration_flags(self, live_migration_flags,
block_migration_flags):
if (live_migration_flags & libvirt.VIR_MIGRATE_NON_SHARED_INC) != 0:
LOG.warning(_LW('Removing the VIR_MIGRATE_NON_SHARED_INC flag '
'from the live_migration_flag config option '
'because it will cause all live-migrations to be '
'block-migrations instead.'))
live_migration_flags &= ~libvirt.VIR_MIGRATE_NON_SHARED_INC
if (block_migration_flags & libvirt.VIR_MIGRATE_NON_SHARED_INC) == 0:
LOG.warning(_LW('Adding the VIR_MIGRATE_NON_SHARED_INC flag to '
'the block_migration_flag config option, '
'otherwise all block-migrations will be '
'live-migrations instead.'))
block_migration_flags |= libvirt.VIR_MIGRATE_NON_SHARED_INC
return (live_migration_flags, block_migration_flags)
def _handle_live_migration_tunnelled(self, migration_flags, config_name):
if CONF.libvirt.live_migration_tunnelled is None:
return migration_flags
if CONF.libvirt.live_migration_tunnelled:
if (migration_flags & libvirt.VIR_MIGRATE_TUNNELLED) == 0:
LOG.warning(_LW('The %(config_name)s config option does not '
'contain the VIR_MIGRATE_TUNNELLED flag but '
'the live_migration_tunnelled is set to True '
'which causes VIR_MIGRATE_TUNNELLED to be '
'set'),
{'config_name': config_name})
migration_flags |= libvirt.VIR_MIGRATE_TUNNELLED
else:
if (migration_flags & libvirt.VIR_MIGRATE_TUNNELLED) != 0:
LOG.warning(_LW('The %(config_name)s config option contains '
'the VIR_MIGRATE_TUNNELLED flag but the '
'live_migration_tunnelled is set to False '
'which causes VIR_MIGRATE_TUNNELLED to be '
'unset'),
{'config_name': config_name})
migration_flags &= ~libvirt.VIR_MIGRATE_TUNNELLED
return migration_flags
def _parse_migration_flags(self):
def str2sum(str_val):
logical_sum = 0
for s in [i.strip() for i in str_val.split(',') if i]:
try:
logical_sum |= getattr(libvirt, s)
except AttributeError:
LOG.warning(_LW("Ignoring unknown libvirt live migration "
"flag '%(flag)s'"), {'flag': s})
return logical_sum
live_migration_flags = str2sum(CONF.libvirt.live_migration_flag)
block_migration_flags = str2sum(CONF.libvirt.block_migration_flag)
live_config_name = 'live_migration_flag'
block_config_name = 'block_migration_flag'
live_migration_flags = self._check_required_migration_flags(
live_migration_flags, live_config_name)
block_migration_flags = self._check_required_migration_flags(
block_migration_flags, block_config_name)
(live_migration_flags,
block_migration_flags) = self._check_block_migration_flags(
live_migration_flags, block_migration_flags)
live_migration_flags = self._handle_live_migration_tunnelled(
live_migration_flags, live_config_name)
block_migration_flags = self._handle_live_migration_tunnelled(
block_migration_flags, block_config_name)
self._live_migration_flags = live_migration_flags
self._block_migration_flags = block_migration_flags
# TODO(sahid): This method is targeted for removal when the tests
# have been updated to avoid its use
#
# All libvirt API calls on the libvirt.Connect object should be
# encapsulated by methods on the nova.virt.libvirt.host.Host
# object, rather than directly invoking the libvirt APIs. The goal
# is to avoid a direct dependency on the libvirt API from the
# driver.py file.
def _get_connection(self):
return self._host.get_connection()
_conn = property(_get_connection)
@staticmethod
def _uri():
if CONF.libvirt.virt_type == 'uml':
uri = CONF.libvirt.connection_uri or 'uml:///system'
elif CONF.libvirt.virt_type == 'xen':
uri = CONF.libvirt.connection_uri or 'xen:///'
elif CONF.libvirt.virt_type == 'lxc':
uri = CONF.libvirt.connection_uri or 'lxc:///'
elif CONF.libvirt.virt_type == 'parallels':
uri = CONF.libvirt.connection_uri or 'parallels:///system'
else:
uri = CONF.libvirt.connection_uri or 'qemu:///system'
return uri
@staticmethod
def _live_migration_uri(dest):
# Only Xen and QEMU support live migration, see
# https://libvirt.org/migration.html#scenarios for reference
uris = {
'kvm': 'qemu+tcp://%s/system',
'qemu': 'qemu+tcp://%s/system',
'xen': 'xenmigr://%s/system',
}
virt_type = CONF.libvirt.virt_type
uri = CONF.libvirt.live_migration_uri or uris.get(virt_type)
if uri is None:
raise exception.LiveMigrationURINotAvailable(virt_type=virt_type)
return uri % dest
def instance_exists(self, instance):
"""Efficient override of base instance_exists method."""
try:
self._host.get_guest(instance)
return True
except exception.NovaException:
return False
def list_instances(self):
names = []
for guest in self._host.list_guests(only_running=False):
names.append(guest.name)
return names
def list_instance_uuids(self):
uuids = []
for guest in self._host.list_guests(only_running=False):
uuids.append(guest.uuid)
return uuids
def plug_vifs(self, instance, network_info):
"""Plug VIFs into networks."""
for vif in network_info:
self.vif_driver.plug(instance, vif)
def _unplug_vifs(self, instance, network_info, ignore_errors):
"""Unplug VIFs from networks."""
for vif in network_info:
try:
self.vif_driver.unplug(instance, vif)
except exception.NovaException:
if not ignore_errors:
raise
def unplug_vifs(self, instance, network_info):
self._unplug_vifs(instance, network_info, False)
def _teardown_container(self, instance):
inst_path = libvirt_utils.get_instance_path(instance)
container_dir = os.path.join(inst_path, 'rootfs')
rootfs_dev = instance.system_metadata.get('rootfs_device_name')
LOG.debug('Attempting to teardown container at path %(dir)s with '
'root device: %(rootfs_dev)s',
{'dir': container_dir, 'rootfs_dev': rootfs_dev},
instance=instance)
disk.teardown_container(container_dir, rootfs_dev)
def _destroy(self, instance, attempt=1):
try:
guest = self._host.get_guest(instance)
except exception.InstanceNotFound:
guest = None
# If the instance is already terminated, we're still happy
# Otherwise, destroy it
old_domid = -1
if guest is not None:
try:
old_domid = guest.id
guest.poweroff()
except libvirt.libvirtError as e:
is_okay = False
errcode = e.get_error_code()
if errcode == libvirt.VIR_ERR_NO_DOMAIN:
# Domain already gone. This can safely be ignored.
is_okay = True
elif errcode == libvirt.VIR_ERR_OPERATION_INVALID:
# If the instance is already shut off, we get this:
# Code=55 Error=Requested operation is not valid:
# domain is not running
state = guest.get_power_state(self._host)
if state == power_state.SHUTDOWN:
is_okay = True
elif errcode == libvirt.VIR_ERR_INTERNAL_ERROR:
errmsg = e.get_error_message()
if (CONF.libvirt.virt_type == 'lxc' and
errmsg == 'internal error: '
'Some processes refused to die'):
# Some processes in the container didn't die
# fast enough for libvirt. The container will
# eventually die. For now, move on and let
# the wait_for_destroy logic take over.
is_okay = True
elif errcode == libvirt.VIR_ERR_OPERATION_TIMEOUT:
LOG.warn(_LW("Cannot destroy instance, operation time "
"out"),
instance=instance)
reason = _("operation time out")
raise exception.InstancePowerOffFailure(reason=reason)
elif errcode == libvirt.VIR_ERR_SYSTEM_ERROR:
if e.get_int1() == errno.EBUSY:
# NOTE(danpb): When libvirt kills a process it sends it
# SIGTERM first and waits 10 seconds. If it hasn't gone
# it sends SIGKILL and waits another 5 seconds. If it
# still hasn't gone then you get this EBUSY error.
# Usually when a QEMU process fails to go away upon
# SIGKILL it is because it is stuck in an
# uninterruptable kernel sleep waiting on I/O from
# some non-responsive server.
# Given the CPU load of the gate tests though, it is
# conceivable that the 15 second timeout is too short,
# particularly if the VM running tempest has a high
# steal time from the cloud host. ie 15 wallclock
# seconds may have passed, but the VM might have only
# have a few seconds of scheduled run time.
LOG.warn(_LW('Error from libvirt during destroy. '
'Code=%(errcode)s Error=%(e)s; '
'attempt %(attempt)d of 3'),
{'errcode': errcode, 'e': e,
'attempt': attempt},
instance=instance)
with excutils.save_and_reraise_exception() as ctxt:
# Try up to 3 times before giving up.
if attempt < 3:
ctxt.reraise = False
self._destroy(instance, attempt + 1)
return
if not is_okay:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error from libvirt during destroy. '
'Code=%(errcode)s Error=%(e)s'),
{'errcode': errcode, 'e': e},
instance=instance)
def _wait_for_destroy(expected_domid):
"""Called at an interval until the VM is gone."""
# NOTE(vish): If the instance disappears during the destroy
# we ignore it so the cleanup can still be
# attempted because we would prefer destroy to
# never fail.
try:
dom_info = self.get_info(instance)
state = dom_info.state
new_domid = dom_info.id
except exception.InstanceNotFound:
LOG.info(_LI("During wait destroy, instance disappeared."),
instance=instance)
raise loopingcall.LoopingCallDone()
if state == power_state.SHUTDOWN:
LOG.info(_LI("Instance destroyed successfully."),
instance=instance)
raise loopingcall.LoopingCallDone()
# NOTE(wangpan): If the instance was booted again after destroy,
# this may be an endless loop, so check the id of
# domain here, if it changed and the instance is
# still running, we should destroy it again.
# see https://bugs.launchpad.net/nova/+bug/1111213 for more details
if new_domid != expected_domid:
LOG.info(_LI("Instance may be started again."),
instance=instance)
kwargs['is_running'] = True
raise loopingcall.LoopingCallDone()
kwargs = {'is_running': False}
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_destroy,
old_domid)
timer.start(interval=0.5).wait()
if kwargs['is_running']:
LOG.info(_LI("Going to destroy instance again."),
instance=instance)
self._destroy(instance)
else:
# NOTE(GuanQiang): teardown container to avoid resource leak
if CONF.libvirt.virt_type == 'lxc':
self._teardown_container(instance)
def destroy(self, context, instance, network_info, block_device_info=None,
destroy_disks=True, migrate_data=None):
self._destroy(instance)
self.cleanup(context, instance, network_info, block_device_info,
destroy_disks, migrate_data)
def _undefine_domain(self, instance):
try:
guest = self._host.get_guest(instance)
try:
guest.delete_configuration()
except libvirt.libvirtError as e:
with excutils.save_and_reraise_exception():
errcode = e.get_error_code()
LOG.error(_LE('Error from libvirt during undefine. '
'Code=%(errcode)s Error=%(e)s'),
{'errcode': errcode, 'e': e}, instance=instance)
except exception.InstanceNotFound:
pass
def cleanup(self, context, instance, network_info, block_device_info=None,
destroy_disks=True, migrate_data=None, destroy_vifs=True):
if destroy_vifs:
self._unplug_vifs(instance, network_info, True)
retry = True
while retry:
try:
self.unfilter_instance(instance, network_info)
except libvirt.libvirtError as e:
try:
state = self.get_info(instance).state
except exception.InstanceNotFound:
state = power_state.SHUTDOWN
if state != power_state.SHUTDOWN:
LOG.warn(_LW("Instance may be still running, destroy "
"it again."), instance=instance)
self._destroy(instance)
else:
retry = False
errcode = e.get_error_code()
LOG.exception(_LE('Error from libvirt during unfilter. '
'Code=%(errcode)s Error=%(e)s'),
{'errcode': errcode, 'e': e},
instance=instance)
reason = "Error unfiltering instance."
raise exception.InstanceTerminationFailure(reason=reason)
except Exception:
retry = False
raise
else:
retry = False
# FIXME(wangpan): if the instance is booted again here, such as the
# the soft reboot operation boot it here, it will
# become "running deleted", should we check and destroy
# it at the end of this method?
# NOTE(vish): we disconnect from volumes regardless
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
disk_dev = vol['mount_device']
if disk_dev is not None:
disk_dev = disk_dev.rpartition("/")[2]
if ('data' in connection_info and
'volume_id' in connection_info['data']):
volume_id = connection_info['data']['volume_id']
encryption = encryptors.get_encryption_metadata(
context, self._volume_api, volume_id, connection_info)
if encryption:
# The volume must be detached from the VM before
# disconnecting it from its encryptor. Otherwise, the
# encryptor may report that the volume is still in use.
encryptor = self._get_volume_encryptor(connection_info,
encryption)
encryptor.detach_volume(**encryption)
try:
self._disconnect_volume(connection_info, disk_dev)
except Exception as exc:
with excutils.save_and_reraise_exception() as ctxt:
if destroy_disks:
# Don't block on Volume errors if we're trying to
# delete the instance as we may be partially created
# or deleted
ctxt.reraise = False
LOG.warn(_LW("Ignoring Volume Error on vol %(vol_id)s "
"during delete %(exc)s"),
{'vol_id': vol.get('volume_id'), 'exc': exc},
instance=instance)
if destroy_disks:
# NOTE(haomai): destroy volumes if needed
if CONF.libvirt.images_type == 'lvm':
self._cleanup_lvm(instance, block_device_info)
if CONF.libvirt.images_type == 'rbd':
self._cleanup_rbd(instance)
is_shared_block_storage = False
if migrate_data and 'is_shared_block_storage' in migrate_data:
is_shared_block_storage = migrate_data.is_shared_block_storage
if destroy_disks or is_shared_block_storage:
attempts = int(instance.system_metadata.get('clean_attempts',
'0'))
success = self.delete_instance_files(instance)
# NOTE(mriedem): This is used in the _run_pending_deletes periodic
# task in the compute manager. The tight coupling is not great...
instance.system_metadata['clean_attempts'] = str(attempts + 1)
if success:
instance.cleaned = True
instance.save()
if CONF.serial_console.enabled:
try:
guest = self._host.get_guest(instance)
serials = self._get_serial_ports_from_guest(guest)
for hostname, port in serials:
serial_console.release_port(host=hostname, port=port)
except exception.InstanceNotFound:
pass
self._undefine_domain(instance)
def _detach_encrypted_volumes(self, instance, block_device_info):
"""Detaches encrypted volumes attached to instance."""
disks = jsonutils.loads(self.get_instance_disk_info(instance,
block_device_info))
encrypted_volumes = filter(dmcrypt.is_encrypted,
[disk['path'] for disk in disks])
for path in encrypted_volumes:
dmcrypt.delete_volume(path)
def _get_serial_ports_from_guest(self, guest, mode=None):
"""Returns an iterator over serial port(s) configured on guest.
:param mode: Should be a value in (None, bind, connect)
"""
xml = guest.get_xml_desc()
tree = etree.fromstring(xml)
# The 'serial' device is the base for x86 platforms. Other platforms
# (e.g. kvm on system z = arch.S390X) can only use 'console' devices.
xpath_mode = "[@mode='%s']" % mode if mode else ""
serial_tcp = "./devices/serial[@type='tcp']/source" + xpath_mode
console_tcp = "./devices/console[@type='tcp']/source" + xpath_mode
tcp_devices = tree.findall(serial_tcp)
if len(tcp_devices) == 0:
tcp_devices = tree.findall(console_tcp)
for source in tcp_devices:
yield (source.get("host"), int(source.get("service")))
@staticmethod
def _get_rbd_driver():
return rbd_utils.RBDDriver(
pool=CONF.libvirt.images_rbd_pool,
ceph_conf=CONF.libvirt.images_rbd_ceph_conf,
rbd_user=CONF.libvirt.rbd_user)
def _cleanup_rbd(self, instance):
LibvirtDriver._get_rbd_driver().cleanup_volumes(instance)
def _cleanup_lvm(self, instance, block_device_info):
"""Delete all LVM disks for given instance object."""
if instance.get('ephemeral_key_uuid') is not None:
self._detach_encrypted_volumes(instance, block_device_info)
disks = self._lvm_disks(instance)
if disks:
lvm.remove_volumes(disks)
def _lvm_disks(self, instance):
"""Returns all LVM disks for given instance object."""
if CONF.libvirt.images_volume_group:
vg = os.path.join('/dev', CONF.libvirt.images_volume_group)
if not os.path.exists(vg):
return []
pattern = '%s_' % instance.uuid
def belongs_to_instance(disk):
return disk.startswith(pattern)
def fullpath(name):
return os.path.join(vg, name)
logical_volumes = lvm.list_volumes(vg)
disk_names = filter(belongs_to_instance, logical_volumes)
disks = map(fullpath, disk_names)
return disks
return []
def get_volume_connector(self, instance):
root_helper = utils.get_root_helper()
return connector.get_connector_properties(
root_helper, CONF.my_block_storage_ip,
CONF.libvirt.iscsi_use_multipath,
enforce_multipath=True,
host=CONF.host)
def _cleanup_resize(self, instance, network_info):
# NOTE(wangpan): we get the pre-grizzly instance path firstly,
# so the backup dir of pre-grizzly instance can
# be deleted correctly with grizzly or later nova.
pre_grizzly_name = libvirt_utils.get_instance_path(instance,
forceold=True)
target = pre_grizzly_name + '_resize'
if not os.path.exists(target):
target = libvirt_utils.get_instance_path(instance) + '_resize'
if os.path.exists(target):
# Deletion can fail over NFS, so retry the deletion as required.
# Set maximum attempt as 5, most test can remove the directory
# for the second time.
utils.execute('rm', '-rf', target, delay_on_retry=True,
attempts=5)
backend = self.image_backend.image(instance, 'disk')
# TODO(nic): Set ignore_errors=False in a future release.
# It is set to True here to avoid any upgrade issues surrounding
# instances being in pending resize state when the software is updated;
# in that case there will be no snapshot to remove. Once it can be
# reasonably assumed that no such instances exist in the wild
# anymore, it should be set back to False (the default) so it will
# throw errors, like it should.
backend.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME,
ignore_errors=True)
if instance.host != CONF.host:
self._undefine_domain(instance)
self.unplug_vifs(instance, network_info)
self.unfilter_instance(instance, network_info)
def _get_volume_driver(self, connection_info):
driver_type = connection_info.get('driver_volume_type')
if driver_type not in self.volume_drivers:
raise exception.VolumeDriverNotFound(driver_type=driver_type)
return self.volume_drivers[driver_type]
def _connect_volume(self, connection_info, disk_info):
vol_driver = self._get_volume_driver(connection_info)
vol_driver.connect_volume(connection_info, disk_info)
def _disconnect_volume(self, connection_info, disk_dev):
vol_driver = self._get_volume_driver(connection_info)
vol_driver.disconnect_volume(connection_info, disk_dev)
def _get_volume_config(self, connection_info, disk_info):
vol_driver = self._get_volume_driver(connection_info)
return vol_driver.get_config(connection_info, disk_info)
def _get_volume_encryptor(self, connection_info, encryption):
encryptor = encryptors.get_volume_encryptor(connection_info,
**encryption)
return encryptor
def _check_discard_for_attach_volume(self, conf, instance):
"""Perform some checks for volumes configured for discard support.
If discard is configured for the volume, and the guest is using a
configuration known to not work, we will log a message explaining
the reason why.
"""
if conf.driver_discard == 'unmap' and conf.target_bus == 'virtio':
LOG.debug('Attempting to attach volume %(id)s with discard '
'support enabled to an instance using an '
'unsupported configuration. target_bus = '
'%(bus)s. Trim commands will not be issued to '
'the storage device.',
{'bus': conf.target_bus,
'id': conf.serial},
instance=instance)
def attach_volume(self, context, connection_info, instance, mountpoint,
disk_bus=None, device_type=None, encryption=None):
guest = self._host.get_guest(instance)
disk_dev = mountpoint.rpartition("/")[2]
bdm = {
'device_name': disk_dev,
'disk_bus': disk_bus,
'device_type': device_type}
# Note(cfb): If the volume has a custom block size, check that
# that we are using QEMU/KVM and libvirt >= 0.10.2. The
# presence of a block size is considered mandatory by
# cinder so we fail if we can't honor the request.
data = {}
if ('data' in connection_info):
data = connection_info['data']
if ('logical_block_size' in data or 'physical_block_size' in data):
if ((CONF.libvirt.virt_type != "kvm" and
CONF.libvirt.virt_type != "qemu")):
msg = _("Volume sets block size, but the current "
"libvirt hypervisor '%s' does not support custom "
"block size") % CONF.libvirt.virt_type
raise exception.InvalidHypervisorType(msg)
disk_info = blockinfo.get_info_from_bdm(
instance, CONF.libvirt.virt_type, instance.image_meta, bdm)
self._connect_volume(connection_info, disk_info)
conf = self._get_volume_config(connection_info, disk_info)
self._set_cache_mode(conf)
self._check_discard_for_attach_volume(conf, instance)
try:
state = guest.get_power_state(self._host)
live = state in (power_state.RUNNING, power_state.PAUSED)
if encryption:
encryptor = self._get_volume_encryptor(connection_info,
encryption)
encryptor.attach_volume(context, **encryption)
guest.attach_device(conf, persistent=True, live=live)
except Exception as ex:
LOG.exception(_LE('Failed to attach volume at mountpoint: %s'),
mountpoint, instance=instance)
if isinstance(ex, libvirt.libvirtError):
errcode = ex.get_error_code()
if errcode == libvirt.VIR_ERR_OPERATION_FAILED:
self._disconnect_volume(connection_info, disk_dev)
raise exception.DeviceIsBusy(device=disk_dev)
with excutils.save_and_reraise_exception():
self._disconnect_volume(connection_info, disk_dev)
def _swap_volume(self, guest, disk_path, new_path, resize_to):
"""Swap existing disk with a new block device."""
dev = guest.get_block_device(disk_path)
# Save a copy of the domain's persistent XML file
xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True)
# Abort is an idempotent operation, so make sure any block
# jobs which may have failed are ended.
try:
dev.abort_job()
except Exception:
pass
try:
# NOTE (rmk): blockRebase cannot be executed on persistent
# domains, so we need to temporarily undefine it.
# If any part of this block fails, the domain is
# re-defined regardless.
if guest.has_persistent_configuration():
guest.delete_configuration()
# Start copy with VIR_DOMAIN_REBASE_REUSE_EXT flag to
# allow writing to existing external volume file
dev.rebase(new_path, copy=True, reuse_ext=True)
while dev.wait_for_job():
time.sleep(0.5)
dev.abort_job(pivot=True)
if resize_to:
# NOTE(alex_xu): domain.blockJobAbort isn't sync call. This
# is bug in libvirt. So we need waiting for the pivot is
# finished. libvirt bug #1119173
while dev.wait_for_job(wait_for_job_clean=True):
time.sleep(0.5)
dev.resize(resize_to * units.Gi / units.Ki)
finally:
self._host.write_instance_config(xml)
def swap_volume(self, old_connection_info,
new_connection_info, instance, mountpoint, resize_to):
guest = self._host.get_guest(instance)
disk_dev = mountpoint.rpartition("/")[2]
if not guest.get_disk(disk_dev):
raise exception.DiskNotFound(location=disk_dev)
disk_info = {
'dev': disk_dev,
'bus': blockinfo.get_disk_bus_for_disk_dev(
CONF.libvirt.virt_type, disk_dev),
'type': 'disk',
}
self._connect_volume(new_connection_info, disk_info)
conf = self._get_volume_config(new_connection_info, disk_info)
if not conf.source_path:
self._disconnect_volume(new_connection_info, disk_dev)
raise NotImplementedError(_("Swap only supports host devices"))
# Save updates made in connection_info when connect_volume was called
volume_id = new_connection_info.get('serial')
bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
nova_context.get_admin_context(), volume_id, instance.uuid)
driver_bdm = driver_block_device.DriverVolumeBlockDevice(bdm)
driver_bdm['connection_info'] = new_connection_info
driver_bdm.save()
self._swap_volume(guest, disk_dev, conf.source_path, resize_to)
self._disconnect_volume(old_connection_info, disk_dev)
def _get_existing_domain_xml(self, instance, network_info,
block_device_info=None):
try:
guest = self._host.get_guest(instance)
xml = guest.get_xml_desc()
except exception.InstanceNotFound:
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
instance.image_meta,
block_device_info)
xml = self._get_guest_xml(nova_context.get_admin_context(),
instance, network_info, disk_info,
instance.image_meta,
block_device_info=block_device_info)
return xml
def detach_volume(self, connection_info, instance, mountpoint,
encryption=None):
disk_dev = mountpoint.rpartition("/")[2]
try:
guest = self._host.get_guest(instance)
state = guest.get_power_state(self._host)
live = state in (power_state.RUNNING, power_state.PAUSED)
wait_for_detach = guest.detach_device_with_retry(guest.get_disk,
disk_dev,
persistent=True,
live=live)
if encryption:
# The volume must be detached from the VM before
# disconnecting it from its encryptor. Otherwise, the
# encryptor may report that the volume is still in use.
encryptor = self._get_volume_encryptor(connection_info,
encryption)
encryptor.detach_volume(**encryption)
wait_for_detach()
except exception.InstanceNotFound:
# NOTE(zhaoqin): If the instance does not exist, _lookup_by_name()
# will throw InstanceNotFound exception. Need to
# disconnect volume under this circumstance.
LOG.warn(_LW("During detach_volume, instance disappeared."),
instance=instance)
except exception.DeviceNotFound:
raise exception.DiskNotFound(location=disk_dev)
except libvirt.libvirtError as ex:
# NOTE(vish): This is called to cleanup volumes after live
# migration, so we should still disconnect even if
# the instance doesn't exist here anymore.
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_DOMAIN:
# NOTE(vish):
LOG.warn(_LW("During detach_volume, instance disappeared."),
instance=instance)
else:
raise
self._disconnect_volume(connection_info, disk_dev)
def attach_interface(self, instance, image_meta, vif):
guest = self._host.get_guest(instance)
self.vif_driver.plug(instance, vif)
self.firewall_driver.setup_basic_filtering(instance, [vif])
cfg = self.vif_driver.get_config(instance, vif, image_meta,
instance.flavor,
CONF.libvirt.virt_type,
self._host)
try:
state = guest.get_power_state(self._host)
live = state in (power_state.RUNNING, power_state.PAUSED)
guest.attach_device(cfg, persistent=True, live=live)
except libvirt.libvirtError:
LOG.error(_LE('attaching network adapter failed.'),
instance=instance, exc_info=True)
self.vif_driver.unplug(instance, vif)
raise exception.InterfaceAttachFailed(
instance_uuid=instance.uuid)
def detach_interface(self, instance, vif):
guest = self._host.get_guest(instance)
cfg = self.vif_driver.get_config(instance, vif,
instance.image_meta,
instance.flavor,
CONF.libvirt.virt_type, self._host)
try:
self.vif_driver.unplug(instance, vif)
state = guest.get_power_state(self._host)
live = state in (power_state.RUNNING, power_state.PAUSED)
guest.detach_device(cfg, persistent=True, live=live)
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_DOMAIN:
LOG.warn(_LW("During detach_interface, "
"instance disappeared."),
instance=instance)
else:
# NOTE(mriedem): When deleting an instance and using Neutron,
# we can be racing against Neutron deleting the port and
# sending the vif-deleted event which then triggers a call to
# detach the interface, so we might have failed because the
# network device no longer exists. Libvirt will fail with
# "operation failed: no matching network device was found"
# which unfortunately does not have a unique error code so we
# need to look up the interface by MAC and if it's not found
# then we can just log it as a warning rather than tracing an
# error.
mac = vif.get('address')
interface = guest.get_interface_by_mac(mac)
if interface:
LOG.error(_LE('detaching network adapter failed.'),
instance=instance, exc_info=True)
raise exception.InterfaceDetachFailed(
instance_uuid=instance.uuid)
# The interface is gone so just log it as a warning.
LOG.warning(_LW('Detaching interface %(mac)s failed because '
'the device is no longer found on the guest.'),
{'mac': mac}, instance=instance)
def _create_snapshot_metadata(self, image_meta, instance,
img_fmt, snp_name):
metadata = {'is_public': False,
'status': 'active',
'name': snp_name,
'properties': {
'kernel_id': instance.kernel_id,
'image_location': 'snapshot',
'image_state': 'available',
'owner_id': instance.project_id,
'ramdisk_id': instance.ramdisk_id,
}
}
if instance.os_type:
metadata['properties']['os_type'] = instance.os_type
# NOTE(vish): glance forces ami disk format to be ami
if image_meta.disk_format == 'ami':
metadata['disk_format'] = 'ami'
else:
metadata['disk_format'] = img_fmt
if image_meta.obj_attr_is_set("container_format"):
metadata['container_format'] = image_meta.container_format
else:
metadata['container_format'] = "bare"
return metadata
def snapshot(self, context, instance, image_id, update_task_state):
"""Create snapshot from a running VM instance.
This command only works with qemu 0.14+
"""
try:
guest = self._host.get_guest(instance)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove virt_dom at the end.
virt_dom = guest._domain
except exception.InstanceNotFound:
raise exception.InstanceNotRunning(instance_id=instance.uuid)
snapshot = self._image_api.get(context, image_id)
# source_format is an on-disk format
# source_type is a backend type
disk_path, source_format = libvirt_utils.find_disk(virt_dom)
source_type = libvirt_utils.get_disk_type_from_path(disk_path)
# We won't have source_type for raw or qcow2 disks, because we can't
# determine that from the path. We should have it from the libvirt
# xml, though.
if source_type is None:
source_type = source_format
# For lxc instances we won't have it either from libvirt xml
# (because we just gave libvirt the mounted filesystem), or the path,
# so source_type is still going to be None. In this case,
# snapshot_backend is going to default to CONF.libvirt.images_type
# below, which is still safe.
image_format = CONF.libvirt.snapshot_image_format or source_type
# NOTE(bfilippov): save lvm and rbd as raw
if image_format == 'lvm' or image_format == 'rbd':
image_format = 'raw'
metadata = self._create_snapshot_metadata(instance.image_meta,
instance,
image_format,
snapshot['name'])
snapshot_name = uuid.uuid4().hex
state = guest.get_power_state(self._host)
# NOTE(rmk): Live snapshots require QEMU 1.3 and Libvirt 1.0.0.
# These restrictions can be relaxed as other configurations
# can be validated.
# NOTE(dgenin): Instances with LVM encrypted ephemeral storage require
# cold snapshots. Currently, checking for encryption is
# redundant because LVM supports only cold snapshots.
# It is necessary in case this situation changes in the
# future.
if (self._host.has_min_version(MIN_LIBVIRT_LIVESNAPSHOT_VERSION,
MIN_QEMU_LIVESNAPSHOT_VERSION,
host.HV_DRIVER_QEMU)
and source_type not in ('lvm', 'rbd')
and not CONF.ephemeral_storage_encryption.enabled
and not CONF.workarounds.disable_libvirt_livesnapshot):
live_snapshot = True
# Abort is an idempotent operation, so make sure any block
# jobs which may have failed are ended. This operation also
# confirms the running instance, as opposed to the system as a
# whole, has a new enough version of the hypervisor (bug 1193146).
try:
guest.get_block_device(disk_path).abort_job()
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_CONFIG_UNSUPPORTED:
live_snapshot = False
else:
pass
else:
live_snapshot = False
# NOTE(rmk): We cannot perform live snapshots when a managedSave
# file is present, so we will use the cold/legacy method
# for instances which are shutdown.
if state == power_state.SHUTDOWN:
live_snapshot = False
self._prepare_domain_for_snapshot(context, live_snapshot, state,
instance)
snapshot_backend = self.image_backend.snapshot(instance,
disk_path,
image_type=source_type)
if live_snapshot:
LOG.info(_LI("Beginning live snapshot process"),
instance=instance)
else:
LOG.info(_LI("Beginning cold snapshot process"),
instance=instance)
update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD)
try:
update_task_state(task_state=task_states.IMAGE_UPLOADING,
expected_state=task_states.IMAGE_PENDING_UPLOAD)
metadata['location'] = snapshot_backend.direct_snapshot(
context, snapshot_name, image_format, image_id,
instance.image_ref)
self._snapshot_domain(context, live_snapshot, virt_dom, state,
instance)
self._image_api.update(context, image_id, metadata,
purge_props=False)
except (NotImplementedError, exception.ImageUnacceptable,
exception.Forbidden) as e:
if type(e) != NotImplementedError:
LOG.warning(_LW('Performing standard snapshot because direct '
'snapshot failed: %(error)s'), {'error': e})
failed_snap = metadata.pop('location', None)
if failed_snap:
failed_snap = {'url': str(failed_snap)}
snapshot_backend.cleanup_direct_snapshot(failed_snap,
also_destroy_volume=True,
ignore_errors=True)
update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD,
expected_state=task_states.IMAGE_UPLOADING)
snapshot_directory = CONF.libvirt.snapshots_directory
fileutils.ensure_tree(snapshot_directory)
with utils.tempdir(dir=snapshot_directory) as tmpdir:
try:
out_path = os.path.join(tmpdir, snapshot_name)
if live_snapshot:
# NOTE(xqueralt): libvirt needs o+x in the tempdir
os.chmod(tmpdir, 0o701)
self._live_snapshot(context, instance, guest,
disk_path, out_path, source_format,
image_format, instance.image_meta)
else:
snapshot_backend.snapshot_extract(out_path,
image_format)
finally:
self._snapshot_domain(context, live_snapshot, virt_dom,
state, instance)
LOG.info(_LI("Snapshot extracted, beginning image upload"),
instance=instance)
# Upload that image to the image service
update_task_state(task_state=task_states.IMAGE_UPLOADING,
expected_state=task_states.IMAGE_PENDING_UPLOAD)
with libvirt_utils.file_open(out_path) as image_file:
self._image_api.update(context,
image_id,
metadata,
image_file)
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(_LE("Failed to snapshot image"))
failed_snap = metadata.pop('location', None)
if failed_snap:
failed_snap = {'url': str(failed_snap)}
snapshot_backend.cleanup_direct_snapshot(
failed_snap, also_destroy_volume=True,
ignore_errors=True)
LOG.info(_LI("Snapshot image upload complete"), instance=instance)
def _prepare_domain_for_snapshot(self, context, live_snapshot, state,
instance):
# NOTE(dkang): managedSave does not work for LXC
if CONF.libvirt.virt_type != 'lxc' and not live_snapshot:
if state == power_state.RUNNING or state == power_state.PAUSED:
self.suspend(context, instance)
def _snapshot_domain(self, context, live_snapshot, virt_dom, state,
instance):
guest = None
# NOTE(dkang): because previous managedSave is not called
# for LXC, _create_domain must not be called.
if CONF.libvirt.virt_type != 'lxc' and not live_snapshot:
if state == power_state.RUNNING:
guest = self._create_domain(domain=virt_dom)
elif state == power_state.PAUSED:
guest = self._create_domain(domain=virt_dom, pause=True)
if guest is not None:
self._attach_pci_devices(
guest, pci_manager.get_instance_pci_devs(instance))
self._attach_sriov_ports(context, instance, guest)
def _can_set_admin_password(self, image_meta):
if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or
not self._host.has_min_version(MIN_LIBVIRT_SET_ADMIN_PASSWD)):
raise exception.SetAdminPasswdNotSupported()
hw_qga = image_meta.properties.get('hw_qemu_guest_agent', '')
if not strutils.bool_from_string(hw_qga):
raise exception.QemuGuestAgentNotEnabled()
def set_admin_password(self, instance, new_pass):
self._can_set_admin_password(instance.image_meta)
guest = self._host.get_guest(instance)
user = instance.image_meta.properties.get("os_admin_user")
if not user:
if instance.os_type == "windows":
user = "Administrator"
else:
user = "root"
try:
guest.set_user_password(user, new_pass)
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
msg = (_('Error from libvirt while set password for username '
'"%(user)s": [Error Code %(error_code)s] %(ex)s')
% {'user': user, 'error_code': error_code, 'ex': ex})
raise exception.NovaException(msg)
def _can_quiesce(self, instance, image_meta):
if (CONF.libvirt.virt_type not in ('kvm', 'qemu') or
not self._host.has_min_version(MIN_LIBVIRT_FSFREEZE_VERSION)):
raise exception.InstanceQuiesceNotSupported(
instance_id=instance.uuid)
if not image_meta.properties.get('hw_qemu_guest_agent', False):
raise exception.QemuGuestAgentNotEnabled()
def _set_quiesced(self, context, instance, image_meta, quiesced):
self._can_quiesce(instance, image_meta)
try:
guest = self._host.get_guest(instance)
if quiesced:
guest.freeze_filesystems()
else:
guest.thaw_filesystems()
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
msg = (_('Error from libvirt while quiescing %(instance_name)s: '
'[Error Code %(error_code)s] %(ex)s')
% {'instance_name': instance.name,
'error_code': error_code, 'ex': ex})
raise exception.NovaException(msg)
def quiesce(self, context, instance, image_meta):
"""Freeze the guest filesystems to prepare for snapshot.
The qemu-guest-agent must be setup to execute fsfreeze.
"""
self._set_quiesced(context, instance, image_meta, True)
def unquiesce(self, context, instance, image_meta):
"""Thaw the guest filesystems after snapshot."""
self._set_quiesced(context, instance, image_meta, False)
def _live_snapshot(self, context, instance, guest, disk_path, out_path,
source_format, image_format, image_meta):
"""Snapshot an instance without downtime."""
dev = guest.get_block_device(disk_path)
# Save a copy of the domain's persistent XML file
xml = guest.get_xml_desc(dump_inactive=True, dump_sensitive=True)
# Abort is an idempotent operation, so make sure any block
# jobs which may have failed are ended.
try:
dev.abort_job()
except Exception:
pass
# NOTE (rmk): We are using shallow rebases as a workaround to a bug
# in QEMU 1.3. In order to do this, we need to create
# a destination image with the original backing file
# and matching size of the instance root disk.
src_disk_size = libvirt_utils.get_disk_size(disk_path,
format=source_format)
src_back_path = libvirt_utils.get_disk_backing_file(disk_path,
format=source_format,
basename=False)
disk_delta = out_path + '.delta'
libvirt_utils.create_cow_image(src_back_path, disk_delta,
src_disk_size)
quiesced = False
try:
self._set_quiesced(context, instance, image_meta, True)
quiesced = True
except exception.NovaException as err:
if image_meta.properties.get('os_require_quiesce', False):
raise
LOG.info(_LI('Skipping quiescing instance: %(reason)s.'),
{'reason': err}, instance=instance)
try:
# NOTE (rmk): blockRebase cannot be executed on persistent
# domains, so we need to temporarily undefine it.
# If any part of this block fails, the domain is
# re-defined regardless.
if guest.has_persistent_configuration():
guest.delete_configuration()
# NOTE (rmk): Establish a temporary mirror of our root disk and
# issue an abort once we have a complete copy.
dev.rebase(disk_delta, copy=True, reuse_ext=True, shallow=True)
while dev.wait_for_job():
time.sleep(0.5)
dev.abort_job()
libvirt_utils.chown(disk_delta, os.getuid())
finally:
self._host.write_instance_config(xml)
if quiesced:
self._set_quiesced(context, instance, image_meta, False)
# Convert the delta (CoW) image with a backing file to a flat
# image with no backing file.
libvirt_utils.extract_snapshot(disk_delta, 'qcow2',
out_path, image_format)
def _volume_snapshot_update_status(self, context, snapshot_id, status):
"""Send a snapshot status update to Cinder.
This method captures and logs exceptions that occur
since callers cannot do anything useful with these exceptions.
Operations on the Cinder side waiting for this will time out if
a failure occurs sending the update.
:param context: security context
:param snapshot_id: id of snapshot being updated
:param status: new status value
"""
try:
self._volume_api.update_snapshot_status(context,
snapshot_id,
status)
except Exception:
LOG.exception(_LE('Failed to send updated snapshot status '
'to volume service.'))
def _volume_snapshot_create(self, context, instance, guest,
volume_id, new_file):
"""Perform volume snapshot.
:param guest: VM that volume is attached to
:param volume_id: volume UUID to snapshot
:param new_file: relative path to new qcow2 file present on share
"""
xml = guest.get_xml_desc()
xml_doc = etree.fromstring(xml)
device_info = vconfig.LibvirtConfigGuest()
device_info.parse_dom(xml_doc)
disks_to_snap = [] # to be snapshotted by libvirt
network_disks_to_snap = [] # network disks (netfs, gluster, etc.)
disks_to_skip = [] # local disks not snapshotted
for guest_disk in device_info.devices:
if (guest_disk.root_name != 'disk'):
continue
if (guest_disk.target_dev is None):
continue
if (guest_disk.serial is None or guest_disk.serial != volume_id):
disks_to_skip.append(guest_disk.target_dev)
continue
# disk is a Cinder volume with the correct volume_id
disk_info = {
'dev': guest_disk.target_dev,
'serial': guest_disk.serial,
'current_file': guest_disk.source_path,
'source_protocol': guest_disk.source_protocol,
'source_name': guest_disk.source_name,
'source_hosts': guest_disk.source_hosts,
'source_ports': guest_disk.source_ports
}
# Determine path for new_file based on current path
if disk_info['current_file'] is not None:
current_file = disk_info['current_file']
new_file_path = os.path.join(os.path.dirname(current_file),
new_file)
disks_to_snap.append((current_file, new_file_path))
elif disk_info['source_protocol'] in ('gluster', 'netfs'):
network_disks_to_snap.append((disk_info, new_file))
if not disks_to_snap and not network_disks_to_snap:
msg = _('Found no disk to snapshot.')
raise exception.NovaException(msg)
snapshot = vconfig.LibvirtConfigGuestSnapshot()
for current_name, new_filename in disks_to_snap:
snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
snap_disk.name = current_name
snap_disk.source_path = new_filename
snap_disk.source_type = 'file'
snap_disk.snapshot = 'external'
snap_disk.driver_name = 'qcow2'
snapshot.add_disk(snap_disk)
for disk_info, new_filename in network_disks_to_snap:
snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
snap_disk.name = disk_info['dev']
snap_disk.source_type = 'network'
snap_disk.source_protocol = disk_info['source_protocol']
snap_disk.snapshot = 'external'
snap_disk.source_path = new_filename
old_dir = disk_info['source_name'].split('/')[0]
snap_disk.source_name = '%s/%s' % (old_dir, new_filename)
snap_disk.source_hosts = disk_info['source_hosts']
snap_disk.source_ports = disk_info['source_ports']
snapshot.add_disk(snap_disk)
for dev in disks_to_skip:
snap_disk = vconfig.LibvirtConfigGuestSnapshotDisk()
snap_disk.name = dev
snap_disk.snapshot = 'no'
snapshot.add_disk(snap_disk)
snapshot_xml = snapshot.to_xml()
LOG.debug("snap xml: %s", snapshot_xml, instance=instance)
try:
guest.snapshot(snapshot, no_metadata=True, disk_only=True,
reuse_ext=True, quiesce=True)
return
except libvirt.libvirtError:
LOG.exception(_LE('Unable to create quiesced VM snapshot, '
'attempting again with quiescing disabled.'),
instance=instance)
try:
guest.snapshot(snapshot, no_metadata=True, disk_only=True,
reuse_ext=True, quiesce=False)
except libvirt.libvirtError:
LOG.exception(_LE('Unable to create VM snapshot, '
'failing volume_snapshot operation.'),
instance=instance)
raise
def _volume_refresh_connection_info(self, context, instance, volume_id):
bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
context, volume_id, instance.uuid)
driver_bdm = driver_block_device.convert_volume(bdm)
if driver_bdm:
driver_bdm.refresh_connection_info(context, instance,
self._volume_api, self)
def volume_snapshot_create(self, context, instance, volume_id,
create_info):
"""Create snapshots of a Cinder volume via libvirt.
:param instance: VM instance object reference
:param volume_id: id of volume being snapshotted
:param create_info: dict of information used to create snapshots
- snapshot_id : ID of snapshot
- type : qcow2 / <other>
- new_file : qcow2 file created by Cinder which
becomes the VM's active image after
the snapshot is complete
"""
LOG.debug("volume_snapshot_create: create_info: %(c_info)s",
{'c_info': create_info}, instance=instance)
try:
guest = self._host.get_guest(instance)
except exception.InstanceNotFound:
raise exception.InstanceNotRunning(instance_id=instance.uuid)
if create_info['type'] != 'qcow2':
raise exception.NovaException(_('Unknown type: %s') %
create_info['type'])
snapshot_id = create_info.get('snapshot_id', None)
if snapshot_id is None:
raise exception.NovaException(_('snapshot_id required '
'in create_info'))
try:
self._volume_snapshot_create(context, instance, guest,
volume_id, create_info['new_file'])
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(_LE('Error occurred during '
'volume_snapshot_create, '
'sending error status to Cinder.'),
instance=instance)
self._volume_snapshot_update_status(
context, snapshot_id, 'error')
self._volume_snapshot_update_status(
context, snapshot_id, 'creating')
def _wait_for_snapshot():
snapshot = self._volume_api.get_snapshot(context, snapshot_id)
if snapshot.get('status') != 'creating':
self._volume_refresh_connection_info(context, instance,
volume_id)
raise loopingcall.LoopingCallDone()
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_snapshot)
timer.start(interval=0.5).wait()
@staticmethod
def _rebase_with_qemu_img(guest, device, active_disk_object,
rebase_base):
"""Rebase a device tied to a guest using qemu-img.
:param guest:the Guest which owns the device being rebased
:type guest: nova.virt.libvirt.guest.Guest
:param device: the guest block device to rebase
:type device: nova.virt.libvirt.guest.BlockDevice
:param active_disk_object: the guest block device to rebase
:type active_disk_object: nova.virt.libvirt.config.\
LibvirtConfigGuestDisk
:param rebase_base: the new parent in the backing chain
:type rebase_base: None or string
"""
# It's unsure how well qemu-img handles network disks for
# every protocol. So let's be safe.
active_protocol = active_disk_object.source_protocol
if active_protocol is not None:
msg = _("Something went wrong when deleting a volume snapshot: "
"rebasing a %(protocol)s network disk using qemu-img "
"has not been fully tested") % {'protocol':
active_protocol}
LOG.error(msg)
raise exception.NovaException(msg)
if rebase_base is None:
# If backing_file is specified as "" (the empty string), then
# the image is rebased onto no backing file (i.e. it will exist
# independently of any backing file).
backing_file = ""
qemu_img_extra_arg = []
else:
# If the rebased image is going to have a backing file then
# explicitly set the backing file format to avoid any security
# concerns related to file format auto detection.
backing_file = rebase_base
b_file_fmt = images.qemu_img_info(backing_file).file_format
qemu_img_extra_arg = ['-F', b_file_fmt]
qemu_img_extra_arg.append(active_disk_object.source_path)
utils.execute("qemu-img", "rebase", "-b", backing_file,
*qemu_img_extra_arg)
def _volume_snapshot_delete(self, context, instance, volume_id,
snapshot_id, delete_info=None):
"""Note:
if file being merged into == active image:
do a blockRebase (pull) operation
else:
do a blockCommit operation
Files must be adjacent in snap chain.
:param instance: instance object reference
:param volume_id: volume UUID
:param snapshot_id: snapshot UUID (unused currently)
:param delete_info: {
'type': 'qcow2',
'file_to_merge': 'a.img',
'merge_target_file': 'b.img' or None (if merging file_to_merge into
active image)
}
Libvirt blockjob handling required for this method is broken
in versions of libvirt that do not contain:
http://libvirt.org/git/?p=libvirt.git;h=0f9e67bfad (1.1.1)
(Patch is pending in 1.0.5-maint branch as well, but we cannot detect
libvirt 1.0.5.5 vs. 1.0.5.6 here.)
"""
if not self._host.has_min_version(MIN_LIBVIRT_BLOCKJOBINFO_VERSION):
ver = '.'.join([str(x) for x in MIN_LIBVIRT_BLOCKJOBINFO_VERSION])
msg = _("Libvirt '%s' or later is required for online deletion "
"of volume snapshots.") % ver
raise exception.Invalid(msg)
LOG.debug('volume_snapshot_delete: delete_info: %s', delete_info,
instance=instance)
if delete_info['type'] != 'qcow2':
msg = _('Unknown delete_info type %s') % delete_info['type']
raise exception.NovaException(msg)
try:
guest = self._host.get_guest(instance)
except exception.InstanceNotFound:
raise exception.InstanceNotRunning(instance_id=instance.uuid)
# Find dev name
my_dev = None
active_disk = None
xml = guest.get_xml_desc()
xml_doc = etree.fromstring(xml)
device_info = vconfig.LibvirtConfigGuest()
device_info.parse_dom(xml_doc)
active_disk_object = None
for guest_disk in device_info.devices:
if (guest_disk.root_name != 'disk'):
continue
if (guest_disk.target_dev is None or guest_disk.serial is None):
continue
if guest_disk.serial == volume_id:
my_dev = guest_disk.target_dev
active_disk = guest_disk.source_path
active_protocol = guest_disk.source_protocol
active_disk_object = guest_disk
break
if my_dev is None or (active_disk is None and active_protocol is None):
msg = _('Disk with id: %s '
'not found attached to instance.') % volume_id
LOG.debug('Domain XML: %s', xml, instance=instance)
raise exception.NovaException(msg)
LOG.debug("found device at %s", my_dev, instance=instance)
def _get_snap_dev(filename, backing_store):
if filename is None:
msg = _('filename cannot be None')
raise exception.NovaException(msg)
# libgfapi delete
LOG.debug("XML: %s", xml)
LOG.debug("active disk object: %s", active_disk_object)
# determine reference within backing store for desired image
filename_to_merge = filename
matched_name = None
b = backing_store
index = None
current_filename = active_disk_object.source_name.split('/')[1]
if current_filename == filename_to_merge:
return my_dev + '[0]'
while b is not None:
source_filename = b.source_name.split('/')[1]
if source_filename == filename_to_merge:
LOG.debug('found match: %s', b.source_name)
matched_name = b.source_name
index = b.index
break
b = b.backing_store
if matched_name is None:
msg = _('no match found for %s') % (filename_to_merge)
raise exception.NovaException(msg)
LOG.debug('index of match (%s) is %s', b.source_name, index)
my_snap_dev = '%s[%s]' % (my_dev, index)
return my_snap_dev
if delete_info['merge_target_file'] is None:
# pull via blockRebase()
# Merge the most recent snapshot into the active image
rebase_disk = my_dev
rebase_base = delete_info['file_to_merge'] # often None
if (active_protocol is not None) and (rebase_base is not None):
rebase_base = _get_snap_dev(rebase_base,
active_disk_object.backing_store)
# NOTE(deepakcs): libvirt added support for _RELATIVE in v1.2.7,
# and when available this flag _must_ be used to ensure backing
# paths are maintained relative by qemu.
#
# If _RELATIVE flag not found, continue with old behaviour
# (relative backing path seems to work for this case)
try:
libvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE
relative = rebase_base is not None
except AttributeError:
LOG.warn(_LW("Relative blockrebase support was not detected. "
"Continuing with old behaviour."))
relative = False
LOG.debug(
'disk: %(disk)s, base: %(base)s, '
'bw: %(bw)s, relative: %(relative)s',
{'disk': rebase_disk,
'base': rebase_base,
'bw': libvirt_guest.BlockDevice.REBASE_DEFAULT_BANDWIDTH,
'relative': str(relative)}, instance=instance)
dev = guest.get_block_device(rebase_disk)
if guest.is_active():
result = dev.rebase(rebase_base, relative=relative)
if result == 0:
LOG.debug('blockRebase started successfully',
instance=instance)
while dev.wait_for_job(abort_on_error=True):
LOG.debug('waiting for blockRebase job completion',
instance=instance)
time.sleep(0.5)
# If the guest is not running libvirt won't do a blockRebase.
# In that case, let's ask qemu-img to rebase the disk.
else:
LOG.debug('Guest is not running so doing a block rebase '
'using "qemu-img rebase"', instance=instance)
self._rebase_with_qemu_img(guest, dev, active_disk_object,
rebase_base)
else:
# commit with blockCommit()
my_snap_base = None
my_snap_top = None
commit_disk = my_dev
# NOTE(deepakcs): libvirt added support for _RELATIVE in v1.2.7,
# and when available this flag _must_ be used to ensure backing
# paths are maintained relative by qemu.
#
# If _RELATIVE flag not found, raise exception as relative backing
# path may not be maintained and Cinder flow is broken if allowed
# to continue.
try:
libvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE
except AttributeError:
ver = '.'.join(
[str(x) for x in
MIN_LIBVIRT_BLOCKJOB_RELATIVE_VERSION])
msg = _("Relative blockcommit support was not detected. "
"Libvirt '%s' or later is required for online "
"deletion of file/network storage-backed volume "
"snapshots.") % ver
raise exception.Invalid(msg)
if active_protocol is not None:
my_snap_base = _get_snap_dev(delete_info['merge_target_file'],
active_disk_object.backing_store)
my_snap_top = _get_snap_dev(delete_info['file_to_merge'],
active_disk_object.backing_store)
commit_base = my_snap_base or delete_info['merge_target_file']
commit_top = my_snap_top or delete_info['file_to_merge']
LOG.debug('will call blockCommit with commit_disk=%(commit_disk)s '
'commit_base=%(commit_base)s '
'commit_top=%(commit_top)s ',
{'commit_disk': commit_disk,
'commit_base': commit_base,
'commit_top': commit_top}, instance=instance)
dev = guest.get_block_device(commit_disk)
result = dev.commit(commit_base, commit_top, relative=True)
if result == 0:
LOG.debug('blockCommit started successfully',
instance=instance)
while dev.wait_for_job(abort_on_error=True):
LOG.debug('waiting for blockCommit job completion',
instance=instance)
time.sleep(0.5)
def volume_snapshot_delete(self, context, instance, volume_id, snapshot_id,
delete_info):
try:
self._volume_snapshot_delete(context, instance, volume_id,
snapshot_id, delete_info=delete_info)
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(_LE('Error occurred during '
'volume_snapshot_delete, '
'sending error status to Cinder.'),
instance=instance)
self._volume_snapshot_update_status(
context, snapshot_id, 'error_deleting')
self._volume_snapshot_update_status(context, snapshot_id, 'deleting')
self._volume_refresh_connection_info(context, instance, volume_id)
def reboot(self, context, instance, network_info, reboot_type,
block_device_info=None, bad_volumes_callback=None):
"""Reboot a virtual machine, given an instance reference."""
if reboot_type == 'SOFT':
# NOTE(vish): This will attempt to do a graceful shutdown/restart.
try:
soft_reboot_success = self._soft_reboot(instance)
except libvirt.libvirtError as e:
LOG.debug("Instance soft reboot failed: %s", e,
instance=instance)
soft_reboot_success = False
if soft_reboot_success:
LOG.info(_LI("Instance soft rebooted successfully."),
instance=instance)
return
else:
LOG.warn(_LW("Failed to soft reboot instance. "
"Trying hard reboot."),
instance=instance)
return self._hard_reboot(context, instance, network_info,
block_device_info)
def _soft_reboot(self, instance):
"""Attempt to shutdown and restart the instance gracefully.
We use shutdown and create here so we can return if the guest
responded and actually rebooted. Note that this method only
succeeds if the guest responds to acpi. Therefore we return
success or failure so we can fall back to a hard reboot if
necessary.
:returns: True if the reboot succeeded
"""
guest = self._host.get_guest(instance)
state = guest.get_power_state(self._host)
old_domid = guest.id
# NOTE(vish): This check allows us to reboot an instance that
# is already shutdown.
if state == power_state.RUNNING:
guest.shutdown()
# NOTE(vish): This actually could take slightly longer than the
# FLAG defines depending on how long the get_info
# call takes to return.
self._prepare_pci_devices_for_use(
pci_manager.get_instance_pci_devs(instance, 'all'))
for x in range(CONF.libvirt.wait_soft_reboot_seconds):
guest = self._host.get_guest(instance)
state = guest.get_power_state(self._host)
new_domid = guest.id
# NOTE(ivoks): By checking domain IDs, we make sure we are
# not recreating domain that's already running.
if old_domid != new_domid:
if state in [power_state.SHUTDOWN,
power_state.CRASHED]:
LOG.info(_LI("Instance shutdown successfully."),
instance=instance)
self._create_domain(domain=guest._domain)
timer = loopingcall.FixedIntervalLoopingCall(
self._wait_for_running, instance)
timer.start(interval=0.5).wait()
return True
else:
LOG.info(_LI("Instance may have been rebooted during soft "
"reboot, so return now."), instance=instance)
return True
greenthread.sleep(1)
return False
def _hard_reboot(self, context, instance, network_info,
block_device_info=None):
"""Reboot a virtual machine, given an instance reference.
Performs a Libvirt reset (if supported) on the domain.
If Libvirt reset is unavailable this method actually destroys and
re-creates the domain to ensure the reboot happens, as the guest
OS cannot ignore this action.
"""
self._destroy(instance)
# Convert the system metadata to image metadata
instance_dir = libvirt_utils.get_instance_path(instance)
fileutils.ensure_tree(instance_dir)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
instance.image_meta,
block_device_info)
# NOTE(vish): This could generate the wrong device_format if we are
# using the raw backend and the images don't exist yet.
# The create_images_and_backing below doesn't properly
# regenerate raw backend images, however, so when it
# does we need to (re)generate the xml after the images
# are in place.
xml = self._get_guest_xml(context, instance, network_info, disk_info,
instance.image_meta,
block_device_info=block_device_info,
write_to_disk=True)
if context.auth_token is not None:
# NOTE (rmk): Re-populate any missing backing files.
backing_disk_info = self._get_instance_disk_info(instance.name,
xml,
block_device_info)
self._create_images_and_backing(context, instance, instance_dir,
backing_disk_info)
# Initialize all the necessary networking, block devices and
# start the instance.
self._create_domain_and_network(context, xml, instance, network_info,
disk_info,
block_device_info=block_device_info,
reboot=True,
vifs_already_plugged=True)
self._prepare_pci_devices_for_use(
pci_manager.get_instance_pci_devs(instance, 'all'))
def _wait_for_reboot():
"""Called at an interval until the VM is running again."""
state = self.get_info(instance).state
if state == power_state.RUNNING:
LOG.info(_LI("Instance rebooted successfully."),
instance=instance)
raise loopingcall.LoopingCallDone()
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_reboot)
timer.start(interval=0.5).wait()
def pause(self, instance):
"""Pause VM instance."""
self._host.get_guest(instance).pause()
def unpause(self, instance):
"""Unpause paused VM instance."""
self._host.get_guest(instance).resume()
def _clean_shutdown(self, instance, timeout, retry_interval):
"""Attempt to shutdown the instance gracefully.
:param instance: The instance to be shutdown
:param timeout: How long to wait in seconds for the instance to
shutdown
:param retry_interval: How often in seconds to signal the instance
to shutdown while waiting
:returns: True if the shutdown succeeded
"""
# List of states that represent a shutdown instance
SHUTDOWN_STATES = [power_state.SHUTDOWN,
power_state.CRASHED]
try:
guest = self._host.get_guest(instance)
except exception.InstanceNotFound:
# If the instance has gone then we don't need to
# wait for it to shutdown
return True
state = guest.get_power_state(self._host)
if state in SHUTDOWN_STATES:
LOG.info(_LI("Instance already shutdown."),
instance=instance)
return True
LOG.debug("Shutting down instance from state %s", state,
instance=instance)
guest.shutdown()
retry_countdown = retry_interval
for sec in six.moves.range(timeout):
guest = self._host.get_guest(instance)
state = guest.get_power_state(self._host)
if state in SHUTDOWN_STATES:
LOG.info(_LI("Instance shutdown successfully after %d "
"seconds."), sec, instance=instance)
return True
# Note(PhilD): We can't assume that the Guest was able to process
# any previous shutdown signal (for example it may
# have still been startingup, so within the overall
# timeout we re-trigger the shutdown every
# retry_interval
if retry_countdown == 0:
retry_countdown = retry_interval
# Instance could shutdown at any time, in which case we
# will get an exception when we call shutdown
try:
LOG.debug("Instance in state %s after %d seconds - "
"resending shutdown", state, sec,
instance=instance)
guest.shutdown()
except libvirt.libvirtError:
# Assume this is because its now shutdown, so loop
# one more time to clean up.
LOG.debug("Ignoring libvirt exception from shutdown "
"request.", instance=instance)
continue
else:
retry_countdown -= 1
time.sleep(1)
LOG.info(_LI("Instance failed to shutdown in %d seconds."),
timeout, instance=instance)
return False
def power_off(self, instance, timeout=0, retry_interval=0):
"""Power off the specified instance."""
if timeout:
self._clean_shutdown(instance, timeout, retry_interval)
self._destroy(instance)
def power_on(self, context, instance, network_info,
block_device_info=None):
"""Power on the specified instance."""
# We use _hard_reboot here to ensure that all backing files,
# network, and block device connections, etc. are established
# and available before we attempt to start the instance.
self._hard_reboot(context, instance, network_info, block_device_info)
def trigger_crash_dump(self, instance):
"""Trigger crash dump by injecting an NMI to the specified instance."""
try:
self._host.get_guest(instance).inject_nmi()
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_SUPPORT:
raise exception.TriggerCrashDumpNotSupported()
elif error_code == libvirt.VIR_ERR_OPERATION_INVALID:
raise exception.InstanceNotRunning(instance_id=instance.uuid)
LOG.exception(_LE('Error from libvirt while injecting an NMI to '
'%(instance_uuid)s: '
'[Error Code %(error_code)s] %(ex)s'),
{'instance_uuid': instance.uuid,
'error_code': error_code, 'ex': ex})
raise
def suspend(self, context, instance):
"""Suspend the specified instance."""
guest = self._host.get_guest(instance)
self._detach_pci_devices(guest,
pci_manager.get_instance_pci_devs(instance))
self._detach_sriov_ports(context, instance, guest)
guest.save_memory_state()
def resume(self, context, instance, network_info, block_device_info=None):
"""resume the specified instance."""
disk_info = blockinfo.get_disk_info(
CONF.libvirt.virt_type, instance, instance.image_meta,
block_device_info=block_device_info)
xml = self._get_existing_domain_xml(instance, network_info,
block_device_info)
guest = self._create_domain_and_network(context, xml, instance,
network_info, disk_info,
block_device_info=block_device_info,
vifs_already_plugged=True)
self._attach_pci_devices(guest,
pci_manager.get_instance_pci_devs(instance))
self._attach_sriov_ports(context, instance, guest, network_info)
def resume_state_on_host_boot(self, context, instance, network_info,
block_device_info=None):
"""resume guest state when a host is booted."""
# Check if the instance is running already and avoid doing
# anything if it is.
try:
guest = self._host.get_guest(instance)
state = guest.get_power_state(self._host)
ignored_states = (power_state.RUNNING,
power_state.SUSPENDED,
power_state.NOSTATE,
power_state.PAUSED)
if state in ignored_states:
return
except exception.NovaException:
pass
# Instance is not up and could be in an unknown state.
# Be as absolute as possible about getting it back into
# a known and running state.
self._hard_reboot(context, instance, network_info, block_device_info)
def rescue(self, context, instance, network_info, image_meta,
rescue_password):
"""Loads a VM using rescue images.
A rescue is normally performed when something goes wrong with the
primary images and data needs to be corrected/recovered. Rescuing
should not edit or over-ride the original image, only allow for
data recovery.
"""
instance_dir = libvirt_utils.get_instance_path(instance)
unrescue_xml = self._get_existing_domain_xml(instance, network_info)
unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml')
libvirt_utils.write_to_file(unrescue_xml_path, unrescue_xml)
rescue_image_id = None
if image_meta.obj_attr_is_set("id"):
rescue_image_id = image_meta.id
rescue_images = {
'image_id': (rescue_image_id or
CONF.libvirt.rescue_image_id or instance.image_ref),
'kernel_id': (CONF.libvirt.rescue_kernel_id or
instance.kernel_id),
'ramdisk_id': (CONF.libvirt.rescue_ramdisk_id or
instance.ramdisk_id),
}
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta,
rescue=True)
self._create_image(context, instance, disk_info['mapping'],
suffix='.rescue', disk_images=rescue_images,
network_info=network_info,
admin_pass=rescue_password)
xml = self._get_guest_xml(context, instance, network_info, disk_info,
image_meta, rescue=rescue_images,
write_to_disk=True)
self._destroy(instance)
self._create_domain(xml)
def unrescue(self, instance, network_info):
"""Reboot the VM which is being rescued back into primary images.
"""
instance_dir = libvirt_utils.get_instance_path(instance)
unrescue_xml_path = os.path.join(instance_dir, 'unrescue.xml')
xml = libvirt_utils.load_file(unrescue_xml_path)
guest = self._host.get_guest(instance)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove virt_dom at the end.
virt_dom = guest._domain
self._destroy(instance)
self._create_domain(xml, virt_dom)
libvirt_utils.file_delete(unrescue_xml_path)
rescue_files = os.path.join(instance_dir, "*.rescue")
for rescue_file in glob.iglob(rescue_files):
libvirt_utils.file_delete(rescue_file)
# cleanup rescue volume
lvm.remove_volumes([lvmdisk for lvmdisk in self._lvm_disks(instance)
if lvmdisk.endswith('.rescue')])
def poll_rebooting_instances(self, timeout, instances):
pass
# NOTE(ilyaalekseyev): Implementation like in multinics
# for xenapi(tr3buchet)
def spawn(self, context, instance, image_meta, injected_files,
admin_password, network_info=None, block_device_info=None):
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta,
block_device_info)
self._create_image(context, instance,
disk_info['mapping'],
network_info=network_info,
block_device_info=block_device_info,
files=injected_files,
admin_pass=admin_password)
xml = self._get_guest_xml(context, instance, network_info,
disk_info, image_meta,
block_device_info=block_device_info,
write_to_disk=True)
self._create_domain_and_network(context, xml, instance, network_info,
disk_info,
block_device_info=block_device_info)
LOG.debug("Instance is running", instance=instance)
def _wait_for_boot():
"""Called at an interval until the VM is running."""
state = self.get_info(instance).state
if state == power_state.RUNNING:
LOG.info(_LI("Instance spawned successfully."),
instance=instance)
raise loopingcall.LoopingCallDone()
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_boot)
timer.start(interval=0.5).wait()
def _flush_libvirt_console(self, pty):
out, err = utils.execute('dd',
'if=%s' % pty,
'iflag=nonblock',
run_as_root=True,
check_exit_code=False)
return out
def _append_to_file(self, data, fpath):
LOG.info(_LI('data: %(data)r, fpath: %(fpath)r'),
{'data': data, 'fpath': fpath})
with open(fpath, 'a+') as fp:
fp.write(data)
return fpath
def get_console_output(self, context, instance):
guest = self._host.get_guest(instance)
xml = guest.get_xml_desc()
tree = etree.fromstring(xml)
console_types = {}
# NOTE(comstud): We want to try 'file' types first, then try 'pty'
# types. We can't use Python 2.7 syntax of:
# tree.find("./devices/console[@type='file']/source")
# because we need to support 2.6.
console_nodes = tree.findall('./devices/console')
for console_node in console_nodes:
console_type = console_node.get('type')
console_types.setdefault(console_type, [])
console_types[console_type].append(console_node)
# If the guest has a console logging to a file prefer to use that
if console_types.get('file'):
for file_console in console_types.get('file'):
source_node = file_console.find('./source')
if source_node is None:
continue
path = source_node.get("path")
if not path:
continue
if not os.path.exists(path):
LOG.info(_LI('Instance is configured with a file console, '
'but the backing file is not (yet?) present'),
instance=instance)
return ""
libvirt_utils.chown(path, os.getuid())
with libvirt_utils.file_open(path, 'rb') as fp:
log_data, remaining = utils.last_bytes(fp,
MAX_CONSOLE_BYTES)
if remaining > 0:
LOG.info(_LI('Truncated console log returned, '
'%d bytes ignored'), remaining,
instance=instance)
return log_data
# Try 'pty' types
if console_types.get('pty'):
for pty_console in console_types.get('pty'):
source_node = pty_console.find('./source')
if source_node is None:
continue
pty = source_node.get("path")
if not pty:
continue
break
else:
raise exception.ConsoleNotAvailable()
self._chown_console_log_for_instance(instance)
data = self._flush_libvirt_console(pty)
console_log = self._get_console_log_path(instance)
fpath = self._append_to_file(data, console_log)
with libvirt_utils.file_open(fpath, 'rb') as fp:
log_data, remaining = utils.last_bytes(fp, MAX_CONSOLE_BYTES)
if remaining > 0:
LOG.info(_LI('Truncated console log returned, '
'%d bytes ignored'),
remaining, instance=instance)
return log_data
def get_host_ip_addr(self):
ips = compute_utils.get_machine_ips()
if CONF.my_ip not in ips:
LOG.warn(_LW('my_ip address (%(my_ip)s) was not found on '
'any of the interfaces: %(ifaces)s'),
{'my_ip': CONF.my_ip, 'ifaces': ", ".join(ips)})
return CONF.my_ip
def get_vnc_console(self, context, instance):
def get_vnc_port_for_instance(instance_name):
guest = self._host.get_guest(instance)
xml = guest.get_xml_desc()
xml_dom = etree.fromstring(xml)
graphic = xml_dom.find("./devices/graphics[@type='vnc']")
if graphic is not None:
return graphic.get('port')
# NOTE(rmk): We had VNC consoles enabled but the instance in
# question is not actually listening for connections.
raise exception.ConsoleTypeUnavailable(console_type='vnc')
port = get_vnc_port_for_instance(instance.name)
host = CONF.vnc.vncserver_proxyclient_address
return ctype.ConsoleVNC(host=host, port=port)
def get_spice_console(self, context, instance):
def get_spice_ports_for_instance(instance_name):
guest = self._host.get_guest(instance)
xml = guest.get_xml_desc()
xml_dom = etree.fromstring(xml)
graphic = xml_dom.find("./devices/graphics[@type='spice']")
if graphic is not None:
return (graphic.get('port'), graphic.get('tlsPort'))
# NOTE(rmk): We had Spice consoles enabled but the instance in
# question is not actually listening for connections.
raise exception.ConsoleTypeUnavailable(console_type='spice')
ports = get_spice_ports_for_instance(instance.name)
host = CONF.spice.server_proxyclient_address
return ctype.ConsoleSpice(host=host, port=ports[0], tlsPort=ports[1])
def get_serial_console(self, context, instance):
guest = self._host.get_guest(instance)
for hostname, port in self._get_serial_ports_from_guest(
guest, mode='bind'):
return ctype.ConsoleSerial(host=hostname, port=port)
raise exception.ConsoleTypeUnavailable(console_type='serial')
@staticmethod
def _supports_direct_io(dirpath):
if not hasattr(os, 'O_DIRECT'):
LOG.debug("This python runtime does not support direct I/O")
return False
testfile = os.path.join(dirpath, ".directio.test")
hasDirectIO = True
try:
f = os.open(testfile, os.O_CREAT | os.O_WRONLY | os.O_DIRECT)
# Check is the write allowed with 512 byte alignment
align_size = 512
m = mmap.mmap(-1, align_size)
m.write(r"x" * align_size)
os.write(f, m)
os.close(f)
LOG.debug("Path '%(path)s' supports direct I/O",
{'path': dirpath})
except OSError as e:
if e.errno == errno.EINVAL:
LOG.debug("Path '%(path)s' does not support direct I/O: "
"'%(ex)s'", {'path': dirpath, 'ex': e})
hasDirectIO = False
else:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error on '%(path)s' while checking "
"direct I/O: '%(ex)s'"),
{'path': dirpath, 'ex': e})
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error on '%(path)s' while checking direct I/O: "
"'%(ex)s'"), {'path': dirpath, 'ex': e})
finally:
try:
os.unlink(testfile)
except Exception:
pass
return hasDirectIO
@staticmethod
def _create_ephemeral(target, ephemeral_size,
fs_label, os_type, is_block_dev=False,
max_size=None, context=None, specified_fs=None):
if not is_block_dev:
libvirt_utils.create_image('raw', target, '%dG' % ephemeral_size)
# Run as root only for block devices.
disk.mkfs(os_type, fs_label, target, run_as_root=is_block_dev,
specified_fs=specified_fs)
@staticmethod
def _create_swap(target, swap_mb, max_size=None, context=None):
"""Create a swap file of specified size."""
libvirt_utils.create_image('raw', target, '%dM' % swap_mb)
utils.mkfs('swap', target)
@staticmethod
def _get_console_log_path(instance):
return os.path.join(libvirt_utils.get_instance_path(instance),
'console.log')
@staticmethod
def _get_disk_config_path(instance, suffix=''):
return os.path.join(libvirt_utils.get_instance_path(instance),
'disk.config' + suffix)
@staticmethod
def _get_disk_config_image_type():
# TODO(mikal): there is a bug here if images_type has
# changed since creation of the instance, but I am pretty
# sure that this bug already exists.
return 'rbd' if CONF.libvirt.images_type == 'rbd' else 'raw'
def _chown_console_log_for_instance(self, instance):
console_log = self._get_console_log_path(instance)
if os.path.exists(console_log):
libvirt_utils.chown(console_log, os.getuid())
def _chown_disk_config_for_instance(self, instance):
disk_config = self._get_disk_config_path(instance)
if os.path.exists(disk_config):
libvirt_utils.chown(disk_config, os.getuid())
@staticmethod
def _is_booted_from_volume(instance, disk_mapping):
"""Determines whether the VM is booting from volume
Determines whether the disk mapping indicates that the VM
is booting from a volume.
"""
return ((not bool(instance.get('image_ref')))
or 'disk' not in disk_mapping)
@staticmethod
def _has_local_disk(instance, disk_mapping):
"""Determines whether the VM has a local disk
Determines whether the disk mapping indicates that the VM
has a local disk (e.g. ephemeral, swap disk and config-drive).
"""
if disk_mapping:
if ('disk.local' in disk_mapping or
'disk.swap' in disk_mapping or
'disk.config' in disk_mapping):
return True
return False
def _inject_data(self, instance, network_info, admin_pass, files, suffix):
"""Injects data in a disk image
Helper used for injecting data in a disk image file system.
Keyword arguments:
instance -- a dict that refers instance specifications
network_info -- a dict that refers network speficications
admin_pass -- a string used to set an admin password
files -- a list of files needs to be injected
suffix -- a string used as an image name suffix
"""
# Handles the partition need to be used.
target_partition = None
if not instance.kernel_id:
target_partition = CONF.libvirt.inject_partition
if target_partition == 0:
target_partition = None
if CONF.libvirt.virt_type == 'lxc':
target_partition = None
# Handles the key injection.
if CONF.libvirt.inject_key and instance.get('key_data'):
key = str(instance.key_data)
else:
key = None
# Handles the admin password injection.
if not CONF.libvirt.inject_password:
admin_pass = None
# Handles the network injection.
net = netutils.get_injected_network_template(
network_info, libvirt_virt_type=CONF.libvirt.virt_type)
# Handles the metadata injection
metadata = instance.get('metadata')
image_type = CONF.libvirt.images_type
if any((key, net, metadata, admin_pass, files)):
injection_image = self.image_backend.image(
instance,
'disk' + suffix,
image_type)
img_id = instance.image_ref
if not injection_image.check_image_exists():
LOG.warn(_LW('Image %s not found on disk storage. '
'Continue without injecting data'),
injection_image.path, instance=instance)
return
try:
disk.inject_data(injection_image.get_model(self._conn),
key, net, metadata, admin_pass, files,
partition=target_partition,
mandatory=('files',))
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error injecting data into image '
'%(img_id)s (%(e)s)'),
{'img_id': img_id, 'e': e},
instance=instance)
# NOTE(sileht): many callers of this method assume that this
# method doesn't fail if an image already exists but instead
# think that it will be reused (ie: (live)-migration/resize)
def _create_image(self, context, instance,
disk_mapping, suffix='',
disk_images=None, network_info=None,
block_device_info=None, files=None,
admin_pass=None, inject_files=True,
fallback_from_host=None):
booted_from_volume = self._is_booted_from_volume(
instance, disk_mapping)
def image(fname, image_type=CONF.libvirt.images_type):
return self.image_backend.image(instance,
fname + suffix, image_type)
def raw(fname):
return image(fname, image_type='raw')
# ensure directories exist and are writable
fileutils.ensure_tree(libvirt_utils.get_instance_path(instance))
LOG.info(_LI('Creating image'), instance=instance)
# NOTE(dprince): for rescue console.log may already exist... chown it.
self._chown_console_log_for_instance(instance)
# NOTE(yaguang): For evacuate disk.config already exist in shared
# storage, chown it.
self._chown_disk_config_for_instance(instance)
# NOTE(vish): No need add the suffix to console.log
libvirt_utils.write_to_file(
self._get_console_log_path(instance), '', 7)
if not disk_images:
disk_images = {'image_id': instance.image_ref,
'kernel_id': instance.kernel_id,
'ramdisk_id': instance.ramdisk_id}
if disk_images['kernel_id']:
fname = imagecache.get_cache_fname(disk_images, 'kernel_id')
raw('kernel').cache(fetch_func=libvirt_utils.fetch_raw_image,
context=context,
filename=fname,
image_id=disk_images['kernel_id'],
user_id=instance.user_id,
project_id=instance.project_id)
if disk_images['ramdisk_id']:
fname = imagecache.get_cache_fname(disk_images, 'ramdisk_id')
raw('ramdisk').cache(fetch_func=libvirt_utils.fetch_raw_image,
context=context,
filename=fname,
image_id=disk_images['ramdisk_id'],
user_id=instance.user_id,
project_id=instance.project_id)
inst_type = instance.get_flavor()
# NOTE(ndipanov): Even if disk_mapping was passed in, which
# currently happens only on rescue - we still don't want to
# create a base image.
if not booted_from_volume:
root_fname = imagecache.get_cache_fname(disk_images, 'image_id')
size = instance.root_gb * units.Gi
if size == 0 or suffix == '.rescue':
size = None
backend = image('disk')
if instance.task_state == task_states.RESIZE_FINISH:
backend.create_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME)
if backend.SUPPORTS_CLONE:
def clone_fallback_to_fetch(*args, **kwargs):
try:
backend.clone(context, disk_images['image_id'])
except exception.ImageUnacceptable:
libvirt_utils.fetch_image(*args, **kwargs)
fetch_func = clone_fallback_to_fetch
else:
fetch_func = libvirt_utils.fetch_image
self._try_fetch_image_cache(backend, fetch_func, context,
root_fname, disk_images['image_id'],
instance, size, fallback_from_host)
# Lookup the filesystem type if required
os_type_with_default = disk.get_fs_type_for_os_type(instance.os_type)
# Generate a file extension based on the file system
# type and the mkfs commands configured if any
file_extension = disk.get_file_extension_for_os_type(
os_type_with_default)
ephemeral_gb = instance.ephemeral_gb
if 'disk.local' in disk_mapping:
disk_image = image('disk.local')
fn = functools.partial(self._create_ephemeral,
fs_label='ephemeral0',
os_type=instance.os_type,
is_block_dev=disk_image.is_block_dev)
fname = "ephemeral_%s_%s" % (ephemeral_gb, file_extension)
size = ephemeral_gb * units.Gi
disk_image.cache(fetch_func=fn,
context=context,
filename=fname,
size=size,
ephemeral_size=ephemeral_gb)
for idx, eph in enumerate(driver.block_device_info_get_ephemerals(
block_device_info)):
disk_image = image(blockinfo.get_eph_disk(idx))
specified_fs = eph.get('guest_format')
if specified_fs and not self.is_supported_fs_format(specified_fs):
msg = _("%s format is not supported") % specified_fs
raise exception.InvalidBDMFormat(details=msg)
fn = functools.partial(self._create_ephemeral,
fs_label='ephemeral%d' % idx,
os_type=instance.os_type,
is_block_dev=disk_image.is_block_dev)
size = eph['size'] * units.Gi
fname = "ephemeral_%s_%s" % (eph['size'], file_extension)
disk_image.cache(fetch_func=fn,
context=context,
filename=fname,
size=size,
ephemeral_size=eph['size'],
specified_fs=specified_fs)
if 'disk.swap' in disk_mapping:
mapping = disk_mapping['disk.swap']
swap_mb = 0
swap = driver.block_device_info_get_swap(block_device_info)
if driver.swap_is_usable(swap):
swap_mb = swap['swap_size']
elif (inst_type['swap'] > 0 and
not block_device.volume_in_mapping(
mapping['dev'], block_device_info)):
swap_mb = inst_type['swap']
if swap_mb > 0:
size = swap_mb * units.Mi
image('disk.swap').cache(fetch_func=self._create_swap,
context=context,
filename="swap_%s" % swap_mb,
size=size,
swap_mb=swap_mb)
# Config drive
if configdrive.required_by(instance):
LOG.info(_LI('Using config drive'), instance=instance)
extra_md = {}
if admin_pass:
extra_md['admin_pass'] = admin_pass
inst_md = instance_metadata.InstanceMetadata(instance,
content=files, extra_md=extra_md, network_info=network_info)
with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb:
configdrive_path = self._get_disk_config_path(instance, suffix)
LOG.info(_LI('Creating config drive at %(path)s'),
{'path': configdrive_path}, instance=instance)
try:
cdb.make_drive(configdrive_path)
except processutils.ProcessExecutionError as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Creating config drive failed '
'with error: %s'),
e, instance=instance)
try:
# Tell the storage backend about the config drive
config_drive_image = self.image_backend.image(
instance, 'disk.config' + suffix,
self._get_disk_config_image_type())
config_drive_image.import_file(
instance, configdrive_path, 'disk.config' + suffix)
finally:
# NOTE(mikal): if the config drive was imported into RBD, then
# we no longer need the local copy
if CONF.libvirt.images_type == 'rbd':
os.unlink(configdrive_path)
# File injection only if needed
elif inject_files and CONF.libvirt.inject_partition != -2:
if booted_from_volume:
LOG.warn(_LW('File injection into a boot from volume '
'instance is not supported'), instance=instance)
self._inject_data(
instance, network_info, admin_pass, files, suffix)
if CONF.libvirt.virt_type == 'uml':
libvirt_utils.chown(image('disk').path, 'root')
def _prepare_pci_devices_for_use(self, pci_devices):
# kvm , qemu support managed mode
# In managed mode, the configured device will be automatically
# detached from the host OS drivers when the guest is started,
# and then re-attached when the guest shuts down.
if CONF.libvirt.virt_type != 'xen':
# we do manual detach only for xen
return
try:
for dev in pci_devices:
libvirt_dev_addr = dev['hypervisor_name']
libvirt_dev = \
self._host.device_lookup_by_name(libvirt_dev_addr)
# Note(yjiang5) Spelling for 'dettach' is correct, see
# http://libvirt.org/html/libvirt-libvirt.html.
libvirt_dev.dettach()
# Note(yjiang5): A reset of one PCI device may impact other
# devices on the same bus, thus we need two separated loops
# to detach and then reset it.
for dev in pci_devices:
libvirt_dev_addr = dev['hypervisor_name']
libvirt_dev = \
self._host.device_lookup_by_name(libvirt_dev_addr)
libvirt_dev.reset()
except libvirt.libvirtError as exc:
raise exception.PciDevicePrepareFailed(id=dev['id'],
instance_uuid=
dev['instance_uuid'],
reason=six.text_type(exc))
def _detach_pci_devices(self, guest, pci_devs):
# for libvirt version < 1.1.1, this is race condition
# so forbid detach if not had this version
if not self._host.has_min_version(MIN_LIBVIRT_DEVICE_CALLBACK_VERSION):
if pci_devs:
reason = (_("Detaching PCI devices with libvirt < %(ver)s"
" is not permitted") %
{'ver': MIN_LIBVIRT_DEVICE_CALLBACK_VERSION})
raise exception.PciDeviceDetachFailed(reason=reason,
dev=pci_devs)
try:
for dev in pci_devs:
guest.detach_device(self._get_guest_pci_device(dev), live=True)
# after detachDeviceFlags returned, we should check the dom to
# ensure the detaching is finished
xml = guest.get_xml_desc()
xml_doc = etree.fromstring(xml)
guest_config = vconfig.LibvirtConfigGuest()
guest_config.parse_dom(xml_doc)
for hdev in [d for d in guest_config.devices
if isinstance(d, vconfig.LibvirtConfigGuestHostdevPCI)]:
hdbsf = [hdev.domain, hdev.bus, hdev.slot, hdev.function]
dbsf = pci_utils.parse_address(dev['address'])
if [int(x, 16) for x in hdbsf] ==\
[int(x, 16) for x in dbsf]:
raise exception.PciDeviceDetachFailed(reason=
"timeout",
dev=dev)
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_DOMAIN:
LOG.warn(_LW("Instance disappeared while detaching "
"a PCI device from it."))
else:
raise
def _attach_pci_devices(self, guest, pci_devs):
try:
for dev in pci_devs:
guest.attach_device(self._get_guest_pci_device(dev))
except libvirt.libvirtError:
LOG.error(_LE('Attaching PCI devices %(dev)s to %(dom)s failed.'),
{'dev': pci_devs, 'dom': guest.id})
raise
@staticmethod
def _has_sriov_port(network_info):
for vif in network_info:
if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT:
return True
return False
def _attach_sriov_ports(self, context, instance, guest, network_info=None):
if network_info is None:
network_info = instance.info_cache.network_info
if network_info is None:
return
if self._has_sriov_port(network_info):
for vif in network_info:
if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV:
cfg = self.vif_driver.get_config(instance,
vif,
instance.image_meta,
instance.flavor,
CONF.libvirt.virt_type,
self._host)
LOG.debug('Attaching SR-IOV port %(port)s to %(dom)s',
{'port': vif, 'dom': guest.id},
instance=instance)
guest.attach_device(cfg)
def _detach_sriov_ports(self, context, instance, guest):
network_info = instance.info_cache.network_info
if network_info is None:
return
if self._has_sriov_port(network_info):
# for libvirt version < 1.1.1, this is race condition
# so forbid detach if it's an older version
if not self._host.has_min_version(
MIN_LIBVIRT_DEVICE_CALLBACK_VERSION):
reason = (_("Detaching SR-IOV ports with"
" libvirt < %(ver)s is not permitted") %
{'ver': MIN_LIBVIRT_DEVICE_CALLBACK_VERSION})
raise exception.PciDeviceDetachFailed(reason=reason,
dev=network_info)
# In case of SR-IOV vif types we create pci request per SR-IOV port
# Therefore we can trust that pci_slot value in the vif is correct.
sriov_pci_addresses = [
vif['profile']['pci_slot']
for vif in network_info
if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV and
vif['profile'].get('pci_slot') is not None
]
# use detach_pci_devices to avoid failure in case of
# multiple guest SRIOV ports with the same MAC
# (protection use-case, ports are on different physical
# interfaces)
pci_devs = pci_manager.get_instance_pci_devs(instance, 'all')
sriov_devs = [pci_dev for pci_dev in pci_devs
if pci_dev.address in sriov_pci_addresses]
self._detach_pci_devices(guest, sriov_devs)
def _set_host_enabled(self, enabled,
disable_reason=DISABLE_REASON_UNDEFINED):
"""Enables / Disables the compute service on this host.
This doesn't override non-automatic disablement with an automatic
setting; thereby permitting operators to keep otherwise
healthy hosts out of rotation.
"""
status_name = {True: 'disabled',
False: 'enabled'}
disable_service = not enabled
ctx = nova_context.get_admin_context()
try:
service = objects.Service.get_by_compute_host(ctx, CONF.host)
if service.disabled != disable_service:
# Note(jang): this is a quick fix to stop operator-
# disabled compute hosts from re-enabling themselves
# automatically. We prefix any automatic reason code
# with a fixed string. We only re-enable a host
# automatically if we find that string in place.
# This should probably be replaced with a separate flag.
if not service.disabled or (
service.disabled_reason and
service.disabled_reason.startswith(DISABLE_PREFIX)):
service.disabled = disable_service
service.disabled_reason = (
DISABLE_PREFIX + disable_reason
if disable_service else DISABLE_REASON_UNDEFINED)
service.save()
LOG.debug('Updating compute service status to %s',
status_name[disable_service])
else:
LOG.debug('Not overriding manual compute service '
'status with: %s',
status_name[disable_service])
except exception.ComputeHostNotFound:
LOG.warn(_LW('Cannot update service status on host "%s" '
'since it is not registered.'), CONF.host)
except Exception:
LOG.warn(_LW('Cannot update service status on host "%s" '
'due to an unexpected exception.'), CONF.host,
exc_info=True)
def _get_guest_cpu_model_config(self):
mode = CONF.libvirt.cpu_mode
model = CONF.libvirt.cpu_model
if (CONF.libvirt.virt_type == "kvm" or
CONF.libvirt.virt_type == "qemu"):
if mode is None:
mode = "host-model"
if mode == "none":
return vconfig.LibvirtConfigGuestCPU()
else:
if mode is None or mode == "none":
return None
if ((CONF.libvirt.virt_type != "kvm" and
CONF.libvirt.virt_type != "qemu")):
msg = _("Config requested an explicit CPU model, but "
"the current libvirt hypervisor '%s' does not "
"support selecting CPU models") % CONF.libvirt.virt_type
raise exception.Invalid(msg)
if mode == "custom" and model is None:
msg = _("Config requested a custom CPU model, but no "
"model name was provided")
raise exception.Invalid(msg)
elif mode != "custom" and model is not None:
msg = _("A CPU model name should not be set when a "
"host CPU model is requested")
raise exception.Invalid(msg)
LOG.debug("CPU mode '%(mode)s' model '%(model)s' was chosen",
{'mode': mode, 'model': (model or "")})
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.mode = mode
cpu.model = model
return cpu
def _get_guest_cpu_config(self, flavor, image_meta,
guest_cpu_numa_config, instance_numa_topology):
cpu = self._get_guest_cpu_model_config()
if cpu is None:
return None
topology = hardware.get_best_cpu_topology(
flavor, image_meta, numa_topology=instance_numa_topology)
cpu.sockets = topology.sockets
cpu.cores = topology.cores
cpu.threads = topology.threads
cpu.numa = guest_cpu_numa_config
return cpu
def _get_guest_disk_config(self, instance, name, disk_mapping, inst_type,
image_type=None):
if CONF.libvirt.hw_disk_discard:
if not self._host.has_min_version(MIN_LIBVIRT_DISCARD_VERSION,
MIN_QEMU_DISCARD_VERSION,
host.HV_DRIVER_QEMU):
msg = (_('Volume sets discard option, but libvirt %(libvirt)s'
' or later is required, qemu %(qemu)s'
' or later is required.') %
{'libvirt': MIN_LIBVIRT_DISCARD_VERSION,
'qemu': MIN_QEMU_DISCARD_VERSION})
raise exception.Invalid(msg)
image = self.image_backend.image(instance,
name,
image_type)
disk_info = disk_mapping[name]
return image.libvirt_info(disk_info['bus'],
disk_info['dev'],
disk_info['type'],
self.disk_cachemode,
inst_type['extra_specs'],
self._host.get_version())
def _get_guest_fs_config(self, instance, name, image_type=None):
image = self.image_backend.image(instance,
name,
image_type)
return image.libvirt_fs_info("/", "ploop")
def _get_guest_storage_config(self, instance, image_meta,
disk_info,
rescue, block_device_info,
inst_type, os_type):
devices = []
disk_mapping = disk_info['mapping']
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
mount_rootfs = CONF.libvirt.virt_type == "lxc"
if mount_rootfs:
fs = vconfig.LibvirtConfigGuestFilesys()
fs.source_type = "mount"
fs.source_dir = os.path.join(
libvirt_utils.get_instance_path(instance), 'rootfs')
devices.append(fs)
elif os_type == vm_mode.EXE and CONF.libvirt.virt_type == "parallels":
if 'disk' in disk_mapping:
fs = self._get_guest_fs_config(instance, "disk")
devices.append(fs)
else:
if rescue:
diskrescue = self._get_guest_disk_config(instance,
'disk.rescue',
disk_mapping,
inst_type)
devices.append(diskrescue)
diskos = self._get_guest_disk_config(instance,
'disk',
disk_mapping,
inst_type)
devices.append(diskos)
else:
if 'disk' in disk_mapping:
diskos = self._get_guest_disk_config(instance,
'disk',
disk_mapping,
inst_type)
devices.append(diskos)
if 'disk.local' in disk_mapping:
disklocal = self._get_guest_disk_config(instance,
'disk.local',
disk_mapping,
inst_type)
devices.append(disklocal)
instance.default_ephemeral_device = (
block_device.prepend_dev(disklocal.target_dev))
for idx, eph in enumerate(
driver.block_device_info_get_ephemerals(
block_device_info)):
diskeph = self._get_guest_disk_config(
instance,
blockinfo.get_eph_disk(idx),
disk_mapping, inst_type)
devices.append(diskeph)
if 'disk.swap' in disk_mapping:
diskswap = self._get_guest_disk_config(instance,
'disk.swap',
disk_mapping,
inst_type)
devices.append(diskswap)
instance.default_swap_device = (
block_device.prepend_dev(diskswap.target_dev))
if 'disk.config' in disk_mapping:
diskconfig = self._get_guest_disk_config(
instance, 'disk.config', disk_mapping, inst_type,
self._get_disk_config_image_type())
devices.append(diskconfig)
for vol in block_device.get_bdms_to_connect(block_device_mapping,
mount_rootfs):
connection_info = vol['connection_info']
vol_dev = block_device.prepend_dev(vol['mount_device'])
info = disk_mapping[vol_dev]
self._connect_volume(connection_info, info)
cfg = self._get_volume_config(connection_info, info)
devices.append(cfg)
vol['connection_info'] = connection_info
vol.save()
for d in devices:
self._set_cache_mode(d)
if image_meta.properties.get('hw_scsi_model'):
hw_scsi_model = image_meta.properties.hw_scsi_model
scsi_controller = vconfig.LibvirtConfigGuestController()
scsi_controller.type = 'scsi'
scsi_controller.model = hw_scsi_model
devices.append(scsi_controller)
return devices
def _get_host_sysinfo_serial_hardware(self):
"""Get a UUID from the host hardware
Get a UUID for the host hardware reported by libvirt.
This is typically from the SMBIOS data, unless it has
been overridden in /etc/libvirt/libvirtd.conf
"""
caps = self._host.get_capabilities()
return caps.host.uuid
def _get_host_sysinfo_serial_os(self):
"""Get a UUID from the host operating system
Get a UUID for the host operating system. Modern Linux
distros based on systemd provide a /etc/machine-id
file containing a UUID. This is also provided inside
systemd based containers and can be provided by other
init systems too, since it is just a plain text file.
"""
if not os.path.exists("/etc/machine-id"):
msg = _("Unable to get host UUID: /etc/machine-id does not exist")
raise exception.NovaException(msg)
with open("/etc/machine-id") as f:
# We want to have '-' in the right place
# so we parse & reformat the value
lines = f.read().split()
if not lines:
msg = _("Unable to get host UUID: /etc/machine-id is empty")
raise exception.NovaException(msg)
return str(uuid.UUID(lines[0]))
def _get_host_sysinfo_serial_auto(self):
if os.path.exists("/etc/machine-id"):
return self._get_host_sysinfo_serial_os()
else:
return self._get_host_sysinfo_serial_hardware()
def _get_guest_config_sysinfo(self, instance):
sysinfo = vconfig.LibvirtConfigGuestSysinfo()
sysinfo.system_manufacturer = version.vendor_string()
sysinfo.system_product = version.product_string()
sysinfo.system_version = version.version_string_with_package()
sysinfo.system_serial = self._sysinfo_serial_func()
sysinfo.system_uuid = instance.uuid
sysinfo.system_family = "Virtual Machine"
return sysinfo
def _get_guest_pci_device(self, pci_device):
dbsf = pci_utils.parse_address(pci_device.address)
dev = vconfig.LibvirtConfigGuestHostdevPCI()
dev.domain, dev.bus, dev.slot, dev.function = dbsf
# only kvm support managed mode
if CONF.libvirt.virt_type in ('xen', 'parallels',):
dev.managed = 'no'
if CONF.libvirt.virt_type in ('kvm', 'qemu'):
dev.managed = 'yes'
return dev
def _get_guest_config_meta(self, context, instance):
"""Get metadata config for guest."""
meta = vconfig.LibvirtConfigGuestMetaNovaInstance()
meta.package = version.version_string_with_package()
meta.name = instance.display_name
meta.creationTime = time.time()
if instance.image_ref not in ("", None):
meta.roottype = "image"
meta.rootid = instance.image_ref
if context is not None:
ometa = vconfig.LibvirtConfigGuestMetaNovaOwner()
ometa.userid = context.user_id
ometa.username = context.user_name
ometa.projectid = context.project_id
ometa.projectname = context.project_name
meta.owner = ometa
fmeta = vconfig.LibvirtConfigGuestMetaNovaFlavor()
flavor = instance.flavor
fmeta.name = flavor.name
fmeta.memory = flavor.memory_mb
fmeta.vcpus = flavor.vcpus
fmeta.ephemeral = flavor.ephemeral_gb
fmeta.disk = flavor.root_gb
fmeta.swap = flavor.swap
meta.flavor = fmeta
return meta
def _machine_type_mappings(self):
mappings = {}
for mapping in CONF.libvirt.hw_machine_type:
host_arch, _, machine_type = mapping.partition('=')
mappings[host_arch] = machine_type
return mappings
def _get_machine_type(self, image_meta, caps):
# The underlying machine type can be set as an image attribute,
# or otherwise based on some architecture specific defaults
mach_type = None
if image_meta.properties.get('hw_machine_type') is not None:
mach_type = image_meta.properties.hw_machine_type
else:
# For ARM systems we will default to vexpress-a15 for armv7
# and virt for aarch64
if caps.host.cpu.arch == arch.ARMV7:
mach_type = "vexpress-a15"
if caps.host.cpu.arch == arch.AARCH64:
mach_type = "virt"
if caps.host.cpu.arch in (arch.S390, arch.S390X):
mach_type = 's390-ccw-virtio'
# If set in the config, use that as the default.
if CONF.libvirt.hw_machine_type:
mappings = self._machine_type_mappings()
mach_type = mappings.get(caps.host.cpu.arch)
return mach_type
@staticmethod
def _create_idmaps(klass, map_strings):
idmaps = []
if len(map_strings) > 5:
map_strings = map_strings[0:5]
LOG.warn(_LW("Too many id maps, only included first five."))
for map_string in map_strings:
try:
idmap = klass()
values = [int(i) for i in map_string.split(":")]
idmap.start = values[0]
idmap.target = values[1]
idmap.count = values[2]
idmaps.append(idmap)
except (ValueError, IndexError):
LOG.warn(_LW("Invalid value for id mapping %s"), map_string)
return idmaps
def _get_guest_idmaps(self):
id_maps = []
if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.uid_maps:
uid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestUIDMap,
CONF.libvirt.uid_maps)
id_maps.extend(uid_maps)
if CONF.libvirt.virt_type == 'lxc' and CONF.libvirt.gid_maps:
gid_maps = self._create_idmaps(vconfig.LibvirtConfigGuestGIDMap,
CONF.libvirt.gid_maps)
id_maps.extend(gid_maps)
return id_maps
def _update_guest_cputune(self, guest, flavor, virt_type):
is_able = self._host.is_cpu_control_policy_capable()
cputuning = ['shares', 'period', 'quota']
wants_cputune = any([k for k in cputuning
if "quota:cpu_" + k in flavor.extra_specs.keys()])
if wants_cputune and not is_able:
raise exception.UnsupportedHostCPUControlPolicy()
if not is_able or virt_type not in ('lxc', 'kvm', 'qemu'):
return
if guest.cputune is None:
guest.cputune = vconfig.LibvirtConfigGuestCPUTune()
# Setting the default cpu.shares value to be a value
# dependent on the number of vcpus
guest.cputune.shares = 1024 * guest.vcpus
for name in cputuning:
key = "quota:cpu_" + name
if key in flavor.extra_specs:
setattr(guest.cputune, name,
int(flavor.extra_specs[key]))
def _get_cpu_numa_config_from_instance(self, instance_numa_topology,
wants_hugepages):
if instance_numa_topology:
guest_cpu_numa = vconfig.LibvirtConfigGuestCPUNUMA()
for instance_cell in instance_numa_topology.cells:
guest_cell = vconfig.LibvirtConfigGuestCPUNUMACell()
guest_cell.id = instance_cell.id
guest_cell.cpus = instance_cell.cpuset
guest_cell.memory = instance_cell.memory * units.Ki
# The vhost-user network backend requires file backed
# guest memory (ie huge pages) to be marked as shared
# access, not private, so an external process can read
# and write the pages.
#
# You can't change the shared vs private flag for an
# already running guest, and since we can't predict what
# types of NIC may be hotplugged, we have no choice but
# to unconditionally turn on the shared flag. This has
# no real negative functional effect on the guest, so
# is a reasonable approach to take
if wants_hugepages:
guest_cell.memAccess = "shared"
guest_cpu_numa.cells.append(guest_cell)
return guest_cpu_numa
def _has_cpu_policy_support(self):
for ver in BAD_LIBVIRT_CPU_POLICY_VERSIONS:
if self._host.has_version(ver):
ver_ = self._version_to_string(ver)
raise exception.CPUPinningNotSupported(reason=_(
'Invalid libvirt version %(version)s') % {'version': ver_})
return True
def _wants_hugepages(self, host_topology, instance_topology):
"""Determine if the guest / host topology implies the
use of huge pages for guest RAM backing
"""
if host_topology is None or instance_topology is None:
return False
avail_pagesize = [page.size_kb
for page in host_topology.cells[0].mempages]
avail_pagesize.sort()
# Remove smallest page size as that's not classed as a largepage
avail_pagesize = avail_pagesize[1:]
# See if we have page size set
for cell in instance_topology.cells:
if (cell.pagesize is not None and
cell.pagesize in avail_pagesize):
return True
return False
def _get_guest_numa_config(self, instance_numa_topology, flavor, pci_devs,
allowed_cpus=None, image_meta=None):
"""Returns the config objects for the guest NUMA specs.
Determines the CPUs that the guest can be pinned to if the guest
specifies a cell topology and the host supports it. Constructs the
libvirt XML config object representing the NUMA topology selected
for the guest. Returns a tuple of:
(cpu_set, guest_cpu_tune, guest_cpu_numa, guest_numa_tune)
With the following caveats:
a) If there is no specified guest NUMA topology, then
all tuple elements except cpu_set shall be None. cpu_set
will be populated with the chosen CPUs that the guest
allowed CPUs fit within, which could be the supplied
allowed_cpus value if the host doesn't support NUMA
topologies.
b) If there is a specified guest NUMA topology, then
cpu_set will be None and guest_cpu_numa will be the
LibvirtConfigGuestCPUNUMA object representing the guest's
NUMA topology. If the host supports NUMA, then guest_cpu_tune
will contain a LibvirtConfigGuestCPUTune object representing
the optimized chosen cells that match the host capabilities
with the instance's requested topology. If the host does
not support NUMA, then guest_cpu_tune and guest_numa_tune
will be None.
"""
if (not self._has_numa_support() and
instance_numa_topology is not None):
# We should not get here, since we should have avoided
# reporting NUMA topology from _get_host_numa_topology
# in the first place. Just in case of a scheduler
# mess up though, raise an exception
raise exception.NUMATopologyUnsupported()
topology = self._get_host_numa_topology()
# We have instance NUMA so translate it to the config class
guest_cpu_numa_config = self._get_cpu_numa_config_from_instance(
instance_numa_topology,
self._wants_hugepages(topology, instance_numa_topology))
if not guest_cpu_numa_config:
# No NUMA topology defined for instance - let the host kernel deal
# with the NUMA effects.
# TODO(ndipanov): Attempt to spread the instance
# across NUMA nodes and expose the topology to the
# instance as an optimisation
return GuestNumaConfig(allowed_cpus, None, None, None)
else:
if topology:
# Now get the CpuTune configuration from the numa_topology
guest_cpu_tune = vconfig.LibvirtConfigGuestCPUTune()
guest_numa_tune = vconfig.LibvirtConfigGuestNUMATune()
allpcpus = []
numa_mem = vconfig.LibvirtConfigGuestNUMATuneMemory()
numa_memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()
for _ in guest_cpu_numa_config.cells]
for host_cell in topology.cells:
for guest_node_id, guest_config_cell in enumerate(
guest_cpu_numa_config.cells):
if guest_config_cell.id == host_cell.id:
node = numa_memnodes[guest_node_id]
node.cellid = guest_config_cell.id
node.nodeset = [host_cell.id]
node.mode = "strict"
numa_mem.nodeset.append(host_cell.id)
object_numa_cell = (
instance_numa_topology.cells[guest_node_id]
)
for cpu in guest_config_cell.cpus:
pin_cpuset = (
vconfig.LibvirtConfigGuestCPUTuneVCPUPin())
pin_cpuset.id = cpu
# If there is pinning information in the cell
# we pin to individual CPUs, otherwise we float
# over the whole host NUMA node
if (object_numa_cell.cpu_pinning and
self._has_cpu_policy_support()):
pcpu = object_numa_cell.cpu_pinning[cpu]
pin_cpuset.cpuset = set([pcpu])
else:
pin_cpuset.cpuset = host_cell.cpuset
allpcpus.extend(pin_cpuset.cpuset)
guest_cpu_tune.vcpupin.append(pin_cpuset)
# TODO(berrange) When the guest has >1 NUMA node, it will
# span multiple host NUMA nodes. By pinning emulator threads
# to the union of all nodes, we guarantee there will be
# cross-node memory access by the emulator threads when
# responding to guest I/O operations. The only way to avoid
# this would be to pin emulator threads to a single node and
# tell the guest OS to only do I/O from one of its virtual
# NUMA nodes. This is not even remotely practical.
#
# The long term solution is to make use of a new QEMU feature
# called "I/O Threads" which will let us configure an explicit
# I/O thread for each guest vCPU or guest NUMA node. It is
# still TBD how to make use of this feature though, especially
# how to associate IO threads with guest devices to eliminiate
# cross NUMA node traffic. This is an area of investigation
# for QEMU community devs.
emulatorpin = vconfig.LibvirtConfigGuestCPUTuneEmulatorPin()
emulatorpin.cpuset = set(allpcpus)
guest_cpu_tune.emulatorpin = emulatorpin
# Sort the vcpupin list per vCPU id for human-friendlier XML
guest_cpu_tune.vcpupin.sort(key=operator.attrgetter("id"))
if hardware.is_realtime_enabled(flavor):
if not self._host.has_min_version(
MIN_LIBVIRT_REALTIME_VERSION):
raise exception.RealtimePolicyNotSupported()
vcpus_rt, vcpus_em = hardware.vcpus_realtime_topology(
set(cpu.id for cpu in guest_cpu_tune.vcpupin),
flavor, image_meta)
vcpusched = vconfig.LibvirtConfigGuestCPUTuneVCPUSched()
vcpusched.vcpus = vcpus_rt
vcpusched.scheduler = "fifo"
vcpusched.priority = (
CONF.libvirt.realtime_scheduler_priority)
guest_cpu_tune.vcpusched.append(vcpusched)
guest_cpu_tune.emulatorpin.cpuset = vcpus_em
guest_numa_tune.memory = numa_mem
guest_numa_tune.memnodes = numa_memnodes
# normalize cell.id
for i, (cell, memnode) in enumerate(
zip(guest_cpu_numa_config.cells,
guest_numa_tune.memnodes)):
cell.id = i
memnode.cellid = i
return GuestNumaConfig(None, guest_cpu_tune,
guest_cpu_numa_config,
guest_numa_tune)
else:
return GuestNumaConfig(allowed_cpus, None,
guest_cpu_numa_config, None)
def _get_guest_os_type(self, virt_type):
"""Returns the guest OS type based on virt type."""
if virt_type == "lxc":
ret = vm_mode.EXE
elif virt_type == "uml":
ret = vm_mode.UML
elif virt_type == "xen":
ret = vm_mode.XEN
else:
ret = vm_mode.HVM
return ret
def _set_guest_for_rescue(self, rescue, guest, inst_path, virt_type,
root_device_name):
if rescue.get('kernel_id'):
guest.os_kernel = os.path.join(inst_path, "kernel.rescue")
if virt_type == "xen":
guest.os_cmdline = "ro root=%s" % root_device_name
else:
guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE))
if virt_type == "qemu":
guest.os_cmdline += " no_timer_check"
if rescue.get('ramdisk_id'):
guest.os_initrd = os.path.join(inst_path, "ramdisk.rescue")
def _set_guest_for_inst_kernel(self, instance, guest, inst_path, virt_type,
root_device_name, image_meta):
guest.os_kernel = os.path.join(inst_path, "kernel")
if virt_type == "xen":
guest.os_cmdline = "ro root=%s" % root_device_name
else:
guest.os_cmdline = ("root=%s %s" % (root_device_name, CONSOLE))
if virt_type == "qemu":
guest.os_cmdline += " no_timer_check"
if instance.ramdisk_id:
guest.os_initrd = os.path.join(inst_path, "ramdisk")
# we only support os_command_line with images with an explicit
# kernel set and don't want to break nova if there's an
# os_command_line property without a specified kernel_id param
if image_meta.properties.get("os_command_line"):
guest.os_cmdline = image_meta.properties.os_command_line
def _set_clock(self, guest, os_type, image_meta, virt_type):
# NOTE(mikal): Microsoft Windows expects the clock to be in
# "localtime". If the clock is set to UTC, then you can use a
# registry key to let windows know, but Microsoft says this is
# buggy in http://support.microsoft.com/kb/2687252
clk = vconfig.LibvirtConfigGuestClock()
if os_type == 'windows':
LOG.info(_LI('Configuring timezone for windows instance to '
'localtime'))
clk.offset = 'localtime'
else:
clk.offset = 'utc'
guest.set_clock(clk)
if virt_type == "kvm":
self._set_kvm_timers(clk, os_type, image_meta)
def _set_kvm_timers(self, clk, os_type, image_meta):
# TODO(berrange) One day this should be per-guest
# OS type configurable
tmpit = vconfig.LibvirtConfigGuestTimer()
tmpit.name = "pit"
tmpit.tickpolicy = "delay"
tmrtc = vconfig.LibvirtConfigGuestTimer()
tmrtc.name = "rtc"
tmrtc.tickpolicy = "catchup"
clk.add_timer(tmpit)
clk.add_timer(tmrtc)
guestarch = libvirt_utils.get_arch(image_meta)
if guestarch in (arch.I686, arch.X86_64):
# NOTE(rfolco): HPET is a hardware timer for x86 arch.
# qemu -no-hpet is not supported on non-x86 targets.
tmhpet = vconfig.LibvirtConfigGuestTimer()
tmhpet.name = "hpet"
tmhpet.present = False
clk.add_timer(tmhpet)
# With new enough QEMU we can provide Windows guests
# with the paravirtualized hyperv timer source. This
# is the windows equiv of kvm-clock, allowing Windows
# guests to accurately keep time.
if (os_type == 'windows' and
self._host.has_min_version(MIN_LIBVIRT_HYPERV_TIMER_VERSION,
MIN_QEMU_HYPERV_TIMER_VERSION)):
tmhyperv = vconfig.LibvirtConfigGuestTimer()
tmhyperv.name = "hypervclock"
tmhyperv.present = True
clk.add_timer(tmhyperv)
def _set_features(self, guest, os_type, caps, virt_type):
if virt_type == "xen":
# PAE only makes sense in X86
if caps.host.cpu.arch in (arch.I686, arch.X86_64):
guest.features.append(vconfig.LibvirtConfigGuestFeaturePAE())
if (virt_type not in ("lxc", "uml", "parallels", "xen") or
(virt_type == "xen" and guest.os_type == vm_mode.HVM)):
guest.features.append(vconfig.LibvirtConfigGuestFeatureACPI())
guest.features.append(vconfig.LibvirtConfigGuestFeatureAPIC())
if (virt_type in ("qemu", "kvm") and
os_type == 'windows' and
self._host.has_min_version(MIN_LIBVIRT_HYPERV_FEATURE_VERSION,
MIN_QEMU_HYPERV_FEATURE_VERSION)):
hv = vconfig.LibvirtConfigGuestFeatureHyperV()
hv.relaxed = True
if self._host.has_min_version(
MIN_LIBVIRT_HYPERV_FEATURE_EXTRA_VERSION):
hv.spinlocks = True
# Increase spinlock retries - value recommended by
# KVM maintainers who certify Windows guests
# with Microsoft
hv.spinlock_retries = 8191
hv.vapic = True
guest.features.append(hv)
def _create_serial_console_devices(self, guest, instance, flavor,
image_meta):
guest_arch = libvirt_utils.get_arch(image_meta)
if CONF.serial_console.enabled:
num_ports = hardware.get_number_of_serial_ports(
flavor, image_meta)
for port in six.moves.range(num_ports):
if guest_arch in (arch.S390, arch.S390X):
console = vconfig.LibvirtConfigGuestConsole()
else:
console = vconfig.LibvirtConfigGuestSerial()
console.port = port
console.type = "tcp"
console.listen_host = (
CONF.serial_console.proxyclient_address)
console.listen_port = (
serial_console.acquire_port(
console.listen_host))
guest.add_device(console)
else:
# The QEMU 'pty' driver throws away any data if no
# client app is connected. Thus we can't get away
# with a single type=pty console. Instead we have
# to configure two separate consoles.
if guest_arch in (arch.S390, arch.S390X):
consolelog = vconfig.LibvirtConfigGuestConsole()
consolelog.target_type = "sclplm"
else:
consolelog = vconfig.LibvirtConfigGuestSerial()
consolelog.type = "file"
consolelog.source_path = self._get_console_log_path(instance)
guest.add_device(consolelog)
def _add_video_driver(self, guest, image_meta, flavor):
VALID_VIDEO_DEVICES = ("vga", "cirrus", "vmvga", "xen", "qxl")
video = vconfig.LibvirtConfigGuestVideo()
# NOTE(ldbragst): The following logic sets the video.type
# depending on supported defaults given the architecture,
# virtualization type, and features. The video.type attribute can
# be overridden by the user with image_meta.properties, which
# is carried out in the next if statement below this one.
guestarch = libvirt_utils.get_arch(image_meta)
if guest.os_type == vm_mode.XEN:
video.type = 'xen'
elif CONF.libvirt.virt_type == 'parallels':
video.type = 'vga'
elif guestarch in (arch.PPC, arch.PPC64, arch.PPC64LE):
# NOTE(ldbragst): PowerKVM doesn't support 'cirrus' be default
# so use 'vga' instead when running on Power hardware.
video.type = 'vga'
elif CONF.spice.enabled:
video.type = 'qxl'
if image_meta.properties.get('hw_video_model'):
video.type = image_meta.properties.hw_video_model
if (video.type not in VALID_VIDEO_DEVICES):
raise exception.InvalidVideoMode(model=video.type)
# Set video memory, only if the flavor's limit is set
video_ram = image_meta.properties.get('hw_video_ram', 0)
max_vram = int(flavor.extra_specs.get('hw_video:ram_max_mb', 0))
if video_ram > max_vram:
raise exception.RequestedVRamTooHigh(req_vram=video_ram,
max_vram=max_vram)
if max_vram and video_ram:
video.vram = video_ram * units.Mi / units.Ki
guest.add_device(video)
def _add_qga_device(self, guest, instance):
qga = vconfig.LibvirtConfigGuestChannel()
qga.type = "unix"
qga.target_name = "org.qemu.guest_agent.0"
qga.source_path = ("/var/lib/libvirt/qemu/%s.%s.sock" %
("org.qemu.guest_agent.0", instance.name))
guest.add_device(qga)
def _add_rng_device(self, guest, flavor):
rng_device = vconfig.LibvirtConfigGuestRng()
rate_bytes = flavor.extra_specs.get('hw_rng:rate_bytes', 0)
period = flavor.extra_specs.get('hw_rng:rate_period', 0)
if rate_bytes:
rng_device.rate_bytes = int(rate_bytes)
rng_device.rate_period = int(period)
rng_path = CONF.libvirt.rng_dev_path
if (rng_path and not os.path.exists(rng_path)):
raise exception.RngDeviceNotExist(path=rng_path)
rng_device.backend = rng_path
guest.add_device(rng_device)
def _set_qemu_guest_agent(self, guest, flavor, instance, image_meta):
# Enable qga only if the 'hw_qemu_guest_agent' is equal to yes
if image_meta.properties.get('hw_qemu_guest_agent', False):
LOG.debug("Qemu guest agent is enabled through image "
"metadata", instance=instance)
self._add_qga_device(guest, instance)
rng_is_virtio = image_meta.properties.get('hw_rng_model') == 'virtio'
rng_allowed_str = flavor.extra_specs.get('hw_rng:allowed', '')
rng_allowed = strutils.bool_from_string(rng_allowed_str)
if rng_is_virtio and rng_allowed:
self._add_rng_device(guest, flavor)
def _get_guest_memory_backing_config(
self, inst_topology, numatune, flavor):
wantsmempages = False
if inst_topology:
for cell in inst_topology.cells:
if cell.pagesize:
wantsmempages = True
break
wantsrealtime = hardware.is_realtime_enabled(flavor)
membacking = None
if wantsmempages:
pages = self._get_memory_backing_hugepages_support(
inst_topology, numatune)
if pages:
membacking = vconfig.LibvirtConfigGuestMemoryBacking()
membacking.hugepages = pages
if wantsrealtime:
if not membacking:
membacking = vconfig.LibvirtConfigGuestMemoryBacking()
membacking.locked = True
membacking.sharedpages = False
return membacking
def _get_memory_backing_hugepages_support(self, inst_topology, numatune):
if not self._has_hugepage_support():
# We should not get here, since we should have avoided
# reporting NUMA topology from _get_host_numa_topology
# in the first place. Just in case of a scheduler
# mess up though, raise an exception
raise exception.MemoryPagesUnsupported()
host_topology = self._get_host_numa_topology()
if host_topology is None:
# As above, we should not get here but just in case...
raise exception.MemoryPagesUnsupported()
# Currently libvirt does not support the smallest
# pagesize set as a backend memory.
# https://bugzilla.redhat.com/show_bug.cgi?id=1173507
avail_pagesize = [page.size_kb
for page in host_topology.cells[0].mempages]
avail_pagesize.sort()
smallest = avail_pagesize[0]
pages = []
for guest_cellid, inst_cell in enumerate(inst_topology.cells):
if inst_cell.pagesize and inst_cell.pagesize > smallest:
for memnode in numatune.memnodes:
if guest_cellid == memnode.cellid:
page = (
vconfig.LibvirtConfigGuestMemoryBackingPage())
page.nodeset = [guest_cellid]
page.size_kb = inst_cell.pagesize
pages.append(page)
break # Quit early...
return pages
def _get_flavor(self, ctxt, instance, flavor):
if flavor is not None:
return flavor
return instance.flavor
def _has_uefi_support(self):
# This means that the host can support uefi booting for guests
supported_archs = [arch.X86_64, arch.AARCH64]
caps = self._host.get_capabilities()
return ((caps.host.cpu.arch in supported_archs) and
self._host.has_min_version(MIN_LIBVIRT_UEFI_VERSION) and
os.path.exists(DEFAULT_UEFI_LOADER_PATH[caps.host.cpu.arch]))
def _configure_guest_by_virt_type(self, guest, virt_type, caps, instance,
image_meta, flavor, root_device_name):
if virt_type == "xen":
if guest.os_type == vm_mode.HVM:
guest.os_loader = CONF.libvirt.xen_hvmloader_path
elif virt_type in ("kvm", "qemu"):
if caps.host.cpu.arch in (arch.I686, arch.X86_64):
guest.sysinfo = self._get_guest_config_sysinfo(instance)
guest.os_smbios = vconfig.LibvirtConfigGuestSMBIOS()
hw_firmware_type = image_meta.properties.get('hw_firmware_type')
if hw_firmware_type == fields.FirmwareType.UEFI:
if self._has_uefi_support():
global uefi_logged
if not uefi_logged:
LOG.warn(_LW("uefi support is without some kind of "
"functional testing and therefore "
"considered experimental."))
uefi_logged = True
guest.os_loader = DEFAULT_UEFI_LOADER_PATH[
caps.host.cpu.arch]
guest.os_loader_type = "pflash"
else:
raise exception.UEFINotSupported()
guest.os_mach_type = self._get_machine_type(image_meta, caps)
if image_meta.properties.get('hw_boot_menu') is None:
guest.os_bootmenu = strutils.bool_from_string(
flavor.extra_specs.get('hw:boot_menu', 'no'))
else:
guest.os_bootmenu = image_meta.properties.hw_boot_menu
elif virt_type == "lxc":
guest.os_init_path = "/sbin/init"
guest.os_cmdline = CONSOLE
elif virt_type == "uml":
guest.os_kernel = "/usr/bin/linux"
guest.os_root = root_device_name
elif virt_type == "parallels":
if guest.os_type == vm_mode.EXE:
guest.os_init_path = "/sbin/init"
def _conf_non_lxc_uml(self, virt_type, guest, root_device_name, rescue,
instance, inst_path, image_meta, disk_info):
if rescue:
self._set_guest_for_rescue(rescue, guest, inst_path, virt_type,
root_device_name)
elif instance.kernel_id:
self._set_guest_for_inst_kernel(instance, guest, inst_path,
virt_type, root_device_name,
image_meta)
else:
guest.os_boot_dev = blockinfo.get_boot_order(disk_info)
def _create_consoles(self, virt_type, guest, instance, flavor, image_meta,
caps):
if virt_type in ("qemu", "kvm"):
# Create the serial console char devices
self._create_serial_console_devices(guest, instance, flavor,
image_meta)
if caps.host.cpu.arch in (arch.S390, arch.S390X):
consolepty = vconfig.LibvirtConfigGuestConsole()
consolepty.target_type = "sclp"
else:
consolepty = vconfig.LibvirtConfigGuestSerial()
else:
consolepty = vconfig.LibvirtConfigGuestConsole()
return consolepty
def _cpu_config_to_vcpu_model(self, cpu_config, vcpu_model):
"""Update VirtCPUModel object according to libvirt CPU config.
:param:cpu_config: vconfig.LibvirtConfigGuestCPU presenting the
instance's virtual cpu configuration.
:param:vcpu_model: VirtCPUModel object. A new object will be created
if None.
:return: Updated VirtCPUModel object, or None if cpu_config is None
"""
if not cpu_config:
return
if not vcpu_model:
vcpu_model = objects.VirtCPUModel()
vcpu_model.arch = cpu_config.arch
vcpu_model.vendor = cpu_config.vendor
vcpu_model.model = cpu_config.model
vcpu_model.mode = cpu_config.mode
vcpu_model.match = cpu_config.match
if cpu_config.sockets:
vcpu_model.topology = objects.VirtCPUTopology(
sockets=cpu_config.sockets,
cores=cpu_config.cores,
threads=cpu_config.threads)
else:
vcpu_model.topology = None
features = [objects.VirtCPUFeature(
name=f.name,
policy=f.policy) for f in cpu_config.features]
vcpu_model.features = features
return vcpu_model
def _vcpu_model_to_cpu_config(self, vcpu_model):
"""Create libvirt CPU config according to VirtCPUModel object.
:param:vcpu_model: VirtCPUModel object.
:return: vconfig.LibvirtConfigGuestCPU.
"""
cpu_config = vconfig.LibvirtConfigGuestCPU()
cpu_config.arch = vcpu_model.arch
cpu_config.model = vcpu_model.model
cpu_config.mode = vcpu_model.mode
cpu_config.match = vcpu_model.match
cpu_config.vendor = vcpu_model.vendor
if vcpu_model.topology:
cpu_config.sockets = vcpu_model.topology.sockets
cpu_config.cores = vcpu_model.topology.cores
cpu_config.threads = vcpu_model.topology.threads
if vcpu_model.features:
for f in vcpu_model.features:
xf = vconfig.LibvirtConfigGuestCPUFeature()
xf.name = f.name
xf.policy = f.policy
cpu_config.features.add(xf)
return cpu_config
def _get_guest_config(self, instance, network_info, image_meta,
disk_info, rescue=None, block_device_info=None,
context=None):
"""Get config data for parameters.
:param rescue: optional dictionary that should contain the key
'ramdisk_id' if a ramdisk is needed for the rescue image and
'kernel_id' if a kernel is needed for the rescue image.
"""
flavor = instance.flavor
inst_path = libvirt_utils.get_instance_path(instance)
disk_mapping = disk_info['mapping']
virt_type = CONF.libvirt.virt_type
guest = vconfig.LibvirtConfigGuest()
guest.virt_type = virt_type
guest.name = instance.name
guest.uuid = instance.uuid
# We are using default unit for memory: KiB
guest.memory = flavor.memory_mb * units.Ki
guest.vcpus = flavor.vcpus
allowed_cpus = hardware.get_vcpu_pin_set()
pci_devs = pci_manager.get_instance_pci_devs(instance, 'all')
guest_numa_config = self._get_guest_numa_config(
instance.numa_topology, flavor, pci_devs, allowed_cpus, image_meta)
guest.cpuset = guest_numa_config.cpuset
guest.cputune = guest_numa_config.cputune
guest.numatune = guest_numa_config.numatune
guest.membacking = self._get_guest_memory_backing_config(
instance.numa_topology,
guest_numa_config.numatune,
flavor)
guest.metadata.append(self._get_guest_config_meta(context,
instance))
guest.idmaps = self._get_guest_idmaps()
self._update_guest_cputune(guest, flavor, virt_type)
guest.cpu = self._get_guest_cpu_config(
flavor, image_meta, guest_numa_config.numaconfig,
instance.numa_topology)
# Notes(yjiang5): we always sync the instance's vcpu model with
# the corresponding config file.
instance.vcpu_model = self._cpu_config_to_vcpu_model(
guest.cpu, instance.vcpu_model)
if 'root' in disk_mapping:
root_device_name = block_device.prepend_dev(
disk_mapping['root']['dev'])
else:
root_device_name = None
if root_device_name:
# NOTE(yamahata):
# for nova.api.ec2.cloud.CloudController.get_metadata()
instance.root_device_name = root_device_name
guest.os_type = (vm_mode.get_from_instance(instance) or
self._get_guest_os_type(virt_type))
caps = self._host.get_capabilities()
self._configure_guest_by_virt_type(guest, virt_type, caps, instance,
image_meta, flavor,
root_device_name)
if virt_type not in ('lxc', 'uml'):
self._conf_non_lxc_uml(virt_type, guest, root_device_name, rescue,
instance, inst_path, image_meta, disk_info)
self._set_features(guest, instance.os_type, caps, virt_type)
self._set_clock(guest, instance.os_type, image_meta, virt_type)
storage_configs = self._get_guest_storage_config(
instance, image_meta, disk_info, rescue, block_device_info,
flavor, guest.os_type)
for config in storage_configs:
guest.add_device(config)
for vif in network_info:
config = self.vif_driver.get_config(
instance, vif, image_meta,
flavor, virt_type, self._host)
guest.add_device(config)
consolepty = self._create_consoles(virt_type, guest, instance, flavor,
image_meta, caps)
if virt_type != 'parallels':
consolepty.type = "pty"
guest.add_device(consolepty)
tablet = self._get_guest_usb_tablet(guest.os_type)
if tablet:
guest.add_device(tablet)
if (CONF.spice.enabled and CONF.spice.agent_enabled and
virt_type not in ('lxc', 'uml', 'xen')):
channel = vconfig.LibvirtConfigGuestChannel()
channel.target_name = "com.redhat.spice.0"
guest.add_device(channel)
# NB some versions of libvirt support both SPICE and VNC
# at the same time. We're not trying to second guess which
# those versions are. We'll just let libvirt report the
# errors appropriately if the user enables both.
add_video_driver = False
if ((CONF.vnc.enabled and
virt_type not in ('lxc', 'uml'))):
graphics = vconfig.LibvirtConfigGuestGraphics()
graphics.type = "vnc"
graphics.keymap = CONF.vnc.keymap
graphics.listen = CONF.vnc.vncserver_listen
guest.add_device(graphics)
add_video_driver = True
if (CONF.spice.enabled and
virt_type not in ('lxc', 'uml', 'xen')):
graphics = vconfig.LibvirtConfigGuestGraphics()
graphics.type = "spice"
graphics.keymap = CONF.spice.keymap
graphics.listen = CONF.spice.server_listen
guest.add_device(graphics)
add_video_driver = True
if add_video_driver:
self._add_video_driver(guest, image_meta, flavor)
# Qemu guest agent only support 'qemu' and 'kvm' hypervisor
if virt_type in ('qemu', 'kvm'):
self._set_qemu_guest_agent(guest, flavor, instance, image_meta)
if virt_type in ('xen', 'qemu', 'kvm'):
for pci_dev in pci_manager.get_instance_pci_devs(instance):
guest.add_device(self._get_guest_pci_device(pci_dev))
else:
if len(pci_devs) > 0:
raise exception.PciDeviceUnsupportedHypervisor(
type=virt_type)
if 'hw_watchdog_action' in flavor.extra_specs:
LOG.warn(_LW('Old property name "hw_watchdog_action" is now '
'deprecated and will be removed in the next release. '
'Use updated property name '
'"hw:watchdog_action" instead'), instance=instance)
# TODO(pkholkin): accepting old property name 'hw_watchdog_action'
# should be removed in the next release
watchdog_action = (flavor.extra_specs.get('hw_watchdog_action') or
flavor.extra_specs.get('hw:watchdog_action')
or 'disabled')
watchdog_action = image_meta.properties.get('hw_watchdog_action',
watchdog_action)
# NB(sross): currently only actually supported by KVM/QEmu
if watchdog_action != 'disabled':
if watchdog_actions.is_valid_watchdog_action(watchdog_action):
bark = vconfig.LibvirtConfigGuestWatchdog()
bark.action = watchdog_action
guest.add_device(bark)
else:
raise exception.InvalidWatchdogAction(action=watchdog_action)
# Memory balloon device only support 'qemu/kvm' and 'xen' hypervisor
if (virt_type in ('xen', 'qemu', 'kvm') and
CONF.libvirt.mem_stats_period_seconds > 0):
balloon = vconfig.LibvirtConfigMemoryBalloon()
if virt_type in ('qemu', 'kvm'):
balloon.model = 'virtio'
else:
balloon.model = 'xen'
balloon.period = CONF.libvirt.mem_stats_period_seconds
guest.add_device(balloon)
return guest
def _get_guest_usb_tablet(self, os_type):
# We want a tablet if VNC is enabled, or SPICE is enabled and
# the SPICE agent is disabled. If the SPICE agent is enabled
# it provides a paravirt mouse which drastically reduces
# overhead (by eliminating USB polling).
#
# NB: this implies that if both SPICE + VNC are enabled
# at the same time, we'll get the tablet whether the
# SPICE agent is used or not.
need_usb_tablet = False
if CONF.vnc.enabled:
need_usb_tablet = CONF.libvirt.use_usb_tablet
elif CONF.spice.enabled and not CONF.spice.agent_enabled:
need_usb_tablet = CONF.libvirt.use_usb_tablet
tablet = None
if need_usb_tablet and os_type == vm_mode.HVM:
tablet = vconfig.LibvirtConfigGuestInput()
tablet.type = "tablet"
tablet.bus = "usb"
return tablet
def _get_guest_xml(self, context, instance, network_info, disk_info,
image_meta, rescue=None,
block_device_info=None, write_to_disk=False):
# NOTE(danms): Stringifying a NetworkInfo will take a lock. Do
# this ahead of time so that we don't acquire it while also
# holding the logging lock.
network_info_str = str(network_info)
msg = ('Start _get_guest_xml '
'network_info=%(network_info)s '
'disk_info=%(disk_info)s '
'image_meta=%(image_meta)s rescue=%(rescue)s '
'block_device_info=%(block_device_info)s' %
{'network_info': network_info_str, 'disk_info': disk_info,
'image_meta': image_meta, 'rescue': rescue,
'block_device_info': block_device_info})
# NOTE(mriedem): block_device_info can contain auth_password so we
# need to sanitize the password in the message.
LOG.debug(strutils.mask_password(msg), instance=instance)
conf = self._get_guest_config(instance, network_info, image_meta,
disk_info, rescue, block_device_info,
context)
xml = conf.to_xml()
if write_to_disk:
instance_dir = libvirt_utils.get_instance_path(instance)
xml_path = os.path.join(instance_dir, 'libvirt.xml')
libvirt_utils.write_to_file(xml_path, xml)
LOG.debug('End _get_guest_xml xml=%(xml)s',
{'xml': xml}, instance=instance)
return xml
def get_info(self, instance):
"""Retrieve information from libvirt for a specific instance name.
If a libvirt error is encountered during lookup, we might raise a
NotFound exception or Error exception depending on how severe the
libvirt error is.
"""
guest = self._host.get_guest(instance)
# Kind of ugly but we need to pass host to get_info as for a
# workaround, see libvirt/compat.py
return guest.get_info(self._host)
def _create_domain_setup_lxc(self, instance, image_meta,
block_device_info, disk_info):
inst_path = libvirt_utils.get_instance_path(instance)
disk_info = disk_info or {}
disk_mapping = disk_info.get('mapping', {})
if self._is_booted_from_volume(instance, disk_mapping):
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
root_disk = block_device.get_root_bdm(block_device_mapping)
disk_info = blockinfo.get_info_from_bdm(
instance, CONF.libvirt.virt_type, image_meta, root_disk)
self._connect_volume(root_disk['connection_info'], disk_info)
disk_path = root_disk['connection_info']['data']['device_path']
# NOTE(apmelton) - Even though the instance is being booted from a
# cinder volume, it is still presented as a local block device.
# LocalBlockImage is used here to indicate that the instance's
# disk is backed by a local block device.
image_model = imgmodel.LocalBlockImage(disk_path)
else:
image = self.image_backend.image(instance, 'disk')
image_model = image.get_model(self._conn)
container_dir = os.path.join(inst_path, 'rootfs')
fileutils.ensure_tree(container_dir)
rootfs_dev = disk.setup_container(image_model,
container_dir=container_dir)
try:
# Save rootfs device to disconnect it when deleting the instance
if rootfs_dev:
instance.system_metadata['rootfs_device_name'] = rootfs_dev
if CONF.libvirt.uid_maps or CONF.libvirt.gid_maps:
id_maps = self._get_guest_idmaps()
libvirt_utils.chown_for_id_maps(container_dir, id_maps)
except Exception:
with excutils.save_and_reraise_exception():
self._create_domain_cleanup_lxc(instance)
def _create_domain_cleanup_lxc(self, instance):
inst_path = libvirt_utils.get_instance_path(instance)
container_dir = os.path.join(inst_path, 'rootfs')
try:
state = self.get_info(instance).state
except exception.InstanceNotFound:
# The domain may not be present if the instance failed to start
state = None
if state == power_state.RUNNING:
# NOTE(uni): Now the container is running with its own private
# mount namespace and so there is no need to keep the container
# rootfs mounted in the host namespace
LOG.debug('Attempting to unmount container filesystem: %s',
container_dir, instance=instance)
disk.clean_lxc_namespace(container_dir=container_dir)
else:
disk.teardown_container(container_dir=container_dir)
@contextlib.contextmanager
def _lxc_disk_handler(self, instance, image_meta,
block_device_info, disk_info):
"""Context manager to handle the pre and post instance boot,
LXC specific disk operations.
An image or a volume path will be prepared and setup to be
used by the container, prior to starting it.
The disk will be disconnected and unmounted if a container has
failed to start.
"""
if CONF.libvirt.virt_type != 'lxc':
yield
return
self._create_domain_setup_lxc(instance, image_meta,
block_device_info, disk_info)
try:
yield
finally:
self._create_domain_cleanup_lxc(instance)
# TODO(sahid): Consider renaming this to _create_guest.
def _create_domain(self, xml=None, domain=None,
power_on=True, pause=False):
"""Create a domain.
Either domain or xml must be passed in. If both are passed, then
the domain definition is overwritten from the xml.
:returns guest.Guest: Guest just created
"""
if xml:
guest = libvirt_guest.Guest.create(xml, self._host)
else:
guest = libvirt_guest.Guest(domain)
if power_on or pause:
guest.launch(pause=pause)
if not utils.is_neutron():
guest.enable_hairpin()
return guest
def _neutron_failed_callback(self, event_name, instance):
LOG.error(_LE('Neutron Reported failure on event '
'%(event)s for instance %(uuid)s'),
{'event': event_name, 'uuid': instance.uuid},
instance=instance)
if CONF.vif_plugging_is_fatal:
raise exception.VirtualInterfaceCreateException()
def _get_neutron_events(self, network_info):
# NOTE(danms): We need to collect any VIFs that are currently
# down that we expect a down->up event for. Anything that is
# already up will not undergo that transition, and for
# anything that might be stale (cache-wise) assume it's
# already up so we don't block on it.
return [('network-vif-plugged', vif['id'])
for vif in network_info if vif.get('active', True) is False]
def _create_domain_and_network(self, context, xml, instance, network_info,
disk_info, block_device_info=None,
power_on=True, reboot=False,
vifs_already_plugged=False):
"""Do required network setup and create domain."""
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
if (not reboot and 'data' in connection_info and
'volume_id' in connection_info['data']):
volume_id = connection_info['data']['volume_id']
encryption = encryptors.get_encryption_metadata(
context, self._volume_api, volume_id, connection_info)
if encryption:
encryptor = self._get_volume_encryptor(connection_info,
encryption)
encryptor.attach_volume(context, **encryption)
timeout = CONF.vif_plugging_timeout
if (self._conn_supports_start_paused and
utils.is_neutron() and not
vifs_already_plugged and power_on and timeout):
events = self._get_neutron_events(network_info)
else:
events = []
pause = bool(events)
guest = None
try:
with self.virtapi.wait_for_instance_event(
instance, events, deadline=timeout,
error_callback=self._neutron_failed_callback):
self.plug_vifs(instance, network_info)
self.firewall_driver.setup_basic_filtering(instance,
network_info)
self.firewall_driver.prepare_instance_filter(instance,
network_info)
with self._lxc_disk_handler(instance, instance.image_meta,
block_device_info, disk_info):
guest = self._create_domain(
xml, pause=pause, power_on=power_on)
self.firewall_driver.apply_instance_filter(instance,
network_info)
except exception.VirtualInterfaceCreateException:
# Neutron reported failure and we didn't swallow it, so
# bail here
with excutils.save_and_reraise_exception():
if guest:
guest.poweroff()
self.cleanup(context, instance, network_info=network_info,
block_device_info=block_device_info)
except eventlet.timeout.Timeout:
# We never heard from Neutron
LOG.warn(_LW('Timeout waiting for vif plugging callback for '
'instance %(uuid)s'), {'uuid': instance.uuid},
instance=instance)
if CONF.vif_plugging_is_fatal:
if guest:
guest.poweroff()
self.cleanup(context, instance, network_info=network_info,
block_device_info=block_device_info)
raise exception.VirtualInterfaceCreateException()
# Resume only if domain has been paused
if pause:
guest.resume()
return guest
def _get_vcpu_total(self):
"""Get available vcpu number of physical computer.
:returns: the number of cpu core instances can be used.
"""
try:
total_pcpus = self._host.get_cpu_count()
except libvirt.libvirtError:
LOG.warn(_LW("Cannot get the number of cpu, because this "
"function is not implemented for this platform. "))
return 0
if CONF.vcpu_pin_set is None:
return total_pcpus
available_ids = hardware.get_vcpu_pin_set()
# We get the list of online CPUs on the host and see if the requested
# set falls under these. If not, we retain the old behavior.
online_pcpus = None
try:
online_pcpus = self._host.get_online_cpus()
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
LOG.warn(_LW("Couldn't retrieve the online CPUs due to a Libvirt "
"error: %(error)s with error code: %(error_code)s"),
{'error': ex, 'error_code': error_code})
if online_pcpus:
if not (available_ids <= online_pcpus):
msg = (_("Invalid vcpu_pin_set config, one or more of the "
"specified cpuset is not online. Online cpuset(s): "
"%(online)s, requested cpuset(s): %(req)s"),
{'online': sorted(online_pcpus),
'req': sorted(available_ids)})
raise exception.Invalid(msg)
elif sorted(available_ids)[-1] >= total_pcpus:
raise exception.Invalid(_("Invalid vcpu_pin_set config, "
"out of hypervisor cpu range."))
return len(available_ids)
@staticmethod
def _get_local_gb_info():
"""Get local storage info of the compute node in GB.
:returns: A dict containing:
:total: How big the overall usable filesystem is (in gigabytes)
:free: How much space is free (in gigabytes)
:used: How much space is used (in gigabytes)
"""
if CONF.libvirt.images_type == 'lvm':
info = lvm.get_volume_group_info(
CONF.libvirt.images_volume_group)
elif CONF.libvirt.images_type == 'rbd':
info = LibvirtDriver._get_rbd_driver().get_pool_info()
else:
info = libvirt_utils.get_fs_info(CONF.instances_path)
for (k, v) in six.iteritems(info):
info[k] = v / units.Gi
return info
def _get_vcpu_used(self):
"""Get vcpu usage number of physical computer.
:returns: The total number of vcpu(s) that are currently being used.
"""
total = 0
if CONF.libvirt.virt_type == 'lxc':
return total + 1
for guest in self._host.list_guests():
try:
vcpus = guest.get_vcpus_info()
if vcpus is not None:
total += len(list(vcpus))
except libvirt.libvirtError as e:
LOG.warn(_LW("couldn't obtain the vcpu count from domain id:"
" %(uuid)s, exception: %(ex)s"),
{"uuid": guest.uuid, "ex": e})
# NOTE(gtt116): give other tasks a chance.
greenthread.sleep(0)
return total
def _get_instance_capabilities(self):
"""Get hypervisor instance capabilities
Returns a list of tuples that describe instances the
hypervisor is capable of hosting. Each tuple consists
of the triplet (arch, hypervisor_type, vm_mode).
:returns: List of tuples describing instance capabilities
"""
caps = self._host.get_capabilities()
instance_caps = list()
for g in caps.guests:
for dt in g.domtype:
instance_cap = (
arch.canonicalize(g.arch),
hv_type.canonicalize(dt),
vm_mode.canonicalize(g.ostype))
instance_caps.append(instance_cap)
return instance_caps
def _get_cpu_info(self):
"""Get cpuinfo information.
Obtains cpu feature from virConnect.getCapabilities.
:return: see above description
"""
caps = self._host.get_capabilities()
cpu_info = dict()
cpu_info['arch'] = caps.host.cpu.arch
cpu_info['model'] = caps.host.cpu.model
cpu_info['vendor'] = caps.host.cpu.vendor
topology = dict()
topology['cells'] = len(getattr(caps.host.topology, 'cells', [1]))
topology['sockets'] = caps.host.cpu.sockets
topology['cores'] = caps.host.cpu.cores
topology['threads'] = caps.host.cpu.threads
cpu_info['topology'] = topology
features = set()
for f in caps.host.cpu.features:
features.add(f.name)
cpu_info['features'] = features
return cpu_info
def _get_pcidev_info(self, devname):
"""Returns a dict of PCI device."""
def _get_device_type(cfgdev, pci_address):
"""Get a PCI device's device type.
An assignable PCI device can be a normal PCI device,
a SR-IOV Physical Function (PF), or a SR-IOV Virtual
Function (VF). Only normal PCI devices or SR-IOV VFs
are assignable, while SR-IOV PFs are always owned by
hypervisor.
"""
for fun_cap in cfgdev.pci_capability.fun_capability:
if fun_cap.type == 'virt_functions':
return {
'dev_type': fields.PciDeviceType.SRIOV_PF,
}
if (fun_cap.type == 'phys_function' and
len(fun_cap.device_addrs) != 0):
phys_address = "%04x:%02x:%02x.%01x" % (
fun_cap.device_addrs[0][0],
fun_cap.device_addrs[0][1],
fun_cap.device_addrs[0][2],
fun_cap.device_addrs[0][3])
return {
'dev_type': fields.PciDeviceType.SRIOV_VF,
'parent_addr': phys_address,
}
# Note(moshele): libvirt < 1.3 reported virt_functions capability
# only when VFs are enabled. The check below is a workaround
# to get the correct report regardless of whether or not any
# VFs are enabled for the device.
if not self._host.has_min_version(
MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION):
is_physical_function = pci_utils.is_physical_function(
*pci_utils.get_pci_address_fields(pci_address))
if is_physical_function:
return {'dev_type': fields.PciDeviceType.SRIOV_PF}
return {'dev_type': fields.PciDeviceType.STANDARD}
virtdev = self._host.device_lookup_by_name(devname)
xmlstr = virtdev.XMLDesc(0)
cfgdev = vconfig.LibvirtConfigNodeDevice()
cfgdev.parse_str(xmlstr)
address = "%04x:%02x:%02x.%1x" % (
cfgdev.pci_capability.domain,
cfgdev.pci_capability.bus,
cfgdev.pci_capability.slot,
cfgdev.pci_capability.function)
device = {
"dev_id": cfgdev.name,
"address": address,
"product_id": "%04x" % cfgdev.pci_capability.product_id,
"vendor_id": "%04x" % cfgdev.pci_capability.vendor_id,
}
device["numa_node"] = cfgdev.pci_capability.numa_node
# requirement by DataBase Model
device['label'] = 'label_%(vendor_id)s_%(product_id)s' % device
device.update(_get_device_type(cfgdev, address))
return device
def _get_pci_passthrough_devices(self):
"""Get host PCI devices information.
Obtains pci devices information from libvirt, and returns
as a JSON string.
Each device information is a dictionary, with mandatory keys
of 'address', 'vendor_id', 'product_id', 'dev_type', 'dev_id',
'label' and other optional device specific information.
Refer to the objects/pci_device.py for more idea of these keys.
:returns: a JSON string containaing a list of the assignable PCI
devices information
"""
# Bail early if we know we can't support `listDevices` to avoid
# repeated warnings within a periodic task
if not getattr(self, '_list_devices_supported', True):
return jsonutils.dumps([])
try:
dev_names = self._host.list_pci_devices() or []
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_NO_SUPPORT:
self._list_devices_supported = False
LOG.warn(_LW("URI %(uri)s does not support "
"listDevices: %(error)s"),
{'uri': self._uri(), 'error': ex})
return jsonutils.dumps([])
else:
raise
pci_info = []
for name in dev_names:
pci_info.append(self._get_pcidev_info(name))
return jsonutils.dumps(pci_info)
def _has_numa_support(self):
# This means that the host can support LibvirtConfigGuestNUMATune
# and the nodeset field in LibvirtConfigGuestMemoryBackingPage
for ver in BAD_LIBVIRT_NUMA_VERSIONS:
if self._host.has_version(ver):
if not getattr(self, '_bad_libvirt_numa_version_warn', False):
LOG.warn(_LW('You are running with libvirt version %s '
'which is known to have broken NUMA support. '
'Consider patching or updating libvirt on '
'this host if you need NUMA support.'),
self._version_to_string(ver))
self._bad_libvirt_numa_version_warn = True
return False
support_matrix = {(arch.I686, arch.X86_64): MIN_LIBVIRT_NUMA_VERSION,
(arch.PPC64,
arch.PPC64LE): MIN_LIBVIRT_NUMA_VERSION_PPC}
caps = self._host.get_capabilities()
is_supported = False
for archs, libvirt_ver in support_matrix.items():
if ((caps.host.cpu.arch in archs) and
self._host.has_min_version(libvirt_ver,
MIN_QEMU_NUMA_HUGEPAGE_VERSION,
host.HV_DRIVER_QEMU)):
is_supported = True
return is_supported
def _has_hugepage_support(self):
# This means that the host can support multiple values for the size
# field in LibvirtConfigGuestMemoryBackingPage
supported_archs = [arch.I686, arch.X86_64]
caps = self._host.get_capabilities()
return ((caps.host.cpu.arch in supported_archs) and
self._host.has_min_version(MIN_LIBVIRT_HUGEPAGE_VERSION,
MIN_QEMU_NUMA_HUGEPAGE_VERSION,
host.HV_DRIVER_QEMU))
def _get_host_numa_topology(self):
if not self._has_numa_support():
return
caps = self._host.get_capabilities()
topology = caps.host.topology
if topology is None or not topology.cells:
return
cells = []
allowed_cpus = hardware.get_vcpu_pin_set()
online_cpus = self._host.get_online_cpus()
if allowed_cpus:
allowed_cpus &= online_cpus
else:
allowed_cpus = online_cpus
for cell in topology.cells:
cpuset = set(cpu.id for cpu in cell.cpus)
siblings = sorted(map(set,
set(tuple(cpu.siblings)
if cpu.siblings else ()
for cpu in cell.cpus)
))
cpuset &= allowed_cpus
siblings = [sib & allowed_cpus for sib in siblings]
# Filter out singles and empty sibling sets that may be left
siblings = [sib for sib in siblings if len(sib) > 1]
mempages = []
if self._has_hugepage_support():
mempages = [
objects.NUMAPagesTopology(
size_kb=pages.size,
total=pages.total,
used=0)
for pages in cell.mempages]
cell = objects.NUMACell(id=cell.id, cpuset=cpuset,
memory=cell.memory / units.Ki,
cpu_usage=0, memory_usage=0,
siblings=siblings,
pinned_cpus=set([]),
mempages=mempages)
cells.append(cell)
return objects.NUMATopology(cells=cells)
def get_all_volume_usage(self, context, compute_host_bdms):
"""Return usage info for volumes attached to vms on
a given host.
"""
vol_usage = []
for instance_bdms in compute_host_bdms:
instance = instance_bdms['instance']
for bdm in instance_bdms['instance_bdms']:
mountpoint = bdm['device_name']
if mountpoint.startswith('/dev/'):
mountpoint = mountpoint[5:]
volume_id = bdm['volume_id']
LOG.debug("Trying to get stats for the volume %s",
volume_id, instance=instance)
vol_stats = self.block_stats(instance, mountpoint)
if vol_stats:
stats = dict(volume=volume_id,
instance=instance,
rd_req=vol_stats[0],
rd_bytes=vol_stats[1],
wr_req=vol_stats[2],
wr_bytes=vol_stats[3])
LOG.debug(
"Got volume usage stats for the volume=%(volume)s,"
" rd_req=%(rd_req)d, rd_bytes=%(rd_bytes)d, "
"wr_req=%(wr_req)d, wr_bytes=%(wr_bytes)d",
stats, instance=instance)
vol_usage.append(stats)
return vol_usage
def block_stats(self, instance, disk_id):
"""Note that this function takes an instance name."""
try:
guest = self._host.get_guest(instance)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove domain at the end.
domain = guest._domain
return domain.blockStats(disk_id)
except libvirt.libvirtError as e:
errcode = e.get_error_code()
LOG.info(_LI('Getting block stats failed, device might have '
'been detached. Instance=%(instance_name)s '
'Disk=%(disk)s Code=%(errcode)s Error=%(e)s'),
{'instance_name': instance.name, 'disk': disk_id,
'errcode': errcode, 'e': e},
instance=instance)
except exception.InstanceNotFound:
LOG.info(_LI('Could not find domain in libvirt for instance %s. '
'Cannot get block stats for device'), instance.name,
instance=instance)
def get_console_pool_info(self, console_type):
# TODO(mdragon): console proxy should be implemented for libvirt,
# in case someone wants to use it with kvm or
# such. For now return fake data.
return {'address': '127.0.0.1',
'username': 'fakeuser',
'password': 'fakepassword'}
def refresh_security_group_rules(self, security_group_id):
self.firewall_driver.refresh_security_group_rules(security_group_id)
def refresh_instance_security_rules(self, instance):
self.firewall_driver.refresh_instance_security_rules(instance)
def get_available_resource(self, nodename):
"""Retrieve resource information.
This method is called when nova-compute launches, and
as part of a periodic task that records the results in the DB.
:param nodename: unused in this driver
:returns: dictionary containing resource info
"""
disk_info_dict = self._get_local_gb_info()
data = {}
# NOTE(dprince): calling capabilities before getVersion works around
# an initialization issue with some versions of Libvirt (1.0.5.5).
# See: https://bugzilla.redhat.com/show_bug.cgi?id=1000116
# See: https://bugs.launchpad.net/nova/+bug/1215593
data["supported_instances"] = self._get_instance_capabilities()
data["vcpus"] = self._get_vcpu_total()
data["memory_mb"] = self._host.get_memory_mb_total()
data["local_gb"] = disk_info_dict['total']
data["vcpus_used"] = self._get_vcpu_used()
data["memory_mb_used"] = self._host.get_memory_mb_used()
data["local_gb_used"] = disk_info_dict['used']
data["hypervisor_type"] = self._host.get_driver_type()
data["hypervisor_version"] = self._host.get_version()
data["hypervisor_hostname"] = self._host.get_hostname()
# TODO(berrange): why do we bother converting the
# libvirt capabilities XML into a special JSON format ?
# The data format is different across all the drivers
# so we could just return the raw capabilities XML
# which 'compare_cpu' could use directly
#
# That said, arch_filter.py now seems to rely on
# the libvirt drivers format which suggests this
# data format needs to be standardized across drivers
data["cpu_info"] = jsonutils.dumps(self._get_cpu_info())
disk_free_gb = disk_info_dict['free']
disk_over_committed = self._get_disk_over_committed_size_total()
available_least = disk_free_gb * units.Gi - disk_over_committed
data['disk_available_least'] = available_least / units.Gi
data['pci_passthrough_devices'] = \
self._get_pci_passthrough_devices()
numa_topology = self._get_host_numa_topology()
if numa_topology:
data['numa_topology'] = numa_topology._to_json()
else:
data['numa_topology'] = None
return data
def check_instance_shared_storage_local(self, context, instance):
"""Check if instance files located on shared storage.
This runs check on the destination host, and then calls
back to the source host to check the results.
:param context: security context
:param instance: nova.objects.instance.Instance object
:returns:
- tempfile: A dict containing the tempfile info on the destination
host
- None:
1. If the instance path is not existing.
2. If the image backend is shared block storage type.
"""
if self.image_backend.backend().is_shared_block_storage():
return None
dirpath = libvirt_utils.get_instance_path(instance)
if not os.path.exists(dirpath):
return None
fd, tmp_file = tempfile.mkstemp(dir=dirpath)
LOG.debug("Creating tmpfile %s to verify with other "
"compute node that the instance is on "
"the same shared storage.",
tmp_file, instance=instance)
os.close(fd)
return {"filename": tmp_file}
def check_instance_shared_storage_remote(self, context, data):
return os.path.exists(data['filename'])
def check_instance_shared_storage_cleanup(self, context, data):
fileutils.delete_if_exists(data["filename"])
def check_can_live_migrate_destination(self, context, instance,
src_compute_info, dst_compute_info,
block_migration=False,
disk_over_commit=False):
"""Check if it is possible to execute live migration.
This runs checks on the destination host, and then calls
back to the source host to check the results.
:param context: security context
:param instance: nova.db.sqlalchemy.models.Instance
:param block_migration: if true, prepare for block migration
:param disk_over_commit: if true, allow disk over commit
:returns: a LibvirtLiveMigrateData object
"""
disk_available_gb = dst_compute_info['disk_available_least']
disk_available_mb = (
(disk_available_gb * units.Ki) - CONF.reserved_host_disk_mb)
# Compare CPU
if not instance.vcpu_model or not instance.vcpu_model.model:
source_cpu_info = src_compute_info['cpu_info']
self._compare_cpu(None, source_cpu_info)
else:
self._compare_cpu(instance.vcpu_model, None)
# Create file on storage, to be checked on source host
filename = self._create_shared_storage_test_file()
data = objects.LibvirtLiveMigrateData()
data.filename = filename
data.image_type = CONF.libvirt.images_type
# Notes(eliqiao): block_migration and disk_over_commit are not
# nullable, so just don't set them if they are None
if block_migration is not None:
data.block_migration = block_migration
if disk_over_commit is not None:
data.disk_over_commit = disk_over_commit
data.disk_available_mb = disk_available_mb
return data
def check_can_live_migrate_destination_cleanup(self, context,
dest_check_data):
"""Do required cleanup on dest host after check_can_live_migrate calls
:param context: security context
"""
filename = dest_check_data.filename
self._cleanup_shared_storage_test_file(filename)
def check_can_live_migrate_source(self, context, instance,
dest_check_data,
block_device_info=None):
"""Check if it is possible to execute live migration.
This checks if the live migration can succeed, based on the
results from check_can_live_migrate_destination.
:param context: security context
:param instance: nova.db.sqlalchemy.models.Instance
:param dest_check_data: result of check_can_live_migrate_destination
:param block_device_info: result of _get_instance_block_device_info
:returns: a LibvirtLiveMigrateData object
"""
# Checking shared storage connectivity
# if block migration, instances_paths should not be on shared storage.
source = CONF.host
if not isinstance(dest_check_data, migrate_data_obj.LiveMigrateData):
md_obj = objects.LibvirtLiveMigrateData()
md_obj.from_legacy_dict(dest_check_data)
dest_check_data = md_obj
dest_check_data.is_shared_instance_path = (
self._check_shared_storage_test_file(
dest_check_data.filename))
dest_check_data.is_shared_block_storage = (
self._is_shared_block_storage(instance, dest_check_data,
block_device_info))
disk_info_text = self.get_instance_disk_info(
instance, block_device_info=block_device_info)
booted_from_volume = self._is_booted_from_volume(instance,
disk_info_text)
has_local_disk = self._has_local_disk(instance, disk_info_text)
if 'block_migration' not in dest_check_data:
dest_check_data.block_migration = (
not dest_check_data.is_on_shared_storage())
if dest_check_data.block_migration:
# TODO(eliqiao): Once block_migration flag is removed from the API
# we can safely remove the if condition
if dest_check_data.is_on_shared_storage():
reason = _("Block migration can not be used "
"with shared storage.")
raise exception.InvalidLocalStorage(reason=reason, path=source)
if 'disk_over_commit' in dest_check_data:
self._assert_dest_node_has_enough_disk(context, instance,
dest_check_data.disk_available_mb,
dest_check_data.disk_over_commit,
block_device_info)
if block_device_info:
bdm = block_device_info.get('block_device_mapping')
# NOTE(pkoniszewski): libvirt from version 1.2.17 upwards
# supports selective block device migration. It means that it
# is possible to define subset of block devices to be copied
# during migration. If they are not specified - block devices
# won't be migrated. However, it does not work when live
# migration is tunnelled through libvirt.
if bdm and not self._host.has_min_version(
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION):
# NOTE(stpierre): if this instance has mapped volumes,
# we can't do a block migration, since that will result
# in volumes being copied from themselves to themselves,
# which is a recipe for disaster.
ver = ".".join([str(x) for x in
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION])
msg = (_('Cannot block migrate instance %(uuid)s with'
' mapped volumes. Selective block device'
' migration feature requires libvirt version'
' %(libvirt_ver)s') %
{'uuid': instance.uuid, 'libvirt_ver': ver})
LOG.error(msg, instance=instance)
raise exception.MigrationPreCheckError(reason=msg)
elif not (dest_check_data.is_shared_block_storage or
dest_check_data.is_shared_instance_path or
(booted_from_volume and not has_local_disk)):
reason = _("Live migration can not be used "
"without shared storage except "
"a booted from volume VM which "
"does not have a local disk.")
raise exception.InvalidSharedStorage(reason=reason, path=source)
# NOTE(mikal): include the instance directory name here because it
# doesn't yet exist on the destination but we want to force that
# same name to be used
instance_path = libvirt_utils.get_instance_path(instance,
relative=True)
dest_check_data.instance_relative_path = instance_path
return dest_check_data
def _is_shared_block_storage(self, instance, dest_check_data,
block_device_info=None):
"""Check if all block storage of an instance can be shared
between source and destination of a live migration.
Returns true if the instance is volume backed and has no local disks,
or if the image backend is the same on source and destination and the
backend shares block storage between compute nodes.
:param instance: nova.objects.instance.Instance object
:param dest_check_data: dict with boolean fields image_type,
is_shared_instance_path, and is_volume_backed
"""
if (dest_check_data.obj_attr_is_set('image_type') and
CONF.libvirt.images_type == dest_check_data.image_type and
self.image_backend.backend().is_shared_block_storage()):
# NOTE(dgenin): currently true only for RBD image backend
return True
if (dest_check_data.is_shared_instance_path and
self.image_backend.backend().is_file_in_instance_path()):
# NOTE(angdraug): file based image backends (Raw, Qcow2)
# place block device files under the instance path
return True
if (dest_check_data.is_volume_backed and
not bool(jsonutils.loads(
self.get_instance_disk_info(instance,
block_device_info)))):
return True
return False
def _assert_dest_node_has_enough_disk(self, context, instance,
available_mb, disk_over_commit,
block_device_info=None):
"""Checks if destination has enough disk for block migration."""
# Libvirt supports qcow2 disk format,which is usually compressed
# on compute nodes.
# Real disk image (compressed) may enlarged to "virtual disk size",
# that is specified as the maximum disk size.
# (See qemu-img -f path-to-disk)
# Scheduler recognizes destination host still has enough disk space
# if real disk size < available disk size
# if disk_over_commit is True,
# otherwise virtual disk size < available disk size.
available = 0
if available_mb:
available = available_mb * units.Mi
ret = self.get_instance_disk_info(instance,
block_device_info=block_device_info)
disk_infos = jsonutils.loads(ret)
necessary = 0
if disk_over_commit:
for info in disk_infos:
necessary += int(info['disk_size'])
else:
for info in disk_infos:
necessary += int(info['virt_disk_size'])
# Check that available disk > necessary disk
if (available - necessary) < 0:
reason = (_('Unable to migrate %(instance_uuid)s: '
'Disk of instance is too large(available'
' on destination host:%(available)s '
'< need:%(necessary)s)') %
{'instance_uuid': instance.uuid,
'available': available,
'necessary': necessary})
raise exception.MigrationPreCheckError(reason=reason)
def _compare_cpu(self, guest_cpu, host_cpu_str):
"""Check the host is compatible with the requested CPU
:param guest_cpu: nova.objects.VirtCPUModel or None
:param host_cpu_str: JSON from _get_cpu_info() method
If the 'guest_cpu' parameter is not None, this will be
validated for migration compatibility with the host.
Otherwise the 'host_cpu_str' JSON string will be used for
validation.
:returns:
None. if given cpu info is not compatible to this server,
raise exception.
"""
# NOTE(berendt): virConnectCompareCPU not working for Xen
if CONF.libvirt.virt_type not in ['qemu', 'kvm']:
return
if guest_cpu is None:
info = jsonutils.loads(host_cpu_str)
LOG.info(_LI('Instance launched has CPU info: %s'), host_cpu_str)
cpu = vconfig.LibvirtConfigCPU()
cpu.arch = info['arch']
cpu.model = info['model']
cpu.vendor = info['vendor']
cpu.sockets = info['topology']['sockets']
cpu.cores = info['topology']['cores']
cpu.threads = info['topology']['threads']
for f in info['features']:
cpu.add_feature(vconfig.LibvirtConfigCPUFeature(f))
else:
cpu = self._vcpu_model_to_cpu_config(guest_cpu)
u = ("http://libvirt.org/html/libvirt-libvirt-host.html#"
"virCPUCompareResult")
m = _("CPU doesn't have compatibility.\n\n%(ret)s\n\nRefer to %(u)s")
# unknown character exists in xml, then libvirt complains
try:
ret = self._host.compare_cpu(cpu.to_xml())
except libvirt.libvirtError as e:
error_code = e.get_error_code()
if error_code == libvirt.VIR_ERR_NO_SUPPORT:
LOG.debug("URI %(uri)s does not support cpu comparison. "
"It will be proceeded though. Error: %(error)s",
{'uri': self._uri(), 'error': e})
return
else:
LOG.error(m, {'ret': e, 'u': u})
raise exception.MigrationPreCheckError(
reason=m % {'ret': e, 'u': u})
if ret <= 0:
LOG.error(m, {'ret': ret, 'u': u})
raise exception.InvalidCPUInfo(reason=m % {'ret': ret, 'u': u})
def _create_shared_storage_test_file(self):
"""Makes tmpfile under CONF.instances_path."""
dirpath = CONF.instances_path
fd, tmp_file = tempfile.mkstemp(dir=dirpath)
LOG.debug("Creating tmpfile %s to notify to other "
"compute nodes that they should mount "
"the same storage.", tmp_file)
os.close(fd)
return os.path.basename(tmp_file)
def _check_shared_storage_test_file(self, filename):
"""Confirms existence of the tmpfile under CONF.instances_path.
Cannot confirm tmpfile return False.
"""
tmp_file = os.path.join(CONF.instances_path, filename)
if not os.path.exists(tmp_file):
return False
else:
return True
def _cleanup_shared_storage_test_file(self, filename):
"""Removes existence of the tmpfile under CONF.instances_path."""
tmp_file = os.path.join(CONF.instances_path, filename)
os.remove(tmp_file)
def ensure_filtering_rules_for_instance(self, instance, network_info):
"""Ensure that an instance's filtering rules are enabled.
When migrating an instance, we need the filtering rules to
be configured on the destination host before starting the
migration.
Also, when restarting the compute service, we need to ensure
that filtering rules exist for all running services.
"""
self.firewall_driver.setup_basic_filtering(instance, network_info)
self.firewall_driver.prepare_instance_filter(instance,
network_info)
# nwfilters may be defined in a separate thread in the case
# of libvirt non-blocking mode, so we wait for completion
timeout_count = list(range(CONF.live_migration_retry_count))
while timeout_count:
if self.firewall_driver.instance_filter_exists(instance,
network_info):
break
timeout_count.pop()
if len(timeout_count) == 0:
msg = _('The firewall filter for %s does not exist')
raise exception.NovaException(msg % instance.name)
greenthread.sleep(1)
def filter_defer_apply_on(self):
self.firewall_driver.filter_defer_apply_on()
def filter_defer_apply_off(self):
self.firewall_driver.filter_defer_apply_off()
def live_migration(self, context, instance, dest,
post_method, recover_method, block_migration=False,
migrate_data=None):
"""Spawning live_migration operation for distributing high-load.
:param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param dest: destination host
:param post_method:
post operation method.
expected nova.compute.manager._post_live_migration.
:param recover_method:
recovery method when any exception occurs.
expected nova.compute.manager._rollback_live_migration.
:param block_migration: if true, do block migration.
:param migrate_data: a LibvirtLiveMigrateData object
"""
# 'dest' will be substituted into 'migration_uri' so ensure
# it does't contain any characters that could be used to
# exploit the URI accepted by libivrt
if not libvirt_utils.is_valid_hostname(dest):
raise exception.InvalidHostname(hostname=dest)
self._live_migration(context, instance, dest,
post_method, recover_method, block_migration,
migrate_data)
def live_migration_abort(self, instance):
"""Aborting a running live-migration.
:param instance: instance object that is in migration
"""
guest = self._host.get_guest(instance)
dom = guest._domain
try:
dom.abortJob()
except libvirt.libvirtError as e:
LOG.error(_LE("Failed to cancel migration %s"),
e, instance=instance)
raise
def _update_xml(self, xml_str, migrate_bdm_info, listen_addrs,
serial_listen_addr):
xml_doc = etree.fromstring(xml_str)
if migrate_bdm_info:
xml_doc = self._update_volume_xml(xml_doc, migrate_bdm_info)
if listen_addrs:
xml_doc = self._update_graphics_xml(xml_doc, listen_addrs)
else:
self._check_graphics_addresses_can_live_migrate(listen_addrs)
if serial_listen_addr:
xml_doc = self._update_serial_xml(xml_doc, serial_listen_addr)
else:
self._verify_serial_console_is_disabled()
return etree.tostring(xml_doc)
def _update_graphics_xml(self, xml_doc, listen_addrs):
# change over listen addresses
for dev in xml_doc.findall('./devices/graphics'):
gr_type = dev.get('type')
listen_tag = dev.find('listen')
if gr_type in ('vnc', 'spice'):
if listen_tag is not None:
listen_tag.set('address', listen_addrs[gr_type])
if dev.get('listen') is not None:
dev.set('listen', listen_addrs[gr_type])
return xml_doc
def _update_volume_xml(self, xml_doc, migrate_bdm_info):
"""Update XML using device information of destination host."""
# Update volume xml
parser = etree.XMLParser(remove_blank_text=True)
disk_nodes = xml_doc.findall('./devices/disk')
bdm_info_by_serial = {x.serial: x for x in migrate_bdm_info}
for pos, disk_dev in enumerate(disk_nodes):
serial_source = disk_dev.findtext('serial')
bdm_info = bdm_info_by_serial.get(serial_source)
if (serial_source is None or
not bdm_info or not bdm_info.connection_info or
serial_source not in bdm_info_by_serial):
continue
conf = self._get_volume_config(
bdm_info.connection_info, bdm_info.as_disk_info())
xml_doc2 = etree.XML(conf.to_xml(), parser)
serial_dest = xml_doc2.findtext('serial')
# Compare source serial and destination serial number.
# If these serial numbers match, continue the process.
if (serial_dest and (serial_source == serial_dest)):
LOG.debug("Find same serial number: pos=%(pos)s, "
"serial=%(num)s",
{'pos': pos, 'num': serial_source})
for cnt, item_src in enumerate(disk_dev):
# If source and destination have same item, update
# the item using destination value.
for item_dst in xml_doc2.findall(item_src.tag):
disk_dev.remove(item_src)
item_dst.tail = None
disk_dev.insert(cnt, item_dst)
# If destination has additional items, thses items should be
# added here.
for item_dst in list(xml_doc2):
item_dst.tail = None
disk_dev.insert(cnt, item_dst)
return xml_doc
def _update_serial_xml(self, xml_doc, listen_addr):
for dev in xml_doc.findall("./devices/serial[@type='tcp']/source"):
if dev.get('host') is not None:
dev.set('host', listen_addr)
for dev in xml_doc.findall("./devices/console[@type='tcp']/source"):
if dev.get('host') is not None:
dev.set('host', listen_addr)
return xml_doc
def _check_graphics_addresses_can_live_migrate(self, listen_addrs):
LOCAL_ADDRS = ('0.0.0.0', '127.0.0.1', '::', '::1')
local_vnc = CONF.vnc.vncserver_listen in LOCAL_ADDRS
local_spice = CONF.spice.server_listen in LOCAL_ADDRS
if ((CONF.vnc.enabled and not local_vnc) or
(CONF.spice.enabled and not local_spice)):
msg = _('Your libvirt version does not support the'
' VIR_DOMAIN_XML_MIGRATABLE flag or your'
' destination node does not support'
' retrieving listen addresses. In order'
' for live migration to work properly, you'
' must configure the graphics (VNC and/or'
' SPICE) listen addresses to be either'
' the catch-all address (0.0.0.0 or ::) or'
' the local address (127.0.0.1 or ::1).')
raise exception.MigrationError(reason=msg)
if listen_addrs:
dest_local_vnc = listen_addrs.get('vnc') in LOCAL_ADDRS
dest_local_spice = listen_addrs.get('spice') in LOCAL_ADDRS
if ((CONF.vnc.enabled and not dest_local_vnc) or
(CONF.spice.enabled and not dest_local_spice)):
LOG.warn(_LW('Your libvirt version does not support the'
' VIR_DOMAIN_XML_MIGRATABLE flag, and the'
' graphics (VNC and/or SPICE) listen'
' addresses on the destination node do not'
' match the addresses on the source node.'
' Since the source node has listen'
' addresses set to either the catch-all'
' address (0.0.0.0 or ::) or the local'
' address (127.0.0.1 or ::1), the live'
' migration will succeed, but the VM will'
' continue to listen on the current'
' addresses.'))
def _verify_serial_console_is_disabled(self):
if CONF.serial_console.enabled:
msg = _('Your libvirt version does not support the'
' VIR_DOMAIN_XML_MIGRATABLE flag or your'
' destination node does not support'
' retrieving listen addresses. In order'
' for live migration to work properly you'
' must either disable serial console or'
' upgrade your libvirt version.')
raise exception.MigrationError(reason=msg)
def _live_migration_operation(self, context, instance, dest,
block_migration, migrate_data, dom,
device_names):
"""Invoke the live migration operation
:param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param dest: destination host
:param block_migration: if true, do block migration.
:param migrate_data: a LibvirtLiveMigrateData object
:param dom: the libvirt domain object
:param device_names: list of device names that are being migrated with
instance
This method is intended to be run in a background thread and will
block that thread until the migration is finished or failed.
"""
# TODO(sahid): Should pass a guest to this method.
guest = libvirt_guest.Guest(dom)
try:
if migrate_data.block_migration:
migration_flags = self._block_migration_flags
else:
migration_flags = self._live_migration_flags
listen_addrs = {}
if 'graphics_listen_addr_vnc' in migrate_data:
listen_addrs['vnc'] = str(
migrate_data.graphics_listen_addr_vnc)
if 'graphics_listen_addr_spice' in migrate_data:
listen_addrs['spice'] = str(
migrate_data.graphics_listen_addr_spice)
serial_listen_addr = (migrate_data.serial_listen_addr if
'serial_listen_addr' in migrate_data else None)
if ('target_connect_addr' in migrate_data and
migrate_data.target_connect_addr is not None):
dest = migrate_data.target_connect_addr
migratable_flag = getattr(libvirt, 'VIR_DOMAIN_XML_MIGRATABLE',
None)
if (migratable_flag is None or (
not listen_addrs and not migrate_data.bdms)):
# TODO(alexs-h): These checks could be moved to the
# check_can_live_migrate_destination/source phase
self._check_graphics_addresses_can_live_migrate(listen_addrs)
self._verify_serial_console_is_disabled()
dom.migrateToURI(self._live_migration_uri(dest),
migration_flags,
None,
CONF.libvirt.live_migration_bandwidth)
else:
old_xml_str = guest.get_xml_desc(dump_migratable=True)
new_xml_str = self._update_xml(old_xml_str,
migrate_data.bdms,
listen_addrs,
serial_listen_addr)
try:
if self._host.has_min_version(
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION):
params = {
'bandwidth': CONF.libvirt.live_migration_bandwidth,
'destination_xml': new_xml_str,
'migrate_disks': device_names,
}
dom.migrateToURI3(
self._live_migration_uri(dest),
params,
migration_flags)
else:
dom.migrateToURI2(
self._live_migration_uri(dest),
None,
new_xml_str,
migration_flags,
None,
CONF.libvirt.live_migration_bandwidth)
except libvirt.libvirtError as ex:
# NOTE(mriedem): There is a bug in older versions of
# libvirt where the VIR_DOMAIN_XML_MIGRATABLE flag causes
# virDomainDefCheckABIStability to not compare the source
# and target domain xml's correctly for the CPU model.
# We try to handle that error here and attempt the legacy
# migrateToURI path, which could fail if the console
# addresses are not correct, but in that case we have the
# _check_graphics_addresses_can_live_migrate check in place
# to catch it.
# TODO(mriedem): Remove this workaround when
# Red Hat BZ #1141838 is closed.
error_code = ex.get_error_code()
if error_code == libvirt.VIR_ERR_CONFIG_UNSUPPORTED:
LOG.warn(_LW('An error occurred trying to live '
'migrate. Falling back to legacy live '
'migrate flow. Error: %s'), ex,
instance=instance)
self._check_graphics_addresses_can_live_migrate(
listen_addrs)
self._verify_serial_console_is_disabled()
dom.migrateToURI(
self._live_migration_uri(dest),
migration_flags,
None,
CONF.libvirt.live_migration_bandwidth)
else:
raise
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Live Migration failure: %s"), e,
instance=instance)
# If 'migrateToURI' fails we don't know what state the
# VM instances on each host are in. Possibilities include
#
# 1. src==running, dst==none
#
# Migration failed & rolled back, or never started
#
# 2. src==running, dst==paused
#
# Migration started but is still ongoing
#
# 3. src==paused, dst==paused
#
# Migration data transfer completed, but switchover
# is still ongoing, or failed
#
# 4. src==paused, dst==running
#
# Migration data transfer completed, switchover
# happened but cleanup on source failed
#
# 5. src==none, dst==running
#
# Migration fully succeeded.
#
# Libvirt will aim to complete any migration operation
# or roll it back. So even if the migrateToURI call has
# returned an error, if the migration was not finished
# libvirt should clean up.
#
# So we take the error raise here with a pinch of salt
# and rely on the domain job info status to figure out
# what really happened to the VM, which is a much more
# reliable indicator.
#
# In particular we need to try very hard to ensure that
# Nova does not "forget" about the guest. ie leaving it
# running on a different host to the one recorded in
# the database, as that would be a serious resource leak
LOG.debug("Migration operation thread has finished",
instance=instance)
@staticmethod
def _migration_downtime_steps(data_gb):
'''Calculate downtime value steps and time between increases.
:param data_gb: total GB of RAM and disk to transfer
This looks at the total downtime steps and upper bound
downtime value and uses an exponential backoff. So initially
max downtime is increased by small amounts, and as time goes
by it is increased by ever larger amounts
For example, with 10 steps, 30 second step delay, 3 GB
of RAM and 400ms target maximum downtime, the downtime will
be increased every 90 seconds in the following progression:
- 0 seconds -> set downtime to 37ms
- 90 seconds -> set downtime to 38ms
- 180 seconds -> set downtime to 39ms
- 270 seconds -> set downtime to 42ms
- 360 seconds -> set downtime to 46ms
- 450 seconds -> set downtime to 55ms
- 540 seconds -> set downtime to 70ms
- 630 seconds -> set downtime to 98ms
- 720 seconds -> set downtime to 148ms
- 810 seconds -> set downtime to 238ms
- 900 seconds -> set downtime to 400ms
This allows the guest a good chance to complete migration
with a small downtime value.
'''
downtime = CONF.libvirt.live_migration_downtime
steps = CONF.libvirt.live_migration_downtime_steps
delay = CONF.libvirt.live_migration_downtime_delay
if downtime < LIVE_MIGRATION_DOWNTIME_MIN:
downtime = LIVE_MIGRATION_DOWNTIME_MIN
if steps < LIVE_MIGRATION_DOWNTIME_STEPS_MIN:
steps = LIVE_MIGRATION_DOWNTIME_STEPS_MIN
if delay < LIVE_MIGRATION_DOWNTIME_DELAY_MIN:
delay = LIVE_MIGRATION_DOWNTIME_DELAY_MIN
delay = int(delay * data_gb)
offset = downtime / float(steps + 1)
base = (downtime - offset) ** (1 / float(steps))
for i in range(steps + 1):
yield (int(delay * i), int(offset + base ** i))
def _live_migration_copy_disk_paths(self, context, instance, guest):
'''Get list of disks to copy during migration
:param context: security context
:param instance: the instance being migrated
:param guest: the Guest instance being migrated
Get the list of disks to copy during migration.
:returns: a list of local source paths and a list of device names to
copy
'''
disk_paths = []
device_names = []
block_devices = []
# TODO(pkoniszewski): Remove this if-statement when we bump min libvirt
# version to >= 1.2.17
if self._host.has_min_version(
MIN_LIBVIRT_BLOCK_LM_WITH_VOLUMES_VERSION):
bdm_list = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, instance.uuid)
block_device_info = driver.get_block_device_info(instance,
bdm_list)
block_device_mappings = driver.block_device_info_get_mapping(
block_device_info)
for bdm in block_device_mappings:
device_name = str(bdm['mount_device'].rsplit('/', 1)[1])
block_devices.append(device_name)
for dev in guest.get_all_disks():
if dev.readonly or dev.shareable:
continue
if dev.source_type not in ["file", "block"]:
continue
if dev.target_dev in block_devices:
continue
disk_paths.append(dev.source_path)
device_names.append(dev.target_dev)
return (disk_paths, device_names)
def _live_migration_data_gb(self, instance, disk_paths):
'''Calculate total amount of data to be transferred
:param instance: the nova.objects.Instance being migrated
:param disk_paths: list of disk paths that are being migrated
with instance
Calculates the total amount of data that needs to be
transferred during the live migration. The actual
amount copied will be larger than this, due to the
guest OS continuing to dirty RAM while the migration
is taking place. So this value represents the minimal
data size possible.
:returns: data size to be copied in GB
'''
ram_gb = instance.flavor.memory_mb * units.Mi / units.Gi
if ram_gb < 2:
ram_gb = 2
disk_gb = 0
for path in disk_paths:
try:
size = os.stat(path).st_size
size_gb = (size / units.Gi)
if size_gb < 2:
size_gb = 2
disk_gb += size_gb
except OSError as e:
LOG.warn(_LW("Unable to stat %(disk)s: %(ex)s"),
{'disk': path, 'ex': e})
# Ignore error since we don't want to break
# the migration monitoring thread operation
return ram_gb + disk_gb
def _live_migration_monitor(self, context, instance, guest,
dest, post_method,
recover_method, block_migration,
migrate_data, dom, finish_event,
disk_paths):
data_gb = self._live_migration_data_gb(instance, disk_paths)
downtime_steps = list(self._migration_downtime_steps(data_gb))
completion_timeout = int(
CONF.libvirt.live_migration_completion_timeout * data_gb)
progress_timeout = CONF.libvirt.live_migration_progress_timeout
migration = migrate_data.migration
n = 0
start = time.time()
progress_time = start
progress_watermark = None
while True:
info = host.DomainJobInfo.for_domain(dom)
if info.type == libvirt.VIR_DOMAIN_JOB_NONE:
# Annoyingly this could indicate many possible
# states, so we must fix the mess:
#
# 1. Migration has not yet begun
# 2. Migration has stopped due to failure
# 3. Migration has stopped due to completion
#
# We can detect option 1 by seeing if thread is still
# running. We can distinguish 2 vs 3 by seeing if the
# VM still exists & running on the current host
#
if not finish_event.ready():
LOG.debug("Operation thread is still running",
instance=instance)
# Leave type untouched
else:
try:
if guest.is_active():
LOG.debug("VM running on src, migration failed",
instance=instance)
info.type = libvirt.VIR_DOMAIN_JOB_FAILED
else:
LOG.debug("VM is shutoff, migration finished",
instance=instance)
info.type = libvirt.VIR_DOMAIN_JOB_COMPLETED
except libvirt.libvirtError as ex:
LOG.debug("Error checking domain status %(ex)s",
ex, instance=instance)
if ex.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
LOG.debug("VM is missing, migration finished",
instance=instance)
info.type = libvirt.VIR_DOMAIN_JOB_COMPLETED
else:
LOG.info(_LI("Error %(ex)s, migration failed"),
instance=instance)
info.type = libvirt.VIR_DOMAIN_JOB_FAILED
if info.type != libvirt.VIR_DOMAIN_JOB_NONE:
LOG.debug("Fixed incorrect job type to be %d",
info.type, instance=instance)
if info.type == libvirt.VIR_DOMAIN_JOB_NONE:
# Migration is not yet started
LOG.debug("Migration not running yet",
instance=instance)
elif info.type == libvirt.VIR_DOMAIN_JOB_UNBOUNDED:
# Migration is still running
#
# This is where we wire up calls to change live
# migration status. eg change max downtime, cancel
# the operation, change max bandwidth
now = time.time()
elapsed = now - start
abort = False
if ((progress_watermark is None) or
(progress_watermark > info.data_remaining)):
progress_watermark = info.data_remaining
progress_time = now
if (progress_timeout != 0 and
(now - progress_time) > progress_timeout):
LOG.warn(_LW("Live migration stuck for %d sec"),
(now - progress_time), instance=instance)
abort = True
if (completion_timeout != 0 and
elapsed > completion_timeout):
LOG.warn(_LW("Live migration not completed after %d sec"),
completion_timeout, instance=instance)
abort = True
if abort:
try:
dom.abortJob()
except libvirt.libvirtError as e:
LOG.warn(_LW("Failed to abort migration %s"),
e, instance=instance)
raise
# See if we need to increase the max downtime. We
# ignore failures, since we'd rather continue trying
# to migrate
if (len(downtime_steps) > 0 and
elapsed > downtime_steps[0][0]):
downtime = downtime_steps.pop(0)
LOG.info(_LI("Increasing downtime to %(downtime)d ms "
"after %(waittime)d sec elapsed time"),
{"downtime": downtime[1],
"waittime": downtime[0]},
instance=instance)
try:
dom.migrateSetMaxDowntime(downtime[1])
except libvirt.libvirtError as e:
LOG.warn(
_LW("Unable to increase max downtime to %(time)d"
"ms: %(e)s"),
{"time": downtime[1], "e": e}, instance=instance)
# We loop every 500ms, so don't log on every
# iteration to avoid spamming logs for long
# running migrations. Just once every 5 secs
# is sufficient for developers to debug problems.
# We log once every 30 seconds at info to help
# admins see slow running migration operations
# when debug logs are off.
if (n % 10) == 0:
# Note(Shaohe Feng) every 5 secs to update the migration
# db, that keeps updates to the instance and migration
# objects in sync.
migration.memory_total = info.memory_total
migration.memory_processed = info.memory_processed
migration.memory_remaining = info.memory_remaining
migration.disk_total = info.disk_total
migration.disk_processed = info.disk_processed
migration.disk_remaining = info.disk_remaining
migration.save()
# Ignoring memory_processed, as due to repeated
# dirtying of data, this can be way larger than
# memory_total. Best to just look at what's
# remaining to copy and ignore what's done already
#
# TODO(berrange) perhaps we could include disk
# transfer stats in the progress too, but it
# might make memory info more obscure as large
# disk sizes might dwarf memory size
remaining = 100
if info.memory_total != 0:
remaining = round(info.memory_remaining *
100 / info.memory_total)
instance.progress = 100 - remaining
instance.save()
lg = LOG.debug
if (n % 60) == 0:
lg = LOG.info
lg(_LI("Migration running for %(secs)d secs, "
"memory %(remaining)d%% remaining; "
"(bytes processed=%(processed_memory)d, "
"remaining=%(remaining_memory)d, "
"total=%(total_memory)d)"),
{"secs": n / 2, "remaining": remaining,
"processed_memory": info.memory_processed,
"remaining_memory": info.memory_remaining,
"total_memory": info.memory_total}, instance=instance)
if info.data_remaining > progress_watermark:
lg(_LI("Data remaining %(remaining)d bytes, "
"low watermark %(watermark)d bytes "
"%(last)d seconds ago"),
{"remaining": info.data_remaining,
"watermark": progress_watermark,
"last": (now - progress_time)}, instance=instance)
n = n + 1
elif info.type == libvirt.VIR_DOMAIN_JOB_COMPLETED:
# Migration is all done
LOG.info(_LI("Migration operation has completed"),
instance=instance)
post_method(context, instance, dest, block_migration,
migrate_data)
break
elif info.type == libvirt.VIR_DOMAIN_JOB_FAILED:
# Migration did not succeed
LOG.error(_LE("Migration operation has aborted"),
instance=instance)
recover_method(context, instance, dest, block_migration,
migrate_data)
break
elif info.type == libvirt.VIR_DOMAIN_JOB_CANCELLED:
# Migration was stopped by admin
LOG.warn(_LW("Migration operation was cancelled"),
instance=instance)
recover_method(context, instance, dest, block_migration,
migrate_data, migration_status='cancelled')
break
else:
LOG.warn(_LW("Unexpected migration job type: %d"),
info.type, instance=instance)
time.sleep(0.5)
def _live_migration(self, context, instance, dest, post_method,
recover_method, block_migration,
migrate_data):
"""Do live migration.
:param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param dest: destination host
:param post_method:
post operation method.
expected nova.compute.manager._post_live_migration.
:param recover_method:
recovery method when any exception occurs.
expected nova.compute.manager._rollback_live_migration.
:param block_migration: if true, do block migration.
:param migrate_data: a LibvirtLiveMigrateData object
This fires off a new thread to run the blocking migration
operation, and then this thread monitors the progress of
migration and controls its operation
"""
guest = self._host.get_guest(instance)
disk_paths = []
device_names = []
if migrate_data.block_migration:
disk_paths, device_names = self._live_migration_copy_disk_paths(
context, instance, guest)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove dom at the end.
dom = guest._domain
opthread = utils.spawn(self._live_migration_operation,
context, instance, dest,
block_migration,
migrate_data, dom,
device_names)
finish_event = eventlet.event.Event()
def thread_finished(thread, event):
LOG.debug("Migration operation thread notification",
instance=instance)
event.send()
opthread.link(thread_finished, finish_event)
# Let eventlet schedule the new thread right away
time.sleep(0)
try:
LOG.debug("Starting monitoring of live migration",
instance=instance)
self._live_migration_monitor(context, instance, guest, dest,
post_method, recover_method,
block_migration, migrate_data,
dom, finish_event, disk_paths)
except Exception as ex:
LOG.warn(_LW("Error monitoring migration: %(ex)s"),
{"ex": ex}, instance=instance, exc_info=True)
raise
finally:
LOG.debug("Live migration monitoring is all done",
instance=instance)
def live_migration_force_complete(self, instance):
# NOTE(pkoniszewski): currently only pause during live migration is
# supported to force live migration to complete, so just try to pause
# the instance
self.pause(instance)
def _try_fetch_image(self, context, path, image_id, instance,
fallback_from_host=None):
try:
libvirt_utils.fetch_image(context, path,
image_id,
instance.user_id,
instance.project_id)
except exception.ImageNotFound:
if not fallback_from_host:
raise
LOG.debug("Image %(image_id)s doesn't exist anymore on "
"image service, attempting to copy image "
"from %(host)s",
{'image_id': image_id, 'host': fallback_from_host})
libvirt_utils.copy_image(src=path, dest=path,
host=fallback_from_host,
receive=True)
def _fetch_instance_kernel_ramdisk(self, context, instance,
fallback_from_host=None):
"""Download kernel and ramdisk for instance in instance directory."""
instance_dir = libvirt_utils.get_instance_path(instance)
if instance.kernel_id:
kernel_path = os.path.join(instance_dir, 'kernel')
# NOTE(dsanders): only fetch image if it's not available at
# kernel_path. This also avoids ImageNotFound exception if
# the image has been deleted from glance
if not os.path.exists(kernel_path):
self._try_fetch_image(context,
kernel_path,
instance.kernel_id,
instance, fallback_from_host)
if instance.ramdisk_id:
ramdisk_path = os.path.join(instance_dir, 'ramdisk')
# NOTE(dsanders): only fetch image if it's not available at
# ramdisk_path. This also avoids ImageNotFound exception if
# the image has been deleted from glance
if not os.path.exists(ramdisk_path):
self._try_fetch_image(context,
ramdisk_path,
instance.ramdisk_id,
instance, fallback_from_host)
def rollback_live_migration_at_destination(self, context, instance,
network_info,
block_device_info,
destroy_disks=True,
migrate_data=None):
"""Clean up destination node after a failed live migration."""
try:
self.destroy(context, instance, network_info, block_device_info,
destroy_disks, migrate_data)
finally:
# NOTE(gcb): Failed block live migration may leave instance
# directory at destination node, ensure it is always deleted.
is_shared_instance_path = True
if migrate_data:
is_shared_instance_path = migrate_data.is_shared_instance_path
if not is_shared_instance_path:
instance_dir = libvirt_utils.get_instance_path_at_destination(
instance, migrate_data)
if os.path.exists(instance_dir):
shutil.rmtree(instance_dir)
def pre_live_migration(self, context, instance, block_device_info,
network_info, disk_info, migrate_data=None):
"""Preparation live migration."""
if disk_info is not None:
disk_info = jsonutils.loads(disk_info)
# Steps for volume backed instance live migration w/o shared storage.
is_shared_block_storage = True
is_shared_instance_path = True
is_block_migration = True
if migrate_data:
if not isinstance(migrate_data, migrate_data_obj.LiveMigrateData):
obj = objects.LibvirtLiveMigrateData()
obj.from_legacy_dict(migrate_data)
migrate_data = obj
LOG.debug('migrate_data in pre_live_migration: %s', migrate_data,
instance=instance)
is_shared_block_storage = migrate_data.is_shared_block_storage
is_shared_instance_path = migrate_data.is_shared_instance_path
is_block_migration = migrate_data.block_migration
if configdrive.required_by(instance):
# NOTE(sileht): configdrive is stored into the block storage
# kvm is a block device, live migration will work
# NOTE(sileht): the configdrive is stored into a shared path
# kvm don't need to migrate it, live migration will work
# NOTE(dims): Using config drive with iso format does not work
# because of a bug in libvirt with read only devices. However
# one can use vfat as config_drive_format which works fine.
# Please see bug/1246201 for details on the libvirt bug.
if (is_shared_block_storage or
is_shared_instance_path or
CONF.config_drive_format == 'vfat'):
pass
else:
raise exception.NoLiveMigrationForConfigDriveInLibVirt()
if not is_shared_instance_path:
instance_dir = libvirt_utils.get_instance_path_at_destination(
instance, migrate_data)
if os.path.exists(instance_dir):
raise exception.DestinationDiskExists(path=instance_dir)
LOG.debug('Creating instance directory: %s', instance_dir,
instance=instance)
os.mkdir(instance_dir)
# Recreate the disk.info file and in doing so stop the
# imagebackend from recreating it incorrectly by inspecting the
# contents of each file when using the Raw backend.
if disk_info:
image_disk_info = {}
for info in disk_info:
image_file = os.path.basename(info['path'])
image_path = os.path.join(instance_dir, image_file)
image_disk_info[image_path] = info['type']
LOG.debug('Creating disk.info with the contents: %s',
image_disk_info, instance=instance)
image_disk_info_path = os.path.join(instance_dir,
'disk.info')
libvirt_utils.write_to_file(image_disk_info_path,
jsonutils.dumps(image_disk_info))
if not is_shared_block_storage:
# Ensure images and backing files are present.
LOG.debug('Checking to make sure images and backing files are '
'present before live migration.', instance=instance)
self._create_images_and_backing(
context, instance, instance_dir, disk_info,
fallback_from_host=instance.host)
if not is_block_migration:
# NOTE(angdraug): when block storage is shared between source
# and destination and instance path isn't (e.g. volume backed
# or rbd backed instance), instance path on destination has to
# be prepared
# Touch the console.log file, required by libvirt.
console_file = self._get_console_log_path(instance)
LOG.debug('Touch instance console log: %s', console_file,
instance=instance)
libvirt_utils.file_open(console_file, 'a').close()
# if image has kernel and ramdisk, just download
# following normal way.
self._fetch_instance_kernel_ramdisk(context, instance)
# Establishing connection to volume server.
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
if len(block_device_mapping):
LOG.debug('Connecting volumes before live migration.',
instance=instance)
for bdm in block_device_mapping:
connection_info = bdm['connection_info']
disk_info = blockinfo.get_info_from_bdm(
instance, CONF.libvirt.virt_type,
instance.image_meta, bdm)
self._connect_volume(connection_info, disk_info)
# We call plug_vifs before the compute manager calls
# ensure_filtering_rules_for_instance, to ensure bridge is set up
# Retry operation is necessary because continuously request comes,
# concurrent request occurs to iptables, then it complains.
LOG.debug('Plugging VIFs before live migration.', instance=instance)
max_retry = CONF.live_migration_retry_count
for cnt in range(max_retry):
try:
self.plug_vifs(instance, network_info)
break
except processutils.ProcessExecutionError:
if cnt == max_retry - 1:
raise
else:
LOG.warn(_LW('plug_vifs() failed %(cnt)d. Retry up to '
'%(max_retry)d.'),
{'cnt': cnt,
'max_retry': max_retry},
instance=instance)
greenthread.sleep(1)
# Store vncserver_listen and latest disk device info
if not migrate_data:
migrate_data = objects.LibvirtLiveMigrateData(bdms=[])
else:
migrate_data.bdms = []
migrate_data.graphics_listen_addr_vnc = CONF.vnc.vncserver_listen
migrate_data.graphics_listen_addr_spice = CONF.spice.server_listen
migrate_data.serial_listen_addr = \
CONF.serial_console.proxyclient_address
# Store live_migration_inbound_addr
migrate_data.target_connect_addr = \
CONF.libvirt.live_migration_inbound_addr
for vol in block_device_mapping:
connection_info = vol['connection_info']
if connection_info.get('serial'):
disk_info = blockinfo.get_info_from_bdm(
instance, CONF.libvirt.virt_type,
instance.image_meta, vol)
bdmi = objects.LibvirtLiveMigrateBDMInfo()
bdmi.serial = connection_info['serial']
bdmi.connection_info = connection_info
bdmi.bus = disk_info['bus']
bdmi.dev = disk_info['dev']
bdmi.type = disk_info['type']
bdmi.format = disk_info.get('format')
bdmi.boot_index = disk_info.get('boot_index')
migrate_data.bdms.append(bdmi)
return migrate_data
def _try_fetch_image_cache(self, image, fetch_func, context, filename,
image_id, instance, size,
fallback_from_host=None):
try:
image.cache(fetch_func=fetch_func,
context=context,
filename=filename,
image_id=image_id,
user_id=instance.user_id,
project_id=instance.project_id,
size=size)
except exception.ImageNotFound:
if not fallback_from_host:
raise
LOG.debug("Image %(image_id)s doesn't exist anymore "
"on image service, attempting to copy "
"image from %(host)s",
{'image_id': image_id, 'host': fallback_from_host},
instance=instance)
def copy_from_host(target, max_size):
libvirt_utils.copy_image(src=target,
dest=target,
host=fallback_from_host,
receive=True)
image.cache(fetch_func=copy_from_host,
filename=filename)
def _create_images_and_backing(self, context, instance, instance_dir,
disk_info, fallback_from_host=None):
""":param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param instance_dir:
instance path to use, calculated externally to handle block
migrating an instance with an old style instance path
:param disk_info:
disk info specified in _get_instance_disk_info (list of dicts)
:param fallback_from_host:
host where we can retrieve images if the glance images are
not available.
"""
if not disk_info:
disk_info = []
for info in disk_info:
base = os.path.basename(info['path'])
# Get image type and create empty disk image, and
# create backing file in case of qcow2.
instance_disk = os.path.join(instance_dir, base)
if not info['backing_file'] and not os.path.exists(instance_disk):
libvirt_utils.create_image(info['type'], instance_disk,
info['virt_disk_size'])
elif info['backing_file']:
# Creating backing file follows same way as spawning instances.
cache_name = os.path.basename(info['backing_file'])
image = self.image_backend.image(instance,
instance_disk,
CONF.libvirt.images_type)
if cache_name.startswith('ephemeral'):
image.cache(fetch_func=self._create_ephemeral,
fs_label=cache_name,
os_type=instance.os_type,
filename=cache_name,
size=info['virt_disk_size'],
ephemeral_size=instance.ephemeral_gb)
elif cache_name.startswith('swap'):
inst_type = instance.get_flavor()
swap_mb = inst_type.swap
image.cache(fetch_func=self._create_swap,
filename="swap_%s" % swap_mb,
size=swap_mb * units.Mi,
swap_mb=swap_mb)
else:
self._try_fetch_image_cache(image,
libvirt_utils.fetch_image,
context, cache_name,
instance.image_ref,
instance,
info['virt_disk_size'],
fallback_from_host)
# if image has kernel and ramdisk, just download
# following normal way.
self._fetch_instance_kernel_ramdisk(
context, instance, fallback_from_host=fallback_from_host)
def post_live_migration(self, context, instance, block_device_info,
migrate_data=None):
# Disconnect from volume server
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
connector = self.get_volume_connector(instance)
volume_api = self._volume_api
for vol in block_device_mapping:
# Retrieve connection info from Cinder's initialize_connection API.
# The info returned will be accurate for the source server.
volume_id = vol['connection_info']['serial']
connection_info = volume_api.initialize_connection(context,
volume_id,
connector)
# TODO(leeantho) The following multipath_id logic is temporary
# and will be removed in the future once os-brick is updated
# to handle multipath for drivers in a more efficient way.
# For now this logic is needed to ensure the connection info
# data is correct.
# Pull out multipath_id from the bdm information. The
# multipath_id can be placed into the connection info
# because it is based off of the volume and will be the
# same on the source and destination hosts.
if 'multipath_id' in vol['connection_info']['data']:
multipath_id = vol['connection_info']['data']['multipath_id']
connection_info['data']['multipath_id'] = multipath_id
disk_dev = vol['mount_device'].rpartition("/")[2]
self._disconnect_volume(connection_info, disk_dev)
def post_live_migration_at_source(self, context, instance, network_info):
"""Unplug VIFs from networks at source.
:param context: security context
:param instance: instance object reference
:param network_info: instance network information
"""
self.unplug_vifs(instance, network_info)
def post_live_migration_at_destination(self, context,
instance,
network_info,
block_migration=False,
block_device_info=None):
"""Post operation of live migration at destination host.
:param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param network_info: instance network information
:param block_migration: if true, post operation of block_migration.
"""
# Define migrated instance, otherwise, suspend/destroy does not work.
# In case of block migration, destination does not have
# libvirt.xml
disk_info = blockinfo.get_disk_info(
CONF.libvirt.virt_type, instance,
instance.image_meta, block_device_info)
xml = self._get_guest_xml(context, instance,
network_info, disk_info,
instance.image_meta,
block_device_info=block_device_info,
write_to_disk=True)
self._host.write_instance_config(xml)
def _get_instance_disk_info(self, instance_name, xml,
block_device_info=None):
"""Get the non-volume disk information from the domain xml
:param str instance_name: the name of the instance (domain)
:param str xml: the libvirt domain xml for the instance
:param dict block_device_info: block device info for BDMs
:returns disk_info: list of dicts with keys:
* 'type': the disk type (str)
* 'path': the disk path (str)
* 'virt_disk_size': the virtual disk size (int)
* 'backing_file': backing file of a disk image (str)
* 'disk_size': physical disk size (int)
* 'over_committed_disk_size': virt_disk_size - disk_size or 0
"""
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
volume_devices = set()
for vol in block_device_mapping:
disk_dev = vol['mount_device'].rpartition("/")[2]
volume_devices.add(disk_dev)
disk_info = []
doc = etree.fromstring(xml)
disk_nodes = doc.findall('.//devices/disk')
path_nodes = doc.findall('.//devices/disk/source')
driver_nodes = doc.findall('.//devices/disk/driver')
target_nodes = doc.findall('.//devices/disk/target')
for cnt, path_node in enumerate(path_nodes):
disk_type = disk_nodes[cnt].get('type')
path = path_node.get('file') or path_node.get('dev')
target = target_nodes[cnt].attrib['dev']
if not path:
LOG.debug('skipping disk for %s as it does not have a path',
instance_name)
continue
if disk_type not in ['file', 'block']:
LOG.debug('skipping disk because it looks like a volume', path)
continue
if target in volume_devices:
LOG.debug('skipping disk %(path)s (%(target)s) as it is a '
'volume', {'path': path, 'target': target})
continue
# get the real disk size or
# raise a localized error if image is unavailable
if disk_type == 'file':
dk_size = int(os.path.getsize(path))
elif disk_type == 'block' and block_device_info:
dk_size = lvm.get_volume_size(path)
else:
LOG.debug('skipping disk %(path)s (%(target)s) - unable to '
'determine if volume',
{'path': path, 'target': target})
continue
disk_type = driver_nodes[cnt].get('type')
if disk_type == "qcow2":
backing_file = libvirt_utils.get_disk_backing_file(path)
virt_size = disk.get_disk_size(path)
over_commit_size = int(virt_size) - dk_size
else:
backing_file = ""
virt_size = dk_size
over_commit_size = 0
disk_info.append({'type': disk_type,
'path': path,
'virt_disk_size': virt_size,
'backing_file': backing_file,
'disk_size': dk_size,
'over_committed_disk_size': over_commit_size})
return disk_info
def get_instance_disk_info(self, instance,
block_device_info=None):
try:
guest = self._host.get_guest(instance)
xml = guest.get_xml_desc()
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
LOG.warn(_LW('Error from libvirt while getting description of '
'%(instance_name)s: [Error Code %(error_code)s] '
'%(ex)s'),
{'instance_name': instance.name,
'error_code': error_code,
'ex': ex},
instance=instance)
raise exception.InstanceNotFound(instance_id=instance.uuid)
return jsonutils.dumps(
self._get_instance_disk_info(instance.name, xml,
block_device_info))
def _get_disk_over_committed_size_total(self):
"""Return total over committed disk size for all instances."""
# Disk size that all instance uses : virtual_size - disk_size
disk_over_committed_size = 0
instance_domains = self._host.list_instance_domains()
if not instance_domains:
return disk_over_committed_size
# Get all instance uuids
instance_uuids = [dom.UUIDString() for dom in instance_domains]
ctx = nova_context.get_admin_context()
# Get instance object list by uuid filter
filters = {'uuid': instance_uuids}
# NOTE(ankit): objects.InstanceList.get_by_filters method is
# getting called twice one is here and another in the
# _update_available_resource method of resource_tracker. Since
# _update_available_resource method is synchronized, there is a
# possibility the instances list retrieved here to calculate
# disk_over_committed_size would differ to the list you would get
# in _update_available_resource method for calculating usages based
# on instance utilization.
local_instance_list = objects.InstanceList.get_by_filters(
ctx, filters, use_slave=True)
# Convert instance list to dictionary with instace uuid as key.
local_instances = {inst.uuid: inst for inst in local_instance_list}
# Get bdms by instance uuids
bdms = objects.BlockDeviceMappingList.bdms_by_instance_uuid(
ctx, instance_uuids)
for dom in instance_domains:
try:
guest = libvirt_guest.Guest(dom)
xml = guest.get_xml_desc()
block_device_info = None
if guest.uuid in local_instances:
# Get block device info for instance
block_device_info = driver.get_block_device_info(
local_instances[guest.uuid], bdms[guest.uuid])
disk_infos = self._get_instance_disk_info(guest.name, xml,
block_device_info=block_device_info)
for info in disk_infos:
disk_over_committed_size += int(
info['over_committed_disk_size'])
except libvirt.libvirtError as ex:
error_code = ex.get_error_code()
LOG.warn(_LW(
'Error from libvirt while getting description of '
'%(instance_name)s: [Error Code %(error_code)s] %(ex)s'
), {'instance_name': guest.name,
'error_code': error_code,
'ex': ex})
except OSError as e:
if e.errno == errno.ENOENT:
LOG.warn(_LW('Periodic task is updating the host stat, '
'it is trying to get disk %(i_name)s, '
'but disk file was removed by concurrent '
'operations such as resize.'),
{'i_name': guest.name})
elif e.errno == errno.EACCES:
LOG.warn(_LW('Periodic task is updating the host stat, '
'it is trying to get disk %(i_name)s, '
'but access is denied. It is most likely '
'due to a VM that exists on the compute '
'node but is not managed by Nova.'),
{'i_name': guest.name})
else:
raise
except exception.VolumeBDMPathNotFound as e:
LOG.warn(_LW('Periodic task is updating the host stats, '
'it is trying to get disk info for %(i_name)s, '
'but the backing volume block device was removed '
'by concurrent operations such as resize. '
'Error: %(error)s'),
{'i_name': guest.name,
'error': e})
# NOTE(gtt116): give other tasks a chance.
greenthread.sleep(0)
return disk_over_committed_size
def unfilter_instance(self, instance, network_info):
"""See comments of same method in firewall_driver."""
self.firewall_driver.unfilter_instance(instance,
network_info=network_info)
def get_available_nodes(self, refresh=False):
return [self._host.get_hostname()]
def get_host_cpu_stats(self):
"""Return the current CPU state of the host."""
return self._host.get_cpu_stats()
def get_host_uptime(self):
"""Returns the result of calling "uptime"."""
out, err = utils.execute('env', 'LANG=C', 'uptime')
return out
def manage_image_cache(self, context, all_instances):
"""Manage the local cache of images."""
self.image_cache_manager.update(context, all_instances)
def _cleanup_remote_migration(self, dest, inst_base, inst_base_resize,
shared_storage=False):
"""Used only for cleanup in case migrate_disk_and_power_off fails."""
try:
if os.path.exists(inst_base_resize):
utils.execute('rm', '-rf', inst_base)
utils.execute('mv', inst_base_resize, inst_base)
if not shared_storage:
self._remotefs.remove_dir(dest, inst_base)
except Exception:
pass
def _is_storage_shared_with(self, dest, inst_base):
# NOTE (rmk): There are two methods of determining whether we are
# on the same filesystem: the source and dest IP are the
# same, or we create a file on the dest system via SSH
# and check whether the source system can also see it.
shared_storage = (dest == self.get_host_ip_addr())
if not shared_storage:
tmp_file = uuid.uuid4().hex + '.tmp'
tmp_path = os.path.join(inst_base, tmp_file)
try:
self._remotefs.create_file(dest, tmp_path)
if os.path.exists(tmp_path):
shared_storage = True
os.unlink(tmp_path)
else:
self._remotefs.remove_file(dest, tmp_path)
except Exception:
pass
return shared_storage
def migrate_disk_and_power_off(self, context, instance, dest,
flavor, network_info,
block_device_info=None,
timeout=0, retry_interval=0):
LOG.debug("Starting migrate_disk_and_power_off",
instance=instance)
ephemerals = driver.block_device_info_get_ephemerals(block_device_info)
# get_bdm_ephemeral_disk_size() will return 0 if the new
# instance's requested block device mapping contain no
# ephemeral devices. However, we still want to check if
# the original instance's ephemeral_gb property was set and
# ensure that the new requested flavor ephemeral size is greater
eph_size = (block_device.get_bdm_ephemeral_disk_size(ephemerals) or
instance.ephemeral_gb)
# Checks if the migration needs a disk resize down.
root_down = flavor.root_gb < instance.root_gb
ephemeral_down = flavor.ephemeral_gb < eph_size
disk_info_text = self.get_instance_disk_info(
instance, block_device_info=block_device_info)
booted_from_volume = self._is_booted_from_volume(instance,
disk_info_text)
if (root_down and not booted_from_volume) or ephemeral_down:
reason = _("Unable to resize disk down.")
raise exception.InstanceFaultRollback(
exception.ResizeError(reason=reason))
disk_info = jsonutils.loads(disk_info_text)
# NOTE(dgenin): Migration is not implemented for LVM backed instances.
if CONF.libvirt.images_type == 'lvm' and not booted_from_volume:
reason = _("Migration is not supported for LVM backed instances")
raise exception.InstanceFaultRollback(
exception.MigrationPreCheckError(reason=reason))
# copy disks to destination
# rename instance dir to +_resize at first for using
# shared storage for instance dir (eg. NFS).
inst_base = libvirt_utils.get_instance_path(instance)
inst_base_resize = inst_base + "_resize"
shared_storage = self._is_storage_shared_with(dest, inst_base)
# try to create the directory on the remote compute node
# if this fails we pass the exception up the stack so we can catch
# failures here earlier
if not shared_storage:
try:
self._remotefs.create_dir(dest, inst_base)
except processutils.ProcessExecutionError as e:
reason = _("not able to execute ssh command: %s") % e
raise exception.InstanceFaultRollback(
exception.ResizeError(reason=reason))
self.power_off(instance, timeout, retry_interval)
block_device_mapping = driver.block_device_info_get_mapping(
block_device_info)
for vol in block_device_mapping:
connection_info = vol['connection_info']
disk_dev = vol['mount_device'].rpartition("/")[2]
self._disconnect_volume(connection_info, disk_dev)
try:
utils.execute('mv', inst_base, inst_base_resize)
# if we are migrating the instance with shared storage then
# create the directory. If it is a remote node the directory
# has already been created
if shared_storage:
dest = None
utils.execute('mkdir', '-p', inst_base)
on_execute = lambda process: \
self.job_tracker.add_job(instance, process.pid)
on_completion = lambda process: \
self.job_tracker.remove_job(instance, process.pid)
active_flavor = instance.get_flavor()
for info in disk_info:
# assume inst_base == dirname(info['path'])
img_path = info['path']
fname = os.path.basename(img_path)
from_path = os.path.join(inst_base_resize, fname)
# To properly resize the swap partition, it must be
# re-created with the proper size. This is acceptable
# because when an OS is shut down, the contents of the
# swap space are just garbage, the OS doesn't bother about
# what is in it.
# We will not copy over the swap disk here, and rely on
# finish_migration/_create_image to re-create it for us.
if not (fname == 'disk.swap' and
active_flavor.get('swap', 0) != flavor.get('swap', 0)):
compression = info['type'] not in NO_COMPRESSION_TYPES
libvirt_utils.copy_image(from_path, img_path, host=dest,
on_execute=on_execute,
on_completion=on_completion,
compression=compression)
# Ensure disk.info is written to the new path to avoid disks being
# reinspected and potentially changing format.
src_disk_info_path = os.path.join(inst_base_resize, 'disk.info')
if os.path.exists(src_disk_info_path):
dst_disk_info_path = os.path.join(inst_base, 'disk.info')
libvirt_utils.copy_image(src_disk_info_path,
dst_disk_info_path,
host=dest, on_execute=on_execute,
on_completion=on_completion)
except Exception:
with excutils.save_and_reraise_exception():
self._cleanup_remote_migration(dest, inst_base,
inst_base_resize,
shared_storage)
return disk_info_text
def _wait_for_running(self, instance):
state = self.get_info(instance).state
if state == power_state.RUNNING:
LOG.info(_LI("Instance running successfully."), instance=instance)
raise loopingcall.LoopingCallDone()
@staticmethod
def _disk_size_from_instance(instance, disk_name):
"""Determines the disk size from instance properties
Returns the disk size by using the disk name to determine whether it
is a root or an ephemeral disk, then by checking properties of the
instance returns the size converted to bytes.
Returns 0 if the disk name not match (disk, disk.local).
"""
if disk_name == 'disk':
size = instance.root_gb
elif disk_name == 'disk.local':
size = instance.ephemeral_gb
# N.B. We don't handle ephemeral disks named disk.ephN here,
# which is almost certainly a bug. It's not clear what this function
# should return if an instance has multiple ephemeral disks.
else:
size = 0
return size * units.Gi
@staticmethod
def _disk_raw_to_qcow2(path):
"""Converts a raw disk to qcow2."""
path_qcow = path + '_qcow'
utils.execute('qemu-img', 'convert', '-f', 'raw',
'-O', 'qcow2', path, path_qcow)
utils.execute('mv', path_qcow, path)
@staticmethod
def _disk_qcow2_to_raw(path):
"""Converts a qcow2 disk to raw."""
path_raw = path + '_raw'
utils.execute('qemu-img', 'convert', '-f', 'qcow2',
'-O', 'raw', path, path_raw)
utils.execute('mv', path_raw, path)
def _disk_resize(self, image, size):
"""Attempts to resize a disk to size
:param image: an instance of nova.virt.image.model.Image
Attempts to resize a disk by checking the capabilities and
preparing the format, then calling disk.api.extend.
Note: Currently only support disk extend.
"""
if not isinstance(image, imgmodel.LocalFileImage):
LOG.debug("Skipping resize of non-local image")
return
# If we have a non partitioned image that we can extend
# then ensure we're in 'raw' format so we can extend file system.
converted = False
if (size and
image.format == imgmodel.FORMAT_QCOW2 and
disk.can_resize_image(image.path, size) and
disk.is_image_extendable(image)):
self._disk_qcow2_to_raw(image.path)
converted = True
image = imgmodel.LocalFileImage(image.path,
imgmodel.FORMAT_RAW)
if size:
disk.extend(image, size)
if converted:
# back to qcow2 (no backing_file though) so that snapshot
# will be available
self._disk_raw_to_qcow2(image.path)
def finish_migration(self, context, migration, instance, disk_info,
network_info, image_meta, resize_instance,
block_device_info=None, power_on=True):
LOG.debug("Starting finish_migration", instance=instance)
block_disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta,
block_device_info)
# assume _create_image does nothing if a target file exists.
# NOTE: This has the intended side-effect of fetching a missing
# backing file.
self._create_image(context, instance, block_disk_info['mapping'],
network_info=network_info,
block_device_info=None, inject_files=False,
fallback_from_host=migration.source_compute)
# Resize root disk and a single ephemeral disk called disk.local
# Also convert raw disks to qcow2 if migrating to host which uses
# qcow2 from host which uses raw.
# TODO(mbooth): Handle resize of multiple ephemeral disks, and
# ephemeral disks not called disk.local.
disk_info = jsonutils.loads(disk_info)
for info in disk_info:
path = info['path']
disk_name = os.path.basename(path)
size = self._disk_size_from_instance(instance, disk_name)
if resize_instance:
image = imgmodel.LocalFileImage(path, info['type'])
self._disk_resize(image, size)
# NOTE(mdbooth): The code below looks wrong, but is actually
# required to prevent a security hole when migrating from a host
# with use_cow_images=False to one with use_cow_images=True.
# Imagebackend uses use_cow_images to select between the
# atrociously-named-Raw and Qcow2 backends. The Qcow2 backend
# writes to disk.info, but does not read it as it assumes qcow2.
# Therefore if we don't convert raw to qcow2 here, a raw disk will
# be incorrectly assumed to be qcow2, which is a severe security
# flaw. The reverse is not true, because the atrociously-named-Raw
# backend supports both qcow2 and raw disks, and will choose
# appropriately between them as long as disk.info exists and is
# correctly populated, which it is because Qcow2 writes to
# disk.info.
#
# In general, we do not yet support format conversion during
# migration. For example:
# * Converting from use_cow_images=True to use_cow_images=False
# isn't handled. This isn't a security bug, but is almost
# certainly buggy in other cases, as the 'Raw' backend doesn't
# expect a backing file.
# * Converting to/from lvm and rbd backends is not supported.
#
# This behaviour is inconsistent, and therefore undesirable for
# users. It is tightly-coupled to implementation quirks of 2
# out of 5 backends in imagebackend and defends against a severe
# security flaw which is not at all obvious without deep analysis,
# and is therefore undesirable to developers. We should aim to
# remove it. This will not be possible, though, until we can
# represent the storage layout of a specific instance
# independent of the default configuration of the local compute
# host.
# Config disks are hard-coded to be raw even when
# use_cow_images=True (see _get_disk_config_image_type),so don't
# need to be converted.
if (disk_name != 'disk.config' and
info['type'] == 'raw' and CONF.use_cow_images):
self._disk_raw_to_qcow2(info['path'])
xml = self._get_guest_xml(context, instance, network_info,
block_disk_info, image_meta,
block_device_info=block_device_info,
write_to_disk=True)
# NOTE(mriedem): vifs_already_plugged=True here, regardless of whether
# or not we've migrated to another host, because we unplug VIFs locally
# and the status change in the port might go undetected by the neutron
# L2 agent (or neutron server) so neutron may not know that the VIF was
# unplugged in the first place and never send an event.
self._create_domain_and_network(context, xml, instance, network_info,
block_disk_info,
block_device_info=block_device_info,
power_on=power_on,
vifs_already_plugged=True)
if power_on:
timer = loopingcall.FixedIntervalLoopingCall(
self._wait_for_running,
instance)
timer.start(interval=0.5).wait()
LOG.debug("finish_migration finished successfully.", instance=instance)
def _cleanup_failed_migration(self, inst_base):
"""Make sure that a failed migrate doesn't prevent us from rolling
back in a revert.
"""
try:
shutil.rmtree(inst_base)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def finish_revert_migration(self, context, instance, network_info,
block_device_info=None, power_on=True):
LOG.debug("Starting finish_revert_migration",
instance=instance)
inst_base = libvirt_utils.get_instance_path(instance)
inst_base_resize = inst_base + "_resize"
# NOTE(danms): if we're recovering from a failed migration,
# make sure we don't have a left-over same-host base directory
# that would conflict. Also, don't fail on the rename if the
# failure happened early.
if os.path.exists(inst_base_resize):
self._cleanup_failed_migration(inst_base)
utils.execute('mv', inst_base_resize, inst_base)
backend = self.image_backend.image(instance, 'disk')
# Once we rollback, the snapshot is no longer needed, so remove it
# TODO(nic): Remove the try/except/finally in a future release
# To avoid any upgrade issues surrounding instances being in pending
# resize state when the software is updated, this portion of the
# method logs exceptions rather than failing on them. Once it can be
# reasonably assumed that no such instances exist in the wild
# anymore, the try/except/finally should be removed,
# and ignore_errors should be set back to False (the default) so
# that problems throw errors, like they should.
try:
backend.rollback_to_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME)
except exception.SnapshotNotFound:
LOG.warning(_LW("Failed to rollback snapshot (%s)"),
libvirt_utils.RESIZE_SNAPSHOT_NAME)
finally:
backend.remove_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME,
ignore_errors=True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
instance.image_meta,
block_device_info)
xml = self._get_guest_xml(context, instance, network_info, disk_info,
instance.image_meta,
block_device_info=block_device_info)
self._create_domain_and_network(context, xml, instance, network_info,
disk_info,
block_device_info=block_device_info,
power_on=power_on,
vifs_already_plugged=True)
if power_on:
timer = loopingcall.FixedIntervalLoopingCall(
self._wait_for_running,
instance)
timer.start(interval=0.5).wait()
LOG.debug("finish_revert_migration finished successfully.",
instance=instance)
def confirm_migration(self, migration, instance, network_info):
"""Confirms a resize, destroying the source VM."""
self._cleanup_resize(instance, network_info)
@staticmethod
def _get_io_devices(xml_doc):
"""get the list of io devices from the xml document."""
result = {"volumes": [], "ifaces": []}
try:
doc = etree.fromstring(xml_doc)
except Exception:
return result
blocks = [('./devices/disk', 'volumes'),
('./devices/interface', 'ifaces')]
for block, key in blocks:
section = doc.findall(block)
for node in section:
for child in node.getchildren():
if child.tag == 'target' and child.get('dev'):
result[key].append(child.get('dev'))
return result
def get_diagnostics(self, instance):
guest = self._host.get_guest(instance)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove domain at the end.
domain = guest._domain
output = {}
# get cpu time, might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
try:
for vcpu in guest.get_vcpus_info():
output["cpu" + str(vcpu.id) + "_time"] = vcpu.time
except libvirt.libvirtError:
pass
# get io status
xml = guest.get_xml_desc()
dom_io = LibvirtDriver._get_io_devices(xml)
for guest_disk in dom_io["volumes"]:
try:
# blockStats might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
stats = domain.blockStats(guest_disk)
output[guest_disk + "_read_req"] = stats[0]
output[guest_disk + "_read"] = stats[1]
output[guest_disk + "_write_req"] = stats[2]
output[guest_disk + "_write"] = stats[3]
output[guest_disk + "_errors"] = stats[4]
except libvirt.libvirtError:
pass
for interface in dom_io["ifaces"]:
try:
# interfaceStats might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
stats = domain.interfaceStats(interface)
output[interface + "_rx"] = stats[0]
output[interface + "_rx_packets"] = stats[1]
output[interface + "_rx_errors"] = stats[2]
output[interface + "_rx_drop"] = stats[3]
output[interface + "_tx"] = stats[4]
output[interface + "_tx_packets"] = stats[5]
output[interface + "_tx_errors"] = stats[6]
output[interface + "_tx_drop"] = stats[7]
except libvirt.libvirtError:
pass
output["memory"] = domain.maxMemory()
# memoryStats might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
try:
mem = domain.memoryStats()
for key in mem.keys():
output["memory-" + key] = mem[key]
except (libvirt.libvirtError, AttributeError):
pass
return output
def get_instance_diagnostics(self, instance):
guest = self._host.get_guest(instance)
# TODO(sahid): We are converting all calls from a
# virDomain object to use nova.virt.libvirt.Guest.
# We should be able to remove domain at the end.
domain = guest._domain
xml = guest.get_xml_desc()
xml_doc = etree.fromstring(xml)
# TODO(sahid): Needs to use get_info but more changes have to
# be done since a mapping STATE_MAP LIBVIRT_POWER_STATE is
# needed.
(state, max_mem, mem, num_cpu, cpu_time) = \
guest._get_domain_info(self._host)
config_drive = configdrive.required_by(instance)
launched_at = timeutils.normalize_time(instance.launched_at)
uptime = timeutils.delta_seconds(launched_at,
timeutils.utcnow())
diags = diagnostics.Diagnostics(state=power_state.STATE_MAP[state],
driver='libvirt',
config_drive=config_drive,
hypervisor_os='linux',
uptime=uptime)
diags.memory_details.maximum = max_mem / units.Mi
diags.memory_details.used = mem / units.Mi
# get cpu time, might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
try:
for vcpu in guest.get_vcpus_info():
diags.add_cpu(time=vcpu.time)
except libvirt.libvirtError:
pass
# get io status
dom_io = LibvirtDriver._get_io_devices(xml)
for guest_disk in dom_io["volumes"]:
try:
# blockStats might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
stats = domain.blockStats(guest_disk)
diags.add_disk(read_bytes=stats[1],
read_requests=stats[0],
write_bytes=stats[3],
write_requests=stats[2])
except libvirt.libvirtError:
pass
for interface in dom_io["ifaces"]:
try:
# interfaceStats might launch an exception if the method
# is not supported by the underlying hypervisor being
# used by libvirt
stats = domain.interfaceStats(interface)
diags.add_nic(rx_octets=stats[0],
rx_errors=stats[2],
rx_drop=stats[3],
rx_packets=stats[1],
tx_octets=stats[4],
tx_errors=stats[6],
tx_drop=stats[7],
tx_packets=stats[5])
except libvirt.libvirtError:
pass
# Update mac addresses of interface if stats have been reported
if diags.nic_details:
nodes = xml_doc.findall('./devices/interface/mac')
for index, node in enumerate(nodes):
diags.nic_details[index].mac_address = node.get('address')
return diags
def instance_on_disk(self, instance):
# ensure directories exist and are writable
instance_path = libvirt_utils.get_instance_path(instance)
LOG.debug('Checking instance files accessibility %s', instance_path,
instance=instance)
shared_instance_path = os.access(instance_path, os.W_OK)
# NOTE(flwang): For shared block storage scenario, the file system is
# not really shared by the two hosts, but the volume of evacuated
# instance is reachable.
shared_block_storage = (self.image_backend.backend().
is_shared_block_storage())
return shared_instance_path or shared_block_storage
def inject_network_info(self, instance, nw_info):
self.firewall_driver.setup_basic_filtering(instance, nw_info)
def delete_instance_files(self, instance):
target = libvirt_utils.get_instance_path(instance)
# A resize may be in progress
target_resize = target + '_resize'
# Other threads may attempt to rename the path, so renaming the path
# to target + '_del' (because it is atomic) and iterating through
# twice in the unlikely event that a concurrent rename occurs between
# the two rename attempts in this method. In general this method
# should be fairly thread-safe without these additional checks, since
# other operations involving renames are not permitted when the task
# state is not None and the task state should be set to something
# other than None by the time this method is invoked.
target_del = target + '_del'
for i in six.moves.range(2):
try:
utils.execute('mv', target, target_del)
break
except Exception:
pass
try:
utils.execute('mv', target_resize, target_del)
break
except Exception:
pass
# Either the target or target_resize path may still exist if all
# rename attempts failed.
remaining_path = None
for p in (target, target_resize):
if os.path.exists(p):
remaining_path = p
break
# A previous delete attempt may have been interrupted, so target_del
# may exist even if all rename attempts during the present method
# invocation failed due to the absence of both target and
# target_resize.
if not remaining_path and os.path.exists(target_del):
self.job_tracker.terminate_jobs(instance)
LOG.info(_LI('Deleting instance files %s'), target_del,
instance=instance)
remaining_path = target_del
try:
shutil.rmtree(target_del)
except OSError as e:
LOG.error(_LE('Failed to cleanup directory %(target)s: '
'%(e)s'), {'target': target_del, 'e': e},
instance=instance)
# It is possible that the delete failed, if so don't mark the instance
# as cleaned.
if remaining_path and os.path.exists(remaining_path):
LOG.info(_LI('Deletion of %s failed'), remaining_path,
instance=instance)
return False
LOG.info(_LI('Deletion of %s complete'), target_del, instance=instance)
return True
@property
def need_legacy_block_device_info(self):
return False
def default_root_device_name(self, instance, image_meta, root_bdm):
disk_bus = blockinfo.get_disk_bus_for_device_type(
instance, CONF.libvirt.virt_type, image_meta, "disk")
cdrom_bus = blockinfo.get_disk_bus_for_device_type(
instance, CONF.libvirt.virt_type, image_meta, "cdrom")
root_info = blockinfo.get_root_info(
instance, CONF.libvirt.virt_type, image_meta,
root_bdm, disk_bus, cdrom_bus)
return block_device.prepend_dev(root_info['dev'])
def default_device_names_for_instance(self, instance, root_device_name,
*block_device_lists):
block_device_mapping = list(itertools.chain(*block_device_lists))
# NOTE(ndipanov): Null out the device names so that blockinfo code
# will assign them
for bdm in block_device_mapping:
if bdm.device_name is not None:
LOG.warn(_LW("Ignoring supplied device name: %(device_name)s. "
"Libvirt can't honour user-supplied dev names"),
{'device_name': bdm.device_name}, instance=instance)
bdm.device_name = None
block_device_info = driver.get_block_device_info(instance,
block_device_mapping)
blockinfo.default_device_names(CONF.libvirt.virt_type,
nova_context.get_admin_context(),
instance,
block_device_info,
instance.image_meta)
def get_device_name_for_instance(self, instance, bdms, block_device_obj):
block_device_info = driver.get_block_device_info(instance, bdms)
instance_info = blockinfo.get_disk_info(
CONF.libvirt.virt_type, instance,
instance.image_meta, block_device_info=block_device_info)
suggested_dev_name = block_device_obj.device_name
if suggested_dev_name is not None:
LOG.warn(_LW('Ignoring supplied device name: %(suggested_dev)s'),
{'suggested_dev': suggested_dev_name}, instance=instance)
# NOTE(ndipanov): get_info_from_bdm will generate the new device name
# only when it's actually not set on the bd object
block_device_obj.device_name = None
disk_info = blockinfo.get_info_from_bdm(
instance, CONF.libvirt.virt_type, instance.image_meta,
block_device_obj, mapping=instance_info['mapping'])
return block_device.prepend_dev(disk_info['dev'])
def is_supported_fs_format(self, fs_type):
return fs_type in [disk.FS_FORMAT_EXT2, disk.FS_FORMAT_EXT3,
disk.FS_FORMAT_EXT4, disk.FS_FORMAT_XFS]
def _wait_for_dom_block_job(self, uuid):
out, err = utils.trycmd('virsh', 'qemu-monitor-command', uuid, '--hmp', 'info', 'block-jobs',
run_as_root=True)
if out.find('No active') >= 0:
return False
return True
def backup2_instance(self, instance, bak_info):
try:
guest = self._host.get_guest(instance)
virt_dom = guest._domain
#virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
# Find the disk
xml_desc = virt_dom.XMLDesc(0)
domain = etree.fromstring(xml_desc)
disk_path, source_format = libvirt_utils.find_disk(virt_dom)
#old_disk_size = os.path.getsize(disk_path)
domain_name = str(domain.find('name').text)
fileutils.ensure_tree(CONF.libvirt.backup_path)
name = 'backup-' + bak_info['id']
path = os.path.join(CONF.libvirt.backup_path, name)
# Abort is an idempotent operation, so make sure any block
# jobs which may have failed are ended.
try:
virt_dom.blockJobAbort(disk_path, 0)
except Exception:
pass
# NOTE (rmk): We are using shallow rebases as a workaround to a bug
# in QEMU 1.3. In order to do this, we need to create
# a destination image with the original backing file
# and matching size of the instance root disk.
src_disk_size = libvirt_utils.get_disk_size(disk_path)
src_back_path = libvirt_utils.get_disk_backing_file(disk_path,
basename=False)
libvirt_utils.create_cow_image(src_back_path, path,
src_disk_size)
utils.execute('chmod', '777', path, run_as_root=True)
try:
# NOTE (rmk): Establish a temporary mirror of our root disk and
# issue an abort once we have a complete copy.
if CONF.libvirt.images_type == 'rbd':
utils.execute('virsh', 'qemu-monitor-command', domain_name, '--hmp',
'drive_backup', '-f', 'drive-virtio-disk0', path,
run_as_root=True, attempts=3)
else:
utils.execute('virsh', 'qemu-monitor-command', domain_name, '--hmp',
'drive_backup', '-n', 'drive-virtio-disk0', path,
run_as_root=True, attempts=3)
while self._wait_for_dom_block_job(instance['uuid']):
time.sleep(0.5)
utils.execute('chmod', '777', path, run_as_root=True)
if CONF.libvirt.images_type == 'rbd':
LibvirtDriver._get_rbd_driver().import_image(path,name)
except Exception as e:
LOG.error(e)
raise exception.InstanceBackupCreateFailed(
instance_uuid=instance['uuid'],
backup_id=bak_info['id'])
new_disk_size = os.path.getsize(path)
res = {'path': path, 'size': new_disk_size}
return res
def backup2_resume_instance(self, context, instance, bak_info):
try:
guest = self._host.get_guest(instance)
virt_dom = guest._domain
#virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
size = bak_info['backup_size']
path = bak_info['backup_path']
assert size > 0 and path is not None
if CONF.libvirt.images_type == 'rbd':
try:
LibvirtDriver._get_rbd_driver().volume_copy('backup-'+bak_info['id'])
LibvirtDriver._get_rbd_driver().backup_resume_volumes('backup-'+bak_info['id']+'-tmp',instance['uuid']+'_disk')
except Exception as e:
LOG.error(e)
raise exception.InstanceBackupNotFound(backup_id=bak_info['id'])
else:
#file_size = libvirt_utils.get_disk_size(path)
#disk_path = libvirt_utils.find_disk(virt_dom)
#source_format = libvirt_utils.get_disk_type(disk_path)
disk_path, source_format = libvirt_utils.find_disk(virt_dom)
disk_path_last = disk_path + '.last'
utils.execute('mv', '-f', disk_path, disk_path_last)
libvirt_utils.copy_image(path, disk_path)
#utils.flush_page_cache()
def backup2_delete(self, instance, bak_info):
if CONF.libvirt.images_type == 'rbd':
try:
LibvirtDriver._get_rbd_driver().cleanup_backup_volumes('backup-'+bak_info['id'])
except Exception as e:
LOG.error(e)
raise exception.InstanceBackupNotFound(backup_id=bak_info['id'])
bak_dir = bak_info.get('backup_path')
if not bak_dir:
bak_dir_if_error = os.path.join(CONF.libvirt.backup_path, 'backup-'+bak_info['id'])
utils.execute('rm', '-f', bak_dir_if_error)
LOG.error("backup_file's path is None")
return
if not os.path.exists(bak_dir):
LOG.error("backup_file is not exists")
return
utils.execute('rm', '-f', bak_dir)
if not os.path.exists(bak_dir):
LOG.debug("+++ Delete Result: succeed +++")
else:
LOG.error("+++ Delete Result: failed +++")
raise exception.InstanceBackupDeleteFailed(
backup_id=bak_info['id'])
def backup2_to_image(self, context, instance, bak_info, ori_image_id):
path = bak_info['backup_path']
size = bak_info['backup_size']
assert path is not None and size > 0
(image_service, image_id) = glance.get_remote_image_service(
context, ori_image_id)
#base = compute_utils.get_image_metadata(context, image_service, image_id, instance)
image_href = image_id
_image_service = glance.get_remote_image_service(context, image_href)
snapshot_image_service, snapshot_image_id = _image_service
snapshot = snapshot_image_service.show(context, snapshot_image_id)
metadata = {
'is_public': False,
'status': 'active',
'name': snapshot['name'],
'properties': {
'kernel_id': instance['kernel_id'],
'image_location': 'snapshot',
'image_state': 'available',
'owner_id': instance['project_id'],
'ramdisk_id': instance['ramdisk_id'],
#'os-type': instance['os_type'],
}
}
#disk_path = libvirt_utils.find_disk(virt_dom)
#source_format = libvirt_utils.get_disk_type(disk_path)
image_format = CONF.libvirt.snapshot_image_format or 'raw'
# NOTE(bfilippov): save lvm and rbd as raw
if image_format == 'lvm' or image_format == 'rbd':
image_format = 'raw'
snapshot_name = uuid.uuid4().hex
snapshot_directory = CONF.libvirt.snapshots_directory
fileutils.ensure_tree(snapshot_directory)
if not os.path.exists(path) and CONF.libvirt.images_type == 'rbd':
try:
LibvirtDriver._get_rbd_driver().export_volume('backup-'+bak_info['id'],path)
except Exception as e:
LOG.error(e)
raise exception.InstanceBackupNotFound(backup_id=bak_info['id'])
with utils.tempdir(dir=snapshot_directory) as tmpdir:
try:
utils.execute('chmod', '777', tmpdir, run_as_root=True)
out_path = os.path.join(tmpdir, snapshot_name)
if CONF.libvirt.images_type == 'rbd':
metadata['disk_format'] = 'qcow2'
libvirt_utils.extract_snapshot(path, image_format, out_path, 'qcow2')
else:
libvirt_utils.extract_snapshot(path, 'qcow2', out_path, image_format)
except Exception, e:
LOG.error(e)
LOG.error(_("backup image upload failed"),
instance=instance)
return
with libvirt_utils.file_open(out_path) as image_file:
LOG.info(_("backup image upload beging"),
instance=instance)
image_service.update(context,
image_href,
metadata,
image_file)
LOG.info(_("backup image upload complete"),
instance=instance)
def change_admin_password_win(self, instance, admin_pass, files, partition):
try:
virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
# Find the disk
xml_desc = virt_dom.XMLDesc(0)
domain = etree.fromstring(xml_desc)
source = domain.find('devices/disk/source')
disk_path = source.get('file')
injection_path = disk_path
key = net = metadata = admin_pass = None
target_partition = partition
try:
disk.inject_data(injection_path,
key, net, metadata, admin_pass, files,
partition=target_partition,
use_cow=CONF.use_cow_images)
except Exception as e:
# This could be a windows image, or a vmdk format disk
LOG.warn(_('Ignoring error injecting password into instance '), instance=instance)
LOG.error(e.message)
def change_admin_password(self, instance, admin_pass):
try:
virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
# Find the disk
xml_desc = virt_dom.XMLDesc(0)
domain = etree.fromstring(xml_desc)
source = domain.find('devices/disk/source')
disk_path = source.get('file')
injection_path = disk_path
key = net = metadata = files = None
target_partition = CONF.libvirt.inject_partition
try:
disk.inject_data(injection_path,
key, net, metadata, admin_pass, files,
partition=target_partition,
use_cow=CONF.use_cow_images)
except Exception as e:
# This could be a windows image, or a vmdk format disk
LOG.warn(_('Ignoring error injecting password into instance '), instance=instance)
LOG.error(e.message)
def blkdeviotune(self, uuid, device, value):
out, err = utils.execute('virsh',
'blkdeviotune',
'%s' % uuid,
'%s' % device,
'--total_iops_sec',
'%s' % value,
run_as_root=True,
check_exit_code=True)
def update_instance_quota(self, instance, key, value):
try:
virt_dom = self._lookup_by_name(instance['name'])
except exception.InstanceNotFound:
raise exception.InstanceNotRunning()
if key == 'quota:disk_total_iops_sec':
self.blkdeviotune(instance["uuid"], 'vda', value)
def update_metadata(self, context, instance, metadata):
LOG.info(_("Starting update_metadata"), instance=instance)
tune_items = ['disk_read_bytes_sec', 'disk_read_iops_sec',
'disk_write_bytes_sec', 'disk_write_iops_sec',
'disk_total_bytes_sec', 'disk_total_iops_sec']
for key, value in metadata.iteritems():
scope = key.split(':')
if len(scope) > 1 and scope[0] == 'quota':
if scope[1] in tune_items:
self.update_instance_quota(instance, key, value)
| [
"xuchao@chinacloud.com.cn"
] | xuchao@chinacloud.com.cn |
f37c9c9e677a1228090ec17d5e20eddddd95fdfe | f526a5c3a7ca9fb25d4edef88be2e2e353171710 | /TypedTokenEditor/editor_typed_token_impl.py | cb497bba6beb35a35e89a513c6bc7fa47d140c4d | [] | no_license | drvgautam/ProMo-packages-OntologyBuilder | b4d7a71226e9dd385a8857253915b758726315fc | 60aeac5e3b92816f8f5361cffb9eb4e5750ff14b | refs/heads/master | 2023-08-03T01:49:21.231517 | 2021-09-28T12:20:05 | 2021-09-28T12:20:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,464 | py | #!/usr/local/bin/python3
# encoding: utf-8
"""
===============================================================================
editor for typed tokens -- list definition and conversion
===============================================================================
"""
__project__ = "ProcessModeller Suite"
__author__ = "PREISIG, Heinz A"
__copyright__ = "Copyright 2015, PREISIG, Heinz A"
__since__ = "2019. 01. 04"
__license__ = "GPL planned -- until further notice for Bio4Fuel & MarketPlace internal use only"
__version__ = "6.00"
__email__ = "heinz.preisig@chemeng.ntnu.no"
__status__ = "beta"
from collections import OrderedDict
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from Common.common_resources import getData
from Common.common_resources import getOntologyName
from Common.common_resources import M_None
from Common.common_resources import putData
from Common.ontology_container import OntologyContainer
from Common.resource_initialisation import FILES
from Common.ui_two_list_selector_dialog_impl import UI_TwoListSelector
from OntologyBuilder.TypedTokenEditor.editor_typed_token import Ui_MainWindow
from Common.resources_icons import roundButton
SPACING = 20
INSTANCES_Generic = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
INSTANCES = ["A", "W", "C", "R", "I"] # "F", "G", "H", "I", "J",
# "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
# "U", "V", "W", "X", "Y", "Z"]
class Conversion(dict):
def __init__(self, reactants, products):
dict.__init__(self)
self["reactants"] = reactants
self["products"] = products
class TypedTokenData(OrderedDict):
def __init__(self, file=None):
OrderedDict.__init__(self)
if file:
self.read(file)
else:
pass
def initialise(self, typed_tokens):
for ttoken in typed_tokens:
self[ttoken] = {}
self[ttoken]["instances"] = []
self[ttoken]["conversions"] = []
def write(self, f):
# print("write typed-tokens to %s" % f)
putData(self, f, indent=2)
def read(self, f):
data = getData(f)
status = False
if data:
for hash in data:
self[hash] = data[hash]
status = True
return status
class TypedRadioButton(QtWidgets.QRadioButton):
def __init__(self, ID, typed_token):
QtWidgets.QRadioButton.__init__(self, ID)
self.ID = ID
self.typed_token = typed_token
self.setFixedHeight(SPACING)
self.setAutoExclusive(False)
class Ui_TokenEditor(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
roundButton(self.ui.pushSave, "save", tooltip="add typed token")
roundButton(self.ui.pushAddTypedToken, "plus", tooltip="save to file")
# attach ontology
ontology_name = getOntologyName(task="task_typed_tokens")
ontology = OntologyContainer(ontology_name) # DIRECTORIES["ontology_location"] % ontology_name)
self.networks = ontology.list_leave_networks
self.typed_token_file_spec = FILES["typed_token_file"] % ontology_name
self.DATA = TypedTokenData()
typed_tokens = []
self.instances = {}
for nw in self.networks:
for token in ontology.token_typedtoken_on_networks[nw]:
for typed_token in ontology.token_typedtoken_on_networks[nw][token]:
typed_tokens.append(typed_token)
# self.instances[typed_token] = INSTANCES
self.DATA.initialise(typed_tokens)
self.__interfaceLogics("start")
self.new = False
self.selected_typed_token_class = None
gotten = self.load()
if gotten:
self.__interfaceLogics("loaded")
else:
self.__interfaceLogics("start")
typed_tokens_class = self.__makeTokenWithTypedTokensCombo()
self.new = True
self.__interfaceLogics("new")
def __interfaceLogics(self, state):
if state == "start":
self.ui.groupToken.hide()
self.ui.groupConversion.hide()
self.ui.pushSave.hide()
self.ui.statusbar.showMessage("starting")
elif state == "new":
self.ui.groupToken.show()
self.ui.pushAddTypedToken.hide()
self.ui.pushSave.hide()
self.ui.statusbar.showMessage("new definitions")
elif state == "loaded":
self.ui.groupToken.show()
self.ui.pushAddTypedToken.show()
self.ui.pushSave.show()
self.ui.statusbar.showMessage("loaded file")
elif state == "converting token defined":
self.ui.groupConversion.show()
self.ui.groupConverstonControl.show()
self.ui.pushAddTypedToken.show()
self.ui.pushSave.show()
self.ui.statusbar.showMessage("")
elif state == "not converting token define":
self.ui.groupConversion.hide()
self.ui.groupConverstonControl.hide()
self.ui.pushAddTypedToken.show()
elif state == "no conversion defined":
self.ui.groupConverstonControl.hide()
elif state == "conversion defined":
self.ui.groupConverstonControl.show()
elif state == "modified":
self.ui.pushSave.show()
elif state == "saved":
self.ui.pushSave.hide()
def __makeTokenWithTypedTokensCombo(self):
self.ui.comboTokenWithTypedTokens.clear()
self.ui.comboTokenWithTypedTokens.addItem(M_None)
### typed_tokens_class
typed_tokens_class = sorted(
self.DATA.keys()) # self.typed_token_classs_without_conversion | self.typed_token_classs_with_conversion
self.ui.comboTokenWithTypedTokens.addItems(list(typed_tokens_class))
return list(typed_tokens_class)
def __makeConversionCombos(self):
conversions = self.DATA[self.typed_token_class]["conversions"]
if len(conversions) == 0:
self.__interfaceLogics("no conversion defined")
else:
self.ui.spinConversion.setMinimum(0)
self.ui.spinConversion.setMaximum(len(conversions) - 1)
self.ui.comboConversion.clear()
for c in conversions:
s = "%s --> %s" % (c["reactants"], c["products"])
self.ui.comboConversion.addItem(s)
self.__interfaceLogics("conversion defined")
def __clearLayout(self, layout):
""" removes the widgets from the layout """
for i in reversed(range(layout.count())):
widgetToRemove = layout.itemAt(i).widget()
# remove it from the layout list
layout.removeWidget(widgetToRemove)
# remove it from the gui
widgetToRemove.setParent(None)
def __minNumberTypedTokens(self):
conversions = self.DATA[self.typed_token_class]["conversions"]
if len(conversions) == 0:
return 1
index = -1
for no in range(len(INSTANCES)):
s = INSTANCES[no]
for c in conversions:
for r in c["reactants"]:
if r == s:
if index < no:
index = no
for r in c["products"]:
if r == s:
if index < no:
index = no
return index + 1
def load(self):
state = False
if self.DATA.read(self.typed_token_file_spec):
# self.ui.message_box.clear()
# self.ui.message_box.setText('Loading previous typed token file')
state = True
typed_tokens_class = self.__makeTokenWithTypedTokensCombo()
return state
def on_comboTokenWithTypedTokens_currentTextChanged(self, token):
self.selected_typed_token_class = self.ui.comboTokenWithTypedTokens.currentText() # str(token)
if self.selected_typed_token_class == M_None: return
self.typed_token_class = self.selected_typed_token_class
self.__interfaceLogics("not converting token defined")
if self.new:
self.__interfaceLogics("not converting token defined")
two_list_selector = UI_TwoListSelector()
two_list_selector.populateLists(INSTANCES_Generic, [])
two_list_selector.exec_()
selection = two_list_selector.getSelected()
if len(selection) > 0:
self.new = False
self.DATA[self.typed_token_class]["instances"] = selection
else:
pass
self.__interfaceLogics("converting token defined")
min_no = self.__minNumberTypedTokens()
self.__makeConversionCombos()
self.redraw_conversion_radios()
def redraw_conversion_radios(self):
no_of_typed_tokens = len(
self.DATA[self.typed_token_class]["instances"])
self.__interfaceLogics("modified")
token = self.typed_token_class
self.__clearLayout(self.ui.formReactants)
self.__clearLayout(self.ui.formProducts)
self.radioButtonsTokens = {
"reactants": {},
"products" : {}
}
for no in range(int(no_of_typed_tokens)):
self.radioButtonsTokens[token] = {}
t = self.DATA[self.typed_token_class]["instances"][no]
label = "%s :: %s" % (token, t)
r = TypedRadioButton(label, t)
self.radioButtonsTokens["reactants"][no] = r
self.ui.formReactants.setWidget(no, QtWidgets.QFormLayout.LabelRole, r)
r = TypedRadioButton(label, t)
self.radioButtonsTokens["products"][no] = r
self.ui.formProducts.setWidget(no, QtWidgets.QFormLayout.LabelRole, r)
@QtCore.pyqtSlot(int)
def on_spinConversion_valueChanged(self, index):
# print(" change index: ", index)
self.ui.comboConversion.setCurrentIndex(index)
def on_comboConversion_activated(self, index):
set_products = self.ui.comboConversion.currentText()
r, p = self.products = set_products.split('-->')
index = self.ui.comboConversion.currentIndex()
self.ui.spinConversion.setValue(index)
def on_pushSave_pressed(self):
# self.ui.message_box.clear()
# self.ui.message_box.setText('Saving typed token file to:\n'
# + str(self.typed_token_file_spec))
self.DATA.write(self.typed_token_file_spec)
self.__interfaceLogics("saved")
pass
def on_pushNewConversion_pressed(self):
reactants = []
products = []
for r in self.radioButtonsTokens["reactants"]:
a = self.radioButtonsTokens["reactants"][r]
if a.isChecked():
reactants.append(a.typed_token)
a.setChecked(False)
b = self.radioButtonsTokens["products"][r]
if b.isChecked():
products.append(b.typed_token)
b.setChecked(False)
if (not reactants) or (not products):
# self.ui.message_box.setText("you need to define reactants and products to define a new conversion")
return
c = Conversion(reactants, products)
self.DATA[self.typed_token_class]["conversions"].append(c)
self.__makeConversionCombos()
self.__interfaceLogics("modified")
def on_pushDelete_pressed(self):
c = self.DATA[self.typed_token_class]["conversions"].pop(self.ui.spinConversion.value())
self.__makeConversionCombos()
self.__interfaceLogics("modified")
def on_pushAddTypedToken_pressed(self):
selected = self.DATA[self.selected_typed_token_class]["instances"]
selected_set = set(selected)
possible_set = set(INSTANCES_Generic)
enabled_set = possible_set - selected_set
two_list_selector = UI_TwoListSelector()
two_list_selector.populateLists(sorted(enabled_set), sorted(selected))
two_list_selector.exec_()
selection_add = set(two_list_selector.getSelected())
new_selection = selected_set.union(selection_add)
selection = sorted(new_selection)
if len(selection) > 0:
self.new = False
self.DATA[self.selected_typed_token_class]["instances"] = selection
self.redraw_conversion_radios()
| [
"heinz.preisig@chemeng.ntnu.no"
] | heinz.preisig@chemeng.ntnu.no |
4d0ff100df96f78e91c164cc6b0f8108ad06d5c1 | a4da2975725394a1b4973afdd8395bfae04d5a4b | /operaciones_basicas (1).py | e43bd92eb30d3772f7f8a4458f44cf3b64cc5f75 | [
"MIT"
] | permissive | Michikouwu/primerrepo3c | 7c425f30071059632a1e20934f1156f4f83a19d1 | 22f8fcc5c4927657e7fbfca52e06af3d9680eeaf | refs/heads/main | 2023-08-27T22:04:26.576034 | 2021-09-20T17:30:17 | 2021-09-20T17:30:17 | 403,972,855 | 0 | 0 | MIT | 2021-10-04T17:28:31 | 2021-09-07T12:38:18 | Python | UTF-8 | Python | false | false | 410 | py | # Este es el ejercicio del grupo tercero c
# del dia 13 de septiembre de 2021
# esta linea coloca un mensaje en la consola
print("Este programa hace operaciones basicas")
num1 = 130
numero_2 = 345
suma = num1 + numero_2 # la resta se hace con el simbolo '-'
multip = num1 * numero_2 # la division se hace con una '/'
print("la suma es: ")
print(suma)
print("La multiplicacion da como resultado: ", multip)
| [
"noreply@github.com"
] | noreply@github.com |
695b834fd9242f05d4e9da6c8417c9762ee8c321 | 53902f5c212f8b0024ea723109989085876adef1 | /emailnotifications/apps.py | d3aaf8207483e3cafc6ea1d775adb46e7e9fbdff | [] | no_license | GammaWind/Url-Shortner-main | 40fc4d088f1ed4a283ae705251d4962d6b497a6b | 93fd46dbc90034a589b0d7ca4cbd0d58fb8e9e7d | refs/heads/main | 2023-03-08T10:18:50.658087 | 2021-02-21T10:16:34 | 2021-02-21T10:16:34 | 336,628,574 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 111 | py | from django.apps import AppConfig
class EmailnotificationsConfig(AppConfig):
name = 'emailnotifications'
| [
"niharpawade@outlook.com"
] | niharpawade@outlook.com |
c0ecc3296cd811fe782785ac56a926a7383d5c13 | 128b3bb5e5e3797ea73b8d71ec479b02d2d02b75 | /py/h2o_nodes.py | 55df64bb6144d92806a795cb08cbf9c422050764 | [
"Apache-2.0"
] | permissive | JerryZhong/h2o | 14819b044466dffe4ec461cb154898610f6be8b3 | c8ce6d223786673b5baf28f26d653bf4bd9f4ba9 | refs/heads/master | 2021-01-17T10:12:35.547837 | 2014-11-07T11:05:47 | 2014-11-07T11:05:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | py |
# does the globally visible update behavior on these depend on them being mutables?
# to get rid of circular imports
# should think of managing this differently
print "h2o_nodes"
nodes = []
# used to get a browser pointing to the last RFview
global json_url_history
json_url_history = []
| [
"kevin@0xdata.com"
] | kevin@0xdata.com |
962fcdea414dd16c0440dbb76f316855a7adf46d | 30f89269bf4507c92b1161080feb007d614c99ed | /LAUG/aug/Word_Perturbation/multiwoz/run.py | d46d51caa1eeab4a100c1db916eef44bb96e8908 | [
"Apache-2.0"
] | permissive | xiaoanshi/LAUG | 525b93d25d53c616466fd28d162f6c6f6fa34658 | c3e7f98f71de77b5d73945b15f37dd22d8a2f8c8 | refs/heads/main | 2023-06-19T16:29:18.075959 | 2021-07-23T10:50:17 | 2021-07-23T10:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,109 | py | import os, json
from LAUG.aug.Word_Perturbation.multiwoz.multiwoz_eda import MultiwozEDA
from LAUG.aug.Word_Perturbation.multiwoz.db.slot_value_replace import MultiSourceDBLoader, MultiSourceDBLoaderArgs
from LAUG.aug.Word_Perturbation.multiwoz.util import load_json
from LAUG import DATA_ROOT
def main(multiwoz_filepath, output_filepath, alpha_sr=0.1, alpha_ri=0.1, alpha_rs=0.1, p_rd=0.1, num_aug=2,
p_slot_value_replacement=0.25):
multiwoz = load_json(multiwoz_filepath)
db_dir = os.path.join(DATA_ROOT, 'multiwoz', 'db')
multiwoz_multiwoz_domain_slot_map = {
('attraction', 'area'): ('attraction', 'Area'),
('attraction', 'type'): ('attraction', 'Type'),
('attraction', 'name'): ('attraction', 'Name'),
('attraction', 'address'): ('attraction', 'Addr'),
('hospital', 'department'): ('hospital', 'Department'),
('hospital', 'address'): ('hospital', 'Addr'),
('hotel', 'type'): ('hotel', 'Type'),
('hotel', 'area'): ('hotel', 'Area'),
('hotel', 'name'): ('hotel', 'Name'),
('hotel', 'address'): ('hotel', 'Addr'),
('restaurant', 'food'): ('restaurant', 'Food'),
('restaurant', 'area'): ('restaurant', 'Area'),
('restaurant', 'name'): ('restaurant', 'Name'),
('restaurant', 'address'): ('restaurant', 'Addr'),
('train', 'destination'): ('train', 'Dest'),
('train', 'departure'): ('train', 'Depart')
}
loader_args = MultiSourceDBLoaderArgs(db_dir, multiwoz_multiwoz_domain_slot_map)
db_loader = MultiSourceDBLoader(loader_args)
eda = MultiwozEDA(multiwoz, db_loader,
slot_value_replacement_probability=p_slot_value_replacement,
alpha_sr=alpha_sr, alpha_ri=alpha_ri, alpha_rs=alpha_rs, p_rd=p_rd, num_aug=num_aug)
result = eda.augment_multiwoz_dataset('usr')
os.makedirs(os.path.dirname(os.path.abspath(output_filepath)), exist_ok=True)
with open(output_filepath, 'w', encoding='utf-8') as out:
json.dump(result, out, indent=4)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--multiwoz_filepath", '--multiwoz', default='multiwoz.json')
parser.add_argument('--output_filepath', '--output', '-o', default='augmented_multiwoz.json')
parser.add_argument('--alpha_sr', type=float, default=0.1, help='probability of replacement')
parser.add_argument('--alpha_ri', type=float, default=0.1, help='probability of insertion')
parser.add_argument('--alpha_rs', type=float, default=0.1, help='probability of swap')
parser.add_argument('--p_rd', type=float, default=0.1, help="probability of deletion")
parser.add_argument('--num_aug', type=int, default=2, help="generate `num_aug` candidates with EDA and randomly choose one dialog as augmented dialog.")
parser.add_argument('--p_slot_value_replacement', '-p_svr', type=float, default=0.25, help='probability to replace a slot value.')
opts = parser.parse_args()
main(**vars(opts))
| [
"hualai-liujiexi"
] | hualai-liujiexi |
802391643c571e18444c6d654b5d64d6f05396f0 | dd18a5762680e4d0ec6306fd58a8d80adf9e8187 | /train_ddpg_psne.py | eb2087119582166489e3628d97d7c6ab83e59d20 | [] | no_license | gtuzi/Deep_RL_continuous_control | 747cfcef623daa1901870b152d8597c5f6b2f119 | f270724baf42328aefe23417b8d87aea47737faa | refs/heads/master | 2020-04-10T11:51:25.329554 | 2019-03-21T03:34:17 | 2019-03-21T03:34:17 | 161,004,608 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 7,617 | py | import torch
import numpy as np
from collections import deque
from unityagents import UnityEnvironment
from udacity.ddpg_psne import Agent
from tensorboardX import SummaryWriter
import os
cwd = os.getcwd()
def get_env(agents = 'multi'):
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
# linux
if agents == 'single':
env = UnityEnvironment(file_name="./Reacher_Linux/Reacher.x86_64", no_graphics = False)
elif agents == 'multi':
env = UnityEnvironment(file_name="./Reacher_Linux_Multi/Reacher.x86_64", no_graphics=False)
else:
raise Exception('Unrecognized environment type')
elif _platform == "darwin":
# MAC OS X
if agents == 'single':
env = UnityEnvironment(file_name="Reacher.app", no_graphics = False)
elif agents == 'multi':
env = UnityEnvironment(file_name="Reacher_Multi.app", no_graphics=False)
else:
raise Exception('Unrecognized environment type')
else:
raise Exception('Unsupported OS')
return env
def welcome(agents):
env = get_env(agents)
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents
num_agents = len(env_info.agents)
# size of each action
action_size = brain.vector_action_space_size
# examine the state space
states = env_info.vector_observations
state_size = states.shape[1]
print('Number of agents:', num_agents)
print('Size of each action:', action_size)
print('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size))
return env, state_size, action_size
def save_nets(agent, subdir):
if not os.path.isdir(cwd + '/models/{}'.format(subdir)):
os.makedirs(cwd + '/models/{}'.format(subdir))
torch.save(agent.actor_local.state_dict(), 'local_actor.pth'.format(subdir))
torch.save(agent.critic_local.state_dict(), 'local_critic.pth'.format(subdir))
torch.save(agent.actor_target.state_dict(), 'target_actor.pth'.format(subdir))
torch.save(agent.critic_target.state_dict(), 'target_critic.pth'.format(subdir))
def ddpg_single_agent(env, agent, n_episodes=2000, max_t=int(10000), subdir=''):
scores_deque = deque(maxlen=100)
episode_horizons = deque(maxlen=100)
scores = []
max_score = -np.Inf
brain_name = env.brain_names[0]
for i_episode in range(1, n_episodes + 1):
env_info = env.reset(train_mode=True)[brain_name]
state = env_info.vector_observations
agent.reset()
score = 0
for t in range(max_t):
action = agent.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations
reward = np.array(env_info.rewards)
done = np.array(env_info.local_done)
if t + 1 == max_t:
done = np.ones_like(done, dtype=np.bool)
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if done:
episode_horizons.append(t)
break
scores_deque.append(score)
scores.append(score)
print(
'\rEpisode {}\tAverage Score: {:.2f}\tScore: {:.2f}\tTime Step: {}'.format(i_episode, np.mean(scores_deque),
float(score), agent.total_steps),
end="")
if i_episode % 50 == 0:
print('\tAvg. Horizon: {:.2f}'.format(np.mean(episode_horizons)))
if np.mean(scores_deque) >= 30.:
print('The environment was solved in {} episodes'.format(i_episode))
break
save_nets(agent, subdir)
return scores
def ddpg_multi_agent(env, agent, n_episodes=2000, max_t=int(10000), subdir=''):
scores_deque = deque(maxlen=100)
scores = []
episode_horizons = deque(maxlen=100)
max_score = -np.Inf
brain_name = env.brain_names[0]
solved = False
for i_episode in range(1, n_episodes + 1):
env_info = env.reset(train_mode=True)[brain_name]
state = env_info.vector_observations
n_agents = state.shape[0]
agent.reset()
score = np.zeros((n_agents, 1), dtype=np.float32)
for t in range(max_t):
action = agent.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations
reward = np.array(env_info.rewards)[..., None]
done = np.array(env_info.local_done)[..., None]
if t + 1 == max_t:
done = np.ones_like(done, dtype=np.bool)
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if np.all(done):
episode_horizons.append(t)
break
scores_deque.append(score)
scores.append(score)
_mu_score_moving = np.mean(np.mean(scores_deque, axis=1))
print('\rEpisode {}\t100-episode avg score: {:.2f}\tScore: {:.2f}\tTime Step: {}'.format(i_episode,
_mu_score_moving,
float(np.mean(score)),
agent.total_steps),
end="")
if i_episode % 50 == 0:
print(
'\rEpisode {}\t100-episode avg score: {:.2f}\tAvg. Horizon: {:.2f}'.format(i_episode, _mu_score_moving,
np.mean(episode_horizons)))
if (np.mean(scores_deque) >= 30.) and (i_episode > 99) and (not solved):
print('\nThe environment was solved in {} episodes'.format(i_episode))
solved = True
save_nets(agent, subdir)
return scores
import sys, getopt
if __name__== "__main__":
# Defaults
agents = 'multi'
max_t = 1000
n_episodes = 2000
prefix = 'ddpg_psne_'
_prefix = None
# Parse arguments and options
try:
opts, args = getopt.getopt(sys.argv[1:], shortopts="a:e:f:")
except getopt.GetoptError as ex:
print('train_ddpg_psne.py -a <string: single / multi> -e <int: number of episodes> -f <string: subdir in <~/models> for saved nets, <~/logs> for logs')
sys.exit(2)
for opt, arg in opts:
if opt in ("-a",):
agents = str(arg)
assert (agents == 'single') or (agents == 'multi'), 'Agents must be either <single> or <multi>'
if opt in ("-e",):
n_episodes = int(str(arg))
if opt in ("-f",):
_prefix = str(arg)
prefix = _prefix if _prefix is not None else prefix + agents
logpath = cwd + '/logs/{}'.format(prefix)
if not os.path.isdir(logpath):
os.makedirs(logpath)
writer = SummaryWriter(log_dir=logpath)
env, state_size, action_size = welcome(agents)
agent = Agent(state_size=state_size, action_size=action_size, random_seed=0, writer=writer)
if agents == 'multi':
ddpg_multi_agent(env, agent, n_episodes=n_episodes, max_t=1000, subdir=prefix)
elif agents == 'single':
ddpg_single_agent(env, agent, n_episodes=n_episodes, max_t=1000, subdir=prefix)
| [
"gertituzi@gmail.com"
] | gertituzi@gmail.com |
cd8c39eff00b00f3071855b64494d6159d08584a | 45b64f620e474ac6d6b2c04fbad2730f67a62b8e | /Varsity-Final-Project-by-Django-master/.history/project/quiz/views_20210423112204.py | 7280d320c23c7ccb25ba0eff899768fde6d05502 | [] | no_license | ashimmitra/Final-Project | 99de00b691960e25b1ad05c2c680015a439277e0 | a3e1d3c9d377e7b95b3eaf4dbf757a84a3858003 | refs/heads/master | 2023-04-11T06:12:35.123255 | 2021-04-26T15:41:52 | 2021-04-26T15:41:52 | 361,796,607 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 974 | py | from django.shortcuts import render
from quiz.models import Quiz
from quiz.models import Bangla
from quiz.models import Math
from quiz.models import Science
from quiz.models import GK
#def welcome(request):
#return render(request, 'welcome.html')
def english(request):
questions = Quiz.objects.all()
return render(request, 'english.html', { 'questions': questions})
def bangla(request):
questions = Bangla.objects.all()
return render(request, 'bangla.html', { 'questions': questions})
def math(request):
questions = Math.objects.all()
return render(request, 'math.html', { 'questions': questions})
def science(request):
questions = Science.objects.all()
return render(request, 'science.html', { 'questions': questions})
def generalknowledge(request):
questions = GK.objects.all()
return render(request, 'generalknowledge.html', { 'questions': questions})
def result(request):
return render(request, 'result.html')
| [
"34328617+ashimmitra@users.noreply.github.com"
] | 34328617+ashimmitra@users.noreply.github.com |
dac776dc3cbec6baf5fef351ff9702cb37705b62 | ec0b8551b15f73628d7afe01855bdd7171887097 | /solutions/fibo.py | 01ae1caa8e2e934db1a122059877e4629fd66af4 | [] | no_license | krishna-kumar456/Code-Every-Single-Day | 146a6f65b53a16bb174c2b61dbac8366cc4ca53a | 8746f74fe29c1dd639453826ef0e30788674d984 | refs/heads/master | 2021-08-08T11:45:04.134707 | 2017-11-10T08:39:21 | 2017-11-10T08:39:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 233 | py | def print_fibonacci(n):
if n <= 1:
return 1
else:
return print_fibonacci(n-1) + print_fibonacci(n-2)
user_input = int(input("Enter number whose fibonacci needs to be found"))
result = print_fibonacci(user_input)
print(result)
| [
"krishnaqmar@gmail.com"
] | krishnaqmar@gmail.com |
88e37ae61086666bf49c3decdda3ec5c96620c45 | 018d76162bc1e52f3550989d2274614cf0e197b4 | /pc/build/hector_imu_tools/catkin_generated/pkg.installspace.context.pc.py | 8431c101abd726a29c549a411cf676489bf2f7ad | [] | no_license | HarryOMalley/final_year_project | 0682f40561ffa4a7eb07fe52a0e2231851b689ea | 5c7ff41d3493b3b4a25f9c071f2edc1faef61ae4 | refs/heads/master | 2020-04-14T18:19:44.030559 | 2019-05-16T19:53:49 | 2019-05-16T19:53:49 | 164,014,785 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "hector_imu_tools"
PROJECT_SPACE_DIR = "/home/harry/Documents/Git/final_year_project/pc/install"
PROJECT_VERSION = "0.3.5"
| [
"hazaomalley@gmail.com"
] | hazaomalley@gmail.com |
e2c69efcc974d82561d092fe3f64a39b5e67c823 | 2b5d0b42f233caf8b1842f6f6db378207952d7ff | /nthprime.py | fd29f5ab2a07318326e5f93e5531f4df27b536b0 | [] | no_license | aslamup/euler | 8edf7d90f593f2bd8b1f8fc9cdb83cd9dea679cf | 755878ad8c64bff1b33cc94802983aeed425dd8c | refs/heads/master | 2021-01-01T15:18:10.335949 | 2014-04-01T06:44:19 | 2014-04-01T06:44:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 477 | py | import math
def is_prime(number):
if number<=1:
return False
if number==2:
return True
if number%2==0:
return False
for i in range(3,int(math.sqrt(number))+1):
if number%i==0:
return False
return True
def term(n):
x = 0
count = 0
while count != n:
x = x + 1
if is_prime(x) == True:
count = count + 1
return x
print term(1000)
| [
"aslam@aslam-Satellite-Pro-C660.(none)"
] | aslam@aslam-Satellite-Pro-C660.(none) |
0c5c6040ea01905558080880129f9e0e4d4d5263 | 2d30f85c30ba069830a872554786c2f7b645ee4e | /aoc2022/day20.py | 526f39a7daa7633e2415f906a5e6260a69be2ab5 | [] | no_license | jhuang97/adventofcode | fff0cb8f803ec37bff889dc897e3e474f3f00a36 | e2e83a5b8b4e6b8fad14b9484a64fbe404a6c37e | refs/heads/master | 2022-12-27T07:54:08.140910 | 2022-12-25T05:24:39 | 2022-12-25T05:24:39 | 225,652,688 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,192 | py | import numpy as np
file = open('day20_in.txt', 'r')
num_str = file.read().strip().splitlines()
nums = np.array([int(n) for n in num_str])
# nums = np.array([1, 2, -3, 3, -2, 0, 4])
right = np.zeros(len(nums), dtype=int)
left = np.zeros(len(nums), dtype=int)
right[:-1] = np.arange(1, len(nums))
right[-1] = 0
left[1:] = np.arange(len(nums)-1)
left[0] = len(nums)-1
# assume that i2 is to the right of i1
def swap(i1, i2):
right_i2 = right[i2]
left_i1 = left[i1]
right[left_i1], right[i2], right[i1] = i2, i1, right_i2
left[i2], left[i1], left[right_i2] = left_i1, i2, i1
def move(idx, dist):
from_left, from_right = left[idx], right[idx]
if dist > 0:
to_left = idx
for _ in range(abs(dist)):
to_left = right[to_left]
to_right = right[to_left]
elif dist < 0:
to_right = idx
for _ in range(abs(dist)):
to_right = left[to_right]
to_left = left[to_right]
right[from_left], left[from_right] = from_right, from_left
right[idx], left[idx] = to_right, to_left
right[to_left], left[to_right] = idx, idx
def decrypt(nums, n_mix):
# print(np.where(nums==0))
idx_0 = np.where(nums == 0)[0][0]
p = len(nums)-1
phalf = p//2
nums_modded = (nums + phalf) % p - phalf
right[:-1] = np.arange(1, len(nums))
right[-1] = 0
left[1:] = np.arange(len(nums)-1)
left[0] = len(nums)-1
for mix_index in range(n_mix):
print(mix_index)
for k in range(len(nums)):
# if k % 2000 == 0:
# print(k)
# nmove = np.abs(nums[k])
# move_dist = nums[k]
# move_dist = nums[k] % (len(nums) - 1)
move_dist = nums_modded[k]
if move_dist != 0:
move(k, move_dist)
# print(f'turn {k}')
# print(k, nums[k], nums[k] % len(nums))
# list_str = ''
# idx = 0
# for _ in range(len(nums)):
# list_str += str(nums[idx]) + ' '
# idx = right[idx]
# print(list_str)
grove_num = []
idx = idx_0
for _ in range(3):
for _ in range(1000):
idx = right[idx]
grove_num.append(nums[idx])
# print(grove_num)
return sum(grove_num)
print(decrypt(np.array([int(n) for n in num_str]), 1))
print(decrypt(np.array([int(n) * 811589153 for n in num_str]), 10)) | [
"noreply@github.com"
] | noreply@github.com |
741f4f977054d674b6570a9cbd439392f1bdf378 | c8a0f1ee8ca4b27d6b71e1a358f950a5f168b953 | /Sessão 4/Atributos de classe/Encapsulamento.py | cf204b06b1de3f55ff1b2bc2ec9d5e83d5a6d641 | [] | no_license | natanaelfelix/Estudos | 0c3a54903a5ac457c1c1cfbdc22202683c46b62c | 10b33fa7cb8521d63ea6a14c04894a5f7e86ee0c | refs/heads/master | 2022-12-16T12:07:45.088305 | 2020-09-19T19:56:07 | 2020-09-19T19:56:07 | 296,936,330 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,553 | py | #esconde codigos em python
'''
public, # metodos e atributos podem ser acesso dentro e fora da class,
protect # atributos que podem ser acesso apenas dentro da classe ou nas filhas da classe
private # atributo ou metodo só está disponível dentro da classe
em python:
isso é chamado de convenção
_ = é o mesmo que é privado, as é um protected mais fraco
__ = é o mesmo que privado, diz que não se deve usar em hipotese nenhuma
para acessar o real do pivado:
(instancia_nomedaclasse__nomedoatributo)
#tudo isso para proteger a aplicação
'''
class BaseDeDados:
def __init__(self):
#self.dados = {} # essa é publica, acessada de dentro e fora da classe, caso seja mudado esse valor de variável quebra toda a classe
#self.__dados = {} #usando o _ na frente do nome ele diz q é privado e não consiguimos utilizar de fora
self.__dados = {} #usando so dois __ ele não deixa utilizar, se caso utilizarmo sd fora ele cria outro atributo
def inserir_cliente(self, id, nome):
if 'clientes' not in self.__dados:
self.__dados['clientes'] = {id: nome}
else:
self.__dados['clientes'].update({id: nome})
def lista_clientes(self):
for id, nome in self.__dados['clientes'].items():
print(id, nome)
def apaga_cliente(self, id):
del self.__dados['clientes'][id]
bd = BaseDeDados()
bd.inserir_cliente(1, 'Adriano')
bd.inserir_cliente(2, 'Ronaldo')
bd.inserir_cliente(3, 'Priscila')
bd.apaga_cliente(2)
bd.lista_clientes()
print(bd.__dados)
| [
"natanaelmartinsfelix@hotmail.com"
] | natanaelmartinsfelix@hotmail.com |
ccedc17ba5f223b2b46ee55cbe835f9f835c7af1 | 2cf1f60d5adcc9fe56366e26b95860a440bcb230 | /Previous Year CodeVita/Travel_Cost.py | 3818cb399113612f5e097dfbda7f072ec2e90394 | [] | no_license | rohanJa/DSA_IMP | 619a7b5c89b55cbff3c77b265242c05ebedd6140 | b0ead018814d53a00cc47cda1915ad0dfe5c30dc | refs/heads/master | 2022-12-23T22:56:32.775027 | 2020-09-01T06:52:25 | 2020-09-01T06:52:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 463 | py | import heapq
N = int(input())
cities = list(map(int, input().split(' ')))
M = int(input())
if(len(cities)<=1 or cities[-1]==-1):
print(-1)
else:
cost = cities[0] + cities[-1]
cities = cities[1:len(cities)-1]
heapq.heapify(cities)
for i in range(0,len(cities)):
if(cities[i]==-1):
M-=1
else:
cost+=cities[i]
if(M<0):
print(-1)
else:
print(cost - sum(heapq.nlargest(M,cities)))
| [
"pkopergaonkar@gmail.com"
] | pkopergaonkar@gmail.com |
8dff3d3ce71476161dacbf91ee9ed73af5530b6b | 919c60040c4cafe6dbbde0025068bf5501cf133f | /my-function.py | a1ba39911b138667bd5bedc6dff47153aa2282fc | [] | no_license | bs3537/lambdata | 29ef219e1258523f8d5a71fc3dd5d5c6e805cd04 | 39ea67107dd8c3f9bfee608b0e0b1f0382a02586 | refs/heads/master | 2020-12-15T21:06:16.581498 | 2020-01-21T04:18:07 | 2020-01-21T04:18:07 | 235,254,373 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 34 | py | def my-function():
pass
| [
"noreply@github.com"
] | noreply@github.com |
8f756a1da0a0b4cd1ff061bdc03f1117d72ff621 | 2d055d8d62c8fdc33cda8c0b154e2b1e81814c46 | /python/demo_everyday/JCP005.py | 65afb4f4b0f92658ee5703d854d43dd3882ff39d | [
"MIT"
] | permissive | harkhuang/harkcode | d9ff7d61c3f55ceeeac4124a2a6ba8a006cff8c9 | faab86571ad0fea04c873569a806d2d7bada2e61 | refs/heads/master | 2022-05-15T07:49:23.875775 | 2022-05-13T17:21:42 | 2022-05-13T17:21:53 | 20,355,721 | 3 | 2 | MIT | 2019-05-22T10:09:50 | 2014-05-31T12:56:19 | C | GB18030 | Python | false | false | 469 | py | '''
【程序5】
题目:输入三个整数x,y,z,请把这三个数由小到大输出。
1.程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,
然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
2.程序源代码:
'''
l = []
for i in range(3):
x = int(raw_input('integer:\n'))
l.append(x)
l.sort()
print l
| [
"shiyanhk@gmail.com"
] | shiyanhk@gmail.com |
f5984b8c2b82af6c55adb0808338d331021ee8e8 | 84eb931716477828f05d8e4343c7fa2b21c2f02a | /从数据库查询数据/dynamic/mini_frame.py | ec1dab5cb631ff8c9a6b299edc34e9095041f0b9 | [] | no_license | wawawawawawawawawawa/My_Python_Practise | 506c93413d9ed0ddeac594e115b7c39e60a1c915 | 89c23d80eb3d86f333a9832828f0527c60cdff2e | refs/heads/master | 2020-09-01T09:05:08.097710 | 2020-05-26T09:20:31 | 2020-05-26T09:20:31 | 218,926,440 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,856 | py | import re
from pymysql import connect
"""
URL_FUNC_DICT = {
"/index.html": index,
"/center.html": center
}
"""
URL_FUNC_DICT = dict()
def route(url):
def set_func(func):
# URL_FUNC_DICT["/index.py"] = index
URL_FUNC_DICT[url] = func
def call_func(*args, **kwargs):
return func(*args, **kwargs)
return call_func
return set_func
@route("/index.html")
def index():
with open("./templates/index.html") as f:
content = f.read()
# my_stock_info = "哈哈哈哈 这是你的本月名称....."
# content = re.sub(r"\{%content%\}", my_stock_info, content)
# 创建Connection连接
conn = connect(host='localhost', port=3306, user='root', password='mysql', database='stock_db', charset='utf8')
# 获得Cursor对象
cs = conn.cursor()
cs.execute("select * from info;")
stock_infos = cs.fetchall()
cs.close()
conn.close()
content = re.sub(r"\{%content%\}", str(stock_infos), content)
return content
@route("/center.html")
def center():
with open("./templates/center.html") as f:
content = f.read()
my_stock_info = "这里是从mysql查询出来的数据。。。"
content = re.sub(r"\{%content%\}", my_stock_info, content)
return content
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
file_name = env['PATH_INFO']
# file_name = "/index.py"
"""
if file_name == "/index.py":
return index()
elif file_name == "/center.py":
return center()
else:
return 'Hello World! 我爱你中国....'
"""
try:
# func = URL_FUNC_DICT[file_name]
# return func()
return URL_FUNC_DICT[file_name]()
except Exception as ret:
return "产生了异常:%s" % str(ret)
| [
"1746409650@qq.com"
] | 1746409650@qq.com |
dda676cdb3b83bb87b4f3f945fa07df61dae7315 | f5fc727b8dce88283bf95406527ea7dc6be567dd | /backup_sql_upload_s3_updated.py | a0a691965f2ed80e111f0635cfb4ce45a537f1a6 | [] | no_license | vecrofund/devops-task-4 | 09260c7512cb39981f2efc12c55f166ac638607a | e94b3dde61b109451970405271b8e6c51ec4ac25 | refs/heads/master | 2023-04-03T21:26:52.372317 | 2021-03-26T08:53:19 | 2021-03-26T08:53:19 | 349,724,855 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,754 | py | ### SOURCES:
### https://docs.python.org/3/library/shutil.html#module-shutil
### http://boto.cloudhackers.com/en/latest/#
### https://python-forum.io/Thread-Menu-selection-using-function
import os
import shutil
import boto
import datetime
import string
import tarfile
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from datetime import timedelta
from cryptography.fernet import Fernet
### variables:
### data/time variables
today = str(datetime.date.today())
now = datetime.datetime.now()
### connection info:
aws_secret_access_key = 'access_key'
aws_access_key = 'access_key'
aws_bucket_name = 'bucket name'
aws_folder_name = '/tmp/'
### MENU
def showmenu():
print("\nBackup menu")
print("---------------")
print("A - Start backup")
print("B - Remove backup")
print("C - Status backup")
print("Q - Exit\n")
def menu():
while True:
showmenu()
choice = input("Enter your choice:")
if choice == 'A':
startBackup()
elif choice == 'B':
removeBackup()
elif choice == 'C':
statusBackup()
elif choice == 'Q':
return
else:
print("Try again")
if __name__ == '__main__':
menu()
def startBackup():
print(now + '- Backup is starting!')
### insert backup info:
insert_backup_name = input ('Insert database name where you want to backup: ')
backup_name = print(insert_backup_name + '.sql')
insert_backup_dir = input ('Insert path to directory where you want to save backup: /tmp/...')
backup_dir = print('/tmp/' +insert_backup_dir)
## backup info:
backup_create_dir("mkdir" + backup_dir)
backup_mysqldump= "mysqldump '"+ backup_name +"' > '"+ backup_dir +"''"+ backup_name +"'"
os.system(backup_create_dir)
os.execute(backup_cmd)
### backup/archive variables:
archieve_name = backup_name
backup_path = backup_dir + backup_name
archieve_path = backup_dir + archieve_name
### backuping/archiving:
print(now + ' - Creating archive for ' + backup_name)
## shutil copying and removal functions
shutil.make_archive(archieve_path, 'gztar', backup_dir)
print(now + ' - Completed archiving database')
full_archive_file_path = archieve_path + ".tar.gz"
full_archive_name = archieve_name + ".tar.gz"
### Connect to S3
s3 = S3Connection(aws_access_key, aws_secret_access_key)
bucket_name = s3.get_bucket(aws_bucket_name)
### Upload backup to S3
print(now + '- Uploading file archive ' + full_archive_name + '...')
s3_bucket = Key(bucket_name)
s3_bucket.key = aws_folder_name + full_archive_name
print(s3_bucket.key)
s3_bucket.set_contents_from_filename(full_archive_file_path)
s3_bucket.set_acl("public-read")
print(now + '- Clearing previous archives ' + full_archive_name + '...')
shutil.rmtree(backup_dir)
print(now + '- Removed backup of local database')
print(now + '- Backup job is done')
def removeBackup():
if os.path.exists(backup_dir + backup_name):
### removing backup file
print("Removing backup file" + backup_dir + backup_name)
os.remove(backup_dir + backup_name)
print("Removed")
else:
print("The file does not exist!")
def statusBackup():
import os.path
if os.path.isfile(backup_dir + backup_name):
print ("Backup file" + backupdir + backup_name + " exists ")
else:
print ("File not exist")
| [
"vecrofund@gmail.com"
] | vecrofund@gmail.com |
e8085ea325193628fcec58e94df32db540328951 | 5739dcfe59868b83b3c4d88684d0e29e86a29dc2 | /data/templates/derived/nav/create_page.html.py | d60abe0efb76251b468277c5fa1b27eb5719c7ef | [] | no_license | manumilou/chezwam | 95fb075dc986a4535f3b1b459c8dcabb851a2767 | b89594dc66001ea6b64493e21b1d851f20b0212c | refs/heads/master | 2021-01-19T00:08:02.424572 | 2010-09-23T15:59:00 | 2010-09-23T15:59:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 749 | py | from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1285039074.021173
_template_filename='/home/remix/dev/ChezWam/chezwam/templates/derived/nav/create_page.html'
_template_uri='/derived/nav/create_page.html'
_template_cache=cache.Cache(__name__, _modified_time)
_source_encoding='utf-8'
from webhelpers.html import escape
_exports = []
def render_body(context,**pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
__M_writer(u'\n')
return ''
finally:
context.caller_stack._pop_frame()
| [
"remix@eeepc-remix.(none)"
] | remix@eeepc-remix.(none) |
953d993189efb3d5fa2ee45a39a059e6fdf9d196 | dd6c70ba403c80610f5a78a3492f367388102505 | /src/codeforces/educational145/one.py | d7692b9219abe5cfc8e84989c53e1fc4c0252af3 | [
"MIT"
] | permissive | paramsingh/cp | 80e13abe4dddb2ea1517a6423a7426c452a59be2 | 126ac919e7ccef78c4571cfc104be21da4a1e954 | refs/heads/master | 2023-04-11T05:20:47.473163 | 2023-03-23T20:20:58 | 2023-03-23T20:21:05 | 27,965,608 | 16 | 6 | null | 2017-03-21T03:10:03 | 2014-12-13T16:01:19 | C++ | UTF-8 | Python | false | false | 344 | py | from collections import defaultdict
t = int(input())
for _ in range(t):
chars = map(int, input()[::])
freqs = defaultdict(int)
for char in chars:
freqs[char] += 1
max_freq = max(freqs.values())
if max_freq == 1 or max_freq == 2:
print(4)
elif max_freq == 3:
print(6)
else:
print(-1)
| [
"me@param.codes"
] | me@param.codes |
4bbdd427e894721dcab89747826e62687cd73703 | c27c0f9a799f2232b0a75d2184019df239ea941f | /lista1/questao10.py | deb7c2a519fefe843ff94d97a879360ccd400499 | [] | no_license | anderson89marques/WebResultadoSimulacaoPyramid | 88d0f8f4f57752a26fa7205a5768910686fe3682 | a7d51f79b348467dd771925f3a24aa6463a65e03 | refs/heads/master | 2016-09-06T01:01:47.711626 | 2014-11-19T21:19:49 | 2014-11-19T21:19:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 638 | py | __author__ = 'andersonmarques'
import random
class Questao10():
def __init__(self):
pass
def getquestao(self):
#1 = cara, 2 = coroa
experimentos = 10000
cont = 0
for x in range(experimentos):
contcara = 0
contcoroa = 0
for i in range(100):
if random.randint(1, 2) == 1:
contcara += 1
else:
contcoroa += 1
if contcara == 40:
cont += 1
#print("probabilidade %.4f" % (cont/experimentos))
return {'questao 10': "%.4f" % (cont/experimentos)} | [
"Andersonoanjo18@gmail.com"
] | Andersonoanjo18@gmail.com |
d4d244acc6de2aa772ee2339ee4e09cf3d0b86c2 | 8b51701f6e224e373db06ccbfa1c08387b2b8d5a | /FB fetching/geopy/geocoders/wiki_semantic.py | 156bd88cdda2eac1b246a787e48712c811fa2606 | [] | no_license | nickedes/MinimaPy | efdd40c0fb135d44fc105105df8dbcee5baa9aaa | 23e7887e1a87a5ac3f19d9bd75e37a98a16b1905 | refs/heads/master | 2021-01-22T10:22:12.739714 | 2014-09-21T20:22:00 | 2014-09-21T20:22:00 | 17,544,073 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,447 | py | """
:class:`.SemanticMediaWiki` geocoder.
"""
import xml.dom.minidom
from geopy.compat import BeautifulSoup
from geopy.geocoders.base import Geocoder, DEFAULT_TIMEOUT
from geopy import util
try:
set
except NameError:
from sets import Set as set # pylint: disable=W0622
class SemanticMediaWiki(Geocoder):
"""
SemanticMediaWiki geocoder. No idea on documentation. Not compliant with
geocoder API of #geocode &c. TODO.
"""
def __init__(self, format_url, attributes=None, relations=None, # pylint: disable=R0913
prefer_semantic=False, transform_string=None, timeout=DEFAULT_TIMEOUT,
proxies=None):
super(SemanticMediaWiki, self).__init__(timeout=timeout, proxies=proxies)
self.format_url = format_url
self.attributes = attributes
self.relations = relations
self.prefer_semantic = prefer_semantic
if transform_string:
self._transform_string = transform_string
def _get_url(self, string):
"""
Generate full query URL.
"""
return self.format_url % self._transform_string(string)
def get_label(self, thing):
raise NotImplementedError()
@staticmethod
def parse_rdf_link(page, mime_type='application/rdf+xml'):
"""Parse the URL of the RDF link from the <head> of ``page``."""
soup = BeautifulSoup(page)
link = soup.head.find( # pylint: disable=E1101,E1103
'link', rel='alternate', type=mime_type
)
return link and link['href'] or None
def parse_rdf(self, data):
# TODO cleanup
dom = xml.dom.minidom.parseString(data)
things = dom.getElementsByTagName('smw:Thing')
things.reverse()
for thing in things:
name = thing.attributes['rdf:about'].value
articles = thing.getElementsByTagName('smw:hasArticle')
things[name] = articles[0].attributes['rdf:resource'].value
return (things, thing)
@staticmethod
def _transform_string(string): # pylint: disable=E0202
"""Normalize semantic attribute and relation names by replacing spaces
with underscores and capitalizing the result."""
return string.replace(' ', '_').capitalize()
def get_relations(self, thing, relations=None):
if relations is None:
relations = self.relations
for relation in relations:
relation = self._transform_string(relation)
for node in thing.getElementsByTagName('relation:' + relation):
resource = node.attributes['rdf:resource'].value
yield (relation, resource)
def get_attributes(self, thing, attributes=None):
if attributes is None:
attributes = self.attributes
for attribute in attributes:
attribute = self._transform_string(attribute)
for node in thing.getElementsByTagName('attribute:' + attribute):
value = node.firstChild.nodeValue.strip()
yield (attribute, value)
def get_thing_label(self, thing):
return util.get_first_text(thing, 'rdfs:label')
def geocode_url(self, url, attempted=None):
if attempted is None:
attempted = set()
util.logger.debug("Fetching %s...", url)
page = self._call_geocoder(url)
soup = BeautifulSoup(page)
rdf_url = self.parse_rdf_link(soup)
util.logger.debug("Fetching %s..." % rdf_url)
page = self.urlopen(rdf_url)
things, thing = self.parse_rdf(page) # TODO
name = self.get_label(thing)
attributes = self.get_attributes(thing)
for _, value in attributes:
latitude, longitude = util.parse_geo(value)
if None not in (latitude, longitude):
break
if None in (latitude, longitude):
tried = set() # TODO undefined tried -- is this right?
relations = self.get_relations(thing)
for _, resource in relations:
url = things.get(resource, resource) # pylint: disable=E1103
if url in tried: # Avoid cyclic relationships.
continue
tried.add(url)
name, (latitude, longitude) = self.geocode_url(url, tried)
if None not in (name, latitude, longitude):
break
return (name, (latitude, longitude))
| [
"shivam@shivam.(none)"
] | shivam@shivam.(none) |
f9a71bdd2c4bdf13412426a760f164f68cae350b | a0a4bda67eacbc1fe922591e12fdc5bf1f13a9c0 | /perceptron/perceptron.py | 2c6bcc53101ba098c4faadac8c37495bdebc8add | [] | no_license | zzag/codesamples | cdd713a62e08480988f3372d33d0e8ca1c326d7b | de3496cd572d4b27f9781078c69b23df22ad7c18 | refs/heads/master | 2023-01-21T05:44:34.628273 | 2023-01-09T11:20:39 | 2023-01-09T11:20:39 | 133,409,760 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,087 | py | import numpy as np
class Perceptron:
def __init__(self, max_iter=10, threshold=0, learning_rate=0.1):
self.weights = None
self.max_iter = max_iter
self.threshold = threshold
self.learning_rate = learning_rate
def round(self, value):
if value > self.threshold:
return 1
return 0
def train(self, X, y):
n = X.shape[1]
self.weights = np.zeros(shape=(n + 1, 1))
for iteration in range(self.max_iter):
for x_, desired_output in zip(X, y):
x = np.hstack((1, x_))
actual_output = self.round(np.dot(self.weights.transpose(), x)[0])
error = actual_output - desired_output
self.weights = self.weights - self.learning_rate * error * x.reshape((n + 1,1))
return self
def predict(self, x):
x = np.hstack((1.0, x))
output = np.dot(self.weights.transpose(), x)
return self.round(output[0])
def __repr__(self):
msg = "Weights: \n%s" % (str(self.weights))
return msg
| [
"vladzzag@gmail.com"
] | vladzzag@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.