hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
958k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f727740bd33f10993c9982599ba782f10061bf7f
2,831
py
Python
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
1
2021-06-25T22:48:39.000Z
2021-06-25T22:48:39.000Z
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
null
null
null
Bigeleisen_KIE.py
valkenzz/Bigeleisen_KIE
aa82ee63c77be2e9d0bd97702c297aa70dfaa362
[ "MIT" ]
null
null
null
#Importation : import pandas as pd import numpy as np ################################################ #Parameters : #Planck constant (J/Hz) h=6.62607004*10**-34 #Boltzmann constant (J/K) kB=1.38064852*10**-23 #Light velocity in vaccum (m/s) c=299792458.0 #################################################################################### #Functions: ###################################################################################### #We check for errors : #We check if all values are positiv for initial states def CheckPositiv(Data): if len(Data)!=len([i for i in Data if (i>0)]): print("At least one initial state hasn't every frequency that are positiv") def error(isH,isD,tsH,tsD): CheckPositiv(isH) CheckPositiv(isD) ##################################################################################### #Function which takes the lists of vibration frequencies of 2 states to give the product of the ratio of frequencies def Operation(Data1,Data2): if len(Data1)!=len(Data2): print("The number of frequencies isn't the same for two same states") return x=1 for i in range(len(Data1)): x=x*Data1[i]/Data2[i] return x #Function which takes one list of vibration frequencies to give the sinh of Ui = h*x/(kB*T) according to the Biegelheisen equation def Ui(Data,T): return pd.Series(Data).apply(lambda x : np.sinh(float(x)*((h*100*c)/(2.0*kB*float(T))))) #Function which takes in entry the lists of frequencies (cm-1) and the temperature (K) and gives the KIE #isH is the vibration frequencies of the molecule containing the light isotope at the initial state #isD is the vibration frequencies of the molecule containing the heavy isotope at the initial state #tsH is the vibration frequencies of the molecule containing the light isotope at the transition state #tsD is the vibration frequencies of the molecule containing the heavy isotope at the transition state #T is the temperature in Kelvin def KIE(isH,isD,tsH,tsD,T): error(isH,isD,tsH,tsD) #We calculate the sinh of h*x/(kB*T) UisH=Ui(isH,T).tolist() UtsH=Ui(tsH,T).tolist() UisD=Ui(isD,T).tolist() UtsD=Ui(tsD,T).tolist() ####################### #We begin to calculate the ratio of the two imaginary frequencies op1=tsH[0]/tsD[0] Result=op1 #We calculate the second factor Result=Result*Operation(tsH[1:],tsD[1:]) #We calculate the third factor Result=Result*Operation(isD,isH) #We calculate the fourth factor Result=Result*Operation(UtsD[1:],UtsH[1:]) #We calculate the fifth factor Result=Result*Operation(UisH,UisD) return Result ####################################################################################
37.746667
131
0.585306
import pandas as pd import numpy as np
true
true
f727743056c35927215b3d1cff28914c0160ba53
1,714
py
Python
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
61
2020-10-12T11:46:09.000Z
2022-02-07T04:26:05.000Z
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
26
2020-10-07T20:25:26.000Z
2022-03-25T11:40:57.000Z
examples/python/modulation-example.py
ideoforms/signalflow
1283cdf565d004495f1561d4d0683d51c11da50a
[ "MIT" ]
6
2021-02-27T19:50:25.000Z
2021-11-09T11:02:20.000Z
#!/usr/bin/env python3 #------------------------------------------------------------------------ # SignalFlow: Modulation example. #------------------------------------------------------------------------ from signalflow import * #------------------------------------------------------------------------ # Create the global processing graph. #------------------------------------------------------------------------ graph = AudioGraph(start=True) graph.show_status(1) #------------------------------------------------------------------------ # Create a regular impulse that is used to trigger an envelope and S&H. #------------------------------------------------------------------------ clock = Impulse(8) frequency = ScaleLinExp(SawLFO(0.2), 0, 1, 200, 2000) sample_hold = SampleAndHold(frequency, clock) sine = TriangleOscillator(sample_hold) * 0.5 env = EnvelopeASR(attack=0.001, sustain=0.001, release=0.1, clock=clock) #------------------------------------------------------------------------ # Apply the envelope, and stereo pan between speakers. #------------------------------------------------------------------------ mono = sine * env stereo = StereoPanner(mono, SineLFO(0.5, -1, 1)) #------------------------------------------------------------------------ # Add some delay. #------------------------------------------------------------------------ delay1 = CombDelay(mono, 0.1, 0.8) delay2 = OneTapDelay(CombDelay(mono, 0.05, 0.8), 0.125) stereo = stereo + ChannelArray([ delay1, delay2 ]) * 0.2 #------------------------------------------------------------------------ # Play the output. #------------------------------------------------------------------------ graph.play(stereo) graph.wait()
41.804878
73
0.351225
from signalflow import * graph = AudioGraph(start=True) graph.show_status(1) clock = Impulse(8) frequency = ScaleLinExp(SawLFO(0.2), 0, 1, 200, 2000) sample_hold = SampleAndHold(frequency, clock) sine = TriangleOscillator(sample_hold) * 0.5 env = EnvelopeASR(attack=0.001, sustain=0.001, release=0.1, clock=clock) mono = sine * env stereo = StereoPanner(mono, SineLFO(0.5, -1, 1)) delay1 = CombDelay(mono, 0.1, 0.8) delay2 = OneTapDelay(CombDelay(mono, 0.05, 0.8), 0.125) stereo = stereo + ChannelArray([ delay1, delay2 ]) * 0.2 graph.play(stereo) graph.wait()
true
true
f7277478cfed614fa4d55c97d1352a6fcb46bccc
2,908
py
Python
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
cifar10/custom_models.py
apexnetai/cifar-10-guide
7c76f310e93da3a229ce9d66defd770ee1c7dc56
[ "Apache-2.0" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F import torchvision class CustomResnetV1(nn.Module): def __init__(self): super(CustomResnetV1, self).__init__() self.resnet = torchvision.models.resnet18(pretrained=True) self.resnet.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(0, 0), bias=False) self.resnet.fc = nn.Linear(512, 256) self.bn1a = nn.BatchNorm1d(256) self.fc11 = nn.Linear(256, 256) self.fc12 = nn.Linear(256, 256) self.bn1b = nn.BatchNorm1d(256) self.fc13 = nn.Linear(256, 256) self.fc14 = nn.Linear(256, 256) self.bn1c = nn.BatchNorm1d(256) self.fc15 = nn.Linear(256, 256) self.fc16 = nn.Linear(256, 256) self.fc_down1 = nn.Linear(256, 128) self.bn2a = nn.BatchNorm1d(128) self.fc21 = nn.Linear(128, 128) self.fc22 = nn.Linear(128, 128) self.bn2b = nn.BatchNorm1d(128) self.fc23 = nn.Linear(128, 128) self.fc24 = nn.Linear(128, 128) self.bn2c = nn.BatchNorm1d(128) self.fc25 = nn.Linear(128, 128) self.fc26 = nn.Linear(128, 128) self.fc_down2 = nn.Linear(128, 64) self.bn3a = nn.BatchNorm1d(64) self.fc31 = nn.Linear(64, 64) self.fc32 = nn.Linear(64, 64) self.bn3b = nn.BatchNorm1d(64) self.fc33 = nn.Linear(64, 64) self.fc34 = nn.Linear(64, 64) self.bn3c = nn.BatchNorm1d(64) self.fc35 = nn.Linear(64, 64) self.fc36 = nn.Linear(64, 64) self.fc4 = nn.Linear(64, 10) #self.drop1 = nn.Dropout2d(0.5) def forward(self, x): x_ = F.relu(self.resnet(x)) x = self.bn1a(x_) x = F.relu(self.fc11(x)) x = F.relu(self.fc12(x)) x_ = torch.add(x, x_) x = self.bn1b(x_) x = F.relu(self.fc13(x)) x = F.relu(self.fc14(x)) x_ = torch.add(x, x_) x = self.bn1c(x_) x = F.relu(self.fc15(x)) x = F.relu(self.fc16(x)) x_ = self.fc_down1(torch.add(x, x_)) x = self.bn2a(x_) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) x_ = torch.add(x, x_) x = self.bn2b(x_) x = F.relu(self.fc23(x)) x = F.relu(self.fc24(x)) x_ = torch.add(x, x_) x = self.bn2c(x_) x = F.relu(self.fc25(x)) x = F.relu(self.fc26(x)) x_ = self.fc_down2(torch.add(x, x_)) x = self.bn3a(x_) x = F.relu(self.fc31(x)) x = F.relu(self.fc32(x)) x_ = torch.add(x, x_) x = self.bn3b(x_) x = F.relu(self.fc33(x)) x = F.relu(self.fc34(x)) x_ = torch.add(x, x_) x = self.bn3c(x_) x = F.relu(self.fc35(x)) x = F.relu(self.fc36(x)) x_ = torch.add(x, x_) x = self.fc4(x_) return F.log_softmax(x, dim=1)
29.979381
107
0.532669
import torch import torch.nn as nn import torch.nn.functional as F import torchvision class CustomResnetV1(nn.Module): def __init__(self): super(CustomResnetV1, self).__init__() self.resnet = torchvision.models.resnet18(pretrained=True) self.resnet.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(0, 0), bias=False) self.resnet.fc = nn.Linear(512, 256) self.bn1a = nn.BatchNorm1d(256) self.fc11 = nn.Linear(256, 256) self.fc12 = nn.Linear(256, 256) self.bn1b = nn.BatchNorm1d(256) self.fc13 = nn.Linear(256, 256) self.fc14 = nn.Linear(256, 256) self.bn1c = nn.BatchNorm1d(256) self.fc15 = nn.Linear(256, 256) self.fc16 = nn.Linear(256, 256) self.fc_down1 = nn.Linear(256, 128) self.bn2a = nn.BatchNorm1d(128) self.fc21 = nn.Linear(128, 128) self.fc22 = nn.Linear(128, 128) self.bn2b = nn.BatchNorm1d(128) self.fc23 = nn.Linear(128, 128) self.fc24 = nn.Linear(128, 128) self.bn2c = nn.BatchNorm1d(128) self.fc25 = nn.Linear(128, 128) self.fc26 = nn.Linear(128, 128) self.fc_down2 = nn.Linear(128, 64) self.bn3a = nn.BatchNorm1d(64) self.fc31 = nn.Linear(64, 64) self.fc32 = nn.Linear(64, 64) self.bn3b = nn.BatchNorm1d(64) self.fc33 = nn.Linear(64, 64) self.fc34 = nn.Linear(64, 64) self.bn3c = nn.BatchNorm1d(64) self.fc35 = nn.Linear(64, 64) self.fc36 = nn.Linear(64, 64) self.fc4 = nn.Linear(64, 10) def forward(self, x): x_ = F.relu(self.resnet(x)) x = self.bn1a(x_) x = F.relu(self.fc11(x)) x = F.relu(self.fc12(x)) x_ = torch.add(x, x_) x = self.bn1b(x_) x = F.relu(self.fc13(x)) x = F.relu(self.fc14(x)) x_ = torch.add(x, x_) x = self.bn1c(x_) x = F.relu(self.fc15(x)) x = F.relu(self.fc16(x)) x_ = self.fc_down1(torch.add(x, x_)) x = self.bn2a(x_) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) x_ = torch.add(x, x_) x = self.bn2b(x_) x = F.relu(self.fc23(x)) x = F.relu(self.fc24(x)) x_ = torch.add(x, x_) x = self.bn2c(x_) x = F.relu(self.fc25(x)) x = F.relu(self.fc26(x)) x_ = self.fc_down2(torch.add(x, x_)) x = self.bn3a(x_) x = F.relu(self.fc31(x)) x = F.relu(self.fc32(x)) x_ = torch.add(x, x_) x = self.bn3b(x_) x = F.relu(self.fc33(x)) x = F.relu(self.fc34(x)) x_ = torch.add(x, x_) x = self.bn3c(x_) x = F.relu(self.fc35(x)) x = F.relu(self.fc36(x)) x_ = torch.add(x, x_) x = self.fc4(x_) return F.log_softmax(x, dim=1)
true
true
f72776a94e62bdff703e0bd58ce268bc183b1b92
8,160
py
Python
grr/lib/builders/osx.py
ethicalhackeragnidhra/Grr
9ff9178396d9d16575e42dded33627cb09ac3af1
[ "Apache-2.0" ]
1
2020-12-18T00:47:19.000Z
2020-12-18T00:47:19.000Z
grr/lib/builders/osx.py
ethicalhackeragnidhra/Grr
9ff9178396d9d16575e42dded33627cb09ac3af1
[ "Apache-2.0" ]
null
null
null
grr/lib/builders/osx.py
ethicalhackeragnidhra/Grr
9ff9178396d9d16575e42dded33627cb09ac3af1
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """An implementation of an OSX client builder.""" import logging import os import shutil import StringIO import subprocess import zipfile from grr import config from grr.lib import build from grr.lib import config_lib from grr.lib import utils class DarwinClientBuilder(build.ClientBuilder): """Builder class for the Mac OS X (Darwin) client.""" def __init__(self, context=None): """Initialize the Mac OS X client builder.""" super(DarwinClientBuilder, self).__init__(context=context) self.context.append("Target:Darwin") def MakeExecutableTemplate(self, output_file=None): """Create the executable template.""" super(DarwinClientBuilder, self).MakeExecutableTemplate( output_file=output_file) self.SetBuildVars() self.MakeBuildDirectory() self.BuildWithPyInstaller() self.CopyMissingModules() self.BuildInstallerPkg(output_file) self.MakeZip(output_file, self.template_file) def SetBuildVars(self): self.version = config.CONFIG.Get( "Source.version_string", context=self.context) self.client_name = config.CONFIG.Get("Client.name", context=self.context) self.pkg_org = config.CONFIG.Get( "ClientBuilder.package_maker_organization", context=self.context) self.pkg_name = "%s-%s.pkg" % (self.client_name, self.version) self.build_root = config.CONFIG.Get( "ClientBuilder.build_root_dir", context=self.context) self.plist_name = config.CONFIG.Get( "Client.plist_filename", context=self.context) self.output_basename = config.CONFIG.Get( "ClientBuilder.output_basename", context=self.context) self.template_binary_dir = os.path.join( config.CONFIG.Get("PyInstaller.distpath", context=self.context), "grr-client") self.pkg_root = os.path.join(self.build_root, "pkg-root") self.target_binary_dir = os.path.join( self.pkg_root, "usr/local/lib/", self.client_name, self.output_basename) self.pkgbuild_out_dir = os.path.join(self.build_root, "pkgbuild-out") self.pkgbuild_out_binary = os.path.join(self.pkgbuild_out_dir, self.pkg_name) self.prodbuild_out_dir = os.path.join(self.build_root, "prodbuild-out") self.prodbuild_out_binary = os.path.join(self.prodbuild_out_dir, self.pkg_name) def MakeZip(self, xar_file, output_file): """Add a zip to the end of the .xar containing build.yaml. The build.yaml is already inside the .xar file, but we can't easily open this on linux. To make repacking easier we add a zip to the end of the .xar and add in the build.yaml. The repack step will then look at the build.yaml and insert the config.yaml. We end up storing the build.yaml twice but it is tiny, so this doesn't matter. Args: xar_file: the name of the xar file. output_file: the name of the output ZIP archive. """ logging.info("Generating zip template file at %s", output_file) with zipfile.ZipFile(output_file, mode="a") as zf: # Get the build yaml build_yaml = StringIO.StringIO() self.WriteBuildYaml(build_yaml) build_yaml.seek(0) zf.writestr("build.yaml", build_yaml.read()) def MakeBuildDirectory(self): super(DarwinClientBuilder, self).MakeBuildDirectory() self.CleanDirectory(self.pkg_root) self.CleanDirectory(self.pkgbuild_out_dir) self.CleanDirectory(self.prodbuild_out_dir) self.script_dir = os.path.join(self.build_dir, "scripts") self.CleanDirectory(self.script_dir) def InterpolateFiles(self): build_files_dir = config_lib.Resource().Filter("install_data/macosx/client") self.GenerateFile( input_filename=os.path.join(build_files_dir, "grr.plist.in"), output_filename=os.path.join(self.pkg_root, "Library/LaunchDaemons", self.plist_name)) # We pass in scripts separately with --scripts so they don't go in pkg_root self.GenerateFile( input_filename=os.path.join(build_files_dir, "preinstall.sh.in"), output_filename=os.path.join(self.script_dir, "preinstall")) self.GenerateFile( input_filename=os.path.join(build_files_dir, "postinstall.sh.in"), output_filename=os.path.join(self.script_dir, "postinstall")) self.GenerateFile( input_filename=os.path.join(build_files_dir, "Distribution.xml.in"), output_filename=os.path.join(self.build_dir, "Distribution.xml")) def RenameGRRPyinstallerBinaries(self): if self.template_binary_dir != self.target_binary_dir: shutil.move(self.template_binary_dir, self.target_binary_dir) shutil.move( os.path.join(self.target_binary_dir, "grr-client"), os.path.join(self.target_binary_dir, config.CONFIG.Get( "Client.binary_name", context=self.context))) def SignGRRPyinstallerBinaries(self): cert_name = config.CONFIG.Get( "ClientBuilder.signing_cert_name", context=self.context) keychain_file = config.CONFIG.Get( "ClientBuilder.signing_keychain_file", context=self.context) if not keychain_file: print("No keychain file specified in the config, skipping " "binaries signing...") return print "Signing binaries with keychain: %s" % keychain_file subprocess.check_call([ "codesign", "--verbose", "--deep", "--force", "--sign", cert_name, "--keychain", keychain_file, os.path.join(self.target_binary_dir, config.CONFIG.Get( "Client.binary_name", context=self.context)) ]) def CreateInstallDirs(self): utils.EnsureDirExists(self.build_dir) utils.EnsureDirExists(self.script_dir) utils.EnsureDirExists(self.pkg_root) utils.EnsureDirExists(os.path.join(self.pkg_root, "Library/LaunchDaemons")) utils.EnsureDirExists(os.path.join(self.pkg_root, "usr/local/lib/")) utils.EnsureDirExists(self.pkgbuild_out_dir) utils.EnsureDirExists(self.prodbuild_out_dir) def WriteClientConfig(self): repacker = build.ClientRepacker(context=self.context) repacker.context = self.context # Generate a config file. with open( os.path.join(self.target_binary_dir, config.CONFIG.Get( "ClientBuilder.config_filename", context=self.context)), "wb") as fd: fd.write( repacker.GetClientConfig( ["Client Context"] + self.context, validate=False)) def RunCmd(self, command): print "Running: %s" % " ".join(command) subprocess.check_call(command) def Set755Permissions(self): command = ["/bin/chmod", "-R", "755", self.script_dir] self.RunCmd(command) command = ["/bin/chmod", "-R", "755", self.pkg_root] self.RunCmd(command) def RunPkgBuild(self): pkg_id = "%s.%s.%s_%s" % (self.pkg_org, self.client_name, self.client_name, self.version) command = [ "pkgbuild", "--root=%s" % self.pkg_root, "--identifier", pkg_id, "--scripts", self.script_dir, "--version", self.version, self.pkgbuild_out_binary ] self.RunCmd(command) def RunProductBuild(self): command = [ "productbuild", "--distribution", os.path.join(self.build_dir, "distribution.xml"), "--package-path", self.pkgbuild_out_dir, self.prodbuild_out_binary ] self.RunCmd(command) def RenamePkgToTemplate(self, output_file): print "Copying output to templates location: %s -> %s" % ( self.prodbuild_out_binary, output_file) utils.EnsureDirExists(os.path.dirname(output_file)) shutil.copyfile(self.prodbuild_out_binary, output_file) def BuildInstallerPkg(self, output_file): """Builds a package (.pkg) using PackageMaker.""" self.CreateInstallDirs() self.InterpolateFiles() self.RenameGRRPyinstallerBinaries() self.SignGRRPyinstallerBinaries() self.WriteClientConfig() self.Set755Permissions() self.RunPkgBuild() self.RunProductBuild() self.RenamePkgToTemplate(output_file)
39.804878
80
0.684191
"""An implementation of an OSX client builder.""" import logging import os import shutil import StringIO import subprocess import zipfile from grr import config from grr.lib import build from grr.lib import config_lib from grr.lib import utils class DarwinClientBuilder(build.ClientBuilder): """Builder class for the Mac OS X (Darwin) client.""" def __init__(self, context=None): """Initialize the Mac OS X client builder.""" super(DarwinClientBuilder, self).__init__(context=context) self.context.append("Target:Darwin") def MakeExecutableTemplate(self, output_file=None): """Create the executable template.""" super(DarwinClientBuilder, self).MakeExecutableTemplate( output_file=output_file) self.SetBuildVars() self.MakeBuildDirectory() self.BuildWithPyInstaller() self.CopyMissingModules() self.BuildInstallerPkg(output_file) self.MakeZip(output_file, self.template_file) def SetBuildVars(self): self.version = config.CONFIG.Get( "Source.version_string", context=self.context) self.client_name = config.CONFIG.Get("Client.name", context=self.context) self.pkg_org = config.CONFIG.Get( "ClientBuilder.package_maker_organization", context=self.context) self.pkg_name = "%s-%s.pkg" % (self.client_name, self.version) self.build_root = config.CONFIG.Get( "ClientBuilder.build_root_dir", context=self.context) self.plist_name = config.CONFIG.Get( "Client.plist_filename", context=self.context) self.output_basename = config.CONFIG.Get( "ClientBuilder.output_basename", context=self.context) self.template_binary_dir = os.path.join( config.CONFIG.Get("PyInstaller.distpath", context=self.context), "grr-client") self.pkg_root = os.path.join(self.build_root, "pkg-root") self.target_binary_dir = os.path.join( self.pkg_root, "usr/local/lib/", self.client_name, self.output_basename) self.pkgbuild_out_dir = os.path.join(self.build_root, "pkgbuild-out") self.pkgbuild_out_binary = os.path.join(self.pkgbuild_out_dir, self.pkg_name) self.prodbuild_out_dir = os.path.join(self.build_root, "prodbuild-out") self.prodbuild_out_binary = os.path.join(self.prodbuild_out_dir, self.pkg_name) def MakeZip(self, xar_file, output_file): """Add a zip to the end of the .xar containing build.yaml. The build.yaml is already inside the .xar file, but we can't easily open this on linux. To make repacking easier we add a zip to the end of the .xar and add in the build.yaml. The repack step will then look at the build.yaml and insert the config.yaml. We end up storing the build.yaml twice but it is tiny, so this doesn't matter. Args: xar_file: the name of the xar file. output_file: the name of the output ZIP archive. """ logging.info("Generating zip template file at %s", output_file) with zipfile.ZipFile(output_file, mode="a") as zf: build_yaml = StringIO.StringIO() self.WriteBuildYaml(build_yaml) build_yaml.seek(0) zf.writestr("build.yaml", build_yaml.read()) def MakeBuildDirectory(self): super(DarwinClientBuilder, self).MakeBuildDirectory() self.CleanDirectory(self.pkg_root) self.CleanDirectory(self.pkgbuild_out_dir) self.CleanDirectory(self.prodbuild_out_dir) self.script_dir = os.path.join(self.build_dir, "scripts") self.CleanDirectory(self.script_dir) def InterpolateFiles(self): build_files_dir = config_lib.Resource().Filter("install_data/macosx/client") self.GenerateFile( input_filename=os.path.join(build_files_dir, "grr.plist.in"), output_filename=os.path.join(self.pkg_root, "Library/LaunchDaemons", self.plist_name)) self.GenerateFile( input_filename=os.path.join(build_files_dir, "preinstall.sh.in"), output_filename=os.path.join(self.script_dir, "preinstall")) self.GenerateFile( input_filename=os.path.join(build_files_dir, "postinstall.sh.in"), output_filename=os.path.join(self.script_dir, "postinstall")) self.GenerateFile( input_filename=os.path.join(build_files_dir, "Distribution.xml.in"), output_filename=os.path.join(self.build_dir, "Distribution.xml")) def RenameGRRPyinstallerBinaries(self): if self.template_binary_dir != self.target_binary_dir: shutil.move(self.template_binary_dir, self.target_binary_dir) shutil.move( os.path.join(self.target_binary_dir, "grr-client"), os.path.join(self.target_binary_dir, config.CONFIG.Get( "Client.binary_name", context=self.context))) def SignGRRPyinstallerBinaries(self): cert_name = config.CONFIG.Get( "ClientBuilder.signing_cert_name", context=self.context) keychain_file = config.CONFIG.Get( "ClientBuilder.signing_keychain_file", context=self.context) if not keychain_file: print("No keychain file specified in the config, skipping " "binaries signing...") return print "Signing binaries with keychain: %s" % keychain_file subprocess.check_call([ "codesign", "--verbose", "--deep", "--force", "--sign", cert_name, "--keychain", keychain_file, os.path.join(self.target_binary_dir, config.CONFIG.Get( "Client.binary_name", context=self.context)) ]) def CreateInstallDirs(self): utils.EnsureDirExists(self.build_dir) utils.EnsureDirExists(self.script_dir) utils.EnsureDirExists(self.pkg_root) utils.EnsureDirExists(os.path.join(self.pkg_root, "Library/LaunchDaemons")) utils.EnsureDirExists(os.path.join(self.pkg_root, "usr/local/lib/")) utils.EnsureDirExists(self.pkgbuild_out_dir) utils.EnsureDirExists(self.prodbuild_out_dir) def WriteClientConfig(self): repacker = build.ClientRepacker(context=self.context) repacker.context = self.context # Generate a config file. with open( os.path.join(self.target_binary_dir, config.CONFIG.Get( "ClientBuilder.config_filename", context=self.context)), "wb") as fd: fd.write( repacker.GetClientConfig( ["Client Context"] + self.context, validate=False)) def RunCmd(self, command): print "Running: %s" % " ".join(command) subprocess.check_call(command) def Set755Permissions(self): command = ["/bin/chmod", "-R", "755", self.script_dir] self.RunCmd(command) command = ["/bin/chmod", "-R", "755", self.pkg_root] self.RunCmd(command) def RunPkgBuild(self): pkg_id = "%s.%s.%s_%s" % (self.pkg_org, self.client_name, self.client_name, self.version) command = [ "pkgbuild", "--root=%s" % self.pkg_root, "--identifier", pkg_id, "--scripts", self.script_dir, "--version", self.version, self.pkgbuild_out_binary ] self.RunCmd(command) def RunProductBuild(self): command = [ "productbuild", "--distribution", os.path.join(self.build_dir, "distribution.xml"), "--package-path", self.pkgbuild_out_dir, self.prodbuild_out_binary ] self.RunCmd(command) def RenamePkgToTemplate(self, output_file): print "Copying output to templates location: %s -> %s" % ( self.prodbuild_out_binary, output_file) utils.EnsureDirExists(os.path.dirname(output_file)) shutil.copyfile(self.prodbuild_out_binary, output_file) def BuildInstallerPkg(self, output_file): """Builds a package (.pkg) using PackageMaker.""" self.CreateInstallDirs() self.InterpolateFiles() self.RenameGRRPyinstallerBinaries() self.SignGRRPyinstallerBinaries() self.WriteClientConfig() self.Set755Permissions() self.RunPkgBuild() self.RunProductBuild() self.RenamePkgToTemplate(output_file)
false
true
f7277809d5c13e30181663ab40928852ffba8dea
2,031
py
Python
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
nyuki/geotiff_reprojector.py
raghuramdr/nyuki
664d3a955ae765214a42e8dbeb009029d5600c15
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Console script for geotiff_reprojector.""" import sys import os import click import rasterio from rasterio.warp import calculate_default_transform, reproject, Resampling def reprojector(sourcefile, target_epsg='EPSG:4326', yes=False): # load file to get epsg info. dat = rasterio.open(sourcefile) # create new target filename targetfile = os.path.basename(sourcefile).split('.')[0] \ + '_proj_' \ + str(target_epsg).split(':')[1] \ + '.tif' click.echo("Application Settings:\n") click.echo(f"source filename: {sourcefile}") click.echo(f"target filename: {targetfile}") click.echo(f"source epsg: {dat.crs}") click.echo(f"target epsg: {target_epsg}\n") dat.close() if not yes: click.confirm('[INFO] File reprojection takes a while.\nDo you want to continue?', abort=True) click.echo('\n[INFO] Good time to get a cup of coffee.\n[INFO] This task can take 15-30 minutes or longer depending on file size.\n') with rasterio.open(sourcefile) as src: transform, width, height = calculate_default_transform( src.crs, target_epsg, src.width, src.height, *src.bounds) kwargs = src.meta.copy() kwargs.update({ 'crs': target_epsg, 'transform': transform, 'width': width, 'height': height, 'compress': 'LZW', 'BIGTIFF' : 'IF_SAFER' }) with rasterio.open(targetfile, 'w', **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rasterio.band(src, i), destination=rasterio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=target_epsg, resampling=Resampling.nearest) click.echo('[INFO] Task complete.') return targetfile
32.758065
141
0.58001
import sys import os import click import rasterio from rasterio.warp import calculate_default_transform, reproject, Resampling def reprojector(sourcefile, target_epsg='EPSG:4326', yes=False): dat = rasterio.open(sourcefile) targetfile = os.path.basename(sourcefile).split('.')[0] \ + '_proj_' \ + str(target_epsg).split(':')[1] \ + '.tif' click.echo("Application Settings:\n") click.echo(f"source filename: {sourcefile}") click.echo(f"target filename: {targetfile}") click.echo(f"source epsg: {dat.crs}") click.echo(f"target epsg: {target_epsg}\n") dat.close() if not yes: click.confirm('[INFO] File reprojection takes a while.\nDo you want to continue?', abort=True) click.echo('\n[INFO] Good time to get a cup of coffee.\n[INFO] This task can take 15-30 minutes or longer depending on file size.\n') with rasterio.open(sourcefile) as src: transform, width, height = calculate_default_transform( src.crs, target_epsg, src.width, src.height, *src.bounds) kwargs = src.meta.copy() kwargs.update({ 'crs': target_epsg, 'transform': transform, 'width': width, 'height': height, 'compress': 'LZW', 'BIGTIFF' : 'IF_SAFER' }) with rasterio.open(targetfile, 'w', **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rasterio.band(src, i), destination=rasterio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=target_epsg, resampling=Resampling.nearest) click.echo('[INFO] Task complete.') return targetfile
true
true
f72779a298c969c64055451d767bd20d007cf308
576
py
Python
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
2
2015-09-27T13:13:31.000Z
2015-09-28T01:16:11.000Z
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos-V2
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
null
null
null
django_todos/migrations/0005_list_createdat.py
cxhandley/django-ddp-todos-V2
e752133e31c901aba2ca056d16dc2022c57da823
[ "MIT" ]
1
2015-12-27T15:43:42.000Z
2015-12-27T15:43:42.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('django_todos', '0004_auto_20150909_1213'), ] operations = [ migrations.AddField( model_name='list', name='createdAt', field=models.DateTimeField(default=datetime.datetime(2015, 9, 14, 11, 27, 52, 487531, tzinfo=utc), auto_now_add=True), preserve_default=False, ), ]
25.043478
130
0.647569
from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('django_todos', '0004_auto_20150909_1213'), ] operations = [ migrations.AddField( model_name='list', name='createdAt', field=models.DateTimeField(default=datetime.datetime(2015, 9, 14, 11, 27, 52, 487531, tzinfo=utc), auto_now_add=True), preserve_default=False, ), ]
true
true
f72779dd707f715614f9cebb5334c248393f7004
90
py
Python
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
03_operator/03_operator.py
Jasper-Li/PythonTutorial
270d18a1830ae74eaa6fc797a6d4f672688f1cee
[ "CC0-1.0" ]
null
null
null
# 03 operator print(4+3) print(4-3) print(4*3) print(4 ** 3) # 这个小学没学 print(4/3)
11.25
24
0.566667
print(4+3) print(4-3) print(4*3) print(4 ** 3) print(4/3)
true
true
f7277a1c322b021d0f7590078adba406bb5b75a3
13,460
py
Python
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
1
2021-01-19T01:44:47.000Z
2021-01-19T01:44:47.000Z
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
null
null
null
utils/Finger/tool/tools.py
zxpzhong/DR_3DFM
6ef7d0d86813f4cc407a0d1011a2623e4775fbee
[ "MIT" ]
null
null
null
# 定义全局变量和方法 import numpy as np import math # import process.process_finger_data as pfd # 目前选用的图片尺寸 cur_pic_size = [640, 400] # cur_pic_size = [1280, 800] # 相机索引对应相机名称 camera_index_to_name = ['A', 'B', 'C', 'D', 'E', 'F'] # 6个相机的外参 camera_a_outer_para = np.mat([[0.574322111, 0.771054881, 0.275006333, 0.93847817], [0.565423192, -0.130698104, -0.814379899, -0.36935905], [-0.591988790, 0.623211341, -0.511035123, 4.78810628], [0, 0, 0, 1]]) camera_b_outer_para = np.mat([[0.456023570, 0.727006744, 0.513326112, 1.72205846], [-0.146061166, 0.630108915, -0.762645980, -0.30452329], [-0.877900131, 0.272807532, 0.393531969, 5.53092307], [0, 0, 0, 1]]) camera_c_outer_para = np.mat([[0.609183831, 0.528225460, 0.591500569, 1.59956459], [-0.738350101, 0.649953779, 0.179997814, 0.5030131], [-0.289368602, -0.546386263, 0.785956655, 5.58635091], [0, 0, 0, 1]]) camera_d_outer_para = np.mat([[0.771746127, 0.478767298, 0.418556793, 0.955855425], [-0.476877262, 0.000270229651, 0.878969854, 0.477556906], [0.420708915, -0.877941799, 0.228521787, 4.61760675], [0, 0, 0, 1]]) camera_e_outer_para = np.mat([[0.788882832, 0.555210653, 0.263448302, 0.71648894], [0.159053746, -0.598545227, 0.785140445, 0.00777088], [0.593604063, -0.577481378, -0.560490387, 4.30437514], [0, 0, 0, 1]]) camera_f_outer_para = np.mat([[0.712321206, 0.689000523, 0.133704068, 1.13938413], [0.694227260, -0.719684989, 0.0101009224, -0.28640104], [0.103184351, 0.0856259076, -0.990969825, 4.49819911], [0, 0, 0, 1]]) # 六个相机的内参 camera_a_inner_para = np.mat([[967.5377197, 0, 703.1273732, 0], [0, 967.9393921, 351.0187561, 0], [0, 0, 1, 0]]) camera_b_inner_para = np.mat([[963.2991943, 0, 589.8122291, 0], [0, 962.7422485, 412.5244055, 0], [0, 0, 1, 0]]) camera_c_inner_para = np.mat([[967.4086914, 0, 612.7826353, 0], [0, 968.0758667, 451.7366286, 0], [0, 0, 1, 0]]) camera_d_inner_para = np.mat([[961.0868530, 0, 692.7282436, 0], [0, 960.6126708, 417.4375162, 0], [0, 0, 1, 0]]) camera_e_inner_para = np.mat([[955.4882812, 0, 730.3056525, 0], [0, 953.7589722, 451.5117967, 0], [0, 0, 1, 0]]) camera_f_inner_para = np.mat([[962.0779419, 0, 595.2503222, 0], [0, 961.0998535, 396.8389609, 0], [0, 0, 1, 0]]) # 六个相机的投影矩阵为 投影矩阵=内参x外参 # 所有相机的投影矩阵放到一个三维矩阵里(1280x800) all_camera_projection_mat = [ [[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]], [[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]], [[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]] ] # camera_a_projection_mat = np.mat([[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], # [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], # [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]]) # # camera_b_projection_mat = np.mat([[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], # [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], # [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]]) # # camera_c_projection_mat = np.mat([[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], # [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], # [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]]) # # camera_d_projection_mat = np.mat([[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], # [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], # [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]]) # # camera_e_projection_mat = np.mat([[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], # [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], # [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]]) # # camera_f_projection_mat = np.mat([[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], # [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], # [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]]) # 将图片缩小为640*400后的相机内参为: 四个参数都除以二 camera_a_inner_para_640_400 = np.mat([[483.76885985, 0, 351.5636866, 0], [0, 483.96969605, 175.50937805, 0], [0, 0, 1, 0]]) camera_b_inner_para_640_400 = np.mat([[481.64959715, 0, 294.90611455, 0], [0, 481.37112425, 206.26220275, 0], [0, 0, 1, 0]]) camera_c_inner_para_640_400 = np.mat([[483.7043457, 0, 306.39131765, 0], [0, 484.03793335, 225.8683143, 0], [0, 0, 1, 0]]) camera_d_inner_para_640_400 = np.mat([[480.5434265, 0, 346.3641218, 0], [0, 480.3063354, 208.7187581, 0], [0, 0, 1, 0]]) camera_e_inner_para_640_400 = np.mat([[477.7441406, 0, 365.15282625, 0], [0, 476.8794861, 225.75589835, 0], [0, 0, 1, 0]]) camera_f_inner_para_640_400 = np.mat([[481.03897095, 0, 297.6251611, 0], [0, 480.54992675, 198.41948045, 0], [0, 0, 1, 0]]) # 将图片resize为640*400后的投影矩阵 all_camera_projection_mat_640_400 = [ [[6.97173914e+01, 5.92110817e+02, - 4.66218917e+01, 2.13733081e+03], [1.69748106e+02, 4.61255132e+01, - 4.83826649e+02, 6.61598968e+02], [-5.91988790e-01, 6.23211341e-01, - 5.11035123e-01, 4.78810628e+00]], [[-3.92545478e+01, 4.30615115e+02, 3.63298299e+02, 2.46053180e+03], [-2.51387243e+02, 3.59586119e+02, - 2.85944982e+02, 9.94231657e+02], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[2.06004839e+02, 8.80969434e+01, 5.26921691e+02, 2.48532576e+03], [-4.22748655e+02, 1.91190940e+02, 2.64648475e+02, 1.50525708e+03], [-2.89368602e-01, - 5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[5.16576002e+02, - 7.40190623e+01, 2.80286464e+02, 2.05870335e+03], [-1.41237328e+02, - 1.83113129e+02, 4.69871573e+02, 1.19315475e+03], [4.20708915e-01, - 8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[5.93640352e+02, 5.43796790e+01, - 7.88037663e+01, 1.91405314e+03], [2.09859087e+02, - 4.15803768e+02, 2.47883361e+02, 9.75443850e+02], [5.93604063e-01, - 5.77481378e-01, - 5.60490387e-01, 4.30437514e+00]], [[3.73364519e+02, 3.56920527e+02, - 2.30620687e+02, 1.88686540e+03], [3.54084644e+02, - 3.28854721e+02, - 1.91773720e+02, 7.54900332e+02], [1.03184351e-01, 8.56259076e-02, - 9.90969825e-01, 4.49819911e+00]] ] # 六个相机在世界坐标系下的坐标 cameras_coordinate = [[2.50436065, -3.75589484, 1.88800446], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.12155638, 2.09254542, 2.21770186], [-1.07692383, -1.37631717, 4.3081322]] # 六个相机组成的空间平面方程参数 AX+BY+CZ+D=0 camera_plane_para = [19.467678495159983, 18.098947303577706, 10.253452426300939, 1.884526845005233] # 六个相机映射到同一平面后的相机坐标,这里选用的是BCD三个相机作为相机平面,因此只需要将AEF映射到平面 cameras_coordinate_mapping = [[2.45592658, -3.80092362, 1.86249467], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.16297766, 2.05403639, 2.19588564], [-1.08130466, -1.38038999, 4.30582486]] # 六张bmp图片的像素信息,读取后放在全局变量中,避免每次都去重新读取 bmp_pixel = [[], [], [], [], [], []] # 哈希表,存储顶点对应的像素uv信息 map_vertex_to_texture = dict() # 哈希表,存储三角面片顶点对应的vt的index(行数) map_vertex_to_vt_index = dict() # 每个相机对应的三角面片 如faces_belong_camera_A=[[1,3,5],[2,3,5]...] # faces_belong_camera_A = [] # faces_belong_camera_B = [] # faces_belong_camera_C = [] # faces_belong_camera_D = [] # faces_belong_camera_E = [] # faces_belong_camera_F = [] # 所有相机对应的三角面片,A相机放在0索引,以此类推 faces_belong_camera = [[], [], [], [], [], []] # 所有相机对应的bmp应该crop出的范围,[Umin,Vmin,Umax,Vmax],初始化时给相反的最大最小值,这里取的10000和-100,因为不可能有超过这个范围的了 bmp_crop_ranges = [[10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100]] # 提前计算出crop的宽度u_width和高度v_height,先初始化为0 crops_width_and_height = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # 在得到crops_width_and_height后,提前计算出各个相机crop出的图在png中v所占的范围比重(0-1),例如A:0-0.25,B:0.25-0.4...F:0.8-1 crops_v_scale_in_png = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] # uvmap_png的长度和宽度 uv_map_size = [0, 0] # face的索引 寻找bug时使用 face_index = 1 # 打印数据点 def print_data_points(data_points): for li in data_points: print(li) # 计算两个向量的夹角的余弦 # 公式为cos<a,b>=a.b/|a||b|. a.b=(x1x2+y1y2+z1z2) |a|=√(x1^2+y1^2+z1^2), |b|=√(x2^2+y2^2+z2^2). def calculate_cosine(vector1, vector2): a = vector1[0] * vector2[0] + vector1[1] * vector2[1] + vector1[2] * vector2[2] b = math.sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1] + vector1[2] * vector1[2]) c = math.sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1] + vector2[2] * vector2[2]) res = a / (b * c) return res # 计算两个向量的向量积 # AB=(x1,y1,z1) CD=(x2,y2,z2) cross(AB,CD)=(y1*z2-y2z1,z1x2-z2x1,x1y2-x2y1) def calculate_vector_product(vector1, vector2): vector_product = [vector1[1] * vector2[2] - vector1[2] * vector2[1], vector1[2] * vector2[0] - vector1[0] * vector2[2], vector1[0] * vector2[1] - vector1[1] * vector2[0]] return vector_product # 点到空间平面的映射点(投影) def get_mapping_point_in_camera_plane(point, camera_plane_para): a = camera_plane_para[0] b = camera_plane_para[1] c = camera_plane_para[2] d = camera_plane_para[3] x = point[0] y = point[1] z = point[2] # 避免重复计算,不知python是否已有优化 a_ = a * a b_ = b * b c_ = c * c temp = a_ + b_ + c_ x_ = ((b_ + c_) * x - a * (b * y + c * z + d)) / temp y_ = ((a_ + c_) * y - b * (a * x + c * z + d)) / temp z_ = ((a_ + b_) * z - c * (a * x + b * y + d)) / temp point_ = [x_, y_, z_] return point_ # # 全局变量中部分数据的由来(在main函数中直接使用了)(因为外参已经固定,所以部分数据基本不会改变,减少计算量) # def pre_process(): # # 求出六个相机在世界坐标系下的坐标 # cameras_coordinate = pfd.get_cameras_coordinate() # # 求出相机参数平面 # camera_plane_para = pfd.get_camera_plane(cameras_coordinate) # # 获取A,E,F的映射点 # camera_a_point = get_mapping_point_in_camera_plane(cameras_coordinate[0], camera_plane_para) # camera_e_point = get_mapping_point_in_camera_plane(cameras_coordinate[4], camera_plane_para) # camera_f_point = get_mapping_point_in_camera_plane(cameras_coordinate[5], camera_plane_para) # # 六个相机归到一个平面之后的坐标:BCD不变,AEF映射到BCD平面 # camera_point_mapping = [camera_a_point, cameras_coordinate[1], cameras_coordinate[2], # cameras_coordinate[3], camera_e_point, camera_f_point] # camera_point_mapping = np.array(camera_point_mapping)
52.784314
104
0.568722
import numpy as np import math cur_pic_size = [640, 400] camera_index_to_name = ['A', 'B', 'C', 'D', 'E', 'F'] camera_a_outer_para = np.mat([[0.574322111, 0.771054881, 0.275006333, 0.93847817], [0.565423192, -0.130698104, -0.814379899, -0.36935905], [-0.591988790, 0.623211341, -0.511035123, 4.78810628], [0, 0, 0, 1]]) camera_b_outer_para = np.mat([[0.456023570, 0.727006744, 0.513326112, 1.72205846], [-0.146061166, 0.630108915, -0.762645980, -0.30452329], [-0.877900131, 0.272807532, 0.393531969, 5.53092307], [0, 0, 0, 1]]) camera_c_outer_para = np.mat([[0.609183831, 0.528225460, 0.591500569, 1.59956459], [-0.738350101, 0.649953779, 0.179997814, 0.5030131], [-0.289368602, -0.546386263, 0.785956655, 5.58635091], [0, 0, 0, 1]]) camera_d_outer_para = np.mat([[0.771746127, 0.478767298, 0.418556793, 0.955855425], [-0.476877262, 0.000270229651, 0.878969854, 0.477556906], [0.420708915, -0.877941799, 0.228521787, 4.61760675], [0, 0, 0, 1]]) camera_e_outer_para = np.mat([[0.788882832, 0.555210653, 0.263448302, 0.71648894], [0.159053746, -0.598545227, 0.785140445, 0.00777088], [0.593604063, -0.577481378, -0.560490387, 4.30437514], [0, 0, 0, 1]]) camera_f_outer_para = np.mat([[0.712321206, 0.689000523, 0.133704068, 1.13938413], [0.694227260, -0.719684989, 0.0101009224, -0.28640104], [0.103184351, 0.0856259076, -0.990969825, 4.49819911], [0, 0, 0, 1]]) camera_a_inner_para = np.mat([[967.5377197, 0, 703.1273732, 0], [0, 967.9393921, 351.0187561, 0], [0, 0, 1, 0]]) camera_b_inner_para = np.mat([[963.2991943, 0, 589.8122291, 0], [0, 962.7422485, 412.5244055, 0], [0, 0, 1, 0]]) camera_c_inner_para = np.mat([[967.4086914, 0, 612.7826353, 0], [0, 968.0758667, 451.7366286, 0], [0, 0, 1, 0]]) camera_d_inner_para = np.mat([[961.0868530, 0, 692.7282436, 0], [0, 960.6126708, 417.4375162, 0], [0, 0, 1, 0]]) camera_e_inner_para = np.mat([[955.4882812, 0, 730.3056525, 0], [0, 953.7589722, 451.5117967, 0], [0, 0, 1, 0]]) camera_f_inner_para = np.mat([[962.0779419, 0, 595.2503222, 0], [0, 961.0998535, 396.8389609, 0], [0, 0, 1, 0]]) all_camera_projection_mat = [ [[1.39434783e+02, 1.18422163e+03, -9.32437833e+01, 4.27466162e+03], [3.39496212e+02, 9.22510264e+01, -9.67653298e+02, 1.32319794e+03], [-5.91988790e-01, 6.23211341e-01, -5.11035123e-01, 4.78810628e+00]], [[-7.85090956e+01, 8.61230229e+02, 7.26596598e+02, 4.92106359e+03], [-5.02774485e+02, 7.19172239e+02, -5.71889964e+02, 1.98846331e+03], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[4.12009678e+02, 1.76193887e+02, 1.05384338e+03, 4.97065152e+03], [-8.45497311e+02, 3.82381880e+02, 5.29296949e+02, 3.01051417e+03], [-2.89368602e-01, -5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[1.03315200e+03, -1.48038125e+02, 5.60572927e+02, 4.11740670e+03], [-2.82474656e+02, -3.66226258e+02, 9.39743146e+02, 2.38630951e+03], [4.20708915e-01, -8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[1.18728070e+03, 1.08759358e+02, -1.57607533e+02, 3.82810628e+03], [4.19718174e+02, -8.31607535e+02, 4.95766722e+02, 1.95088770e+03], [5.93604063e-01, -5.77481378e-01, -5.60490387e-01, 4.30437514e+00]], [[7.46729038e+02, 7.13841054e+02, -4.61241373e+02, 3.77373081e+03], [7.08169289e+02, -6.57709441e+02, -3.83547441e+02, 1.50980066e+03], [1.03184351e-01, 8.56259076e-02, -9.90969825e-01, 4.49819911e+00]] ] camera_a_inner_para_640_400 = np.mat([[483.76885985, 0, 351.5636866, 0], [0, 483.96969605, 175.50937805, 0], [0, 0, 1, 0]]) camera_b_inner_para_640_400 = np.mat([[481.64959715, 0, 294.90611455, 0], [0, 481.37112425, 206.26220275, 0], [0, 0, 1, 0]]) camera_c_inner_para_640_400 = np.mat([[483.7043457, 0, 306.39131765, 0], [0, 484.03793335, 225.8683143, 0], [0, 0, 1, 0]]) camera_d_inner_para_640_400 = np.mat([[480.5434265, 0, 346.3641218, 0], [0, 480.3063354, 208.7187581, 0], [0, 0, 1, 0]]) camera_e_inner_para_640_400 = np.mat([[477.7441406, 0, 365.15282625, 0], [0, 476.8794861, 225.75589835, 0], [0, 0, 1, 0]]) camera_f_inner_para_640_400 = np.mat([[481.03897095, 0, 297.6251611, 0], [0, 480.54992675, 198.41948045, 0], [0, 0, 1, 0]]) all_camera_projection_mat_640_400 = [ [[6.97173914e+01, 5.92110817e+02, - 4.66218917e+01, 2.13733081e+03], [1.69748106e+02, 4.61255132e+01, - 4.83826649e+02, 6.61598968e+02], [-5.91988790e-01, 6.23211341e-01, - 5.11035123e-01, 4.78810628e+00]], [[-3.92545478e+01, 4.30615115e+02, 3.63298299e+02, 2.46053180e+03], [-2.51387243e+02, 3.59586119e+02, - 2.85944982e+02, 9.94231657e+02], [-8.77900131e-01, 2.72807532e-01, 3.93531969e-01, 5.53092307e+00]], [[2.06004839e+02, 8.80969434e+01, 5.26921691e+02, 2.48532576e+03], [-4.22748655e+02, 1.91190940e+02, 2.64648475e+02, 1.50525708e+03], [-2.89368602e-01, - 5.46386263e-01, 7.85956655e-01, 5.58635091e+00]], [[5.16576002e+02, - 7.40190623e+01, 2.80286464e+02, 2.05870335e+03], [-1.41237328e+02, - 1.83113129e+02, 4.69871573e+02, 1.19315475e+03], [4.20708915e-01, - 8.77941799e-01, 2.28521787e-01, 4.61760675e+00]], [[5.93640352e+02, 5.43796790e+01, - 7.88037663e+01, 1.91405314e+03], [2.09859087e+02, - 4.15803768e+02, 2.47883361e+02, 9.75443850e+02], [5.93604063e-01, - 5.77481378e-01, - 5.60490387e-01, 4.30437514e+00]], [[3.73364519e+02, 3.56920527e+02, - 2.30620687e+02, 1.88686540e+03], [3.54084644e+02, - 3.28854721e+02, - 1.91773720e+02, 7.54900332e+02], [1.03184351e-01, 8.56259076e-02, - 9.90969825e-01, 4.49819911e+00]] ] cameras_coordinate = [[2.50436065, -3.75589484, 1.88800446], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.12155638, 2.09254542, 2.21770186], [-1.07692383, -1.37631717, 4.3081322]] camera_plane_para = [19.467678495159983, 18.098947303577706, 10.253452426300939, 1.884526845005233] cameras_coordinate_mapping = [[2.45592658, -3.80092362, 1.86249467], [4.02581981, -2.56894275, -3.29281609], [1.01348544, 1.88043939, -5.4273143], [-2.45261002, 3.5962286, -1.87506165], [-3.16297766, 2.05403639, 2.19588564], [-1.08130466, -1.38038999, 4.30582486]] bmp_pixel = [[], [], [], [], [], []] map_vertex_to_texture = dict() map_vertex_to_vt_index = dict() faces_belong_camera = [[], [], [], [], [], []] bmp_crop_ranges = [[10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100], [10000, 10000, -100, -100]] crops_width_and_height = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] crops_v_scale_in_png = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] uv_map_size = [0, 0] face_index = 1 def print_data_points(data_points): for li in data_points: print(li) def calculate_cosine(vector1, vector2): a = vector1[0] * vector2[0] + vector1[1] * vector2[1] + vector1[2] * vector2[2] b = math.sqrt(vector1[0] * vector1[0] + vector1[1] * vector1[1] + vector1[2] * vector1[2]) c = math.sqrt(vector2[0] * vector2[0] + vector2[1] * vector2[1] + vector2[2] * vector2[2]) res = a / (b * c) return res def calculate_vector_product(vector1, vector2): vector_product = [vector1[1] * vector2[2] - vector1[2] * vector2[1], vector1[2] * vector2[0] - vector1[0] * vector2[2], vector1[0] * vector2[1] - vector1[1] * vector2[0]] return vector_product def get_mapping_point_in_camera_plane(point, camera_plane_para): a = camera_plane_para[0] b = camera_plane_para[1] c = camera_plane_para[2] d = camera_plane_para[3] x = point[0] y = point[1] z = point[2] a_ = a * a b_ = b * b c_ = c * c temp = a_ + b_ + c_ x_ = ((b_ + c_) * x - a * (b * y + c * z + d)) / temp y_ = ((a_ + c_) * y - b * (a * x + c * z + d)) / temp z_ = ((a_ + b_) * z - c * (a * x + b * y + d)) / temp point_ = [x_, y_, z_] return point_
true
true
f7277b8d58f1c9891a3e5c1152697cdc9322e98f
2,719
py
Python
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
15
2019-01-14T13:52:02.000Z
2022-02-27T13:40:38.000Z
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
5
2019-04-09T15:44:38.000Z
2021-04-02T07:01:11.000Z
hdfscm/tests/test_hdfsmanager_api.py
szhem/hdfscm
427e8c85fc70073d9a980e4371804523773545fb
[ "BSD-3-Clause" ]
6
2019-04-15T03:41:08.000Z
2022-03-07T22:48:50.000Z
import nbformat from notebook.services.contents.tests.test_contents_api import ( APITest, assert_http_error ) from traitlets.config import Config from hdfscm import HDFSContentsManager from hdfscm.utils import to_fs_path from .conftest import random_root_dir class HDFSContentsAPITest(APITest): hidden_dirs = [] root_dir = random_root_dir() config = Config() config.NotebookApp.contents_manager_class = HDFSContentsManager config.HDFSContentsManager.root_dir = root_dir @classmethod def setup_class(cls): """Due to https://github.com/docker/for-linux/issues/250, tornado maps localhost to an unresolvable ipv6 address. The easiest way to workaround this is to make it look like python was built without ipv6 support. This patch could fail if `tornado.netutils.bind_sockets` is updated. Note that this doesn't indicate a problem with real world use.""" import socket cls._has_ipv6 = socket.has_ipv6 socket.has_ipv6 = False super().setup_class() @classmethod def teardown_class(cls): """See setUpClass above""" import socket socket.has_ipv6 = cls._has_ipv6 cls.notebook.contents_manager.fs.close() super().teardown_class() def setUp(self): self.notebook.contents_manager.ensure_root_directory() super().setUp() def tearDown(self): super().tearDown() self.fs.delete(self.root_dir, recursive=True) @property def fs(self): return self.notebook.contents_manager.fs def get_hdfs_path(self, api_path): return to_fs_path(api_path, self.root_dir) def make_dir(self, api_path): self.fs.mkdir(self.get_hdfs_path(api_path)) def make_blob(self, api_path, blob): hdfs_path = self.get_hdfs_path(api_path) with self.fs.open(hdfs_path, 'wb') as f: f.write(blob) def make_txt(self, api_path, txt): self.make_blob(api_path, txt.encode('utf-8')) def make_nb(self, api_path, nb): self.make_txt(api_path, nbformat.writes(nb, version=4)) def delete_file(self, api_path): hdfs_path = self.get_hdfs_path(api_path) if self.fs.exists(hdfs_path): self.fs.delete(hdfs_path, recursive=True) delete_dir = delete_file def isfile(self, api_path): return self.fs.isfile(self.get_hdfs_path(api_path)) def isdir(self, api_path): return self.fs.isdir(self.get_hdfs_path(api_path)) # Test overrides. def test_checkpoints_separate_root(self): pass def test_delete_non_empty_dir(self): with assert_http_error(400): self.api.delete('å b') del APITest
29.554348
80
0.681868
import nbformat from notebook.services.contents.tests.test_contents_api import ( APITest, assert_http_error ) from traitlets.config import Config from hdfscm import HDFSContentsManager from hdfscm.utils import to_fs_path from .conftest import random_root_dir class HDFSContentsAPITest(APITest): hidden_dirs = [] root_dir = random_root_dir() config = Config() config.NotebookApp.contents_manager_class = HDFSContentsManager config.HDFSContentsManager.root_dir = root_dir @classmethod def setup_class(cls): import socket cls._has_ipv6 = socket.has_ipv6 socket.has_ipv6 = False super().setup_class() @classmethod def teardown_class(cls): import socket socket.has_ipv6 = cls._has_ipv6 cls.notebook.contents_manager.fs.close() super().teardown_class() def setUp(self): self.notebook.contents_manager.ensure_root_directory() super().setUp() def tearDown(self): super().tearDown() self.fs.delete(self.root_dir, recursive=True) @property def fs(self): return self.notebook.contents_manager.fs def get_hdfs_path(self, api_path): return to_fs_path(api_path, self.root_dir) def make_dir(self, api_path): self.fs.mkdir(self.get_hdfs_path(api_path)) def make_blob(self, api_path, blob): hdfs_path = self.get_hdfs_path(api_path) with self.fs.open(hdfs_path, 'wb') as f: f.write(blob) def make_txt(self, api_path, txt): self.make_blob(api_path, txt.encode('utf-8')) def make_nb(self, api_path, nb): self.make_txt(api_path, nbformat.writes(nb, version=4)) def delete_file(self, api_path): hdfs_path = self.get_hdfs_path(api_path) if self.fs.exists(hdfs_path): self.fs.delete(hdfs_path, recursive=True) delete_dir = delete_file def isfile(self, api_path): return self.fs.isfile(self.get_hdfs_path(api_path)) def isdir(self, api_path): return self.fs.isdir(self.get_hdfs_path(api_path)) def test_checkpoints_separate_root(self): pass def test_delete_non_empty_dir(self): with assert_http_error(400): self.api.delete('å b') del APITest
true
true
f7277cc36cfb1076bc786e7c041456ee46c61223
379
py
Python
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
7
2020-06-18T04:31:18.000Z
2022-03-01T14:54:18.000Z
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
32
2020-05-01T18:56:11.000Z
2021-08-18T15:09:22.000Z
setup.py
CesarCaballeroGaudes/phys2denoise
a86baefb62a45721eaa132b1d47fe6c4a0979f35
[ "Apache-2.0" ]
10
2020-03-23T11:24:40.000Z
2021-11-22T12:55:06.000Z
#!/usr/bin/env python import sys from setuptools import setup import versioneer SETUP_REQUIRES = ['setuptools >= 30.3.0'] SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else [] if __name__ == "__main__": setup(name='phys2denoise', setup_requires=SETUP_REQUIRES, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass())
25.266667
64
0.693931
import sys from setuptools import setup import versioneer SETUP_REQUIRES = ['setuptools >= 30.3.0'] SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else [] if __name__ == "__main__": setup(name='phys2denoise', setup_requires=SETUP_REQUIRES, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass())
true
true
f7277cee7021a14d2b5b0b8305bca5e412827cf0
710
py
Python
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
Timers/timers__.py
nageshnnazare/Python-Advanced-Concepts
cc5aac22799b081abd223c9a7f3c1d5557e3528f
[ "MIT" ]
null
null
null
#Timers # Execute code at timed intervals import time from threading import Timer def display(msg): print(msg + ' ' + time.strftime('%H:%M:%S')) #Basic timer def run_once(): display('Run Once : ') t = Timer(5, display, ['Timeout:']) t.start() run_once() print('Waiting ...') #Interval Timer # Wrap it into class class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) print('Done') timer = RepeatTimer(1, display, ['Repeating ']) timer.start() print('Treading Started ') time.sleep(10) # suspend execution print('Threading finished ') timer.cancel()
20.882353
53
0.622535
import time from threading import Timer def display(msg): print(msg + ' ' + time.strftime('%H:%M:%S')) def run_once(): display('Run Once : ') t = Timer(5, display, ['Timeout:']) t.start() run_once() print('Waiting ...') class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) print('Done') timer = RepeatTimer(1, display, ['Repeating ']) timer.start() print('Treading Started ') time.sleep(10) print('Threading finished ') timer.cancel()
true
true
f7277e3b484818974b6db28812e583f2b833d7dd
605
py
Python
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
242
2018-11-29T13:34:13.000Z
2022-03-26T19:35:17.000Z
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
13
2019-01-31T03:33:36.000Z
2022-01-03T07:03:19.000Z
tests/mock_generator.py
jcheminform/guacamol
dd7f7b12e1ab59151394aba5f4a95ee204fd0203
[ "MIT" ]
68
2018-11-26T10:03:41.000Z
2022-03-28T20:58:20.000Z
from typing import List from guacamol.distribution_matching_generator import DistributionMatchingGenerator class MockGenerator(DistributionMatchingGenerator): """ Mock generator that returns pre-defined molecules, possibly split in several calls """ def __init__(self, molecules: List[str]) -> None: self.molecules = molecules self.cursor = 0 def generate(self, number_samples: int) -> List[str]: end = self.cursor + number_samples sampled_molecules = self.molecules[self.cursor:end] self.cursor = end return sampled_molecules
27.5
82
0.707438
from typing import List from guacamol.distribution_matching_generator import DistributionMatchingGenerator class MockGenerator(DistributionMatchingGenerator): def __init__(self, molecules: List[str]) -> None: self.molecules = molecules self.cursor = 0 def generate(self, number_samples: int) -> List[str]: end = self.cursor + number_samples sampled_molecules = self.molecules[self.cursor:end] self.cursor = end return sampled_molecules
true
true
f7277ef92647633965a12e98c00211e924095a71
158
py
Python
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
null
null
null
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
10
2020-08-19T04:31:52.000Z
2020-09-21T22:48:29.000Z
03_Estrutura_de_Repeticao/12_gerador_tabuada.py
gabrieldcpadilha/ListaDeExercicios-PythonBrasil
a92d477468bde5eac8987a26ea79af2ffeb6ad81
[ "MIT" ]
null
null
null
num = int(input('Informe o numero que voce deseja ver a tabuada: ')) print(f'Tabuada de {num}') for c in range(0, 11): print(f'{num} X {c} = {num * c}')
26.333333
68
0.607595
num = int(input('Informe o numero que voce deseja ver a tabuada: ')) print(f'Tabuada de {num}') for c in range(0, 11): print(f'{num} X {c} = {num * c}')
true
true
f7277f4bc851f4bcbda0ff622dd70c2d8c114bb2
398
py
Python
tgBCoinBot/wsgi.py
steveyout/bitc
3fb227ba35d0daa8c2337cf8761cf68a752a973d
[ "Apache-2.0" ]
1
2021-01-30T10:25:04.000Z
2021-01-30T10:25:04.000Z
tgBCoinBot/wsgi.py
steveyout/pyth
d7178c76fa1a110c3d95df48bbec555b68dad618
[ "Apache-2.0" ]
2
2020-02-12T01:28:33.000Z
2020-06-05T18:52:39.000Z
tgBCoinBot/wsgi.py
steveyout/bitc
3fb227ba35d0daa8c2337cf8761cf68a752a973d
[ "Apache-2.0" ]
null
null
null
""" WSGI config for tgBCoinBot project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tgBCoinBot.settings") application = get_wsgi_application()
23.411765
78
0.788945
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tgBCoinBot.settings") application = get_wsgi_application()
true
true
f7277fcf10b974b66303d90351215882cab6362f
3,232
py
Python
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
3
2019-04-09T22:59:33.000Z
2019-06-14T09:23:24.000Z
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
venv/lib/python2.7/site-packages/test/test_wsgi.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
import cStringIO import sys from netlib import wsgi, odict def tflow(): h = odict.ODictCaseless() h["test"] = ["value"] req = wsgi.Request("http", "GET", "/", h, "") return wsgi.Flow(("127.0.0.1", 8888), req) class TestApp: def __init__(self): self.called = False def __call__(self, environ, start_response): self.called = True status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello', ' world!\n'] class TestWSGI: def test_make_environ(self): w = wsgi.WSGIAdaptor(None, "foo", 80, "version") tf = tflow() assert w.make_environ(tf, None) tf.request.path = "/foo?bar=voing" r = w.make_environ(tf, None) assert r["QUERY_STRING"] == "bar=voing" def test_serve(self): ta = TestApp() w = wsgi.WSGIAdaptor(ta, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() err = w.serve(f, wfile) assert ta.called assert not err val = wfile.getvalue() assert "Hello world" in val assert "Server:" in val def _serve(self, app): w = wsgi.WSGIAdaptor(app, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() w.serve(f, wfile) return wfile.getvalue() def test_serve_empty_body(self): def app(environ, start_response): status = '200 OK' response_headers = [('Foo', 'bar')] start_response(status, response_headers) return [] assert self._serve(app) def test_serve_double_start(self): def app(environ, start_response): try: raise ValueError("foo") except: sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) start_response(status, response_headers) assert "Internal Server Error" in self._serve(app) def test_serve_single_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers, ei) assert "Internal Server Error" in self._serve(app) def test_serve_double_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) yield "aaa" start_response(status, response_headers, ei) yield "bbb" assert "Internal Server Error" in self._serve(app)
30.490566
64
0.537438
import cStringIO import sys from netlib import wsgi, odict def tflow(): h = odict.ODictCaseless() h["test"] = ["value"] req = wsgi.Request("http", "GET", "/", h, "") return wsgi.Flow(("127.0.0.1", 8888), req) class TestApp: def __init__(self): self.called = False def __call__(self, environ, start_response): self.called = True status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello', ' world!\n'] class TestWSGI: def test_make_environ(self): w = wsgi.WSGIAdaptor(None, "foo", 80, "version") tf = tflow() assert w.make_environ(tf, None) tf.request.path = "/foo?bar=voing" r = w.make_environ(tf, None) assert r["QUERY_STRING"] == "bar=voing" def test_serve(self): ta = TestApp() w = wsgi.WSGIAdaptor(ta, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() err = w.serve(f, wfile) assert ta.called assert not err val = wfile.getvalue() assert "Hello world" in val assert "Server:" in val def _serve(self, app): w = wsgi.WSGIAdaptor(app, "foo", 80, "version") f = tflow() f.request.host = "foo" f.request.port = 80 wfile = cStringIO.StringIO() w.serve(f, wfile) return wfile.getvalue() def test_serve_empty_body(self): def app(environ, start_response): status = '200 OK' response_headers = [('Foo', 'bar')] start_response(status, response_headers) return [] assert self._serve(app) def test_serve_double_start(self): def app(environ, start_response): try: raise ValueError("foo") except: sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) start_response(status, response_headers) assert "Internal Server Error" in self._serve(app) def test_serve_single_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers, ei) assert "Internal Server Error" in self._serve(app) def test_serve_double_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ei = sys.exc_info() status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) yield "aaa" start_response(status, response_headers, ei) yield "bbb" assert "Internal Server Error" in self._serve(app)
true
true
f7277fd31391e322ececec43a17017d86e45c1ec
10,296
py
Python
train.py
jojotenya/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
75
2019-12-22T18:59:05.000Z
2021-09-17T06:30:38.000Z
train.py
chho33/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
5
2020-05-03T10:00:05.000Z
2021-08-04T05:35:57.000Z
train.py
jojotenya/LAMOL
03c31d9f0c7bf71295bc2d362ddf40a7656956e1
[ "MIT" ]
9
2020-02-14T17:33:58.000Z
2021-06-08T06:02:13.000Z
import torch from torch.utils.data import DataLoader from torch import nn from pytorch_transformers import AdamW, WEIGHTS_NAME, WarmupLinearSchedule import csv import numpy as np import os import logging from fp16 import FP16_Module, FP16_Optimizer from parallel import DataParallelModel, DataParallelCriterion from collections import OrderedDict from utils import * from settings import args, TASK_DICT, init_logging, MODEL_CONFIG, MODEL_CLASS, SPECIAL_TOKENS, CONFIG_CLASS from settings import TOKENIZER, SPECIAL_TOKEN_IDS, FILL_VAL, SAVE_NAME, FINAL_SAVE_NAME, TOKENS_WEIGHT, CONFIG_NAME from scheduler import AnnealingLR from regularizers import REG_TYPES, REG_TYPE_KEYS, Weight_Regularized_AdamW, Weight_Regularized_SGD from torch.nn import CrossEntropyLoss logger = logging.getLogger(__name__) def train(task_ids, model): tasks = [args.tasks[task_id] for task_id in task_ids] logger.info("start to train { task: %s, seq train type: %s }" % (tasks, args.seq_train_type)) model_dir = get_model_dir(tasks) make_dir(model_dir) train_dataset = [TASK_DICT[t]["train"] for t in tasks] train_extra_data = [] if "lll" in args.seq_train_type and task_ids[0] > 0 and not args.skip_tasks: prev_task = args.tasks[task_ids[0]-1] with torch.no_grad(): create_extra_data(tasks[0], prev_task, model, train_extra_data) elif "gem" in args.seq_train_type and task_ids[0] > 0: get_real_data(tasks[0], train_extra_data, accum=False, encode=True) args.memory_data.append(train_extra_data) train_extra_data = [] logger.info('extra training data size: {}'.format(len(train_extra_data))) if not model: # which_model_to_load = model_dir if os.path.isfile(os.path.join(model_dir, FINAL_SAVE_NAME)) else args.model_name model = MODEL_CLASS.from_pretrained(args.model_name).cuda() model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) gen_token = get_gen_token(tasks[0]) TOKENIZER.add_tokens([gen_token]) TOKENIZER.save_pretrained(model_dir) SPECIAL_TOKENS[tasks[0]] = gen_token SPECIAL_TOKEN_IDS[tasks[0]] = TOKENIZER.convert_tokens_to_ids(gen_token) logger.info('gen token = {} , gen token id = {}'.format(gen_token, SPECIAL_TOKEN_IDS[tasks[0]])) MODEL_CONFIG.vocab_size = len(TOKENIZER) MODEL_CONFIG.to_json_file(os.path.join(model_dir,CONFIG_NAME)) global TOKENS_WEIGHT if len(TOKENIZER) != TOKENS_WEIGHT.shape[0]: TOKENS_WEIGHT = torch.cat((TOKENS_WEIGHT, torch.ones([1]).cuda())) if args.skip_tasks and len(tasks) == 1: logger.info("*********** skip task: {} ***********".format(tasks[0])) if tasks[0] in args.skip_tasks: if len(args.skip_tasks) == 1: model_dir = get_model_dir(tasks) model_path = os.path.join(model_dir, FINAL_SAVE_NAME) config_path = os.path.join(model_dir,CONFIG_NAME) model_config = CONFIG_CLASS.from_json_file(config_path) model = MODEL_CLASS(model_config).cuda() state_dict = torch.load(model_path) model.load_state_dict(state_dict) if not args.fp32: model = FP16_Module(model) if args.seq_train_type in REG_TYPE_KEYS: logger.info("calulating reg_params ...") train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [train_dataloader], tasks[0]) regularizer.task_start_do() regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) logger.info("done reg_params!") args.skip_tasks.remove(tasks[0]) return model model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: # again because resize_token_embeddings makes embedding layer fp32 model = FP16_Module(model) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) if not args.unbound and args.seq_train_type != "multitask": #n_train_epochs = TASK_DICT[tasks[0]]["n_train_epochs"] n_train_epochs = args.n_train_epochs[tasks[0]] else: n_train_epochs = args.n_train_epochs['_'.join(tasks)] n_train_optimization_steps = len(train_qadata) * n_train_epochs logger.info('len of train dataset: {} , max train batch size {} , num of opt steps: {}'.format( len(train_qadata), max_train_batch_size, n_train_optimization_steps)) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] if "gem" in args.seq_train_type: model.task_id = task_ids[0] if not hasattr(model, "grad_dims"): model.grad_dims = [] for param in model.parameters(): model.grad_dims.append(param.data.numel()) if not hasattr(model, "grads"): model.grads = torch.zeros(sum(model.grad_dims),len(args.tasks)) model.grads = model.grads.cuda() if args.seq_train_type in REG_TYPE_KEYS: optimizer = Weight_Regularized_AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) else: optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) if not args.fp32: optimizer = FP16_Optimizer(optimizer, static_loss_scale=None, dynamic_loss_scale=True, dynamic_loss_args={'scale_window': 100, 'min_scale': 1, 'delayed_shift': 2}) scheduler = AnnealingLR(optimizer, start_lr=args.learning_rate, warmup_iter=int(args.n_warmup_ratio*len(train_qadata)), num_iters=int(n_train_optimization_steps), decay_style=args.decay_style) train_loss_fct = DataParallelCriterion(CrossEntropyLoss(ignore_index=FILL_VAL, weight=TOKENS_WEIGHT), args.device_ids) if args.seq_train_type in REG_TYPE_KEYS: copy_train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) prev_task = args.tasks[task_ids[0]-1] regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [copy_train_dataloader], tasks[0], prev_task) regularizer.task_start_do() tot_n_steps = 0 train_once = TrainStep(model, optimizer, scheduler) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step = GEMStep(model, parallel_model, train_loss_fct, optimizer) model.train() for ep in range(n_train_epochs): cum_loss, cum_qa_loss, cum_lm_loss, cur_n_inputs = 0, 0, 0, 0 for n_steps, (_, _, cqa, _, Y, gen_X, gen_Y) in enumerate(train_dataloader): n_inputs = sum(_cqa.shape[0] for _cqa in cqa) for i in range(len(cqa)): cqa[i] = (cqa[i].to(args.device_ids[i]),) Y[i] = Y[i].to(args.device_ids[i]) gen_X[i] = (gen_X[i].to(args.device_ids[i]),) gen_Y[i] = gen_Y[i].to(args.device_ids[i]) losses = get_losses(parallel_model, cqa, Y, gen_X, gen_Y, train_loss_fct) loss = sum(losses) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step(task_ids[0]) train_once(loss, n_inputs) qa_loss = losses[0].item() * n_inputs lm_loss = losses[1].item() * n_inputs cum_loss += (qa_loss + lm_loss) cum_qa_loss += qa_loss cum_lm_loss += lm_loss cur_n_inputs += n_inputs if (n_steps + 1 ) % args.logging_steps == 0: logger.info('progress {:.3f} , lr {:.1E} , loss {:.3f} , qa loss {:.3f} , lm loss {:.3f} , avg batch size {:.1f}'.format( ep + cur_n_inputs/len(train_qadata), scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps + 1) )) torch.save(model.state_dict(), os.path.join(model_dir, SAVE_NAME+str(ep+1))) tot_n_steps += (n_steps + 1) logger.info('epoch {}/{} done , tot steps {} , lr {:.1E} , loss {:.2f} , qa loss {:.2f} , lm loss {:.2f} , avg batch size {:.1f}'.format( ep+1, n_train_epochs, tot_n_steps, scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps+1) )) # task end do for reg if args.seq_train_type in REG_TYPE_KEYS: regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) return model if __name__ == '__main__': if not args.debug: logging.getLogger("pytorch_transformers").setLevel(logging.WARNING) logging.getLogger("pytorch_transformers.tokenization_utils").setLevel(logging.CRITICAL) make_dir(args.model_dir_root) init_logging(os.path.join(args.model_dir_root, 'log_train.txt')) logger.info('args = {}'.format(str(args))) model = None if args.seq_train_type == "multitask": model = train(list(range(len(args.tasks))), model) else: if args.unbound: TASK_DICT = lll_unbound_setting(split_size=args.unbound) for task_id in range(len(args.tasks)): model = train([task_id], model)
49.263158
166
0.668512
import torch from torch.utils.data import DataLoader from torch import nn from pytorch_transformers import AdamW, WEIGHTS_NAME, WarmupLinearSchedule import csv import numpy as np import os import logging from fp16 import FP16_Module, FP16_Optimizer from parallel import DataParallelModel, DataParallelCriterion from collections import OrderedDict from utils import * from settings import args, TASK_DICT, init_logging, MODEL_CONFIG, MODEL_CLASS, SPECIAL_TOKENS, CONFIG_CLASS from settings import TOKENIZER, SPECIAL_TOKEN_IDS, FILL_VAL, SAVE_NAME, FINAL_SAVE_NAME, TOKENS_WEIGHT, CONFIG_NAME from scheduler import AnnealingLR from regularizers import REG_TYPES, REG_TYPE_KEYS, Weight_Regularized_AdamW, Weight_Regularized_SGD from torch.nn import CrossEntropyLoss logger = logging.getLogger(__name__) def train(task_ids, model): tasks = [args.tasks[task_id] for task_id in task_ids] logger.info("start to train { task: %s, seq train type: %s }" % (tasks, args.seq_train_type)) model_dir = get_model_dir(tasks) make_dir(model_dir) train_dataset = [TASK_DICT[t]["train"] for t in tasks] train_extra_data = [] if "lll" in args.seq_train_type and task_ids[0] > 0 and not args.skip_tasks: prev_task = args.tasks[task_ids[0]-1] with torch.no_grad(): create_extra_data(tasks[0], prev_task, model, train_extra_data) elif "gem" in args.seq_train_type and task_ids[0] > 0: get_real_data(tasks[0], train_extra_data, accum=False, encode=True) args.memory_data.append(train_extra_data) train_extra_data = [] logger.info('extra training data size: {}'.format(len(train_extra_data))) if not model: model = MODEL_CLASS.from_pretrained(args.model_name).cuda() model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) gen_token = get_gen_token(tasks[0]) TOKENIZER.add_tokens([gen_token]) TOKENIZER.save_pretrained(model_dir) SPECIAL_TOKENS[tasks[0]] = gen_token SPECIAL_TOKEN_IDS[tasks[0]] = TOKENIZER.convert_tokens_to_ids(gen_token) logger.info('gen token = {} , gen token id = {}'.format(gen_token, SPECIAL_TOKEN_IDS[tasks[0]])) MODEL_CONFIG.vocab_size = len(TOKENIZER) MODEL_CONFIG.to_json_file(os.path.join(model_dir,CONFIG_NAME)) global TOKENS_WEIGHT if len(TOKENIZER) != TOKENS_WEIGHT.shape[0]: TOKENS_WEIGHT = torch.cat((TOKENS_WEIGHT, torch.ones([1]).cuda())) if args.skip_tasks and len(tasks) == 1: logger.info("*********** skip task: {} ***********".format(tasks[0])) if tasks[0] in args.skip_tasks: if len(args.skip_tasks) == 1: model_dir = get_model_dir(tasks) model_path = os.path.join(model_dir, FINAL_SAVE_NAME) config_path = os.path.join(model_dir,CONFIG_NAME) model_config = CONFIG_CLASS.from_json_file(config_path) model = MODEL_CLASS(model_config).cuda() state_dict = torch.load(model_path) model.load_state_dict(state_dict) if not args.fp32: model = FP16_Module(model) if args.seq_train_type in REG_TYPE_KEYS: logger.info("calulating reg_params ...") train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [train_dataloader], tasks[0]) regularizer.task_start_do() regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) logger.info("done reg_params!") args.skip_tasks.remove(tasks[0]) return model model.resize_token_embeddings(len(TOKENIZER)) if not args.fp32: model = FP16_Module(model) parallel_model = DataParallelModel(WrapModel(model), args.device_ids) train_qadata = QADataset(train_dataset, "train", SPECIAL_TOKEN_IDS[tasks[0]], train_extra_data) max_train_batch_size = max(len(train_qadata) // args.min_n_steps, args.min_batch_size) train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) if not args.unbound and args.seq_train_type != "multitask": n_train_epochs = args.n_train_epochs[tasks[0]] else: n_train_epochs = args.n_train_epochs['_'.join(tasks)] n_train_optimization_steps = len(train_qadata) * n_train_epochs logger.info('len of train dataset: {} , max train batch size {} , num of opt steps: {}'.format( len(train_qadata), max_train_batch_size, n_train_optimization_steps)) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] if "gem" in args.seq_train_type: model.task_id = task_ids[0] if not hasattr(model, "grad_dims"): model.grad_dims = [] for param in model.parameters(): model.grad_dims.append(param.data.numel()) if not hasattr(model, "grads"): model.grads = torch.zeros(sum(model.grad_dims),len(args.tasks)) model.grads = model.grads.cuda() if args.seq_train_type in REG_TYPE_KEYS: optimizer = Weight_Regularized_AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) else: optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) if not args.fp32: optimizer = FP16_Optimizer(optimizer, static_loss_scale=None, dynamic_loss_scale=True, dynamic_loss_args={'scale_window': 100, 'min_scale': 1, 'delayed_shift': 2}) scheduler = AnnealingLR(optimizer, start_lr=args.learning_rate, warmup_iter=int(args.n_warmup_ratio*len(train_qadata)), num_iters=int(n_train_optimization_steps), decay_style=args.decay_style) train_loss_fct = DataParallelCriterion(CrossEntropyLoss(ignore_index=FILL_VAL, weight=TOKENS_WEIGHT), args.device_ids) if args.seq_train_type in REG_TYPE_KEYS: copy_train_dataloader = create_dataloader(train_qadata, "train", max_train_batch_size) prev_task = args.tasks[task_ids[0]-1] regularizer = REG_TYPES[args.seq_train_type](model, parallel_model, [copy_train_dataloader], tasks[0], prev_task) regularizer.task_start_do() tot_n_steps = 0 train_once = TrainStep(model, optimizer, scheduler) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step = GEMStep(model, parallel_model, train_loss_fct, optimizer) model.train() for ep in range(n_train_epochs): cum_loss, cum_qa_loss, cum_lm_loss, cur_n_inputs = 0, 0, 0, 0 for n_steps, (_, _, cqa, _, Y, gen_X, gen_Y) in enumerate(train_dataloader): n_inputs = sum(_cqa.shape[0] for _cqa in cqa) for i in range(len(cqa)): cqa[i] = (cqa[i].to(args.device_ids[i]),) Y[i] = Y[i].to(args.device_ids[i]) gen_X[i] = (gen_X[i].to(args.device_ids[i]),) gen_Y[i] = gen_Y[i].to(args.device_ids[i]) losses = get_losses(parallel_model, cqa, Y, gen_X, gen_Y, train_loss_fct) loss = sum(losses) if "gem" in args.seq_train_type and task_ids[0] != 0: gem_step(task_ids[0]) train_once(loss, n_inputs) qa_loss = losses[0].item() * n_inputs lm_loss = losses[1].item() * n_inputs cum_loss += (qa_loss + lm_loss) cum_qa_loss += qa_loss cum_lm_loss += lm_loss cur_n_inputs += n_inputs if (n_steps + 1 ) % args.logging_steps == 0: logger.info('progress {:.3f} , lr {:.1E} , loss {:.3f} , qa loss {:.3f} , lm loss {:.3f} , avg batch size {:.1f}'.format( ep + cur_n_inputs/len(train_qadata), scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps + 1) )) torch.save(model.state_dict(), os.path.join(model_dir, SAVE_NAME+str(ep+1))) tot_n_steps += (n_steps + 1) logger.info('epoch {}/{} done , tot steps {} , lr {:.1E} , loss {:.2f} , qa loss {:.2f} , lm loss {:.2f} , avg batch size {:.1f}'.format( ep+1, n_train_epochs, tot_n_steps, scheduler.get_lr(), cum_loss/cur_n_inputs, cum_qa_loss/cur_n_inputs, cum_lm_loss/cur_n_inputs, cur_n_inputs/(n_steps+1) )) if args.seq_train_type in REG_TYPE_KEYS: regularizer.task_end_do() torch.save(model.state_dict(), os.path.join(model_dir, FINAL_SAVE_NAME)) return model if __name__ == '__main__': if not args.debug: logging.getLogger("pytorch_transformers").setLevel(logging.WARNING) logging.getLogger("pytorch_transformers.tokenization_utils").setLevel(logging.CRITICAL) make_dir(args.model_dir_root) init_logging(os.path.join(args.model_dir_root, 'log_train.txt')) logger.info('args = {}'.format(str(args))) model = None if args.seq_train_type == "multitask": model = train(list(range(len(args.tasks))), model) else: if args.unbound: TASK_DICT = lll_unbound_setting(split_size=args.unbound) for task_id in range(len(args.tasks)): model = train([task_id], model)
true
true
f7278004acfca10614fa1c33b678146eff3e8f86
1,850
py
Python
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
1
2021-11-26T12:22:13.000Z
2021-11-26T12:22:13.000Z
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
null
null
null
scikit-learn-weighted_kde/examples/svm/plot_separating_hyperplane_unbalanced.py
RTHMaK/git-squash-master
76c4c8437dd18114968e69a698f4581927fcdabf
[ "BSD-2-Clause" ]
null
null
null
""" ================================================= SVM: Separating hyperplane for unbalanced classes ================================================= Find the optimal separating hyperplane using an SVC for classes that are unbalanced. We first find the separating plane with a plain SVC and then plot (dashed) the separating hyperplane with automatically correction for unbalanced classes. .. currentmodule:: sklearn.linear_model .. note:: This example will also work by replacing ``SVC(kernel="linear")`` with ``SGDClassifier(loss="hinge")``. Setting the ``loss`` parameter of the :class:`SGDClassifier` equal to ``hinge`` will yield behaviour such as that of a SVC with a linear kernel. For example try instead of the ``SVC``:: clf = SGDClassifier(n_iter=100, alpha=0.01) """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm #from sklearn.linear_model import SGDClassifier # we create 40 separable points rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) # fit the model and get the separating hyperplane clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] # get the separating hyperplane using weighted classes wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] # plot separating hyperplanes and samples h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
27.205882
73
0.651351
print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm rng = np.random.RandomState(0) n_samples_1 = 1000 n_samples_2 = 100 X = np.r_[1.5 * rng.randn(n_samples_1, 2), 0.5 * rng.randn(n_samples_2, 2) + [2, 2]] y = [0] * (n_samples_1) + [1] * (n_samples_2) clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - clf.intercept_[0] / w[1] wclf = svm.SVC(kernel='linear', class_weight={1: 10}) wclf.fit(X, y) ww = wclf.coef_[0] wa = -ww[0] / ww[1] wyy = wa * xx - wclf.intercept_[0] / ww[1] h0 = plt.plot(xx, yy, 'k-', label='no weights') h1 = plt.plot(xx, wyy, 'k--', label='with weights') plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.legend() plt.axis('tight') plt.show()
true
true
f727802bb39ec646082acbc4f4eca9a79e31fb09
1,827
py
Python
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
base.py
thiagosouzalink/Python_Projeto-CRUD_Using_File
20bc87568f1edd69aacc3af7b493b5b2337c6544
[ "MIT" ]
null
null
null
""" FUNÇÕES BÁSICAS PARA O PROGRAMA """ from time import sleep # Imprimir caracter especial def linha(tam=40): print(f"{'='*tam}") # Recebe e valida um nome def ler_nome(txt): stop = True while stop: stop = False nome = input(txt).strip() lista_nome = nome.split() if len(lista_nome) == 0: print("ERRO! Você digitou um nome vazio...") sleep(1) stop = True else: for valor in lista_nome: # Verifica se o nome contém conteúdo não alfabético if not valor.isalpha(): print("ERRO! Você digitou um nome inválido...") sleep(1) stop = True nome = " ".join(lista_nome) return nome # Recebe e valida um número inteiro def ler_inteiro(txt=""): # Caso o texto seja vazio, exibe uma mensagem default if txt == "": txt = "Digite o valor de um número inteiro" while True: try: inteiro = int(input(txt)) except (KeyboardInterrupt): print("ERRO! Entrada de dados interrompida pelo usuário!") inteiro = 0 break except(ValueError): print("ERRO! Você digitou um valor inteiro inválido...") sleep(1) except: # Demais erros print("ERRO! O programa teve um erro durante a leitura...") sleep(1) else: break return inteiro # Recebe e valida uma idade def ler_idade(txt): if txt == "": txt = "Digite o valor da idade" while True: idade = ler_inteiro(txt) if idade < 0: print("ERRO! Você digitou uma valor negativo...") sleep(1) else: break return idade
21.75
71
0.523262
from time import sleep def linha(tam=40): print(f"{'='*tam}") def ler_nome(txt): stop = True while stop: stop = False nome = input(txt).strip() lista_nome = nome.split() if len(lista_nome) == 0: print("ERRO! Você digitou um nome vazio...") sleep(1) stop = True else: for valor in lista_nome: if not valor.isalpha(): print("ERRO! Você digitou um nome inválido...") sleep(1) stop = True nome = " ".join(lista_nome) return nome def ler_inteiro(txt=""): if txt == "": txt = "Digite o valor de um número inteiro" while True: try: inteiro = int(input(txt)) except (KeyboardInterrupt): print("ERRO! Entrada de dados interrompida pelo usuário!") inteiro = 0 break except(ValueError): print("ERRO! Você digitou um valor inteiro inválido...") sleep(1) except: print("ERRO! O programa teve um erro durante a leitura...") sleep(1) else: break return inteiro def ler_idade(txt): if txt == "": txt = "Digite o valor da idade" while True: idade = ler_inteiro(txt) if idade < 0: print("ERRO! Você digitou uma valor negativo...") sleep(1) else: break return idade
true
true
f727809dfe02a4b21995583a93752cc365af2e33
162
py
Python
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
22
2016-09-01T08:27:07.000Z
2021-01-11T13:32:59.000Z
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
null
null
null
plugins/baiaozhi_cms.py
cflq3/getcms
6cf07da0ea3ec644866df715cff1f311a46ee378
[ "MIT" ]
20
2015-11-07T19:09:48.000Z
2018-05-02T03:10:41.000Z
#!/usr/bin/env python # encoding: utf-8 def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "portal/dbportal/popup/popupdiv.js", "'mozilla'")
23.142857
89
0.728395
def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "portal/dbportal/popup/popupdiv.js", "'mozilla'")
true
true
f72780a93d732aedce510f6fc8674fcf936b13b5
2,221
py
Python
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
test_compare_gw.py
namedyangfan/compare_gw
93d8ed205962c92c32d2cf669ee32eef18577d0e
[ "MIT" ]
null
null
null
from compare_data.compare_gw import Obs_well_hgs import unittest import os file_directory = os.path.join(os.getcwd(), 'test_data') output_folder = os.path.join(file_directory, "output") if not os.path.exists(output_folder): os.mkdir(output_folder) class TestStringMethods(unittest.TestCase): def test_reorder_hgsoutput(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.op(op_folder = output_folder, zone_name = 'Baildon059_reorder') def test_reorder_hgsoutput_heat2depth(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.head_to_depth() test.op(op_folder = output_folder, zone_name = 'Baildon059_head_2_depth') def test_simutime2realtime(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.op(op_folder = output_folder, zone_name = 'Baildon059_realtime') def test_weekly_soilmoisture(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 5, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.avg_weekly(date_format= 'YYYYMMDD') test.op(op_folder = output_folder, zone_name = 'Baildon059_weekly_soil_moisture') if __name__ == '__main__': unittest.main()
49.355556
107
0.693381
from compare_data.compare_gw import Obs_well_hgs import unittest import os file_directory = os.path.join(os.getcwd(), 'test_data') output_folder = os.path.join(file_directory, "output") if not os.path.exists(output_folder): os.mkdir(output_folder) class TestStringMethods(unittest.TestCase): def test_reorder_hgsoutput(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.op(op_folder = output_folder, zone_name = 'Baildon059_reorder') def test_reorder_hgsoutput_heat2depth(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name=file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.head_to_depth() test.op(op_folder = output_folder, zone_name = 'Baildon059_head_2_depth') def test_simutime2realtime(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 3, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.op(op_folder = output_folder, zone_name = 'Baildon059_realtime') def test_weekly_soilmoisture(self): file_name = 'ARB_QUAPo.observation_well_flow.Baildon059.dat' test = Obs_well_hgs( file_directory = file_directory, file_name= file_name) test.read_raw_obs() test.reorder_raw2column(var_names = ['H', 'Z', 'S'], start_sheet = 5, end_sheet = 6, ldebug=False) test.to_realtime(t0 = '2002-01-01T00:00:00Z') test.avg_weekly(date_format= 'YYYYMMDD') test.op(op_folder = output_folder, zone_name = 'Baildon059_weekly_soil_moisture') if __name__ == '__main__': unittest.main()
true
true
f72783a0dd98fa8f7f24db93479956beeb8365a7
9,714
py
Python
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
15
2017-11-29T15:51:12.000Z
2022-02-09T13:19:33.000Z
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
5
2018-03-22T04:12:25.000Z
2019-04-30T21:14:00.000Z
operators/s3_to_mysql_operator.py
edbizarro/mysql_plugin
ce0175cec20319b996590e4d3e0ca36cf4331c10
[ "Apache-2.0" ]
20
2018-04-11T07:14:03.000Z
2021-09-14T01:17:20.000Z
from airflow.models import BaseOperator from airflow.hooks.S3_hook import S3Hook from airflow.hooks.mysql_hook import MySqlHook import dateutil.parser import json import logging class S3ToMySQLOperator(BaseOperator): """ NOTE: To avoid invalid characters, it is recommended to specify the character encoding (e.g {"charset":"utf8"}). S3 To MySQL Operator :param s3_conn_id: The source s3 connection id. :type s3_conn_id: string :param s3_bucket: The source s3 bucket. :type s3_bucket: string :param s3_key: The source s3 key. :type s3_key: string :param mysql_conn_id: The destination redshift connection id. :type mysql_conn_id: string :param database: The destination database name. :type database: string :param table: The destination mysql table name. :type table: string :param field_schema: An array of dicts in the following format: {'name': 'column_name', 'type': 'int(11)'} which determine what fields will be created and inserted. :type field_schema: array :param primary_key: The primary key for the destination table. Multiple strings in the array signify a compound key. :type primary_key: array :param incremental_key: *(optional)* The incremental key to compare new data against the destination table with. Only required if using a load_type of "upsert". :type incremental_key: string :param load_type: The method of loading into MySQL that should occur. Options are "append", "rebuild", and "upsert". Defaults to "append." :type load_type: string """ template_fields = ('s3_key',) def __init__(self, s3_conn_id, s3_bucket, s3_key, mysql_conn_id, database, table, field_schema, primary_key=[], incremental_key=None, load_type='append', *args, **kwargs): super().__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.s3_conn_id = s3_conn_id self.s3_bucket = s3_bucket self.s3_key = s3_key self.table = table self.database = database self.field_schema = field_schema self.primary_key = primary_key self.incremental_key = incremental_key self.load_type = load_type def execute(self, context): m_hook = MySqlHook(self.mysql_conn_id) data = (S3Hook(self.s3_conn_id) .get_key(self.s3_key, bucket_name=self.s3_bucket) .get_contents_as_string(encoding='utf-8')) self.copy_data(m_hook, data) def copy_data(self, m_hook, data): if self.load_type == 'rebuild': drop_query = \ """ DROP TABLE IF EXISTS {schema}.{table} """.format(schema=self.database, table=self.table) m_hook.run(drop_query) table_exists_query = \ """ SELECT * FROM information_schema.tables WHERE table_schema = '{database}' AND table_name = '{table}' """.format(database=self.database, table=self.table) if not m_hook.get_records(table_exists_query): self.create_table(m_hook) else: self.reconcile_schemas(m_hook) self.write_data(m_hook, data) def create_table(self, m_hook): # Fields are surround by `` in order to avoid namespace conflicts # with reserved words in MySQL. # https://dev.mysql.com/doc/refman/5.7/en/identifiers.html fields = ['`{name}` {type} {nullable}'.format(name=field['name'], type=field['type'], nullable='NOT NULL' if field['name'] in self.primary_key else 'NULL') for field in self.field_schema] keys = ', '.join(self.primary_key) create_query = \ """ CREATE TABLE IF NOT EXISTS {schema}.{table} ({fields} """.format(schema=self.database, table=self.table, fields=', '.join(fields)) if keys: create_query += ', PRIMARY KEY (`{keys}`)'.format(keys=keys) create_query += ')' m_hook.run(create_query) def reconcile_schemas(self, m_hook): describe_query = 'DESCRIBE {schema}.{table}'.format(schema=self.database, table=self.table) records = m_hook.get_records(describe_query) existing_columns_names = [x[0] for x in records] incoming_column_names = [field['name'] for field in self.field_schema] missing_columns = list(set(incoming_column_names) - set(existing_columns_names)) if len(missing_columns): columns = ['ADD COLUMN {name} {type} NULL'.format(name=field['name'], type=field['type']) for field in self.field_schema if field['name'] in missing_columns] alter_query = \ """ ALTER TABLE {schema}.{table} {columns} """.format(schema=self.database, table=self.table, columns=', '.join(columns)) m_hook.run(alter_query) logging.info('The new columns were:' + str(missing_columns)) else: logging.info('There were no new columns.') def write_data(self, m_hook, data): fields = ', '.join([field['name'] for field in self.field_schema]) placeholders = ', '.join('%({name})s'.format(name=field['name']) for field in self.field_schema) insert_query = \ """ INSERT INTO {schema}.{table} ({columns}) VALUES ({placeholders}) """.format(schema=self.database, table=self.table, columns=fields, placeholders=placeholders) if self.load_type == 'upsert': # Add IF check to ensure that the records being inserted have an # incremental_key with a value greater than the existing records. update_set = ', '.join([""" {name} = IF({ik} < VALUES({ik}), VALUES({name}), {name}) """.format(name=field['name'], ik=self.incremental_key) for field in self.field_schema]) insert_query += ('ON DUPLICATE KEY UPDATE {update_set}' .format(update_set=update_set)) # Split the incoming JSON newlines string along new lines. # Remove cases where two or more '\n' results in empty entries. records = [record for record in data.split('\n') if record] # Create a default "record" object with all available fields # intialized to None. These will be overwritten with the proper # field values as available. default_object = {} for field in self.field_schema: default_object[field['name']] = None # Initialize null to Nonetype for incoming null values in records dict null = None output = [] for record in records: line_object = default_object.copy() line_object.update(json.loads(record)) output.append(line_object) date_fields = [field['name'] for field in self.field_schema if field['type'] in ['datetime', 'date']] def convert_timestamps(key, value): if key in date_fields: try: # Parse strings to look for values that match a timestamp # and convert to datetime. # Set ignoretz=False to keep timezones embedded in datetime. # http://bit.ly/2zwcebe value = dateutil.parser.parse(value, ignoretz=False) return value except (ValueError, TypeError, OverflowError): # If the value does not match a timestamp or is null, # return intial value. return value else: return value output = [dict([k, convert_timestamps(k, v)] if v is not None else [k, v] for k, v in i.items()) for i in output] conn = m_hook.get_conn() cur = conn.cursor() cur.executemany(insert_query, output) cur.close() conn.commit() conn.close()
40.475
109
0.50628
from airflow.models import BaseOperator from airflow.hooks.S3_hook import S3Hook from airflow.hooks.mysql_hook import MySqlHook import dateutil.parser import json import logging class S3ToMySQLOperator(BaseOperator): template_fields = ('s3_key',) def __init__(self, s3_conn_id, s3_bucket, s3_key, mysql_conn_id, database, table, field_schema, primary_key=[], incremental_key=None, load_type='append', *args, **kwargs): super().__init__(*args, **kwargs) self.mysql_conn_id = mysql_conn_id self.s3_conn_id = s3_conn_id self.s3_bucket = s3_bucket self.s3_key = s3_key self.table = table self.database = database self.field_schema = field_schema self.primary_key = primary_key self.incremental_key = incremental_key self.load_type = load_type def execute(self, context): m_hook = MySqlHook(self.mysql_conn_id) data = (S3Hook(self.s3_conn_id) .get_key(self.s3_key, bucket_name=self.s3_bucket) .get_contents_as_string(encoding='utf-8')) self.copy_data(m_hook, data) def copy_data(self, m_hook, data): if self.load_type == 'rebuild': drop_query = \ """ DROP TABLE IF EXISTS {schema}.{table} """.format(schema=self.database, table=self.table) m_hook.run(drop_query) table_exists_query = \ """ SELECT * FROM information_schema.tables WHERE table_schema = '{database}' AND table_name = '{table}' """.format(database=self.database, table=self.table) if not m_hook.get_records(table_exists_query): self.create_table(m_hook) else: self.reconcile_schemas(m_hook) self.write_data(m_hook, data) def create_table(self, m_hook): fields = ['`{name}` {type} {nullable}'.format(name=field['name'], type=field['type'], nullable='NOT NULL' if field['name'] in self.primary_key else 'NULL') for field in self.field_schema] keys = ', '.join(self.primary_key) create_query = \ """ CREATE TABLE IF NOT EXISTS {schema}.{table} ({fields} """.format(schema=self.database, table=self.table, fields=', '.join(fields)) if keys: create_query += ', PRIMARY KEY (`{keys}`)'.format(keys=keys) create_query += ')' m_hook.run(create_query) def reconcile_schemas(self, m_hook): describe_query = 'DESCRIBE {schema}.{table}'.format(schema=self.database, table=self.table) records = m_hook.get_records(describe_query) existing_columns_names = [x[0] for x in records] incoming_column_names = [field['name'] for field in self.field_schema] missing_columns = list(set(incoming_column_names) - set(existing_columns_names)) if len(missing_columns): columns = ['ADD COLUMN {name} {type} NULL'.format(name=field['name'], type=field['type']) for field in self.field_schema if field['name'] in missing_columns] alter_query = \ """ ALTER TABLE {schema}.{table} {columns} """.format(schema=self.database, table=self.table, columns=', '.join(columns)) m_hook.run(alter_query) logging.info('The new columns were:' + str(missing_columns)) else: logging.info('There were no new columns.') def write_data(self, m_hook, data): fields = ', '.join([field['name'] for field in self.field_schema]) placeholders = ', '.join('%({name})s'.format(name=field['name']) for field in self.field_schema) insert_query = \ """ INSERT INTO {schema}.{table} ({columns}) VALUES ({placeholders}) """.format(schema=self.database, table=self.table, columns=fields, placeholders=placeholders) if self.load_type == 'upsert': update_set = ', '.join([""" {name} = IF({ik} < VALUES({ik}), VALUES({name}), {name}) """.format(name=field['name'], ik=self.incremental_key) for field in self.field_schema]) insert_query += ('ON DUPLICATE KEY UPDATE {update_set}' .format(update_set=update_set)) records = [record for record in data.split('\n') if record] default_object = {} for field in self.field_schema: default_object[field['name']] = None null = None output = [] for record in records: line_object = default_object.copy() line_object.update(json.loads(record)) output.append(line_object) date_fields = [field['name'] for field in self.field_schema if field['type'] in ['datetime', 'date']] def convert_timestamps(key, value): if key in date_fields: try: value = dateutil.parser.parse(value, ignoretz=False) return value except (ValueError, TypeError, OverflowError): return value else: return value output = [dict([k, convert_timestamps(k, v)] if v is not None else [k, v] for k, v in i.items()) for i in output] conn = m_hook.get_conn() cur = conn.cursor() cur.executemany(insert_query, output) cur.close() conn.commit() conn.close()
true
true
f72783f41e43e7a6ced69380671e393ee8c3f52c
4,382
py
Python
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
67
2018-05-17T21:54:01.000Z
2022-02-04T09:45:03.000Z
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
11
2018-06-23T11:27:51.000Z
2021-02-20T17:54:18.000Z
contrib/seeds/generate-seeds.py
glemercier/Core-Smart
4ccc12a1b2a55cbad79ddee07449a5fdadf3082b
[ "MIT" ]
43
2018-05-09T07:27:58.000Z
2021-12-14T15:21:51.000Z
#!/usr/bin/python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) The output will be two data structures with the peers in binary format: static SeedSpec6 pnSeed6_main[]={ ... } static SeedSpec6 pnSeed6_test[]={ ... } These should be pasted into `src/chainparamsseeds.h`. ''' from __future__ import print_function, division from base64 import b32decode from binascii import a2b_hex import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: # IPv6 sub = [[], []] # prefix, suffix x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end continue x += 1 # :: skips to suffix assert(x < 2) else: # two bytes per component val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) sys.exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 9678) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 19678) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
31.52518
98
0.582611
from __future__ import print_function, division from base64 import b32decode from binascii import a2b_hex import sys, os import re pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: sub = [[], []] x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): continue x += 1 assert(x < 2) else: val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: host = match.group(1) port = match.group(2) elif s.count(':') > 1: host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) sys.exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 9678) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 19678) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
true
true
f72785479e692aec1709c88b02e8f2700f756609
1,030
py
Python
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
KING-USER1/BLACK-GHOULS-USERBOT-
3db2b42e2f27ce2b4d1fce3e8f016b269e872d05
[ "MIT" ]
null
null
null
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you.""" import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from platform import uname from userbot import ALIVE_NAME from userbot.utils import admin_cmd DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Set ALIVE_NAME in config vars in Heroku" #@command(outgoing=True, pattern="^.alive$") @borg.on(admin_cmd(pattern=r"alive")) async def amireallyalive(alive): """ For .alive command, check if the bot is running. """ await alive.edit("`Abe Dalle Apna Kaam Kar Baap Ko Mat Dekh.\n\nBot version: 1.0\nPython: 3.7.3\n\n`" f"`Mera Maalik`: {DEFAULTUSER}\n" "`Telethon version: 6.9.0\nPython: 3.7.3\nfork by:` @KING_COBRA_OPPp\n" f"`Sabka Baap` : {DEFAULTUSER} \n" "`Always with my Maalik\n`" "[Deploy this userbot Now](https://github.com/KING-USER1/BLACK-GHOULS-USERBOT-)")
46.818182
122
0.683495
import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from platform import uname from userbot import ALIVE_NAME from userbot.utils import admin_cmd DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Set ALIVE_NAME in config vars in Heroku" @borg.on(admin_cmd(pattern=r"alive")) async def amireallyalive(alive): await alive.edit("`Abe Dalle Apna Kaam Kar Baap Ko Mat Dekh.\n\nBot version: 1.0\nPython: 3.7.3\n\n`" f"`Mera Maalik`: {DEFAULTUSER}\n" "`Telethon version: 6.9.0\nPython: 3.7.3\nfork by:` @KING_COBRA_OPPp\n" f"`Sabka Baap` : {DEFAULTUSER} \n" "`Always with my Maalik\n`" "[Deploy this userbot Now](https://github.com/KING-USER1/BLACK-GHOULS-USERBOT-)")
true
true
f727859e96eaa14fd00273ab0b71ffa22bdf4fcf
2,065
py
Python
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
1
2018-12-06T19:34:12.000Z
2018-12-06T19:34:12.000Z
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
6
2018-12-08T08:45:52.000Z
2018-12-08T08:56:19.000Z
web/src/contacto/views.py
DelegacionCienciasUSAL/delcien.usal.es
fbf445c05a13eaa9726b0d8823c3aa34c9334dd3
[ "Apache-2.0" ]
null
null
null
from django.core.mail import send_mail from django.conf import settings from django.shortcuts import render from django.http import Http404 from django.http import HttpResponseRedirect # Create your views here. def main( request): return( render( request, 'contacto/main.html', {'Titulo' : 'Contacto'})) def get_duda(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') duda = request.GET.get('duda') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and duda != None and prev_url != None): subject = f"WEBPAGE : Duda de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nDuda : \n{duda}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer) def get_colab(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') idea = request.GET.get('idea') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and idea != None and prev_url != None): subject = f"WEBPAGE : Propuesta de colaboración de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nidea : \n{idea}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] print(f'colab subject : {subject}\n{from_email}\ncorreo : \n{message}') send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer)
43.020833
87
0.62954
from django.core.mail import send_mail from django.conf import settings from django.shortcuts import render from django.http import Http404 from django.http import HttpResponseRedirect def main( request): return( render( request, 'contacto/main.html', {'Titulo' : 'Contacto'})) def get_duda(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') duda = request.GET.get('duda') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and duda != None and prev_url != None): subject = f"WEBPAGE : Duda de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nDuda : \n{duda}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer) def get_colab(request): referer = request.META.get('HTTP_REFERER') if request.method == 'GET': nombre = request.GET.get('nombre') correo = request.GET.get('correo') ambito = request.GET.get('ambito') idea = request.GET.get('idea') extra = request.GET.get('extra') prev_url = request.GET.get('prev_url') if(nombre != None and idea != None and prev_url != None): subject = f"WEBPAGE : Propuesta de colaboración de {nombre} sobre {ambito}" message = f"{nombre} ( {correo} ):\n" message = message + f"Ambito : {ambito}\nidea : \n{idea}\n\n{extra}" from_email = settings.EMAIL_HOST_USER to_list = [settings.EMAIL_HOST_USER,] print(f'colab subject : {subject}\n{from_email}\ncorreo : \n{message}') send_mail(subject, message, from_email, to_list) return HttpResponseRedirect(referer)
true
true
f72785f26964192007bad38595a7da8e4e0b7024
629
py
Python
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
1
2020-11-16T11:54:29.000Z
2020-11-16T11:54:29.000Z
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
11
2020-05-17T18:39:21.000Z
2021-09-22T19:14:28.000Z
manage.py
BuildForSDG/frontend90
35b7297341f048b08a5ff02c7a96dad968004010
[ "MIT" ]
5
2020-05-18T11:19:44.000Z
2020-11-12T14:46:31.000Z
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcity.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()
28.590909
73
0.683625
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcity.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()
true
true
f72786710d226ad55e4560292df4916f0c08622e
21,421
py
Python
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
gupb/controller/tup_tup.py
syforcee/GUPB
f916acf94efe61c54fa7b4cc33d3f94821fdb3d7
[ "MIT" ]
null
null
null
import random from itertools import product from queue import SimpleQueue from typing import Dict, Type, Optional, Tuple, List, Set from gupb.controller.tup_tup_resources.trained_model import QuartersRelation, MenhirToCentreDistance, Actions, MODEL from gupb.model import arenas, coordinates, weapons, tiles, characters, games FACING_ORDER = [characters.Facing.LEFT, characters.Facing.UP, characters.Facing.RIGHT, characters.Facing.DOWN] ARENA_NAMES = ['archipelago', 'dungeon', 'fisher_island', 'wasteland', 'island', 'mini'] IS_LEARNING = False ALPHA = 0.2 EPSILON = 0.2 GAMMA = 0.99 DEFAULT_VAL = 0 MENHIR_NEIGHBOURHOOD_DISTANCE = 5 CLOSE_DISTANCE_THRESHOLD = 13 MODERATE_DISTANCE_THRESHOLD = 19 # noinspection PyUnusedLocal # noinspection PyMethodMayBeStatic class TupTupController: def __init__(self, name_suffix): self.identifier: str = "TupTup" + name_suffix self.menhir_pos: coordinates.Coords = None self.facing: Optional[characters.Facing] = None self.position: coordinates.Coords = None self.weapon: Type[weapons.Weapon] = weapons.Knife self.action_queue: SimpleQueue[characters.Action] = SimpleQueue() self.has_calculated_path: bool = False self.path: List = [] self.bfs_goal: coordinates.Coords = None self.bfs_potential_goals: Set[coordinates.Coords] = set() self.bfs_potential_goals_visited: Set[coordinates.Coords] = set() self.map: Optional[arenas.Terrain] = None self.map_size: Optional[Tuple[int, int]] = None self.hiding_spot: coordinates.Coords = None self.mist_radius: int = 0 self.episode: int = 0 self.max_num_of_episodes: int = 0 self.arena_name: Optional[str] = None self.arena_data: Optional[Dict] = None self.arenas_knowledge: Dict = self.__init_model() self.game_no: int = 0 self.action: Optional[Actions] = None self.state: Optional[QuartersRelation, MenhirToCentreDistance] = None self.initial_position: coordinates.Coords = None def __eq__(self, other: object) -> bool: if isinstance(other, TupTupController) and other.name == self.name: return True return False def __hash__(self) -> int: return hash(self.identifier) def reset(self, arena_description: arenas.ArenaDescription) -> None: if self.arena_data and self.arena_data['attempt_no'] >= 1: self.arena_data['action'] = self.action self.arena_data['state'] = self.state self.arena_data['reward'] = self.__get_reward() self.arena_data['reward_sum'] += self.arena_data['reward'] self.action_queue = SimpleQueue() self.path = [] self.bfs_potential_goals = set() self.bfs_potential_goals_visited = set() self.has_calculated_path = False self.hiding_spot = None self.episode = 0 self.game_no += 1 arena = arenas.Arena.load(arena_description.name) self.arena_name = arena.name self.arena_data = self.arenas_knowledge[self.arena_name] self.arena_data['attempt_no'] += 1 self.map = arena.terrain self.map_size = arena.size self.mist_radius = int(self.map_size[0] * 2 ** 0.5) + 1 self.max_num_of_episodes = (self.mist_radius - 1) * games.MIST_TTH self.menhir_pos = arena_description.menhir_position self.bfs_goal = self.menhir_pos self.bfs_potential_goals_visited.add(self.menhir_pos) self.arena_data['epsilon'] *= 0.99 self.arena_data['alpha'] *= 0.99 def decide(self, knowledge: characters.ChampionKnowledge) -> characters.Action: self.episode += 1 try: self.__update_char_info(knowledge) if self.episode == 1: self.initial_position = self.position if self.arena_data['attempt_no'] == 1 and self.episode == 1: # if it is the first game on this map first_action = random.choice(list(Actions)) self.action = first_action self.state = self.__discretize() elif self.arena_data['attempt_no'] > 1 and self.episode == 1: # learn when a new game begins but after the first game reward = self.arena_data['reward'] action = self.arena_data['action'] state = self.arena_data['state'] new_action = self.__pick_action(state) new_state = self.__discretize() if IS_LEARNING: self.__learn(action, state, reward, new_action, new_state) self.action = new_action self.state = new_state if self.episode == 1 and self.__needs_to_hide(): self.__go_to_hiding_spot() if self.__is_enemy_in_range(knowledge.position, knowledge.visible_tiles): return characters.Action.ATTACK if not self.action_queue.empty(): return self.action_queue.get() if not self.has_calculated_path: start, end = self.position, self.bfs_goal self.__calculate_optimal_path(start, end) if len(self.path) > 0: # the path was found self.has_calculated_path = True else: neighbors = self.__get_neighbors(self.bfs_goal) for neighbor in neighbors: if neighbor not in self.bfs_potential_goals_visited: self.bfs_potential_goals.add(neighbor) if self.bfs_potential_goals: self.bfs_goal = self.bfs_potential_goals.pop() self.bfs_potential_goals_visited.add(self.bfs_goal) if not self.action_queue.empty(): return self.action_queue.get() if len(self.path) > 1 and self.__has_to_move(): self.__add_moves(2) else: # the destination is reached self.__guard_area() if not self.action_queue.empty(): return self.action_queue.get() return characters.Action.DO_NOTHING except Exception: return characters.Action.DO_NOTHING def __update_char_info(self, knowledge: characters.ChampionKnowledge) -> None: self.position = knowledge.position char_description = knowledge.visible_tiles[knowledge.position].character weapons_map = {w.__name__.lower(): w for w in [weapons.Knife, weapons.Sword, weapons.Bow, weapons.Amulet, weapons.Axe]} self.weapon = weapons_map.get(char_description.weapon.name, weapons.Knife) self.facing = char_description.facing def __needs_to_hide(self) -> bool: quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) start_x, start_y = 0, 0 if self.action == Actions.HIDE_IN_THE_STARTING_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 elif self.action == Actions.HIDE_IN_THE_OPPOSITE_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 corner = {(start_x, start_y)} directions = [(1 if start_x == 0 else -1, 0), (0, 1 if start_y == 0 else -1)] hiding_spots = set() while not hiding_spots: for t in corner: if t in self.map and self.map[t].terrain_passable(): self.hiding_spot = coordinates.Coords(t[0], t[1]) hiding_spots.add(coordinates.Coords(t[0], t[1])) corner = {(t[0] + d[0], t[1] + d[1]) for t in corner for d in directions} for coords in hiding_spots: if self.map[coords].loot: self.hiding_spot = coords return True def __go_to_hiding_spot(self) -> None: start, end = self.position, self.hiding_spot self.__calculate_optimal_path(start, end) self.path.append(end) self.__add_moves(200) def __rotate(self, expected_facing: characters.Facing, starting_facing: characters.Facing = None) -> None: curr_facing_index = FACING_ORDER.index(self.facing if not starting_facing else starting_facing) expected_facing_index = FACING_ORDER.index(expected_facing) diff_expected_curr = expected_facing_index - curr_facing_index if diff_expected_curr < 0: diff_expected_curr += len(FACING_ORDER) if diff_expected_curr == 1: self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 2: self.action_queue.put(characters.Action.TURN_RIGHT) self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 3: self.action_queue.put(characters.Action.TURN_LEFT) def __has_to_move(self) -> bool: return self.episode >= self.max_num_of_episodes - len(self.path) * 5 def __guard_area(self) -> None: self.action_queue.put(characters.Action.TURN_RIGHT) def __is_enemy_in_range(self, position: coordinates.Coords, visible_tiles: Dict[coordinates.Coords, tiles.TileDescription]) -> bool: try: if issubclass(self.weapon, weapons.LineWeapon): weapon_reach = self.weapon.reach() tile_to_check = position for _ in range(1, self.weapon.reach() + 1): tile_to_check = tile_to_check + self.facing.value if visible_tiles[tile_to_check].character: return True elif isinstance(self.weapon, weapons.Amulet): for tile in [position + (1, 1), position + (-1, 1), position + (1, -1), position + (-1, -1)]: if tile in visible_tiles and visible_tiles[tile].character: return True elif isinstance(self.weapon, weapons.Axe): tiles_to_check = [coordinates.Coords(self.facing.value.x, i) for i in [-1, 0, 1]] \ if self.facing.value.x != 0 else [coordinates.Coords(i, self.facing.value.y) for i in [-1, 0, 1]] for tile in tiles_to_check: if tile in visible_tiles and visible_tiles[position + self.facing.value].character: return True else: return False except KeyError: # tile was not visible return False def __get_neighbors(self, coords): available_cells = [] for facing in characters.Facing: next_coords = coords + facing.value if next_coords in self.map and self.map[coords].terrain_passable(): available_cells.append(next_coords) return available_cells def __breadth_first_search(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords) -> \ Dict[coordinates.Coords, Tuple[int, coordinates.Coords]]: queue = SimpleQueue() if self.map[start_coords].terrain_passable(): queue.put(start_coords) visited = set() path = {start_coords: start_coords} while not queue.empty(): cell = queue.get() if cell in visited: continue if cell == end_coords: return path visited.add(cell) for neighbour in self.__get_neighbors(cell): if neighbour not in path: path[neighbour] = cell queue.put(neighbour) raise BFSException("The shortest path wasn't found!") def __backtrack_path(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords, path: Dict, final_path: List): if end_coords == start_coords: return self.facing, end_coords elif end_coords not in path.keys(): raise PathFindingException else: next_coord = path[end_coords] prev_facing, prev_coords = self.__backtrack_path(next_coord, start_coords, path, final_path) next_facing = characters.Facing(end_coords - next_coord) final_path.append(next_coord) return next_facing, next_coord def __get_rotations_number(self, current_facing: characters.Facing, next_facing: characters.Facing) -> int: curr_facing_index = FACING_ORDER.index(current_facing) next_facing_index = FACING_ORDER.index(next_facing) diff = next_facing_index - curr_facing_index if diff < 0: diff += len(FACING_ORDER) if diff % 2 != 0: return 1 elif diff == 2: return 2 return 0 def __calculate_optimal_path(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords): try: bfs_res = self.__breadth_first_search(start_coords, end_coords) final_path = [] self.__backtrack_path(end_coords, start_coords, bfs_res, final_path) self.path = final_path except (BFSException, PathFindingException) as e: pass def __add_moves(self, number_of_moves=1) -> None: starting_facing = None for _ in range(number_of_moves): if len(self.path) < 2: break start_coords = self.path.pop(0) end_coords = self.path[0] starting_facing = self.__move(start_coords, end_coords, starting_facing) def __move(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords, starting_facing: characters.Facing = None) -> characters.Facing: try: destination_facing = self.__get_destination_facing(end_coords, start_coords) self.__rotate(destination_facing, starting_facing) self.action_queue.put(characters.Action.STEP_FORWARD) return destination_facing except Exception: pass def __get_destination_facing(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords) -> characters.Facing: coords_diff = end_coords - start_coords if coords_diff.y == 0: if coords_diff.x < 0: return characters.Facing.LEFT if coords_diff.x > 0: return characters.Facing.RIGHT elif coords_diff.x == 0: if coords_diff.y < 0: return characters.Facing.UP if coords_diff.y > 0: return characters.Facing.DOWN else: # one of the numbers SHOULD be 0, otherwise sth is wrong with the BFS result raise (Exception("The coordinates are not one step away from each other")) @property def name(self) -> str: return self.identifier @property def preferred_tabard(self) -> characters.Tabard: return characters.Tabard.YELLOW def __discretize(self) -> Tuple[QuartersRelation, MenhirToCentreDistance]: start_quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) menhir_quarter = (self.menhir_pos[0] // (self.map_size[0] / 2), self.menhir_pos[1] // (self.map_size[1] / 2)) menhir_to_centre_distance = int(((self.map_size[0] // 2 - self.menhir_pos[0]) ** 2 + (self.map_size[1] // 2 - self.menhir_pos[1]) ** 2) ** 0.5) if start_quarter == menhir_quarter: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.MODERATE else: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.FAR elif (start_quarter[0] + menhir_quarter[0], start_quarter[1] + menhir_quarter[1]) == (1.0, 1.0): if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.FAR else: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.FAR def was_killed_by_mist(self) -> bool: mist_free_radius_when_died = self.mist_radius - self.episode // games.MIST_TTH radius_distance_to_menhir = int(((self.position[0] - self.menhir_pos[0]) ** 2 + (self.position[1] - self.menhir_pos[1]) ** 2) ** 0.5) return mist_free_radius_when_died <= radius_distance_to_menhir def __get_reward(self) -> int: killed_by_mist = self.was_killed_by_mist() if killed_by_mist: if not self.hiding_spot and self.initial_position == self.position: # camping in the initial position return 0 elif not self.has_calculated_path: # going to the hiding place return -3 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: # camping in the hiding place return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[ 0] != self.hiding_spot: # going to the menhir position return -3 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 3 else: if not self.hiding_spot and self.initial_position == self.position: return -2 elif not self.has_calculated_path: return -2 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[0] != self.hiding_spot: return -1 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 2 return 0 def __pick_action(self, state: Tuple[QuartersRelation, MenhirToCentreDistance]) -> Actions: if random.uniform(0, 1) < self.arena_data['epsilon']: return random.choice(list(Actions)) else: knowledge = [self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_STARTING_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_OPPOSITE_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL), DEFAULT_VAL)] max_value = max(knowledge) max_value_index = knowledge.index(max_value) return Actions(max_value_index) def __learn(self, action: Actions, state: Tuple[QuartersRelation, MenhirToCentreDistance], reward: int, new_action: Actions, new_state: Tuple[QuartersRelation, MenhirToCentreDistance]): old_value = self.arena_data['Q'].get((state, action), DEFAULT_VAL) future_value = self.arena_data['Q'].get((new_state, new_action), DEFAULT_VAL) if (state, action) not in self.arena_data['Q'].keys(): self.arena_data['Q'][(state, action)] = 0.0 self.arena_data['Q'][(state, action)] += self.arena_data['alpha'] * ( reward + self.arena_data['discount_factor'] * future_value - old_value) # if self.game_no % 50 == 0: # to show learning progress # print(self.arenas_knowledge) def __init_model(self) -> Dict: if IS_LEARNING: return {arena: { 'Q': {perm: 0.0 for perm in product(product(QuartersRelation, MenhirToCentreDistance), Actions)}, 'state': None, 'action': None, 'reward': None, 'reward_sum': 0, 'attempt_no': 0, 'alpha': ALPHA, 'epsilon': EPSILON, 'discount_factor': GAMMA} for arena in ARENA_NAMES} return MODEL class BFSException(Exception): pass class PathFindingException(Exception): pass POTENTIAL_CONTROLLERS = [ TupTupController('Bot'), ]
46.770742
130
0.6221
import random from itertools import product from queue import SimpleQueue from typing import Dict, Type, Optional, Tuple, List, Set from gupb.controller.tup_tup_resources.trained_model import QuartersRelation, MenhirToCentreDistance, Actions, MODEL from gupb.model import arenas, coordinates, weapons, tiles, characters, games FACING_ORDER = [characters.Facing.LEFT, characters.Facing.UP, characters.Facing.RIGHT, characters.Facing.DOWN] ARENA_NAMES = ['archipelago', 'dungeon', 'fisher_island', 'wasteland', 'island', 'mini'] IS_LEARNING = False ALPHA = 0.2 EPSILON = 0.2 GAMMA = 0.99 DEFAULT_VAL = 0 MENHIR_NEIGHBOURHOOD_DISTANCE = 5 CLOSE_DISTANCE_THRESHOLD = 13 MODERATE_DISTANCE_THRESHOLD = 19 class TupTupController: def __init__(self, name_suffix): self.identifier: str = "TupTup" + name_suffix self.menhir_pos: coordinates.Coords = None self.facing: Optional[characters.Facing] = None self.position: coordinates.Coords = None self.weapon: Type[weapons.Weapon] = weapons.Knife self.action_queue: SimpleQueue[characters.Action] = SimpleQueue() self.has_calculated_path: bool = False self.path: List = [] self.bfs_goal: coordinates.Coords = None self.bfs_potential_goals: Set[coordinates.Coords] = set() self.bfs_potential_goals_visited: Set[coordinates.Coords] = set() self.map: Optional[arenas.Terrain] = None self.map_size: Optional[Tuple[int, int]] = None self.hiding_spot: coordinates.Coords = None self.mist_radius: int = 0 self.episode: int = 0 self.max_num_of_episodes: int = 0 self.arena_name: Optional[str] = None self.arena_data: Optional[Dict] = None self.arenas_knowledge: Dict = self.__init_model() self.game_no: int = 0 self.action: Optional[Actions] = None self.state: Optional[QuartersRelation, MenhirToCentreDistance] = None self.initial_position: coordinates.Coords = None def __eq__(self, other: object) -> bool: if isinstance(other, TupTupController) and other.name == self.name: return True return False def __hash__(self) -> int: return hash(self.identifier) def reset(self, arena_description: arenas.ArenaDescription) -> None: if self.arena_data and self.arena_data['attempt_no'] >= 1: self.arena_data['action'] = self.action self.arena_data['state'] = self.state self.arena_data['reward'] = self.__get_reward() self.arena_data['reward_sum'] += self.arena_data['reward'] self.action_queue = SimpleQueue() self.path = [] self.bfs_potential_goals = set() self.bfs_potential_goals_visited = set() self.has_calculated_path = False self.hiding_spot = None self.episode = 0 self.game_no += 1 arena = arenas.Arena.load(arena_description.name) self.arena_name = arena.name self.arena_data = self.arenas_knowledge[self.arena_name] self.arena_data['attempt_no'] += 1 self.map = arena.terrain self.map_size = arena.size self.mist_radius = int(self.map_size[0] * 2 ** 0.5) + 1 self.max_num_of_episodes = (self.mist_radius - 1) * games.MIST_TTH self.menhir_pos = arena_description.menhir_position self.bfs_goal = self.menhir_pos self.bfs_potential_goals_visited.add(self.menhir_pos) self.arena_data['epsilon'] *= 0.99 self.arena_data['alpha'] *= 0.99 def decide(self, knowledge: characters.ChampionKnowledge) -> characters.Action: self.episode += 1 try: self.__update_char_info(knowledge) if self.episode == 1: self.initial_position = self.position if self.arena_data['attempt_no'] == 1 and self.episode == 1: first_action = random.choice(list(Actions)) self.action = first_action self.state = self.__discretize() elif self.arena_data['attempt_no'] > 1 and self.episode == 1: reward = self.arena_data['reward'] action = self.arena_data['action'] state = self.arena_data['state'] new_action = self.__pick_action(state) new_state = self.__discretize() if IS_LEARNING: self.__learn(action, state, reward, new_action, new_state) self.action = new_action self.state = new_state if self.episode == 1 and self.__needs_to_hide(): self.__go_to_hiding_spot() if self.__is_enemy_in_range(knowledge.position, knowledge.visible_tiles): return characters.Action.ATTACK if not self.action_queue.empty(): return self.action_queue.get() if not self.has_calculated_path: start, end = self.position, self.bfs_goal self.__calculate_optimal_path(start, end) if len(self.path) > 0: self.has_calculated_path = True else: neighbors = self.__get_neighbors(self.bfs_goal) for neighbor in neighbors: if neighbor not in self.bfs_potential_goals_visited: self.bfs_potential_goals.add(neighbor) if self.bfs_potential_goals: self.bfs_goal = self.bfs_potential_goals.pop() self.bfs_potential_goals_visited.add(self.bfs_goal) if not self.action_queue.empty(): return self.action_queue.get() if len(self.path) > 1 and self.__has_to_move(): self.__add_moves(2) else: self.__guard_area() if not self.action_queue.empty(): return self.action_queue.get() return characters.Action.DO_NOTHING except Exception: return characters.Action.DO_NOTHING def __update_char_info(self, knowledge: characters.ChampionKnowledge) -> None: self.position = knowledge.position char_description = knowledge.visible_tiles[knowledge.position].character weapons_map = {w.__name__.lower(): w for w in [weapons.Knife, weapons.Sword, weapons.Bow, weapons.Amulet, weapons.Axe]} self.weapon = weapons_map.get(char_description.weapon.name, weapons.Knife) self.facing = char_description.facing def __needs_to_hide(self) -> bool: quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) start_x, start_y = 0, 0 if self.action == Actions.HIDE_IN_THE_STARTING_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 elif self.action == Actions.HIDE_IN_THE_OPPOSITE_QUARTER: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL: start_x = self.map_size[0] - 1 if quarter[0] == 1.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 0.0 else 0 elif self.action == Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL: start_x = self.map_size[0] - 1 if quarter[0] == 0.0 else 0 start_y = self.map_size[1] - 1 if quarter[1] == 1.0 else 0 corner = {(start_x, start_y)} directions = [(1 if start_x == 0 else -1, 0), (0, 1 if start_y == 0 else -1)] hiding_spots = set() while not hiding_spots: for t in corner: if t in self.map and self.map[t].terrain_passable(): self.hiding_spot = coordinates.Coords(t[0], t[1]) hiding_spots.add(coordinates.Coords(t[0], t[1])) corner = {(t[0] + d[0], t[1] + d[1]) for t in corner for d in directions} for coords in hiding_spots: if self.map[coords].loot: self.hiding_spot = coords return True def __go_to_hiding_spot(self) -> None: start, end = self.position, self.hiding_spot self.__calculate_optimal_path(start, end) self.path.append(end) self.__add_moves(200) def __rotate(self, expected_facing: characters.Facing, starting_facing: characters.Facing = None) -> None: curr_facing_index = FACING_ORDER.index(self.facing if not starting_facing else starting_facing) expected_facing_index = FACING_ORDER.index(expected_facing) diff_expected_curr = expected_facing_index - curr_facing_index if diff_expected_curr < 0: diff_expected_curr += len(FACING_ORDER) if diff_expected_curr == 1: self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 2: self.action_queue.put(characters.Action.TURN_RIGHT) self.action_queue.put(characters.Action.TURN_RIGHT) elif diff_expected_curr == 3: self.action_queue.put(characters.Action.TURN_LEFT) def __has_to_move(self) -> bool: return self.episode >= self.max_num_of_episodes - len(self.path) * 5 def __guard_area(self) -> None: self.action_queue.put(characters.Action.TURN_RIGHT) def __is_enemy_in_range(self, position: coordinates.Coords, visible_tiles: Dict[coordinates.Coords, tiles.TileDescription]) -> bool: try: if issubclass(self.weapon, weapons.LineWeapon): weapon_reach = self.weapon.reach() tile_to_check = position for _ in range(1, self.weapon.reach() + 1): tile_to_check = tile_to_check + self.facing.value if visible_tiles[tile_to_check].character: return True elif isinstance(self.weapon, weapons.Amulet): for tile in [position + (1, 1), position + (-1, 1), position + (1, -1), position + (-1, -1)]: if tile in visible_tiles and visible_tiles[tile].character: return True elif isinstance(self.weapon, weapons.Axe): tiles_to_check = [coordinates.Coords(self.facing.value.x, i) for i in [-1, 0, 1]] \ if self.facing.value.x != 0 else [coordinates.Coords(i, self.facing.value.y) for i in [-1, 0, 1]] for tile in tiles_to_check: if tile in visible_tiles and visible_tiles[position + self.facing.value].character: return True else: return False except KeyError: return False def __get_neighbors(self, coords): available_cells = [] for facing in characters.Facing: next_coords = coords + facing.value if next_coords in self.map and self.map[coords].terrain_passable(): available_cells.append(next_coords) return available_cells def __breadth_first_search(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords) -> \ Dict[coordinates.Coords, Tuple[int, coordinates.Coords]]: queue = SimpleQueue() if self.map[start_coords].terrain_passable(): queue.put(start_coords) visited = set() path = {start_coords: start_coords} while not queue.empty(): cell = queue.get() if cell in visited: continue if cell == end_coords: return path visited.add(cell) for neighbour in self.__get_neighbors(cell): if neighbour not in path: path[neighbour] = cell queue.put(neighbour) raise BFSException("The shortest path wasn't found!") def __backtrack_path(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords, path: Dict, final_path: List): if end_coords == start_coords: return self.facing, end_coords elif end_coords not in path.keys(): raise PathFindingException else: next_coord = path[end_coords] prev_facing, prev_coords = self.__backtrack_path(next_coord, start_coords, path, final_path) next_facing = characters.Facing(end_coords - next_coord) final_path.append(next_coord) return next_facing, next_coord def __get_rotations_number(self, current_facing: characters.Facing, next_facing: characters.Facing) -> int: curr_facing_index = FACING_ORDER.index(current_facing) next_facing_index = FACING_ORDER.index(next_facing) diff = next_facing_index - curr_facing_index if diff < 0: diff += len(FACING_ORDER) if diff % 2 != 0: return 1 elif diff == 2: return 2 return 0 def __calculate_optimal_path(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords): try: bfs_res = self.__breadth_first_search(start_coords, end_coords) final_path = [] self.__backtrack_path(end_coords, start_coords, bfs_res, final_path) self.path = final_path except (BFSException, PathFindingException) as e: pass def __add_moves(self, number_of_moves=1) -> None: starting_facing = None for _ in range(number_of_moves): if len(self.path) < 2: break start_coords = self.path.pop(0) end_coords = self.path[0] starting_facing = self.__move(start_coords, end_coords, starting_facing) def __move(self, start_coords: coordinates.Coords, end_coords: coordinates.Coords, starting_facing: characters.Facing = None) -> characters.Facing: try: destination_facing = self.__get_destination_facing(end_coords, start_coords) self.__rotate(destination_facing, starting_facing) self.action_queue.put(characters.Action.STEP_FORWARD) return destination_facing except Exception: pass def __get_destination_facing(self, end_coords: coordinates.Coords, start_coords: coordinates.Coords) -> characters.Facing: coords_diff = end_coords - start_coords if coords_diff.y == 0: if coords_diff.x < 0: return characters.Facing.LEFT if coords_diff.x > 0: return characters.Facing.RIGHT elif coords_diff.x == 0: if coords_diff.y < 0: return characters.Facing.UP if coords_diff.y > 0: return characters.Facing.DOWN else: # one of the numbers SHOULD be 0, otherwise sth is wrong with the BFS result raise (Exception("The coordinates are not one step away from each other")) @property def name(self) -> str: return self.identifier @property def preferred_tabard(self) -> characters.Tabard: return characters.Tabard.YELLOW def __discretize(self) -> Tuple[QuartersRelation, MenhirToCentreDistance]: start_quarter = (self.position[0] // (self.map_size[0] / 2), self.position[1] // (self.map_size[1] / 2)) menhir_quarter = (self.menhir_pos[0] // (self.map_size[0] / 2), self.menhir_pos[1] // (self.map_size[1] / 2)) menhir_to_centre_distance = int(((self.map_size[0] // 2 - self.menhir_pos[0]) ** 2 + (self.map_size[1] // 2 - self.menhir_pos[1]) ** 2) ** 0.5) if start_quarter == menhir_quarter: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.MODERATE else: return QuartersRelation.THE_SAME_QUARTER, MenhirToCentreDistance.FAR elif (start_quarter[0] + menhir_quarter[0], start_quarter[1] + menhir_quarter[1]) == (1.0, 1.0): if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.OPPOSITE_QUARTERS, MenhirToCentreDistance.FAR else: if menhir_to_centre_distance < CLOSE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.CLOSE elif menhir_to_centre_distance < MODERATE_DISTANCE_THRESHOLD: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.MODERATE else: return QuartersRelation.NEIGHBOR_QUARTERS, MenhirToCentreDistance.FAR def was_killed_by_mist(self) -> bool: mist_free_radius_when_died = self.mist_radius - self.episode // games.MIST_TTH radius_distance_to_menhir = int(((self.position[0] - self.menhir_pos[0]) ** 2 + (self.position[1] - self.menhir_pos[1]) ** 2) ** 0.5) return mist_free_radius_when_died <= radius_distance_to_menhir def __get_reward(self) -> int: killed_by_mist = self.was_killed_by_mist() if killed_by_mist: if not self.hiding_spot and self.initial_position == self.position: # camping in the initial position return 0 elif not self.has_calculated_path: # going to the hiding place return -3 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: # camping in the hiding place return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[ 0] != self.hiding_spot: # going to the menhir position return -3 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 3 else: if not self.hiding_spot and self.initial_position == self.position: return -2 elif not self.has_calculated_path: return -2 elif len(self.path) > 0 and self.path[0] == self.hiding_spot: return -2 elif len(self.path) > MENHIR_NEIGHBOURHOOD_DISTANCE and self.path[0] != self.hiding_spot: return -1 elif len(self.path) < MENHIR_NEIGHBOURHOOD_DISTANCE: return 2 return 0 def __pick_action(self, state: Tuple[QuartersRelation, MenhirToCentreDistance]) -> Actions: if random.uniform(0, 1) < self.arena_data['epsilon']: return random.choice(list(Actions)) else: knowledge = [self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_STARTING_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_OPPOSITE_QUARTER), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_HORIZONTAL), DEFAULT_VAL), self.arena_data['Q'].get((state, Actions.HIDE_IN_THE_NEIGHBOR_QUARTER_VERTICAL), DEFAULT_VAL)] max_value = max(knowledge) max_value_index = knowledge.index(max_value) return Actions(max_value_index) def __learn(self, action: Actions, state: Tuple[QuartersRelation, MenhirToCentreDistance], reward: int, new_action: Actions, new_state: Tuple[QuartersRelation, MenhirToCentreDistance]): old_value = self.arena_data['Q'].get((state, action), DEFAULT_VAL) future_value = self.arena_data['Q'].get((new_state, new_action), DEFAULT_VAL) if (state, action) not in self.arena_data['Q'].keys(): self.arena_data['Q'][(state, action)] = 0.0 self.arena_data['Q'][(state, action)] += self.arena_data['alpha'] * ( reward + self.arena_data['discount_factor'] * future_value - old_value) # if self.game_no % 50 == 0: # to show learning progress # print(self.arenas_knowledge) def __init_model(self) -> Dict: if IS_LEARNING: return {arena: { 'Q': {perm: 0.0 for perm in product(product(QuartersRelation, MenhirToCentreDistance), Actions)}, 'state': None, 'action': None, 'reward': None, 'reward_sum': 0, 'attempt_no': 0, 'alpha': ALPHA, 'epsilon': EPSILON, 'discount_factor': GAMMA} for arena in ARENA_NAMES} return MODEL class BFSException(Exception): pass class PathFindingException(Exception): pass POTENTIAL_CONTROLLERS = [ TupTupController('Bot'), ]
true
true
f72786a183d595e15dd09c998f2bd8b55855c064
314
py
Python
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
singletask_cli/context.py
lenaKuznetsova/singletask-cli
fb7910c090ddfc8ec9a721536808396abb20bfc3
[ "MIT" ]
null
null
null
from singletask_sql.settings import BASE_DIR, dotenv_values from singletask_sql.engine import create_engine # todo - config after auth env_path = [ f'{BASE_DIR}/../.env', f'{BASE_DIR}/../.env.local' ] conf = {} for path in env_path: conf.update(dotenv_values(path)) sql_engine = create_engine(conf)
20.933333
59
0.72293
from singletask_sql.settings import BASE_DIR, dotenv_values from singletask_sql.engine import create_engine env_path = [ f'{BASE_DIR}/../.env', f'{BASE_DIR}/../.env.local' ] conf = {} for path in env_path: conf.update(dotenv_values(path)) sql_engine = create_engine(conf)
true
true
f7278700e1134610692fcc8ae7f5634a20a9f268
560
py
Python
tasks/migrations/0009_alter_task_org.py
jordanm88/Django-CRM
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
1,334
2017-06-04T07:47:14.000Z
2022-03-30T17:12:37.000Z
tasks/migrations/0009_alter_task_org.py
AhmedDoudou/Django-CRM-1
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
317
2017-06-04T07:48:13.000Z
2022-03-29T19:24:26.000Z
tasks/migrations/0009_alter_task_org.py
AhmedDoudou/Django-CRM-1
5faf22acb30aeb32f5830898fd5d8ecd1ac0bbd8
[ "MIT" ]
786
2017-06-06T09:18:48.000Z
2022-03-29T01:29:29.000Z
# Generated by Django 3.2.7 on 2021-10-06 07:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0037_alter_profile_org'), ('tasks', '0008_rename_company_task_org'), ] operations = [ migrations.AlterField( model_name='task', name='org', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_org', to='common.org'), ), ]
26.666667
147
0.644643
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0037_alter_profile_org'), ('tasks', '0008_rename_company_task_org'), ] operations = [ migrations.AlterField( model_name='task', name='org', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='task_org', to='common.org'), ), ]
true
true
f72788069b5b787b60c74366778c57c504270b5a
14,226
py
Python
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/cablam/cablam_res.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
from __future__ import division # (jEdit options) :folding=explicit:collapseFolds=1: #This module contains the linked_residue class and the functions needed to build # and access instances of it. #2012-09-05: # prunerestype() moved to this module from cablam_training # linked_residue.id_with_resname() changed to return pdb-column-formatted ids #2012-10-09: # self.resid is now stored in each linked_residue object #2013_02_01: Added a step in linked_residue.__init__() that flags HETATOMs and a # step in construct_linked_residues() that skips adding them to the # resdata/protein object. Will this be a problem for synthetic or other # non-standard residues? #2013-09-17: changed formatting for id_with_resname to rg.atom.pdb_label_columns # Tried to add handling for HETATOMS in __init__. May or may not fully work. #Next: added mp_id() to produce MolPribity-friendly resids import sys from mmtbx.cablam.cablam_math import veclen, vectorize #{{{ linked_residue class #This class holds information on protein residues (as defined by residue_group # in pdb.hierarchy). See the __init__ for details. It also maintains sequence # relationships through a connectivity check and references "prevres" and # "nextres" to the class instances of sequence-adjacent residues. The intent is # to allow easy stepping forward and backward through the residue sequence. #For example: self.resnum returns the current residue number, # self.nextres.resnum returns the residue number of the next residue in # sequence, if such a residue exists. This is not protected by a .get or # anything, so you have to do your own error catching, usually of the form: # if self.nextres: return self.nextres.resnum #The class was designed for use with cablam, which requires forward and backward # sequence awareness, but it could be used elsewhere. It contains a generic # results={} dictionary usable by anyone willing to make unique keys for their # data. #It is recommended that all instances of this class for a protein be members of # some iterable (I use a dictionary keyed with the cablam_key() function in # this module). Do not rely on sequence connectivity alone (which breaks due to # multiple chains or missing atoms) to let you find all residues. #The class should deal with insertion codes well, since different icodes seem to # be in different rg's in the hierarchy. #The class does not deal with alts well, however, as an rg may contain several # ag's. The firstalt() function provides some relief, but is really a dodge # rather than a fix. I do not expect this to be a problem at low resolution # (where alts are rare), but it does present a problem for high-res training. #------------------------------------------------------------------------------- class linked_residue(object): #Prints kinemage point-style output for a list of measures given in kinorder def printtokin(self, kinorder, writeto=sys.stdout): outline = ['{'+self.pdbid+' '+self.id_with_resname()+'}'] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: return writeto.write(' '.join(outline)+'\n') #Prints comma-separated output for a list of measures given in kinorder def printtocsv(self, kinorder, doconnections=False, writeto=sys.stdout): outline = [self.id_with_resname()] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: outline.append('NULL') if doconnections: if self.prevres: outline.append(self.prevres.id_with_resname()) else: outline.append('NULL') if self.nextres: outline.append(self.nextres.id_with_resname()) else: outline.append('NULL') writeto.write(','.join(outline)+'\n') #note the ',' in the join here #id_to_string and id_with_resname return string concatenations of residue # identifiers. The identifier order should be standard with other RLab def id_to_str(self, sep=' '): resid_string = sep.join( [self.pdbid, self.model, self.chain, str(self.resnum), self.icode]) return resid_string def id_with_resname(self): # Formatted as: 'ALA A####I' resid_string = self.rg.atoms()[0].pdb_label_columns()[5:] return resid_string def mp_id(self): #An id consistent with MolProbity 'cnit' ids #Formatted as: ccnnnnilttt # c: 2-char Chain ID, space for none # n: sequence number, right justified, space padded # i: insertion code, space for none # l: alternate ID, space for none # t: residue type (ALA, LYS, etc.), all caps left justified, space padded #(Not sure about the 2-char Chain IDs just yet) #(alternates are not going to be handled properly yet) resid_string = self.id_with_resname() resname = resid_string[0:3] chain = resid_string[3:5] resnum = resid_string[5:9] ins = resid_string[9:10] alt = self.firstalt("CA") if alt is None or alt == '': alt = " " mpid_string = chain + resnum + ins + alt + resname return mpid_string #Removes the references that sequence-adjacent linked_residue class instances # have to this instance. Helps maintain correct sequence connectivity and may # allow this instance to be removed from memory. #Used in cablam_training.stripB() and cablam_training.prunerestype() def removelinks(self): if self.prevres: self.prevres.nextres = None if self.nextres: self.nextres.prevres = None #Returns the first alt index in alts that has an atom of the requested name # Removes some guesswork from atom lookup, but really just acrobatics around # the problem of how to store and access alts usefully def firstalt(self, atomname): for alt in self.alts: try: if self.atomxyz[alt][atomname]: return alt else: continue except KeyError: continue else: return None #simplified retrieval around firstalt for the common case of atom coords def getatomxyz(self, atomname): firstalt = self.firstalt(atomname) try: return self.atomxyz[firstalt][atomname] except KeyError: return None #There needs to be a CA-only consecutive check. Adding one is a high priority. def consecutive(self, res1, res2): if res1 and res2: #check against empties try: C = res1.atomxyz[res1.firstalt('C')]['C'] N = res2.atomxyz[res2.firstalt('N')]['N'] #firstalt returns None if it can't find an atom, # and a key of None gives a KeyError here except KeyError: #if there aren't a C and an N, assume the two are not properly bonded return False bondlen = veclen(vectorize(C,N)) if bondlen <= 2.0: #2.0A is the peptide bond cutoff used by O for model building and # potentially-fragmented chains. O's generous cutoff seemed appropriate # since I expect to process in-progress models with this program #RLab (probably) uses 1.4 +- 0.3, official textbook is about 1.33 #O's Ca-Ca distance is 4.5A return True else: return False else: return False def seq_dist(self, otherres): ############################################ # Returns distance in sequence with insertion codes accounted for. # The return value is negative if res is N-terminal to this. # The return value is positive if res is C-terminal to this. # The return value is None if res couldn't be found due to chain break etc. ############################################ if self is otherres: return 0 if self.chain != otherres.chain:# or self.model != otherres.model: return None #guess which direction to look # the "<=" and ">=" should let this look back or forward from within an # insertion if self.resnum <= otherres.resnum: delta = 0 cur = self while cur != None: delta += 1 if cur.nextres is otherres: return delta cur = cur.nextres if self.resnum >= otherres.resnum: delta = 0 cur = self while cur != None: delta -= 1 if cur.prevres is otherres: return delta cur = cur.prevres return None def __init__(self, rg, prevres=None, pdbid='pdbid', modelid='', chainid='', targetatoms=["CA","O","C","N"] ): self.rg = rg #the source residue group is preserved for additional data and #ease in transfering back to hierarchy mode self.pdbid = pdbid self.model = modelid self.chain = chainid self.resnum = int(rg.resseq.strip()) #self.resseq = rg.resid[:-1] self.icode = rg.icode self.resid = cablam_key(self.model, self.chain, self.resnum, self.icode) self.hetero = False #marks whether this is a HETATOM #alts: 'alt' and 'resname' keyed by ag.altloc in the form of '','A','B' etc. #atomxyz: xyz coords, indexed by ag.altloc, and atom.name within each alt # e.g. atomxyz['']['CA'] returns the coordinates of a non-alt Calpha #atomb: atomic b, indexed by ag.altloc, and atom.name within each alt self.alts = {} self.atomxyz = {} self.atomb = {} ### What about anisou? Not handled yet. #hierachy looping and data extraction for ag in rg.atom_groups(): #if not ag.is_protein(): Need sopmething like this that works # self.is_protein=True self.alts[ag.altloc] = {'alt':ag.altloc, 'resname':ag.resname} self.atomxyz[ag.altloc] = {} self.atomb[ag.altloc] = {} for atom in ag.atoms(): if atom.hetero and ag.resname.upper() != 'MSE': self.hetero=True for targetatom in targetatoms: if atom.name.strip() == targetatom: self.atomxyz[ag.altloc][targetatom] = atom.xyz self.atomb[ag.altloc][targetatom] = atom.b #Note that a reference to the related residue is stored, not a dictionary # key for the wrapper dictionary #Someone clever may want to teach me how to use weakref() if the mutual # references that result from this cause memory problems if prevres and self.consecutive(prevres, self): self.prevres = prevres #Connect this residue to previous prevres.nextres = self #And the previous residue to this one else: self.prevres = None #Adjacency is handled in an outside function self.nextres = None self.probe = {'O':{},'H':{}} #holder for hydrogen bonding, indexed by 'target' residue+atom, see cablam_training.add_probe_data() self.probeH = [] self.probeO = [] self.measures = {} #Holder for cablam-space geometric measures self.motifs = {} #Holder for identified motifs from fingerprints/probetrain self.results = {} #Generic holder for calcuated values of interest #------------------------------------------------------------------------------- #}}} #{{{ prunerestype function #Deletes all members of a given residue type from a dictionary of residues #"Residue type" is determined from pdb.hierarchy's ag.resname, the upshot being # that non-residues like "HOH" waters and het groups can also be pruned to # improve performance if their three-letter codes are known. #------------------------------------------------------------------------------- def prunerestype(resdata, restype): reslist = resdata.keys() for residue in reslist: for alt in resdata[residue].alts: if resdata[residue].alts[alt]['resname'].strip() == restype: resdata[residue].removelinks() trash = resdata.pop(residue) break #------------------------------------------------------------------------------- #}}} #{{{ cablam_key function #The "protein" or "resdata" dictionary returned by construct_linked_residues() # below uses a particular key construction to access (and order) its contents #This function provides that construction so that residues in resdata may be # accessed from anywhere. The string returned is .sort()able #------------------------------------------------------------------------------- def cablam_key(modelid=None, chainid=None, resnum=None, icode=None): if None not in [modelid, chainid, resnum, icode]: resid_string = ' '.join([modelid, chainid, '%04i' % resnum, icode]) #The bit of string formatting here ('%04i' % resnum) helps .sort() later by # adding 0's to the left side of resnum until resnum is 4 characters long. # May or may not be compatible with Hybrid36 or other numbering schemes. return resid_string else: sys.stderr.write(""" Missing value for cablam_res.cablam_key(pdbid, modelid, chainid, resnum, icode) Please pass complete information """) sys.exit() #------------------------------------------------------------------------------- #}}} #{{{ construct_linked_residues function #------------------------------------------------------------------------------- #This function returns a dictionary of linked_residue objects with keys as # defined by cablam_key() above. It is responsible for iterating over part of # the hierarchy, but most of the work is done by the __init__() in the # linked_residue class. #targetatoms handling is likely to see some change as I add compatibility for # CA-only mainchain traces. Currently "C" and "N" are necessary for the # sequency adjacency check linked_residue.consecutive(), which checks for # appropriate peptide bond length #targetatoms is a list of strings that identify pdb atoms, e.g. "CA" or "CD1" def construct_linked_residues( hierarchy, targetatoms=["CA","O","C","N"], pdbid='pdbid' ): protein = {} for model in hierarchy.models(): for chain in model.chains(): prevres = None for rg in chain.residue_groups(): residue = linked_residue( rg, prevres=prevres, pdbid=pdbid, modelid=model.id, chainid=chain.id, targetatoms=targetatoms) resid_string = cablam_key(model.id, chain.id, residue.resnum, rg.icode) if not residue.hetero: #automatically skip het atoms protein[resid_string] = residue prevres = residue #important update for determining connectivity return protein #------------------------------------------------------------------------------- #}}}
43.638037
135
0.659145
from __future__ import division import sys from mmtbx.cablam.cablam_math import veclen, vectorize #The class does not deal with alts well, however, as an rg may contain several # ag's. The firstalt() function provides some relief, but is really a dodge class linked_residue(object): def printtokin(self, kinorder, writeto=sys.stdout): outline = ['{'+self.pdbid+' '+self.id_with_resname()+'}'] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: return writeto.write(' '.join(outline)+'\n') def printtocsv(self, kinorder, doconnections=False, writeto=sys.stdout): outline = [self.id_with_resname()] for order in kinorder: try: outline.append(str(self.measures[order])) except KeyError: outline.append('NULL') if doconnections: if self.prevres: outline.append(self.prevres.id_with_resname()) else: outline.append('NULL') if self.nextres: outline.append(self.nextres.id_with_resname()) else: outline.append('NULL') writeto.write(','.join(outline)+'\n') def id_to_str(self, sep=' '): resid_string = sep.join( [self.pdbid, self.model, self.chain, str(self.resnum), self.icode]) return resid_string def id_with_resname(self): resid_string = self.rg.atoms()[0].pdb_label_columns()[5:] return resid_string def mp_id(self): resid_string = self.id_with_resname() resname = resid_string[0:3] chain = resid_string[3:5] resnum = resid_string[5:9] ins = resid_string[9:10] alt = self.firstalt("CA") if alt is None or alt == '': alt = " " mpid_string = chain + resnum + ins + alt + resname return mpid_string def removelinks(self): if self.prevres: self.prevres.nextres = None if self.nextres: self.nextres.prevres = None def firstalt(self, atomname): for alt in self.alts: try: if self.atomxyz[alt][atomname]: return alt else: continue except KeyError: continue else: return None def getatomxyz(self, atomname): firstalt = self.firstalt(atomname) try: return self.atomxyz[firstalt][atomname] except KeyError: return None def consecutive(self, res1, res2): if res1 and res2: try: C = res1.atomxyz[res1.firstalt('C')]['C'] N = res2.atomxyz[res2.firstalt('N')]['N'] # and a key of None gives a KeyError here except KeyError: #if there aren't a C and an N, assume the two are not properly bonded return False bondlen = veclen(vectorize(C,N)) if bondlen <= 2.0: # since I expect to process in-progress models with this program #RLab (probably) uses 1.4 +- 0.3, official textbook is about 1.33 #O's Ca-Ca distance is 4.5A return True else: return False else: return False def seq_dist(self, otherres): ransfering back to hierarchy mode self.pdbid = pdbid self.model = modelid self.chain = chainid self.resnum = int(rg.resseq.strip()) #self.resseq = rg.resid[:-1] self.icode = rg.icode self.resid = cablam_key(self.model, self.chain, self.resnum, self.icode) self.hetero = False #marks whether this is a HETATOM #alts: 'alt' and 'resname' keyed by ag.altloc in the form of '','A','B' etc. #atomxyz: xyz coords, indexed by ag.altloc, and atom.name within each alt # e.g. atomxyz['']['CA'] returns the coordinates of a non-alt Calpha #atomb: atomic b, indexed by ag.altloc, and atom.name within each alt self.alts = {} self.atomxyz = {} self.atomb = {} ### What about anisou? Not handled yet. #hierachy looping and data extraction for ag in rg.atom_groups(): #if not ag.is_protein(): Need sopmething like this that works # self.is_protein=True self.alts[ag.altloc] = {'alt':ag.altloc, 'resname':ag.resname} self.atomxyz[ag.altloc] = {} self.atomb[ag.altloc] = {} for atom in ag.atoms(): if atom.hetero and ag.resname.upper() != 'MSE': self.hetero=True for targetatom in targetatoms: if atom.name.strip() == targetatom: self.atomxyz[ag.altloc][targetatom] = atom.xyz self.atomb[ag.altloc][targetatom] = atom.b #Note that a reference to the related residue is stored, not a dictionary # key for the wrapper dictionary #Someone clever may want to teach me how to use weakref() if the mutual # references that result from this cause memory problems if prevres and self.consecutive(prevres, self): self.prevres = prevres #Connect this residue to previous prevres.nextres = self #And the previous residue to this one else: self.prevres = None #Adjacency is handled in an outside function self.nextres = None self.probe = {'O':{},'H':{}} #holder for hydrogen bonding, indexed by 'target' residue+atom, see cablam_training.add_probe_data() self.probeH = [] self.probeO = [] self.measures = {} #Holder for cablam-space geometric measures self.motifs = {} #Holder for identified motifs from fingerprints/probetrain self.results = {} #Generic holder for calcuated values of interest #------------------------------------------------------------------------------- #}}} #{{{ prunerestype function #Deletes all members of a given residue type from a dictionary of residues #"Residue type" is determined from pdb.hierarchy's ag.resname, the upshot being def prunerestype(resdata, restype): reslist = resdata.keys() for residue in reslist: for alt in resdata[residue].alts: if resdata[residue].alts[alt]['resname'].strip() == restype: resdata[residue].removelinks() trash = resdata.pop(residue) break def cablam_key(modelid=None, chainid=None, resnum=None, icode=None): if None not in [modelid, chainid, resnum, icode]: resid_string = ' '.join([modelid, chainid, '%04i' % resnum, icode]) # May or may not be compatible with Hybrid36 or other numbering schemes. return resid_string else: sys.stderr.write(""" Missing value for cablam_res.cablam_key(pdbid, modelid, chainid, resnum, icode) Please pass complete information """) sys.exit() #------------------------------------------------------------------------------- #}}} #{{{ construct_linked_residues function #------------------------------------------------------------------------------- #This function returns a dictionary of linked_residue objects with keys as # defined by cablam_key() above. It is responsible for iterating over part of # the hierarchy, but most of the work is done by the __init__() in the # linked_residue class. #targetatoms handling is likely to see some change as I add compatibility for # CA-only mainchain traces. Currently "C" and "N" are necessary for the # sequency adjacency check linked_residue.consecutive(), which checks for # appropriate peptide bond length #targetatoms is a list of strings that identify pdb atoms, e.g. "CA" or "CD1" def construct_linked_residues( hierarchy, targetatoms=["CA","O","C","N"], pdbid='pdbid' ): protein = {} for model in hierarchy.models(): for chain in model.chains(): prevres = None for rg in chain.residue_groups(): residue = linked_residue( rg, prevres=prevres, pdbid=pdbid, modelid=model.id, chainid=chain.id, targetatoms=targetatoms) resid_string = cablam_key(model.id, chain.id, residue.resnum, rg.icode) if not residue.hetero: #automatically skip het atoms protein[resid_string] = residue prevres = residue #important update for determining connectivity return protein #------------------------------------------------------------------------------- #}}}
true
true
f7278954301c90c618734d8aadfe80011bdfffd8
1,640
py
Python
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
43
2017-12-04T17:38:24.000Z
2021-12-29T09:17:17.000Z
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
49
2017-12-07T21:02:29.000Z
2022-02-04T22:27:16.000Z
Community/ServiceNow CMDB/cmdb_switches/cmdb_switches_logic.py
spenney-bc/gateway-workflows
0311a9224b2d53c01689eb6a9a0a593177abed63
[ "Apache-2.0" ]
82
2017-12-04T17:56:00.000Z
2021-12-29T09:17:21.000Z
""" Component logic """ from bluecat.util import get_password_from_file from ..cmdb_configuration import cmdb_config import requests def raw_table_data(*args, **kwargs): # pylint: disable=redefined-outer-name data = {'columns': [{'title': 'Name'}, {'title': 'IP Address'}, {'title': 'Serial Number'}, {'title': 'Manufacturer'}, ], 'data': []} # HTTP request headers = {"Accept": "application/json"} cmdb_url = cmdb_config.servicenow_url + '/api/now/table/cmdb_ci_ip_switch' response = requests.get(cmdb_url, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) # Check for HTTP codes other than 200 if response.status_code == 200: switches = response.json() for switch in switches['result']: switch_name = switch['name'] switch_ip = switch['ip_address'] switch_serial = switch['serial_number'] if switch['manufacturer']: switch_manufacturer = get_switch_manufacturer(switch['manufacturer']['link']) data['data'].append([switch_name, switch_ip, switch_serial, switch_manufacturer]) return data def get_switch_manufacturer(link): headers = {"Accept": "application/json"} response = requests.get(link, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) manufacturer = response.json() return manufacturer['result']['name']
35.652174
168
0.64878
from bluecat.util import get_password_from_file from ..cmdb_configuration import cmdb_config import requests def raw_table_data(*args, **kwargs): data = {'columns': [{'title': 'Name'}, {'title': 'IP Address'}, {'title': 'Serial Number'}, {'title': 'Manufacturer'}, ], 'data': []} headers = {"Accept": "application/json"} cmdb_url = cmdb_config.servicenow_url + '/api/now/table/cmdb_ci_ip_switch' response = requests.get(cmdb_url, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) if response.status_code == 200: switches = response.json() for switch in switches['result']: switch_name = switch['name'] switch_ip = switch['ip_address'] switch_serial = switch['serial_number'] if switch['manufacturer']: switch_manufacturer = get_switch_manufacturer(switch['manufacturer']['link']) data['data'].append([switch_name, switch_ip, switch_serial, switch_manufacturer]) return data def get_switch_manufacturer(link): headers = {"Accept": "application/json"} response = requests.get(link, auth=(cmdb_config.servicenow_username, get_password_from_file(cmdb_config.servicenow_secret_file)), headers=headers, verify=False) manufacturer = response.json() return manufacturer['result']['name']
true
true
f727899ef981f97f2b9272fee3b9581691701dbe
7,848
py
Python
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
src/pymor/bindings/ngsolve.py
meretp/pymor
0965a5c3d0725466103efae5190493fceb2bf441
[ "Unlicense" ]
null
null
null
# This file is part of the pyMOR project (https://www.pymor.org). # Copyright 2013-2021 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause) from pathlib import Path from pymor.core.config import config from pymor.core.defaults import defaults from pymor.tools.io import change_to_directory if config.HAVE_NGSOLVE: import ngsolve as ngs import numpy as np from pymor.core.base import ImmutableObject from pymor.operators.list import LinearComplexifiedListVectorArrayOperatorBase from pymor.vectorarrays.interface import VectorArray from pymor.vectorarrays.numpy import NumpyVectorSpace from pymor.vectorarrays.list import CopyOnWriteVector, ComplexifiedVector, ComplexifiedListVectorSpace class NGSolveVectorCommon: def amax(self): A = np.abs(self.to_numpy()) max_ind = np.argmax(A) max_val = A[max_ind] return max_ind, max_val def dofs(self, dof_indices): return self.to_numpy()[dof_indices] class NGSolveVector(NGSolveVectorCommon, CopyOnWriteVector): """Wraps a NGSolve BaseVector to make it usable with ListVectorArray.""" def __init__(self, impl): self.impl = impl @classmethod def from_instance(cls, instance): return cls(instance.impl) def _copy_data(self): new_impl = ngs.GridFunction(self.impl.space) new_impl.vec.data = self.impl.vec self.impl = new_impl def to_numpy(self, ensure_copy=False): if ensure_copy: return self.impl.vec.FV().NumPy().copy() self._copy_data_if_needed() return self.impl.vec.FV().NumPy() def _scal(self, alpha): self.impl.vec.data = float(alpha) * self.impl.vec def _axpy(self, alpha, x): self.impl.vec.data = self.impl.vec + float(alpha) * x.impl.vec def inner(self, other): return self.impl.vec.InnerProduct(other.impl.vec) def norm(self): return self.impl.vec.Norm() def norm2(self): return self.impl.vec.Norm() ** 2 class ComplexifiedNGSolveVector(NGSolveVectorCommon, ComplexifiedVector): pass class NGSolveVectorSpace(ComplexifiedListVectorSpace): complexified_vector_type = ComplexifiedNGSolveVector def __init__(self, V, id='STATE'): self.__auto_init(locals()) def __eq__(self, other): return type(other) is NGSolveVectorSpace and self.V == other.V and self.id == other.id def __hash__(self): return hash(self.V) + hash(self.id) @property def value_dim(self): u = self.V.TrialFunction() if isinstance(u, list): return u[0].dim else: return u.dim @property def dim(self): return self.V.ndofglobal * self.value_dim @classmethod def space_from_vector_obj(cls, vec, id): return cls(vec.space, id) def real_zero_vector(self): impl = ngs.GridFunction(self.V) return NGSolveVector(impl) def real_make_vector(self, obj): return NGSolveVector(obj) def real_vector_from_numpy(self, data, ensure_copy=False): v = self.real_zero_vector() v.to_numpy()[:] = data return v class NGSolveMatrixOperator(LinearComplexifiedListVectorArrayOperatorBase): """Wraps a NGSolve matrix as an |Operator|.""" def __init__(self, matrix, range, source, solver_options=None, name=None): self.__auto_init(locals()) @defaults('default_solver') def _prepare_apply(self, U, mu, kind, least_squares=False, default_solver=''): if kind == 'apply_inverse': if least_squares: raise NotImplementedError solver = self.solver_options.get('inverse', default_solver) if self.solver_options else default_solver inv = self.matrix.Inverse(self.source.V.FreeDofs(), inverse=solver) return inv def _real_apply_one_vector(self, u, mu=None, prepare_data=None): r = self.range.real_zero_vector() self.matrix.Mult(u.impl.vec, r.impl.vec) return r def _real_apply_adjoint_one_vector(self, v, mu=None, prepare_data=None): u = self.source.real_zero_vector() try: mat = self.matrix.Transpose() except AttributeError: mat = self.matrix.T mat.Mult(v.impl.vec, u.impl.vec) return u def _real_apply_inverse_one_vector(self, v, mu=None, initial_guess=None, least_squares=False, prepare_data=None): inv = prepare_data r = self.source.real_zero_vector() r.impl.vec.data = inv * v.impl.vec return r def _assemble_lincomb(self, operators, coefficients, identity_shift=0., solver_options=None, name=None): if not all(isinstance(op, NGSolveMatrixOperator) for op in operators): return None if identity_shift != 0: return None matrix = operators[0].matrix.CreateMatrix() matrix.AsVector().data = float(coefficients[0]) * matrix.AsVector() for op, c in zip(operators[1:], coefficients[1:]): matrix.AsVector().data += float(c) * op.matrix.AsVector() return NGSolveMatrixOperator(matrix, self.range, self.source, solver_options=solver_options, name=name) def as_vector(self, copy=True): vec = self.matrix.AsVector().FV().NumPy() return NumpyVectorSpace.make_array(vec.copy() if copy else vec) class NGSolveVisualizer(ImmutableObject): """Visualize an NGSolve grid function.""" def __init__(self, mesh, fespace): self.__auto_init(locals()) self.space = NGSolveVectorSpace(fespace) def visualize(self, U, legend=None, separate_colorbars=True, filename=None, block=True): """Visualize the provided data.""" if isinstance(U, VectorArray): U = (U,) assert all(u in self.space for u in U) if any(len(u) != 1 for u in U): raise NotImplementedError if any(u._list[0].imag_part is not None for u in U): raise NotImplementedError if legend is None: legend = [f'VectorArray{i}' for i in range(len(U))] if isinstance(legend, str): legend = [legend] assert len(legend) == len(U) legend = [l.replace(' ', '_') for l in legend] # NGSolve GUI will fail otherwise if filename: # ngsolve unconditionnaly appends ".vtk" filename = Path(filename).resolve() if filename.suffix == '.vtk': filename = filename.parent / filename.stem else: self.logger.warning(f'NGSolve set VTKOutput filename to {filename}.vtk') coeffs = [u._list[0].real_part.impl for u in U] # ngsolve cannot handle full paths for filenames with change_to_directory(filename.parent): vtk = ngs.VTKOutput(ma=self.mesh, coefs=coeffs, names=legend, filename=str(filename), subdivision=0) vtk.Do() else: if not separate_colorbars: raise NotImplementedError for u, name in zip(U, legend): ngs.Draw(u._list[0].real_part.impl, self.mesh, name=name)
38.660099
120
0.599261
from pathlib import Path from pymor.core.config import config from pymor.core.defaults import defaults from pymor.tools.io import change_to_directory if config.HAVE_NGSOLVE: import ngsolve as ngs import numpy as np from pymor.core.base import ImmutableObject from pymor.operators.list import LinearComplexifiedListVectorArrayOperatorBase from pymor.vectorarrays.interface import VectorArray from pymor.vectorarrays.numpy import NumpyVectorSpace from pymor.vectorarrays.list import CopyOnWriteVector, ComplexifiedVector, ComplexifiedListVectorSpace class NGSolveVectorCommon: def amax(self): A = np.abs(self.to_numpy()) max_ind = np.argmax(A) max_val = A[max_ind] return max_ind, max_val def dofs(self, dof_indices): return self.to_numpy()[dof_indices] class NGSolveVector(NGSolveVectorCommon, CopyOnWriteVector): def __init__(self, impl): self.impl = impl @classmethod def from_instance(cls, instance): return cls(instance.impl) def _copy_data(self): new_impl = ngs.GridFunction(self.impl.space) new_impl.vec.data = self.impl.vec self.impl = new_impl def to_numpy(self, ensure_copy=False): if ensure_copy: return self.impl.vec.FV().NumPy().copy() self._copy_data_if_needed() return self.impl.vec.FV().NumPy() def _scal(self, alpha): self.impl.vec.data = float(alpha) * self.impl.vec def _axpy(self, alpha, x): self.impl.vec.data = self.impl.vec + float(alpha) * x.impl.vec def inner(self, other): return self.impl.vec.InnerProduct(other.impl.vec) def norm(self): return self.impl.vec.Norm() def norm2(self): return self.impl.vec.Norm() ** 2 class ComplexifiedNGSolveVector(NGSolveVectorCommon, ComplexifiedVector): pass class NGSolveVectorSpace(ComplexifiedListVectorSpace): complexified_vector_type = ComplexifiedNGSolveVector def __init__(self, V, id='STATE'): self.__auto_init(locals()) def __eq__(self, other): return type(other) is NGSolveVectorSpace and self.V == other.V and self.id == other.id def __hash__(self): return hash(self.V) + hash(self.id) @property def value_dim(self): u = self.V.TrialFunction() if isinstance(u, list): return u[0].dim else: return u.dim @property def dim(self): return self.V.ndofglobal * self.value_dim @classmethod def space_from_vector_obj(cls, vec, id): return cls(vec.space, id) def real_zero_vector(self): impl = ngs.GridFunction(self.V) return NGSolveVector(impl) def real_make_vector(self, obj): return NGSolveVector(obj) def real_vector_from_numpy(self, data, ensure_copy=False): v = self.real_zero_vector() v.to_numpy()[:] = data return v class NGSolveMatrixOperator(LinearComplexifiedListVectorArrayOperatorBase): def __init__(self, matrix, range, source, solver_options=None, name=None): self.__auto_init(locals()) @defaults('default_solver') def _prepare_apply(self, U, mu, kind, least_squares=False, default_solver=''): if kind == 'apply_inverse': if least_squares: raise NotImplementedError solver = self.solver_options.get('inverse', default_solver) if self.solver_options else default_solver inv = self.matrix.Inverse(self.source.V.FreeDofs(), inverse=solver) return inv def _real_apply_one_vector(self, u, mu=None, prepare_data=None): r = self.range.real_zero_vector() self.matrix.Mult(u.impl.vec, r.impl.vec) return r def _real_apply_adjoint_one_vector(self, v, mu=None, prepare_data=None): u = self.source.real_zero_vector() try: mat = self.matrix.Transpose() except AttributeError: mat = self.matrix.T mat.Mult(v.impl.vec, u.impl.vec) return u def _real_apply_inverse_one_vector(self, v, mu=None, initial_guess=None, least_squares=False, prepare_data=None): inv = prepare_data r = self.source.real_zero_vector() r.impl.vec.data = inv * v.impl.vec return r def _assemble_lincomb(self, operators, coefficients, identity_shift=0., solver_options=None, name=None): if not all(isinstance(op, NGSolveMatrixOperator) for op in operators): return None if identity_shift != 0: return None matrix = operators[0].matrix.CreateMatrix() matrix.AsVector().data = float(coefficients[0]) * matrix.AsVector() for op, c in zip(operators[1:], coefficients[1:]): matrix.AsVector().data += float(c) * op.matrix.AsVector() return NGSolveMatrixOperator(matrix, self.range, self.source, solver_options=solver_options, name=name) def as_vector(self, copy=True): vec = self.matrix.AsVector().FV().NumPy() return NumpyVectorSpace.make_array(vec.copy() if copy else vec) class NGSolveVisualizer(ImmutableObject): def __init__(self, mesh, fespace): self.__auto_init(locals()) self.space = NGSolveVectorSpace(fespace) def visualize(self, U, legend=None, separate_colorbars=True, filename=None, block=True): if isinstance(U, VectorArray): U = (U,) assert all(u in self.space for u in U) if any(len(u) != 1 for u in U): raise NotImplementedError if any(u._list[0].imag_part is not None for u in U): raise NotImplementedError if legend is None: legend = [f'VectorArray{i}' for i in range(len(U))] if isinstance(legend, str): legend = [legend] assert len(legend) == len(U) legend = [l.replace(' ', '_') for l in legend] if filename: filename = Path(filename).resolve() if filename.suffix == '.vtk': filename = filename.parent / filename.stem else: self.logger.warning(f'NGSolve set VTKOutput filename to {filename}.vtk') coeffs = [u._list[0].real_part.impl for u in U] with change_to_directory(filename.parent): vtk = ngs.VTKOutput(ma=self.mesh, coefs=coeffs, names=legend, filename=str(filename), subdivision=0) vtk.Do() else: if not separate_colorbars: raise NotImplementedError for u, name in zip(U, legend): ngs.Draw(u._list[0].real_part.impl, self.mesh, name=name)
true
true
f72789d0e4c9455e928dc2d9cfcad8d7f2a69dd2
6,167
py
Python
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
video_pipeline.py
josehoras/Advanced-Lane-Finding
e6b83d602eb89661d3bf0f4d257ed5af0f6a58bb
[ "MIT" ]
null
null
null
import numpy as np import pickle import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from moviepy.editor import VideoFileClip from image_thresholding import * from plotting_helpers import * from line_fit import * from Line import * # *** PIPELINE *** def pipeline(img): global error_im, skipped_frames # 1. Correct distorsion # open distorsion matrix try: saved_dist = pickle.load(open('calibrate_camera.p', 'rb'), encoding='latin1') mtx = saved_dist['mtx'] dist = saved_dist['dist'] except (OSError, IOError): # No progress file yet available print("No saved distorsion data. Run camera_calibration.py") # apply correction undist = cv2.undistort(img, mtx, dist, None, mtx) # 2. Apply filters to get binary map ksize = 3 gradx = abs_sobel_thresh(undist, orient='x', sobel_kernel=ksize, thresh=(10, 100)) grady = abs_sobel_thresh(undist, orient='y', sobel_kernel=ksize, thresh=(5, 100)) mag_bin = mag_thresh(undist, sobel_kernel=ksize, mag_thresh=(10, 200)) dir_bin = dir_threshold(undist, sobel_kernel=15, thresh=(0.9, 1.2)) hls_bin = hls_select(img, thresh=(50, 255)) white_bin = white_select(img, thresh=195) yellow_bin = yellow_select(img) # combine filters to a final output combined = np.zeros_like(dir_bin) combined[((mag_bin == 1) & (dir_bin == 1) & (hls_bin == 1)) | ((white_bin == 1) | (yellow_bin == 1))] = 1 # 3. Define trapezoid points on the road and transform perspective X = combined.shape[1] Y = combined.shape[0] src = np.float32( [[205, 720], [1075, 720], [700, 460], [580, 460]]) dst = np.float32( [[300, 720], [980, 720], [980, 0], [300, 0]]) # get perspective transformation matrix M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) # warp the result of binary thresholds warped = cv2.warpPerspective(combined, M, (X,Y), flags=cv2.INTER_LINEAR) # 4. Get polinomial fit of lines # if > 4 frames skipped (or first frame, as skipped_frames is initialized to 100) do full search if skipped_frames > 5: fit_method = "Boxes" leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped) else: fit_method = "Around fit" leftx, lefty, rightx, righty, out_img = find_lane_around_fit(warped, left_lane.fit_x, right_lane.fit_x) # fit polynomials and sanity check try: left_fit, right_fit, left_px, right_px, ploty = fit(leftx, lefty, rightx, righty, warped.shape[0]) detected, err_msg = sanity_chk(ploty, left_px, right_px) except: detected, err_msg = False, "Empty data" if detected: skipped_frames = 0 else: skipped_frames += 1 # 5. Calculate distance to center, curvature, and update Line objects if detected or (fit_method == "Boxes" and err_msg != "Empty data"): left_curv, right_curv = find_curv(ploty, left_fit, right_fit) left_lane.update(ploty, left_fit, left_px, left_curv) right_lane.update(ploty, right_fit, right_px, right_curv) lane_w = (right_lane.base_pos - left_lane.base_pos) * 3.7/700 offset = (((right_lane.base_pos + left_lane.base_pos) - img.shape[1]) / 2) * 3.7/700 # 6. Plot fitted lanes into original image # Create an image to draw the lines on warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_lane.fit_x, left_lane.fit_y]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_lane.fit_x, right_lane.fit_y])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) # Combine the result with the original image result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) # if error save original img to check closely in image pipeline if 1 < skipped_frames < 3: mpimg.imsave(err_msg + "_" + str(error_im) + ".jpg", img) error_im += 1 # Add text road_curv = (left_lane.curv_avg + right_lane.curv_avg) // 2 if road_curv > 2000: road_curv_text = "Road curvature: straight" else: road_curv_text = "Road curvature: " + str(road_curv) + "m" side = {True: "left", False: "right"} offset_txt = "Car is {0:.2f}m {1:s} of center".format(offset, side[offset > 0]) for i, txt in enumerate([road_curv_text, offset_txt]): cv2.putText(result, txt, (75, 75 * (i+1)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3) # Uncomment for debugging messages # lane_width_txt = "Lane width: %.2f m" % lane_w # for i, obj, txt in [(1, left_lane, "Left"), (2, right_lane, "Right")]: # if obj.curv_avg > 2000: # curv_txt = txt + " curvature: straight" # else: # curv_txt = txt + " curvature: " + str(int(obj.curv_avg)) + "m" # cv2.putText(result,curv_txt, (550, 50 * i), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # cv2.putText(result, "Skipped frames: " + str(skipped_frames), (550,150), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # cv2.putText(result, fit_method, (550, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) # if err_msg != "": # cv2.putText(result, "Error!: " + err_msg, (550, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2) return result # *** MAIN *** # define global variables to use in the pipeline left_lane = Line() right_lane = Line() error_im = 1 skipped_frames = 100 # load video clip_name = "challenge_video" clip1 = VideoFileClip(clip_name + ".mp4")#.subclip(0, 8) # run video through the pipeline and save output out_clip = clip1.fl_image(pipeline) out_clip.write_videofile("output_videos/" + clip_name + "_output.mp4", audio=False)
40.572368
113
0.65364
import numpy as np import pickle import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from moviepy.editor import VideoFileClip from image_thresholding import * from plotting_helpers import * from line_fit import * from Line import * def pipeline(img): global error_im, skipped_frames try: saved_dist = pickle.load(open('calibrate_camera.p', 'rb'), encoding='latin1') mtx = saved_dist['mtx'] dist = saved_dist['dist'] except (OSError, IOError): print("No saved distorsion data. Run camera_calibration.py") undist = cv2.undistort(img, mtx, dist, None, mtx) ksize = 3 gradx = abs_sobel_thresh(undist, orient='x', sobel_kernel=ksize, thresh=(10, 100)) grady = abs_sobel_thresh(undist, orient='y', sobel_kernel=ksize, thresh=(5, 100)) mag_bin = mag_thresh(undist, sobel_kernel=ksize, mag_thresh=(10, 200)) dir_bin = dir_threshold(undist, sobel_kernel=15, thresh=(0.9, 1.2)) hls_bin = hls_select(img, thresh=(50, 255)) white_bin = white_select(img, thresh=195) yellow_bin = yellow_select(img) combined = np.zeros_like(dir_bin) combined[((mag_bin == 1) & (dir_bin == 1) & (hls_bin == 1)) | ((white_bin == 1) | (yellow_bin == 1))] = 1 X = combined.shape[1] Y = combined.shape[0] src = np.float32( [[205, 720], [1075, 720], [700, 460], [580, 460]]) dst = np.float32( [[300, 720], [980, 720], [980, 0], [300, 0]]) M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) warped = cv2.warpPerspective(combined, M, (X,Y), flags=cv2.INTER_LINEAR) if skipped_frames > 5: fit_method = "Boxes" leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped) else: fit_method = "Around fit" leftx, lefty, rightx, righty, out_img = find_lane_around_fit(warped, left_lane.fit_x, right_lane.fit_x) try: left_fit, right_fit, left_px, right_px, ploty = fit(leftx, lefty, rightx, righty, warped.shape[0]) detected, err_msg = sanity_chk(ploty, left_px, right_px) except: detected, err_msg = False, "Empty data" if detected: skipped_frames = 0 else: skipped_frames += 1 if detected or (fit_method == "Boxes" and err_msg != "Empty data"): left_curv, right_curv = find_curv(ploty, left_fit, right_fit) left_lane.update(ploty, left_fit, left_px, left_curv) right_lane.update(ploty, right_fit, right_px, right_curv) lane_w = (right_lane.base_pos - left_lane.base_pos) * 3.7/700 offset = (((right_lane.base_pos + left_lane.base_pos) - img.shape[1]) / 2) * 3.7/700 warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) pts_left = np.array([np.transpose(np.vstack([left_lane.fit_x, left_lane.fit_y]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_lane.fit_x, right_lane.fit_y])))]) pts = np.hstack((pts_left, pts_right)) cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) if 1 < skipped_frames < 3: mpimg.imsave(err_msg + "_" + str(error_im) + ".jpg", img) error_im += 1 road_curv = (left_lane.curv_avg + right_lane.curv_avg) // 2 if road_curv > 2000: road_curv_text = "Road curvature: straight" else: road_curv_text = "Road curvature: " + str(road_curv) + "m" side = {True: "left", False: "right"} offset_txt = "Car is {0:.2f}m {1:s} of center".format(offset, side[offset > 0]) for i, txt in enumerate([road_curv_text, offset_txt]): cv2.putText(result, txt, (75, 75 * (i+1)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3) return result left_lane = Line() right_lane = Line() error_im = 1 skipped_frames = 100 clip_name = "challenge_video" clip1 = VideoFileClip(clip_name + ".mp4") out_clip = clip1.fl_image(pipeline) out_clip.write_videofile("output_videos/" + clip_name + "_output.mp4", audio=False)
true
true
f7278a13c9265e6e8a34e3ea72f574bcebb85a0d
4,861
py
Python
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
14
2020-06-17T04:28:39.000Z
2022-02-24T07:21:51.000Z
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
null
null
null
src/Network/SR4DFlowNet.py
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
[ "MIT" ]
7
2020-08-13T03:21:31.000Z
2022-02-15T13:01:18.000Z
import tensorflow as tf class SR4DFlowNet(): def __init__(self, res_increase): self.res_increase = res_increase def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64): channel_nr = 64 speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5 mag = (u_mag ** 2 + v_mag ** 2 + w_mag ** 2) ** 0.5 pcmr = mag * speed phase = tf.keras.layers.concatenate([u,v,w]) pc = tf.keras.layers.concatenate([pcmr, mag, speed]) pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') concat_layer = tf.keras.layers.concatenate([phase, pc]) concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu') concat_layer = conv3d(concat_layer, 3, channel_nr, 'SYMMETRIC', 'relu') # res blocks rb = concat_layer for i in range(low_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') rb = upsample3d(rb, self.res_increase) # refinement in HR for i in range(hi_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') # 3 separate path version u_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') u_path = conv3d(u_path, 3, 1, 'SYMMETRIC', None) v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None) w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None) b_out = tf.keras.layers.concatenate([u_path, v_path, w_path]) return b_out def upsample3d(input_tensor, res_increase): """ Resize the image by linearly interpolating the input using TF '``'resize_bilinear' function. :param input_tensor: 2D/3D image tensor, with shape: 'batch, X, Y, Z, Channels' :return: interpolated volume Original source: https://niftynet.readthedocs.io/en/dev/_modules/niftynet/layer/linear_resize.html """ # We need this option for the bilinear resize to prevent shifting bug align = True b_size, x_size, y_size, z_size, c_size = input_tensor.shape x_size_new, y_size_new, z_size_new = x_size * res_increase, y_size * res_increase, z_size * res_increase if res_increase == 1: # already in the target shape return input_tensor # resize y-z squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') # Reorient reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4]) # squeeze and 2d resize squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = tf.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): """ Based on: https://github.com/gitlimlab/CycleGAN-Tensorflow/blob/master/ops.py For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad """ reg_l2 = tf.keras.regularizers.l2(5e-7) if padding == 'SYMMETRIC' or padding == 'REFLECT': p = (kernel_size - 1) // 2 x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding) x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) else: assert padding in ['SAME', 'VALID'] x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) return x def resnet_block(x, block_name='ResBlock', channel_nr=64, scale = 1, pad='SAME'): tmp = conv3d(x, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) tmp = conv3d(tmp, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = x + tmp * scale tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) return tmp
40.173554
163
0.649866
import tensorflow as tf class SR4DFlowNet(): def __init__(self, res_increase): self.res_increase = res_increase def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64): channel_nr = 64 speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5 mag = (u_mag ** 2 + v_mag ** 2 + w_mag ** 2) ** 0.5 pcmr = mag * speed phase = tf.keras.layers.concatenate([u,v,w]) pc = tf.keras.layers.concatenate([pcmr, mag, speed]) pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') concat_layer = tf.keras.layers.concatenate([phase, pc]) concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu') concat_layer = conv3d(concat_layer, 3, channel_nr, 'SYMMETRIC', 'relu') rb = concat_layer for i in range(low_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') rb = upsample3d(rb, self.res_increase) for i in range(hi_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') u_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') u_path = conv3d(u_path, 3, 1, 'SYMMETRIC', None) v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None) w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None) b_out = tf.keras.layers.concatenate([u_path, v_path, w_path]) return b_out def upsample3d(input_tensor, res_increase): align = True b_size, x_size, y_size, z_size, c_size = input_tensor.shape x_size_new, y_size_new, z_size_new = x_size * res_increase, y_size * res_increase, z_size * res_increase if res_increase == 1: return input_tensor squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4]) squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = tf.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): reg_l2 = tf.keras.regularizers.l2(5e-7) if padding == 'SYMMETRIC' or padding == 'REFLECT': p = (kernel_size - 1) // 2 x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding) x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) else: assert padding in ['SAME', 'VALID'] x = tf.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) return x def resnet_block(x, block_name='ResBlock', channel_nr=64, scale = 1, pad='SAME'): tmp = conv3d(x, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) tmp = conv3d(tmp, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = x + tmp * scale tmp = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp) return tmp
true
true
f7278a52cbb84e8828f86b3c9b2a793ccd2f5400
419
py
Python
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
clientes/forms.py
Etxea/gestion_eide_web
8a59be1ddb59a4713cb3346534fd01f643d8f924
[ "MIT" ]
null
null
null
from django import forms from django.forms import ModelForm from models import * from django.forms.models import inlineformset_factory class ClienteForm(forms.ModelForm): class Meta: model = Cliente class ClienteContactoForm(forms.ModelForm): class Meta: model = ClienteContacto exclude = ['cliente'] #ClienteContactoFormset = inlineformset_factory(Cliente, ClienteContacto)
24.647059
73
0.74463
from django import forms from django.forms import ModelForm from models import * from django.forms.models import inlineformset_factory class ClienteForm(forms.ModelForm): class Meta: model = Cliente class ClienteContactoForm(forms.ModelForm): class Meta: model = ClienteContacto exclude = ['cliente']
true
true
f7278a76375e3a6c0657a5bf9351de27906e9406
92,087
py
Python
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
3
2021-08-15T10:00:14.000Z
2022-02-12T22:30:01.000Z
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
null
null
null
xalpha/universal.py
kingmoon3/xalpha
dd877c6bce1b85a4facd38de9dc35a7bf0acf1c6
[ "MIT" ]
1
2021-10-01T13:12:10.000Z
2021-10-01T13:12:10.000Z
# -*- coding: utf-8 -*- """ modules for universal fetcher that gives historical daily data and realtime data for almost everything in the market """ import os import sys import time import datetime as dt import numpy as np import pandas as pd import logging import inspect from bs4 import BeautifulSoup from functools import wraps, lru_cache from uuid import uuid4 from sqlalchemy import exc from dateutil.relativedelta import relativedelta try: from jqdatasdk import ( get_index_weights, query, get_fundamentals, valuation, get_query_count, finance, get_index_stocks, macro, get_price, ) # 本地导入 except ImportError: try: from jqdata import finance, macro # 云平台导入 except ImportError: pass from xalpha.info import basicinfo, fundinfo, mfundinfo, get_fund_holdings from xalpha.indicator import indicator from xalpha.cons import ( rget, rpost, rget_json, rpost_json, tz_bj, last_onday, region_trans, today_obj, _float, ) from xalpha.provider import data_source from xalpha.exceptions import DataPossiblyWrong, ParserFailure pd.options.mode.chained_assignment = None # turn off setwith copy warning thismodule = sys.modules[__name__] xamodule = sys.modules["xalpha"] logger = logging.getLogger(__name__) def tomorrow_ts(): dto = dt.datetime.now() + dt.timedelta(1) return dto.timestamp() def has_weekday(start, end): for d in pd.date_range(start, end): if d.weekday() < 5: return True return False def ts2pdts(ts): dto = dt.datetime.fromtimestamp(ts / 1000, tz=tz_bj).replace(tzinfo=None) return dto.replace( hour=0, minute=0, second=0, microsecond=0 ) # 雪球美股数据时间戳是美国0点,按北京时区换回时间后,把时分秒扔掉就重合了 def decouple_code(code): """ decompose SH600000.A into SH600000, after :param code: :return: Tuple """ if len(code[1:].split(".")) > 1: # .SPI in US stock! type_ = code.split(".")[-1] code = ".".join(code.split(".")[:-1]) if type_.startswith("b") or type_.startswith("B"): type_ = "before" elif type_.startswith("a") or type_.startswith("A"): type_ = "after" elif type_.startswith("n") or type_.startswith("N"): type_ = "normal" else: logger.warning( "unrecoginzed flag for adjusted factor %s, use default" % type_ ) type_ = "before" else: type_ = "before" return code, type_ def lru_cache_time(ttl=None, maxsize=None): """ TTL support on lru_cache :param ttl: float or int, seconds :param maxsize: int, maxsize for lru_cache :return: """ def wrapper(func): # Lazy function that makes sure the lru_cache() invalidate after X secs @lru_cache(maxsize) def time_aware(_ttl, *args, **kwargs): return func(*args, **kwargs) setattr(thismodule, func.__name__ + "_ttl", time_aware) @wraps(func) def newfunc(*args, **kwargs): ttl_hash = round(time.time() / ttl) f_ttl = getattr(thismodule, func.__name__ + "_ttl") return f_ttl(ttl_hash, *args, **kwargs) return newfunc return wrapper # TODO: 缓存 token 的合适时间尺度 @lru_cache_time(ttl=300) def get_token(): """ 获取雪球的验权 token,匿名也可获取,而且似乎永远恒定(大时间范围内会改变) :return: """ r = rget("https://xueqiu.com", headers={"user-agent": "Mozilla"}) return r.cookies["xq_a_token"] def get_historical_fromxq(code, count, type_="before", full=False): """ :param code: :param count: :param type_: str. normal, before, after :param full: :return: """ url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period=day&type={type_}&count=-{count}" if full: url += "&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance" # pe 是 TTM 数据 r = rget_json( url.format( code=code, tomorrow=int(tomorrow_ts() * 1000), count=count, type_=type_ ), cookies={"xq_a_token": get_token()}, headers={"user-agent": "Mozilla/5.0"}, ) df = pd.DataFrame(data=r["data"]["item"], columns=r["data"]["column"]) df["date"] = (df["timestamp"]).apply(ts2pdts) # reset hours to zero return df @lru_cache() def get_industry_fromxq(code): """ part of symbols has empty industry information :param code: :return: dict """ url = ( "https://xueqiu.com/stock/industry/stockList.json?code=%s&type=1&size=100" % code ) r = rget_json(url, cookies={"xq_a_token": get_token()}) return r def get_historical_fromcninvesting(curr_id, st_date, end_date, app=False): data = { "curr_id": curr_id, # "smlID": smlID, # ? but seems to be fixed with curr_id, it turns out it doesn't matter "st_date": st_date, # %Y/%m/%d "end_date": end_date, "interval_sec": "Daily", "sort_col": "date", "sort_ord": "DESC", "action": "historical_data", } if not app: # fetch from web api r = rpost( "https://cn.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) else: # fetch from app api r = rpost( "https://cnappapi.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) s = BeautifulSoup(r.text, "lxml") dfdict = {} cols = [] for col in s.find_all("th"): dfdict[str(col.contents[0])] = [] cols.append(str(col.contents[0])) num_cols = len(cols) for i, td in enumerate(s.find_all("td")[:-5]): if cols[i % num_cols] == "日期": dfdict[cols[i % num_cols]].append( dt.datetime.strptime(str(td.string), "%Y年%m月%d日") ) else: dfdict[cols[i % num_cols]].append(str(td.string)) return pd.DataFrame(dfdict) def prettify(df): _map = { "日期": "date", "收盘": "close", "开盘": "open", "高": "high", "低": "low", "涨跌幅": "percent", "交易量": "volume", } df.rename(_map, axis=1, inplace=True) if len(df) > 1 and df.iloc[1]["date"] < df.iloc[0]["date"]: df = df[::-1] # df = df[["date", "open", "close", "high", "low", "percent"]] df1 = df[["date"]] for k in ["open", "close", "high", "low", "volume"]: if k in df.columns: df1[k] = df[k].apply(_float) df1["percent"] = df["percent"] return df1 def dstr2dobj(dstr): if len(dstr.split("/")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y/%m/%d") elif len(dstr.split(".")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y.%m.%d") elif len(dstr.split("-")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y-%m-%d") else: d_obj = dt.datetime.strptime(dstr, "%Y%m%d") return d_obj @lru_cache(maxsize=1024) def get_investing_id(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") pid = s.find("span", id="last_last")["class"][-1].split("-")[1] return pid def _variate_ua(): last = 20 + np.random.randint(20) ua = [] ua.append( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)" ) ua.append( "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) choice = np.random.randint(2) return ua[choice][:last] @lru_cache_time(ttl=120, maxsize=128) def get_rmb(start=None, end=None, prev=360, currency="USD/CNY"): """ 获取人民币汇率中间价, 该 API 官网数据源,稳定性很差 :param start: :param end: :param prev: :param currency: :return: pd.DataFrame """ bl = ["USD", "EUR", "100JPY", "HKD", "GBP", "AUD", "NZD", "SGD", "CHF", "CAD"] al = [ "MYR", "RUB", "ZAR", "KRW", "AED", "SAR", "HUF", "PLN", "DKK", "SEK", "NOK", "TRY", "MXN", "THB", ] is_inverse = False if (currency[:3] in al) or (currency[4:] in bl): is_inverse = True currency = currency[4:] + "/" + currency[:3] url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={start_str}&endDate={end_str}&currency={currency}&pageNum=1&pageSize=300" if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y-%m-%d") end_str = end_obj.strftime("%Y-%m-%d") count = (end_obj - start_obj).days + 1 rl = [] # API 很奇怪,需要经常变 UA 才好用 headers = { "Referer": "http://www.chinamoney.com.cn/chinese/bkccpr/", "Origin": "http://www.chinamoney.com.cn", "Host": "www.chinamoney.com.cn", "X-Requested-With": "XMLHttpRequest", } if count <= 360: headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format(start_str=start_str, end_str=end_str, currency=currency), headers=headers, ) rl.extend(r["records"]) else: # data more than 1 year cannot be fetched once due to API limitation sepo_obj = end_obj sepn_obj = sepo_obj - dt.timedelta(360) # sep0_obj = end_obj - dt.timedelta(361) while sepn_obj > start_obj: # [sepn sepo] headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=sepn_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) sepo_obj = sepn_obj - dt.timedelta(1) sepn_obj = sepo_obj - dt.timedelta(360) headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=start_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) data = {"date": [], "close": []} for d in rl: data["date"].append(pd.Timestamp(d["date"])) data["close"].append(d["values"][0]) df = pd.DataFrame(data) df = df[::-1] df["close"] = pd.to_numeric(df["close"]) if is_inverse: df["close"] = 1 / df["close"] return df def get_fund(code): # 随意设置非空 path,防止嵌套缓存到 fundinfo if code[0] == "F": if code.startswith("F96"): return get_historical_from_ttjj_oversea(code) else: df = fundinfo(code[1:], path="nobackend", priceonly=True).price elif code[0] == "T": df = fundinfo(code[1:], path="nobackend", priceonly=True).price df["netvalue"] = df["totvalue"] elif code[0] == "M": df = mfundinfo(code[1:], path="nobackend").price else: raise ParserFailure("Unknown fund code %s" % code) df["close"] = df["netvalue"] return df[["date", "close"]] def get_historical_from_ttjj_oversea(code, start=None, end=None): if code.startswith("F"): code = code[1:] pagesize = ( dt.datetime.strptime(end, "%Y%m%d") - dt.datetime.strptime(start, "%Y%m%d") ).days + 1 r = rget_json( "http://overseas.1234567.com.cn/overseasapi/OpenApiHander.ashx?api=HKFDApi&m=MethodJZ&hkfcode={hkfcode}&action=2&pageindex=0&pagesize={pagesize}&date1={startdash}&date2={enddash}&callback=".format( hkfcode=get_hkfcode(code), pagesize=pagesize, startdash=start[:4] + "-" + start[4:6] + "-" + start[6:], enddash=end[:4] + "-" + end[4:6] + "-" + end[6:], ) ) datalist = {"date": [], "close": []} for dd in r["Data"]: datalist["date"].append(pd.to_datetime(dd["PDATE"])) datalist["close"].append(dd["NAV"]) df = pd.DataFrame(datalist) df = df[df["date"] <= end] df = df[df["date"] >= start] df = df.sort_values("date", ascending=True) return df def get_portfolio_fromttjj(code, start=None, end=None): startobj = dt.datetime.strptime(start, "%Y%m%d") endobj = dt.datetime.strptime(end, "%Y%m%d") if (endobj - startobj).days < 90: return None # note start is always 1.1 4.1 7.1 10.1 in incremental updates if code.startswith("F"): code = code[1:] r = rget("http://fundf10.eastmoney.com/zcpz_{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") table = s.find("table", class_="tzxq") df = pd.read_html(str(table))[0] df["date"] = pd.to_datetime(df["报告期"]) df["stock_ratio"] = df["股票占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["bond_ratio"] = df["债券占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["cash_ratio"] = df["现金占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) # df["dr_ratio"] = df["存托凭证占净比"].replace("---", "0%").apply(lambda s: xa.cons._float(s[:-1])) df["assets"] = df["净资产(亿元)"] df = df[::-1] return df[["date", "stock_ratio", "bond_ratio", "cash_ratio", "assets"]] # this is the most elegant approach to dispatch get_daily, the definition can be such simple # you actually don't need to bother on start end blah, everything is taken care of by ``cahcedio`` @data_source("jq") def get_fundshare_byjq(code, **kws): code = _inverse_convert_code(code) df = finance.run_query( query(finance.FUND_SHARE_DAILY) .filter(finance.FUND_SHARE_DAILY.code == code) .filter(finance.FUND_SHARE_DAILY.date >= kws["start"]) .filter(finance.FUND_SHARE_DAILY.date <= kws["end"]) .order_by(finance.FUND_SHARE_DAILY.date) ) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "shares"]] return df @lru_cache(maxsize=1024) def get_futu_id(code): r = rget("https://www.futunn.com/stock/{code}".format(code=code)) sind = r.text.find("securityId") futuid = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip(" ").strip("'") sind = r.text.find("marketType") market = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip().strip("''") return futuid, market def get_futu_historical(code, start=None, end=None): fid, market = get_futu_id(code) r = rget( "https://www.futunn.com/new-quote/kline?security_id={fid}&type=2&market_type={market}".format( fid=fid, market=market ) ) df = pd.DataFrame(r.json()["data"]["list"]) df["date"] = df["k"].map( lambda s: dt.datetime.fromtimestamp(s) .replace(hour=0, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ) df["open"] = df["o"] / 1000 df["close"] = df["c"] / 1000 df["high"] = df["h"] / 1000 df["low"] = df["l"] / 1000 df["volume"] = df["v"] df = df.drop(["k", "t", "o", "c", "h", "l", "v"], axis=1) return df def get_historical_fromsp(code, start=None, end=None, region="us", **kws): """ 标普官网数据源 :param code: :param start: :param end: :param kws: :return: """ if code.startswith("SP"): code = code[2:] if len(code.split(".")) > 1: col = code.split(".")[1] code = code.split(".")[0] else: col = "1" start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 300: flag = "one" elif fromnow < 1000: flag = "three" else: flag = "ten" url = "https://{region}.spindices.com/idsexport/file.xls?\ selectedModule=PerformanceGraphView&selectedSubModule=Graph\ &yearFlag={flag}YearFlag&indexId={code}".format( region=region, flag=flag, code=code ) r = rget( url, headers={ "sec-fetch-dest": "document", "sec-fetch-mode": "navigate", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1", "upgrade-insecure-requests": "1", }, ) df = pd.read_excel(r.content, engine="xlrd") # print(df.iloc[:10]) df = df.iloc[6:] df = df.dropna() df["close"] = df["Unnamed: " + col] df["date"] = pd.to_datetime(df["Unnamed: 0"]) df = df[["date", "close"]] return df def get_historical_frombb(code, start=None, end=None, **kws): """ https://www.bloomberg.com/ 数据源, 试验性支持。 似乎有很严格的 IP 封禁措施, 且最新数据更新滞后,且国内会被 reset,似乎难以支持 T-1 净值预测。强烈建议从英为或雅虎能找到的标的,不要用彭博源,该 API 只能作为 last resort。 :param code: :param start: :param end: :param kws: :return: """ if code.startswith("BB-"): code = code[3:] # end_obj = dt.datetime.strptime(end, "%Y%m%d") start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: years = "1_MONTH" elif fromnow < 300: years = "1_YEAR" else: years = "5_YEAR" url = "https://www.bloomberg.com/markets2/api/history/{code}/PX_LAST?\ timeframe={years}&period=daily&volumePeriod=daily".format( years=years, code=code ) r = rget_json( url, headers={ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)", "referer": "https://www.bloomberg.com/quote/{code}".format(code=code), "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*", }, ) df = pd.DataFrame(r[0]["price"]) df["close"] = df["value"] df["date"] = pd.to_datetime(df["dateTime"]) df = df[["date", "close"]] return df def get_historical_fromft(code, start, end, _type="indices"): """ finance times 数据 :param code: :param start: :param end: :return: """ if not code.isdigit(): code = get_ft_id(code, _type=_type) start = start.replace("/", "").replace("-", "") end = end.replace("/", "").replace("-", "") start = start[:4] + "/" + start[4:6] + "/" + start[6:] end = end[:4] + "/" + end[4:6] + "/" + end[6:] url = "https://markets.ft.com/data/equities/ajax/\ get-historical-prices?startDate={start}&endDate={end}&symbol={code}".format( code=code, start=start, end=end ) r = rget_json(url, headers={"user-agent": "Mozilla/5.0"}) b = BeautifulSoup(r["html"], "lxml") data = {"date": [], "open": [], "close": [], "high": [], "low": []} for i, td in enumerate(b.findAll("td")): if i % 6 == 0: s = td.find("span").string.split(",")[1:] s = ",".join(s) data["date"].append(dt.datetime.strptime(s, " %B %d, %Y")) elif i % 6 == 1: data["open"].append(_float(td.string)) elif i % 6 == 2: data["high"].append(_float(td.string)) elif i % 6 == 3: data["low"].append(_float(td.string)) elif i % 6 == 4: data["close"].append(_float(td.string)) df = pd.DataFrame(data) df = df.iloc[::-1] return df def get_historical_fromyh(code, start=None, end=None): """ 雅虎财经数据源,支持数据丰富,不限于美股。但存在部分历史数据缺失 NAN 或者周末进入交易日的现象,可能数据需要进一步清洗和处理。 :param code: :param start: :param end: :return: """ if code.startswith("YH-"): code = code[3:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: range_ = "1mo" elif fromnow < 50: range_ = "3mo" elif fromnow < 150: range_ = "6mo" elif fromnow < 300: range_ = "1y" elif fromnow < 600: range_ = "2y" elif fromnow < 1500: range_ = "5y" else: range_ = "10y" url = "https://query1.finance.yahoo.com/v8\ /finance/chart/{code}?region=US&lang=en-US&includePrePost=false\ &interval=1d&range={range_}&corsDomain=finance.yahoo.com&.tsrc=finance".format( code=code, range_=range_ ) # 该 API 似乎也支持起止时间选择参数,period1=1427500800&period2=1585353600 # 也可直接从历史数据页面爬取: https://finance.yahoo.com/quote/CSGOLD.SW/history?period1=1427500800&period2=1585353600&interval=1d&filter=history&frequency=1d r = rget_json(url) data = {} datel = [] for t in r["chart"]["result"][0]["timestamp"]: t = dt.datetime.fromtimestamp(t) if t.second != 0: t -= dt.timedelta(hours=8) datel.append(t.replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)) data["date"] = datel for k in ["close", "open", "high", "low"]: data[k] = r["chart"]["result"][0]["indicators"]["quote"][0][k] df = pd.DataFrame(data) return df def get_historical_fromzzindex(code, start, end=None): """ 中证指数源 :param code: :param start: :param end: :return: """ if code.startswith("ZZ"): code = code[2:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: flag = "1%E4%B8%AA%E6%9C%88" elif fromnow < 60: flag = "3%E4%B8%AA%E6%9C%88" # 个月 elif fromnow < 200: flag = "1%E5%B9%B4" # 年 else: flag = "5%E5%B9%B4" r = rget_json( "http://www.csindex.com.cn/zh-CN/indices/index-detail/\ {code}?earnings_performance={flag}&data_type=json".format( code=code, flag=flag ), headers={ "Host": "www.csindex.com.cn", "Referer": "http://www.csindex.com.cn/zh-CN/indices/index-detail/{code}".format( code=code ), "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36", "X-Requested-With": "XMLHttpRequest", "Accept": "application/json, text/javascript, */*; q=0.01", }, ) df = pd.DataFrame(r) df["date"] = pd.to_datetime(df["tradedate"]) df["close"] = df["tclose"].apply(_float) return df[["date", "close"]] def get_historical_fromgzindex(code, start, end): """ 国证指数源 :param code: :param start: :param end: :return: """ if code.startswith("GZ"): code = code[2:] start = start[:4] + "-" + start[4:6] + "-" + start[6:] end = end[:4] + "-" + end[4:6] + "-" + end[6:] params = { "indexCode": code, "startDate": start, "endDate": end, "frequency": "Day", } r = rget_json( "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat", params=params, ) df = pd.DataFrame(r["data"]["data"], columns=r["data"]["item"]) df["date"] = pd.to_datetime(df["timestamp"]) df = df[["date", "close", "open", "low", "high", "percent", "amount", "volume"]] # TODO: 是否有这些列不全的国证指数? df = df[::-1] return df def get_historical_fromhzindex(code, start, end): """ 华证指数源 :param code: :param start: :param end: :return: """ if code.startswith("HZ"): code = code[2:] r = rget_json( "http://www.chindices.com/index/values.val?code={code}".format(code=code) ) df = pd.DataFrame(r["data"]) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "price", "pctChange"]] df.rename(columns={"price": "close", "pctChange": "percent"}, inplace=True) df = df[::-1] return df def get_historical_fromesunny(code, start=None, end=None): """ 易盛商品指数 :param code: eg. ESCI000201 :param start: just placeholder :param end: just placeholder :return: """ # code if code.startswith("ESCI"): code = code[4:] + ".ESCI" r = rget( "http://www.esunny.com.cn/chartES/csv/shareday/day_易盛指数_{code}.es".format( code=code ) ) data = [] for l in r.text.split("\n"): row = [s.strip() for s in l.split("|")] # 开 高 低 收 结 if len(row) > 1: data.append(row[:7]) df = pd.DataFrame( data, columns=["date", "open", "high", "low", "close", "settlement", "amount"] ) df["date"] = pd.to_datetime(df["date"]) for c in ["open", "high", "low", "close", "settlement", "amount"]: df[c] = df[c].apply(_float) return df def get_historical_fromycharts(code, start, end, category, metric): params = { "securities": "include:true,id:{code},,".format(code=code), "calcs": "include:true,id:{metric},,".format(metric=metric), "startDate": start, # %m/%d/%Y "endDate": end, # %m/%d/%Y "zoom": "custom", } r = rget_json( "https://ycharts.com/charts/fund_data.json", params=params, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "ycharts.com", "X-Requested-With": "XMLHttpRequest", "Referer": "https://ycharts.com/{category}/{code}/chart/".format( category=category, code=code ), "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", }, ) df = pd.DataFrame( data=r["chart_data"][0][0]["raw_data"], columns=["timestamp", "close"] ) df["date"] = (df["timestamp"]).apply(ts2pdts) return df[["date", "close"]] @lru_cache() def get_bond_rates(rating, date=None): """ 获取各评级企业债的不同久期的预期利率 :param rating: str. eg AAA, AA-, N for 中国国债 :param date: %Y-%m-%d :return: """ rating = rating.strip() rating_uid = { "N": "2c9081e50a2f9606010a3068cae70001", # 国债 "AAA": "2c9081e50a2f9606010a309f4af50111", "AAA-": "8a8b2ca045e879bf014607ebef677f8e", "AA+": "2c908188138b62cd01139a2ee6b51e25", "AA": "2c90818812b319130112c279222836c3", "AA-": "8a8b2ca045e879bf014607f9982c7fc0", "A+": "2c9081e91b55cc84011be40946ca0925", "A": "2c9081e91e6a3313011e6d438a58000d", "A-": "8a8b2ca04142df6a014148ca880f3046", "A": "2c9081e91e6a3313011e6d438a58000d", "BBB+": "2c9081e91ea160e5011eab1f116c1a59", "BBB": "8a8b2ca0455847ac0145650780ad68fb", "BB": "8a8b2ca0455847ac0145650ba23b68ff", "B": "8a8b2ca0455847ac0145650c3d726901", } # 上边字典不全,非常欢迎贡献 :) def _fetch(date): r = rpost( "https://yield.chinabond.com.cn/cbweb-mn/yc/searchYc?\ xyzSelect=txy&&workTimes={date}&&dxbj=0&&qxll=0,&&yqqxN=N&&yqqxK=K&&\ ycDefIds={uid}&&wrjxCBFlag=0&&locale=zh_CN".format( uid=rating_uid.get(rating, rating), date=date ), ) return r if not date: date = dt.datetime.today().strftime("%Y-%m-%d") r = _fetch(date) while len(r.text.strip()) < 20: # 当天没有数据,非交易日 date = last_onday(date).strftime("%Y-%m-%d") r = _fetch(date) l = r.json()[0]["seriesData"] l = [t for t in l if t[1]] df = pd.DataFrame(l, columns=["year", "rate"]) return df def get_bond_rates_range(rating, duration=3, freq="W-FRI", start=None, end=None): l = [] if rating.startswith("B-"): rating = rating[2:] rs = rating.split(".") if len(rs) > 1: duration = float(rs[1]) rating = rs[0] for d in pd.date_range(start, end, freq=freq): df = get_bond_rates(rating, d.strftime("%Y-%m-%d")) l.append([d, df[df["year"] <= duration].iloc[-1]["rate"]]) return pd.DataFrame(l, columns=["date", "close"]) @data_source("jq") def get_macro(table, start, end, datecol="stat_year"): df = macro.run_query( query(getattr(macro, table)) .filter(getattr(getattr(macro, table), datecol) >= start) .filter(getattr(getattr(macro, table), datecol) <= end) .order_by(getattr(getattr(macro, table), datecol)) ) df[datecol] = pd.to_datetime(df[datecol]) df["date"] = df[datecol] return df def set_handler(method="daily", f=None): """ 为 ``get_daily``, ``get_bar`` 或 ``get_rt`` 设置 hook,优先按照函数 f 进行处理,若返回 None,再按一般情形处理 :param method: str. daily, rt, bar :param f: func, default None. :return: None """ setattr(thismodule, "get_" + method + "_handler", f) def _get_daily( code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws ): """ universal fetcher for daily historical data of literally everything has a value in market. 数据来源包括但不限于天天基金,雪球,英为财情,外汇局官网,聚宽,标普官网,bloomberg,雅虎财经,ycharts等。 :param code: str. 1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。如果数字代码之后接 .A .B .N 分别代表后复权,前复权和不复权数据,不加后缀默认前复权。港股美股同理。 2. 对于香港市场的股票,指数,使用其数字代码,同时开头要添加 HK。 3. 对于美国市场的股票,指数,ETF 等,直接使用其字母缩写代码即可。 4. 对于人民币中间价数据,使用 "USD/CNY" 的形式,具体可能的值可在 http://www.chinamoney.com.cn/chinese/bkccpr/ 历史数据的横栏查询,注意日元需要用 100JPY/CNY. 5. 对于所有可以在 cn.investing.com 网站查到的金融产品,其代码可以是该网站对应的统一代码,或者是网址部分,比如 DAX 30 的概览页面为 https://cn.investing.com/indices/germany-30,那么对应代码即为 "indices/germany-30"。也可去网页 inspect 手动查找其内部代码(一般不需要自己做,推荐直接使用网页url作为 code 变量值),手动 inspect 加粗的实时价格,其对应的网页 span class 中的 pid 的数值即为内部代码。 6. 对于国内发行的基金,使用基金代码,同时开头添加 F。若想考虑分红使用累计净值,则开头添加 T。 7. 对于国内发行的货币基金,使用基金代码,同时开头添加 M。(全部按照净值数据处理) 8. 形如 peb-000807.XSHG 或 peb-SH000807 格式的数据,可以返回每周的指数估值情况,需要 enable 聚宽数据源方可查看。 9. 形如 iw-000807.XSHG 或 iw-SH000807 格式的数据,可以返回每月的指数成分股和实时权重,需要 enable 聚宽数据源方可查看。 10. 形如 fs-SH501018 格式的数据,可以返回指定场内基金每日份额,需要 enable 聚宽数据源方可查看。 11. 形如 SP5475707.2 格式的数据,可以返回标普官网相关指数的日线数据(最近十年),id 5475707 部分可以从相关指数 export 按钮获取的链接中得到,小数点后的部分代表保存的列数。参考链接:https://us.spindices.com/indices/equity/sp-global-oil-index. 若SPC开头,则从中国网站获取。 12. 形如 BB-FGERBIU:ID 格式的数据,对应网页 https://www.bloomberg.com/quote/FGERBIU:ID,可以返回彭博的数据(最近五年) 13. 形如 sw-801720 格式的数据,可以返回对应申万行业的历史数据情况,需要 enable 聚宽数据源方可查看。 14. 形如 teb-SH000300 格式的数据,返回每周指数盈利和净资产总值数据(单位:亿人民币元),需要 enbale 聚宽数据方可查看。 15. 形如 YH-CSGOLD.SW 格式的数据,返回雅虎财经标的日线数据(最近十年)。代码来自标的网页 url:https://finance.yahoo.com/quote/CSGOLD.SW。 16. 形如 FT-22065529 格式的数据或 FT-INX:IOM,可以返回 financial times 的数据,推荐直接用后者。前者数字代码来源,打开浏览器 network 监视,切换图标时间轴时,会新增到 https://markets.ft.com/data/chartapi/series 的 XHR 请求,其 request payload 里的 [elements][symbol] 即为该指数对应数字。 17. 形如 FTC-WTI+Crude+Oil 格式的数据,开头可以是 FTC, FTE, FTX, FTF, FTB, FTI 对应 ft.com 子栏目 commdities,equities,currencies,funds,bonds,indicies。其中 FTI 和 FT 相同。 18. 形如 mcy-MAC_AREA_UNEMPLOY 格式的数据,返回相应的宏观数据,需要聚宽数据源。mcy,mcq,mcm 代表年度,季度和月度的数据,code 为表名,可以参考 https://www.joinquant.com/help/api/help?name=macroData 19. 形如 ZZ000905,ZZH30533 的代码,代表中证官网的指数,ZZ 之后接指数代码,注意有些指数代码里可能包含 H,历史数据最大到近五年。 20. 形如 GZB30018, GZ399299 格式的数据,代表国证系列指数, GZ 之后接指数代码,代码可能包含更多字母。 21. 形如 ESCI000201 格式的数据,易盛商品指数系列,参考 http://www.esunny.com.cn/index.php?a=lists&catid=60。 22. 形如 pt-F100032 格式的数据,返回指定基金每季度股票债券和现金的持仓比例 23. 形如 yc-companies/DBP,yc-companies/DBP/price 格式的数据,返回ycharts股票、ETF数据,对应网页 https://ycharts.com/companies/DBP/price,最后部分为数据含义,默认price,可选:net_asset_value(仅ETF可用)、total_return_price、total_return_forward_adjusted_price、average_volume_30,历史数据限制五年内。 24. 形如 yc-indices/^SPGSCICO,yc-indices/^SPGSCICO/level 格式的数据,返回ycharts指数数据,对应网页 https://ycharts.com/indices/%5ESPGSCICO/level,最后部分为数据含义,默认level,可选:total_return_forward_adjusted_price,历史数据限制五年内。 25. 形如 HZ999001 HZ999005 格式的数据,代表了华证系列指数 http://www.chindices.com/indicator.html# 26. 形如 B-AA+.3 格式的数据,代表了 AA+ 企业债三年久期利率数据 (每周) 27. 形如 fu-00700.HK 或 fu-BA.US 格式的数据,代表了来自 https://www.futunn.com/stock/BA-US 的日线行情数据 :param start: str. "20200101", "2020/01/01", "2020-01-01" are all legal. The starting date of daily data. :param end: str. format is the same as start. The ending date of daily data. :param prev: Optional[int], default 365. If start is not specified, start = end-prev. :param _from: Optional[str]. 一般用户不需设定该选项。can be one of "xueqiu", "zjj", "investing", "tiantianjijin". Only used for debug to enforce data source. For common use, _from can be chosed automatically based on code in the run time. :param wrapper: bool. 一般用户不需设定该选项。 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的原函数嵌套调用。 :return: pd.Dataframe. must include cols: date[pd.Timestamp],close[float64]。 """ if handler: if getattr(thismodule, "get_daily_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_daily_handler") fr = f(**args.locals) if fr is not None: return fr if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dstr2dobj(start) if not _from: if (code.startswith("SH") or code.startswith("SZ")) and code[2:8].isdigit(): _from = "xueqiu" elif code.endswith("/CNY") or code.startswith("CNY/"): _from = "zjj" elif code.isdigit(): _from = "cninvesting" elif code[0] in ["F", "M", "T"] and code[1:].isdigit(): _from = "ttjj" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif code.startswith("SP") and code[2:].split(".")[0].isdigit(): _from = "SP" elif code.startswith("SPC") and code[3:].split(".")[0].isdigit(): _from = "SPC" elif code.startswith("ZZ") and code[4:].isdigit(): # 注意中证系列指数的代码里可能包含字母! _from = "ZZ" elif code.startswith("GZ") and code[-3:].isdigit(): # 注意国证系列指数的代码里可能包含多个字母! _from = "GZ" elif code.startswith("HZ") and code[2:].isdigit(): _from = "HZ" elif code.startswith("ESCI") and code[4:].isdigit(): _from = "ES" elif code.startswith("yc-companies/") or code.startswith("yc-indices/"): _from = "ycharts" params = code.split("/") code = params[1] category = params[0].split("-")[1] if len(params) == 3: metric = params[2] else: if category == "companies": metric = "price" elif category == "indices": metric = "level" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: # peb-000807.XSHG _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code[1:].split("/")) == 2: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股代码 count = (today_obj() - start_obj).days + 1 start_str = start_obj.strftime("%Y/%m/%d") end_str = end_obj.strftime("%Y/%m/%d") if _from in ["cninvesting", "investing", "default", "IN"]: df = get_historical_fromcninvesting(code, start_str, end_str) df = prettify(df) elif _from in ["xueqiu", "xq", "snowball", "XQ"]: code, type_ = decouple_code(code) df = get_historical_fromxq(code, count, type_=type_) df = prettify(df) elif _from in ["zhongjianjia", "zjj", "chinamoney", "ZJJ"]: df = get_rmb(start, end, prev, currency=code) elif _from in ["ttjj", "tiantianjijin", "xalpha", "eastmoney"]: if code.startswith("F96"): df = get_historical_from_ttjj_oversea(code, start=start, end=end) else: df = get_fund(code) elif _from == "peb": if ( code.startswith("SH000") or code.startswith("SZ399") or code.startswith("399") or code.startswith("000") ): df = _get_peb_range(code=code, start=start_str, end=end_str) elif code.startswith("F"): df = get_fund_peb_range(code=code, start=start, end=end) else: df = get_stock_peb_range(code=code, start=start, end=end, wrapper=True) elif _from == "iw": df = _get_index_weight_range(code=code, start=start_str, end=end_str) elif _from == "fs": df = get_fundshare_byjq(code, start=start, end=end) elif _from == "SP": df = get_historical_fromsp(code, start=start, end=end) elif _from == "SPC": df = get_historical_fromsp(code[3:], start=start, end=end, region="chinese") elif _from == "BB": df = get_historical_frombb(code, start=start, end=end) elif _from == "ZZ": df = get_historical_fromzzindex(code, start=start, end=end) elif _from == "GZ": df = get_historical_fromgzindex(code, start=start, end=end) elif _from == "HZ": df = get_historical_fromhzindex(code, start=start, end=end) elif _from == "ES": df = get_historical_fromesunny(code, start=start, end=end) elif _from == "B": df = get_bond_rates_range(code, start=start, end=end) elif _from == "fu": code = code.replace(".", "-") df = get_futu_historical(code, start=start, end=end) elif _from == "ycharts": df = get_historical_fromycharts( code, start=start_obj.strftime("%m/%d/%Y"), end=end_obj.strftime("%m/%d/%Y"), category=category, metric=metric, ) elif _from == "sw": df = get_sw_from_jq(code, start=start, end=end) elif _from == "teb": df = get_teb_range(code, start=start, end=end) elif _from in ["pt", "portfolio"]: df = get_portfolio_fromttjj(code, start=start, end=end) elif _from == "YH": df = get_historical_fromyh(code, start=start, end=end) elif _from in ["FT", "FTI"]: df = get_historical_fromft(code, start=start, end=end) elif _from == "FTE": df = get_historical_fromft(code, start=start, end=end, _type="equities") elif _from == "FTB": df = get_historical_fromft(code, start=start, end=end, _type="bonds") elif _from == "FTF": df = get_historical_fromft(code, start=start, end=end, _type="funds") elif _from == "FTX": df = get_historical_fromft(code, start=start, end=end, _type="currencies") elif _from == "FTC": df = get_historical_fromft(code, start=start, end=end, _type="commodities") elif _from == "INA": # investing app code = get_investing_id(code, app=True) df = get_historical_fromcninvesting(code, start_str, end_str, app=True) df = prettify(df) elif _from == "mcy": df = get_macro(code, start=start[:4], end=end[:4], datecol="stat_year") elif _from == "mcq": df = get_macro(code, start=start, end=end, datecol="stat_quarter") elif _from == "mcm": df = get_macro(code, start=start, end=end, datecol="stat_month") elif _from == "mcd": df = get_macro(code, start=start, end=end, datecol="day") else: raise ParserFailure("no such data source: %s" % _from) if wrapper or len(df) == 0: return df else: df = df[df.date <= end_str] df = df[df.date >= start_str] return df def get_xueqiu_rt(code, token="a664afb60c7036c7947578ac1a5860c4cfb6b3b5"): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] url = "https://stock.xueqiu.com/v5/stock/quote.json?symbol={code}&extend=detail" r = rget_json( url.format(code=code), cookies={"xq_a_token": token}, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)"}, ) n = r["data"]["quote"]["name"] q = r["data"]["quote"]["current"] try: q = _float(q) except TypeError: # 针对雪球实时在9点后开盘前可能出现其他情形的fixup, 效果待 check # 现在的怀疑是在9am 到9:15 am, 雪球 API current 字段返回 Null q = _float(r["data"]["quote"]["last_close"]) q_ext = r["data"]["quote"].get("current_ext", None) percent = r["data"]["quote"]["percent"] try: percent = _float(percent) except: pass currency = r["data"]["quote"]["currency"] market = r["data"]["market"]["region"] timestr = dt.datetime.fromtimestamp(r["data"]["quote"]["time"] / 1000).strftime( "%Y-%m-%d %H:%M:%S" ) if r["data"]["quote"].get("timestamp_ext", None): time_ext = dt.datetime.fromtimestamp( r["data"]["quote"]["timestamp_ext"] / 1000 ).strftime("%Y-%m-%d %H:%M:%S") else: time_ext = None share = r["data"]["quote"]["total_shares"] fshare = r["data"]["quote"]["float_shares"] volume = r["data"]["quote"]["volume"] return { "name": n, "current": q, "percent": percent, "current_ext": _float(q_ext) if q_ext else None, "currency": currency, "market": market, # HK, US, CN "time": timestr, "time_ext": time_ext, "totshare": share, "floatshare": fshare, "volume": volume, } def get_cninvesting_rt(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") last_last = s.find("span", id="last_last") q = _float(last_last.string) name = s.find("h1").string.strip() ind = 0 timestr = s.select('span[class*="ClockBigIcon"]+span')[0].text l = s.find("div", class_="lighterGrayFont").contents for i, c in enumerate(l): if isinstance(c, str) and c.strip() == "货币": ind = i break if ind == 0: currency = None else: currency = l[ind - 1].string percent = _float( s.find("span", attrs={"dir": "ltr", "class": "parentheses"}).string[:-1] ) panhou = s.find("div", class_="afterHoursInfo") if panhou: q_ext = _float(panhou.find("span").string) else: q_ext = None market = None for span in s.findAll("span", class_="elp"): if span.find("a") and span.find("a")["href"].startswith("/markets"): market = span.string market = region_trans.get(market, market) time_ext = s.select("div[class~=lastUpdated]") if time_ext: time_ext = time_ext[0].text.strip() else: time_ext = None d = { "name": name, "current": q, "current_ext": q_ext, "time": timestr, "time_ext": time_ext, "currency": currency, "percent": percent, "market": market, } if suburl.startswith("commodities"): # 商品期货展期日 try: d["rollover"] = s.select("span[class*=float_lang_base_2]")[10].string d["lastrollover"] = s.select("span[class*=float_lang_base_2]")[13].string except (ValueError, IndexError, AttributeError): logger.warning("%s cannot extract rollover date" % suburl) # in case some commodities with strong page structure return d def get_rt_from_sina(code): if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): tinycode = code[:2].lower() + code[2:] if code.startswith("HK"): # 港股额外要求实时 tinycode = "rt_" + tinycode else: # 美股 tinycode = "gb_" if code.startswith("."): code = code[1:] tinycode += code.lower() r = rget("https://hq.sinajs.cn/list={tinycode}".format(tinycode=tinycode)) l = r.text.split("=")[1].split(",") d = {} d["name"] = l[0].strip('"') if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): # TODO: 20200819: API seems changed a bit, index shift? # or things may get zero when the market is closed? if code.startswith("HK"): d["current"] = float(l[9]) # 英文股票名称占位 d["currency"] = "HKD" d["percent"] = round(float(l[8]), 2) d["market"] = "HK" d["time"] = l[17] + " " + l[18] d["current_ext"] = None else: # A 股 d["current"] = float(l[3]) d["currency"] = "CNY" d["percent"] = round((float(l[3]) / float(l[2]) - 1) * 100, 2) d["market"] = "CN" d["time"] = l[-4] + " " + l[-3] for i in range(10, 19)[::2]: d["buy" + str(int((i - 8) / 2))] = (l[i + 1], l[i]) for i in range(20, 29)[::2]: d["sell" + str(int((i - 18) / 2))] = (l[i + 1], l[i]) d["current_ext"] = None else: d["currency"] = "USD" d["current"] = float(l[1]) d["percent"] = float(l[2]) d["current_ext"] = _float(l[21]) if _float(l[21]) > 0 else None d["market"] = "US" d["time"] = l[3] return d def make_ft_url(code, _type="indices"): """ :param code: :param _type: indices, commodities, currencies, funds, equities, bonds :return: """ if _type == "indices": url = "https://markets.ft.com/data/indices/tearsheet/summary?s={code}".format( code=code ) elif _type == "commodities": url = ( "https://markets.ft.com/data/commodities/tearsheet/summary?c={code}".format( code=code ) ) elif _type == "currencies": url = ( "https://markets.ft.com/data/currencies/tearsheet/summary?s={code}".format( code=code ) ) elif _type == "funds": url = "https://markets.ft.com/data/funds/tearsheet/summary?s={code}".format( code=code ) elif _type == "equities": url = "https://markets.ft.com/data/equities/tearsheet/summary?s={code}".format( code=code ) elif _type == "bonds": url = "https://markets.ft.com/data/bonds/tearsheet/summary?s={code}".format( code=code ) else: raise ParserFailure("no reconginzed type for ft datasource: %s" % _type) return url @lru_cache(maxsize=1024) def get_ft_id(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") return eval( b.find("section", class_="mod-tearsheet-add-to-watchlist")["data-mod-config"] )["xid"] def get_rt_from_ft(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") d = {} d["name"] = b.find("h1").string d["current"] = _float(b.find("span", class_="mod-ui-data-list__value").string) d["percent"] = _float( b.select("span[class^='mod-format--']")[0].text.split("/")[-1].strip()[:-1] ) d["current_ext"] = None d["market"] = None d["currency"] = b.find("span", class_="mod-ui-data-list__label").string.split("(")[ 1 ][:-1] d["time"] = b.find("div", class_="mod-disclaimer").string return d def get_rt_from_ycharts(code): if code.startswith("yc-"): code = code[3:] url = "https://ycharts.com/" + code r = rget(url) s = BeautifulSoup(r.text, "lxml") qdiv = s.select("div.index-rank.col-auto") # current spans = [s for s in qdiv[0].contents if s != "\n" and s.contents] d = {} d["name"] = s.select("h1,h3[class=securityName]")[0].text.strip() d["current"], d["percent"] = ( _float(spans[0].string), # current, _float(spans[1].contents[-2].string[1:-1]), # percent ) l = [ c.strip() for c in s.select("span[class=index-info]")[0].string.split("\n") if c.strip() ] d["time"] = l[1] d["currency"] = l[0].split(" ")[0].strip() d["market"] = None return d @lru_cache_time(ttl=300, maxsize=512) def get_newest_netvalue(code): """ 防止天天基金总量 API 最新净值更新不及时,获取基金最新公布净值及对应日期, depracated, use get_rt("F501018") instead :param code: six digits string for fund. :return: netvalue, %Y-%m-%d """ code = code[1:] r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") return ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) @lru_cache(maxsize=512) def get_hkfcode(code): if code.startswith("F"): code = code[1:] page = rget("http://overseas.1234567.com.cn/{code}".format(code=code)).text page.find("hkfcode") hkfcode = ( page[page.find("hkfcode") :] .split("=")[1] .split(";")[0] .lstrip() .lstrip("'") .strip("'") ) return hkfcode def get_rt_from_ttjj_oversea(code): if code.startswith("F"): code = code[1:] if not code.startswith("96"): raise ValueError("%s is not an oversea fund" % code) r = rget("http://overseas.1234567.com.cn/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") start = s.select("dl.dataItem02")[0].text start = start.split("(")[1].split(")")[0] name = s.select("div[class='fundDetail-tit']")[0].text.split("(")[0].strip() name = name.split("(")[0].strip() value = _float(s.select("span.ui-font-large.ui-num")[0].text) date = ( s.select("dl[class='dataItem01']")[0] .find("p") .text.split("(")[-1] .split(")")[0] ) infol = [ r for r in s.select("div[class='infoOfFund']")[0].text.split("\n") if r.strip() ] return { "name": name, "time": date, "current": value, "market": "CN", "currency": None, # 很可能存在非人民币计价的互认基金 "current_ext": None, "type": infol[0].split(":")[1].strip(), "scale": infol[1].split(":")[1].strip(), "manager": infol[2].split(":")[1].strip(), "startdate": start, } @lru_cache_time(ttl=600, maxsize=512) def get_rt_from_ttjj(code): code = code[1:] if code.startswith("96"): return get_rt_from_ttjj_oversea(code) r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") name = s.select("div[style='float: left']")[0].text.split("(")[0] if s.findAll("dd", class_="dataNums")[1].find( "span", class_="ui-font-large" ): # 非货币基金 value, date = ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) estimate = s.select("span[id=gz_gsz]")[0].text # after loading if estimate == "--": gsz = rget( "http://fundgz.1234567.com.cn/js/{code}.js".format(code=code), headers={ "Host": "fundgz.1234567.com.cn", "Referer": "http://fund.eastmoney.com/", }, ) try: # in case eval error gsz_dict = eval(gsz.text[8:-2]) estimate = _float(gsz_dict["gsz"]) estimate_time = gsz_dict["gztime"] except: estimate = None else: try: estimate = _float(estimate) except ValueError: logger.warning("unrecognized estimate netvalue %s" % estimate) estimate = None else: value, date = ( s.findAll("dd", class_="dataNums")[1].text, str(s.findAll("dt")[1]).split("(")[1].split(")")[0], ) estimate = None status = s.select("span[class='staticCell']")[0].text.strip() tb = s.select("div.infoOfFund > table >tr>td") infol = [i.text for i in tb] try: estimate_time except NameError: estimate_time = None return { "name": name, "time": date, "current": value, "market": "CN", "currency": "CNY", "current_ext": None, "status": status, "type": infol[0].split(":")[1].split("\xa0")[0], "scale": infol[1].split(":")[1], "manager": infol[2].split(":")[1], "company": infol[4].split(":")[1], "estimate": estimate, "estimate_time": estimate_time, } # 是否有美元份额计价的基金会出问题? @lru_cache(2048) def get_fund_type(code): """ given fund code, return unified fund category which is extracted from get_rt(code)["type"] :param code: :return: str. """ code = code[-6:] t = get_rt("F" + code)["type"] if t in ["联接基金", "股票指数"] or t.startswith("ETF"): return "指数基金" elif t.startswith("QDII"): return "QDII" elif t.startswith("股票"): return "股票基金" elif t.startswith("混合"): return "混合基金" elif t.startswith("债券"): return "债券基金" elif t.startswith("货币"): return "货币基金" else: return "其他" def get_rt( code, _from=None, double_check=False, double_check_threhold=0.005, handler=True ): """ universal fetcher for realtime price of literally everything. :param code: str. 规则同 :func:`get_daily`. 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。 :param _from: Optional[str]. can be one of "xueqiu", "investing". Only used for debug to enfore data source. For common use, _from can be chosed automatically based on code in the run time. :param double_check: Optional[bool], default False. 如果设为 True,只适用于 A 股,美股,港股实时行情,会通过至少两个不同的数据源交叉验证,确保正确。 适用于需要自动交易等情形,防止实时数据异常。 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。 :return: Dict[str, Any]. 包括 "name", "current", "percent" 三个必有项和 "current_ext"(盘后价格), "currency" (计价货币), "market" (发行市场), "time"(记录时间) 可能为 ``None`` 的选项。 """ # 对于一些标的,get_rt 的主任务可能不是 current 价格,而是去拿 market currency 这些元数据 # 现在用的新浪实时数据源延迟严重, double check 并不靠谱,港股数据似乎有15分钟延迟(已解决) # 雪球实时和新浪实时在9:00之后一段时间可能都有问题 # FT 数据源有10到20分钟的延迟 if handler: if getattr(thismodule, "get_rt_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_rt_handler") fr = f(**args.locals) if fr: return fr if not _from: # if code.startswith("HK") and code[2:].isdigit(): # _from = "xueqiu" if code.startswith("yc-"): _from = "ycharts" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif (code.startswith("F") or code.startswith("T")) and code[1:].isdigit(): _from = "ttjj" elif len(code.split("/")) > 1: _from = "investing" else: # 默认启用雪球实时,新浪纯指数行情不完整 _from = "xueqiu" if _from in ["cninvesting", "investing"]: try: return get_cninvesting_rt(code) except Exception as e: logger.warning( "Fails due to %s, now trying app source of investing.com" % e.args[0] ) return get_cninvesting_rt(code, app=True) elif double_check and _from in ["xueqiu", "sina"]: r1 = get_xueqiu_rt(code, token=get_token()) r2 = get_rt_from_sina(code) if abs(r1["current"] / r2["current"] - 1) > double_check_threhold: raise DataPossiblyWrong("realtime data unmatch for %s" % code) return r2 elif _from in ["xueqiu", "xq", "snowball"]: try: return get_xueqiu_rt(code, token=get_token()) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from sina" % e.args[0] ) return get_rt_from_sina(code) elif _from in ["sina", "sn", "xinlang"]: try: return get_rt_from_sina(code) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from xueqiu" % e.args[0] ) return get_xueqiu_rt(code, token=get_token()) elif _from in ["ttjj"]: return get_rt_from_ttjj(code) elif _from in ["FT", "ft", "FTI"]: return get_rt_from_ft(code) elif _from == "FTE": return get_rt_from_ft(code, _type="equities") elif _from == "FTB": return get_rt_from_ft(code, _type="bonds") elif _from == "FTF": return get_rt_from_ft(code, _type="funds") elif _from == "FTX": return get_rt_from_ft(code, _type="currencies") elif _from == "FTC": return get_rt_from_ft(code, _type="commodities") elif _from in ["INA"]: # investing app return get_cninvesting_rt(code, app=True) elif _from in ["yc", "ycharts"]: return get_rt_from_ycharts(code) else: raise ParserFailure("unrecoginzed _from for %s" % _from) get_realtime = get_rt get_now = get_rt _cached_data = {} def reset_cache(): """ clear all cache of daily data in memory. :return: None. """ global _cached_data _cached_data = {} setattr(thismodule, "cached_dict", {}) def cached(s): """ **Deprecated**, use :func:`cachedio` instead, where ``backend="memory"``. Usage as follows: .. code-block:: python @cached("20170101") def get_daily(*args, **kws): return xa.get_daily(*args, **kws) Automatically cache the result in memory and avoid refetching :param s: str. eg. "20160101", the starting date of cached table. :return: wrapped function. """ def cached_start(f): @wraps(f) def wrapper(*args, **kws): print("cached function is deprecated, please instead use cachedio") if args: code = args[0] else: code = kws.get("code") start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) if not prev: prev = 365 if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") kws["start"] = s kws["end"] = dt.datetime.now().strftime("%Y%m%d") global _cached_data _cached_data.setdefault(s, {}) if code not in _cached_data[s]: df = f(*args, **kws) # print("cached %s" % code) _cached_data[s][code] = df else: pass # print("directly call cache") df = _cached_data[s][code] df = df[df["date"] <= end_str] df = df[df["date"] >= start_str] return df return wrapper return cached_start def cachedio(**ioconf): """ 用法类似:func:`cached`,通用透明缓存器,用来作为 (code, start, end ...) -> pd.DataFrame 形式函数的缓存层, 避免重复爬取已有数据。 :param **ioconf: 可选关键字参数 backend: csv or sql or memory, path: csv 文件夹或 sql engine, refresh True 会刷新结果,重新爬取, default False, prefix 是 key 前统一部分, 缓存 hash 标志 :return: """ def cached(f): @wraps(f) def wrapper(*args, **kws): if args: code = args[0] else: code = kws.get("code") date = ioconf.get("date", "date") # 没利用上这个栏的名字变化 precached = ioconf.get("precached", None) precached = kws.get("precached", precached) key = kws.get("key", code) key = key.replace("/", " ") key_func = ioconf.get("key_func", None) key_func = ioconf.get("keyfunc", key_func) if key_func is not None: key = key_func(key) defaultend = ioconf.get("defaultend", today_obj) defaultend = ioconf.get("default_end", defaultend) defaultprev = ioconf.get("defaultprev", 365) defaultprev = ioconf.get("default_prev", defaultprev) if isinstance(defaultend, str): defaultend = defaultend.replace("/", "").replace("-", "") defaultend = dt.datetime.strptime(defaultend, "%Y%m%d") if callable(defaultend): defaultend = defaultend() start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) prefix = ioconf.get("prefix", "") key = prefix + key if precached: precached = precached.replace("/", "").replace("-", "") precached_obj = dt.datetime.strptime(precached, "%Y%m%d") if not prev: prev = defaultprev if not end: end_obj = defaultend else: end_obj = dt.datetime.strptime( end.replace("/", "").replace("-", ""), "%Y%m%d" ) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dt.datetime.strptime( start.replace("/", "").replace("-", ""), "%Y%m%d" ) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") backend = ioconf.get("backend") backend = kws.get("backend", backend) # if backend == "sql": # reserved for case insensitive database settings # key = key.lower() refresh = ioconf.get("refresh", False) refresh = kws.get("refresh", refresh) fetchonly = ioconf.get("fetchonly", False) fetchonly = ioconf.get("fetch_only", fetchonly) fetchonly = kws.get("fetchonly", fetchonly) fetchonly = kws.get("fetch_only", fetchonly) path = ioconf.get("path") path = kws.get("path", path) kws["start"] = start_str kws["end"] = end_str if not backend: df = f(*args, **kws) df = df[df["date"] <= kws["end"]] df = df[df["date"] >= kws["start"]] return df else: if backend == "csv": key = key + ".csv" if not getattr(thismodule, "cached_dict", None): setattr(thismodule, "cached_dict", {}) if refresh: is_changed = True df0 = f(*args, **kws) else: # non refresh try: if backend == "csv": if key in getattr(thismodule, "cached_dict"): # 即使硬盘级别的缓存,也有内存层,加快读写速度 df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": if key in getattr(thismodule, "cached_dict"): df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_sql(key, path) elif backend == "memory": df0 = getattr(thismodule, "cached_dict")[key] else: raise ValueError("no %s option for backend" % backend) df0[date] = pd.to_datetime(df0[date]) # 向前延拓 is_changed = False if df0.iloc[0][date] > start_obj and not fetchonly: kws["start"] = start_str kws["end"] = ( df0.iloc[0][date] - pd.Timedelta(days=1) ).strftime("%Y%m%d") if has_weekday(kws["start"], kws["end"]): # 考虑到海外市场的不同情况,不用 opendate 判断,采取保守型判别 df1 = f(*args, **kws) if df1 is not None and len(df1) > 0: df1 = df1[df1["date"] <= kws["end"]] if df1 is not None and len(df1) > 0: is_changed = True df0 = df1.append(df0, ignore_index=True, sort=False) # 向后延拓 if df0.iloc[-1][date] < end_obj and not fetchonly: nextday_str = ( df0.iloc[-1][date] + dt.timedelta(days=1) ).strftime("%Y%m%d") if len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1: kws["start"] = (df0.iloc[-1][date]).strftime("%Y%m%d") else: # 单日多行的表默认最后一日是准确的,不再刷新了 kws["start"] = nextday_str kws["end"] = end_str if has_weekday(nextday_str, kws["end"]): # 新更新的日期里有工作日 df2 = f(*args, **kws) if df2 is not None and len(df2) > 0: df2 = df2[df2["date"] >= kws["start"]] if df2 is not None and len(df2) > 0: is_changed = True if ( len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1 ): df0 = df0.iloc[:-1] df0 = df0.append(df2, ignore_index=True, sort=False) # 注意这里抹去更新了原有最后一天的缓存,这是因为日线最新一天可能有实时数据污染 except (FileNotFoundError, exc.ProgrammingError, KeyError) as e: if fetchonly: logger.error( "no cache in backend for %s but you insist `fetchonly`" % code ) raise e if precached: if start_obj > precached_obj: kws["start"] = precached if end_obj < today_obj(): kws["end"] = ( today_obj() - dt.timedelta(days=1) ).strftime("%Y%m%d") is_changed = True df0 = f(*args, **kws) if df0 is not None and len(df0) > 0 and is_changed: if backend == "csv": df0.to_csv(os.path.join(path, key), index=False) elif backend == "sql": df0.to_sql(key, con=path, if_exists="replace", index=False) # elif backend == "memory": # 总是刷新内存层,即使是硬盘缓存 d = getattr(thismodule, "cached_dict") d[key] = df0 if df0 is not None and len(df0) > 0: df0 = df0[df0["date"] <= end_str] df0 = df0[df0["date"] >= start_str] return df0 return wrapper return cached def fetch_backend(key): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" try: if backend == "csv": df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": df0 = pd.read_sql(key, path) else: raise ValueError("no %s option for backend" % backend) return df0 except (FileNotFoundError, exc.ProgrammingError, KeyError): return None def save_backend(key, df, mode="a", header=False): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" if backend == "csv": if mode == "a": df.to_csv(os.path.join(path, key), index=False, header=header, mode=mode) else: df.to_csv(os.path.join(path, key), index=False, mode=mode) elif backend == "sql": if mode == "a": mode = "append" else: mode = "replace" df.to_sql(key, con=path, if_exists=mode, index=False) else: raise ValueError("no %s option for backend" % backend) logger.debug("%s saved into backend successfully" % key) def check_cache(*args, omit_lines=0, **kws): if omit_lines == 0: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True) .equals(get_daily(*args, **kws).reset_index(drop=True)) ) else: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True)[:-omit_lines] .equals(get_daily(*args, **kws).reset_index(drop=True)[:-omit_lines]) ) @data_source("jq") def _get_index_weight_range(code, start, end): if len(code.split(".")) != 2: code = _inverse_convert_code(code) start_obj = dt.datetime.strptime(start.replace("-", "").replace("/", ""), "%Y%m%d") end_obj = dt.datetime.strptime(end.replace("-", "").replace("/", ""), "%Y%m%d") start_m = start_obj.replace(day=1) if start_m < start_obj: start_m = start_m + relativedelta(months=1) end_m = end_obj.replace(day=1) if end_obj < end_m: end_m = end_m - relativedelta(months=1) d = start_m df = pd.DataFrame({"code": [], "weight": [], "display_name": [], "date": []}) while True: if d > end_m: df["date"] = pd.to_datetime(df["date"]) return df logger.debug("fetch index weight on %s for %s" % (d, code)) df0 = get_index_weights(index_id=code, date=d.strftime("%Y-%m-%d")) df0["code"] = df0.index df = df.append(df0, ignore_index=True, sort=False) d = d + relativedelta(months=1) @data_source("jq") def _get_peb_range(code, start, end): # 盈利,净资产,总市值 """ 获取指定指数一段时间内的 pe pb 值。 :param code: 聚宽形式指数代码。 :param start: :param end: :return: pd.DataFrame """ if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) logger.debug("compute pe pb on %s" % d) r = get_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def get_stock_peb_range(code, start, end, wrapper=False): """ 获取股票历史 pe pb :param code: :param start: :param end: :return: """ if code.startswith("HK") and code[2:].isdigit(): code = code[2:] count = (today_obj() - dt.datetime.strptime(start, "%Y%m%d")).days df = get_historical_fromxq(code, count, full=True) df = df[["date", "pe", "pb", "ps"]] if not wrapper: df = df[df["date"] >= start] df = df[df["date"] <= end] return df @lru_cache() def ttjjcode(code): """ 将天天基金的持仓股票代码或其他来源的代码标准化 :param code: str. :return: str. """ code = code.strip() if code.endswith(".HK"): return "HK" + code[:-3] elif code.endswith(".US"): return code[:-3] elif code.isdigit() and len(code) == 5: return "HK" + code elif code.isdigit() and len(code) == 6: if ( code.startswith("16") or code.startswith("15") or code.startswith("12") or code.startswith("0") or code.startswith("3") ): # 注意这里只能对应个股,指数代码有重叠没有办法的事 return "SZ" + code elif code.startswith("5") or code.startswith("6") or code.startswith("11"): return "SH" + code else: logger.warning("unrecognized code format %s" % code) return "0" else: logger.info("not so sure about code format %s, taken as US stock" % code) return code def get_fund_peb(code, date, threhold=0.3): """ 根据基金的股票持仓,获取对应日期的 pe,pb 估值 :param code: str. 基金代码 :param date: :param threhold: float, default 0.3. 为了计算快速,占比小于千分之三的股票将舍弃 :return: """ if code.startswith("F"): code = code[1:] date = date.replace("/", "").replace("-", "") d = dt.datetime.strptime(date, "%Y%m%d") if d.month > 3 and d.month < 8: year = d.year - 1 season = 4 elif d.month <= 3: year = d.year - 1 season = 2 else: year = d.year season = 2 # season 只选 2,4, 具有更详细的持仓信息 df = get_fund_holdings(code, year, season) if df is None: if season == 4: season = 2 else: year -= 1 season = 4 df = get_fund_holdings(code, year, season) if df is None: logger.warning("%s seems has no holdings data in this time %s" % (code, year)) return {"pe": None, "pb": None} df = df[df["ratio"] >= threhold] df["scode"] = df["code"].apply(ttjjcode) df = df[df["scode"] != "0"] if len(df) == 0: return {"pe": None, "pb": None} pel, pbl = [], [] for i, r in df.iterrows(): try: fdf = get_daily("peb-" + r["scode"], end=date, prev=60) if len(fdf) == 0: # 已退市或改名 logger.warning("%s: 无法获取,可能已退市,当时休市或改名" % r["scode"]) pel.append(None) pbl.append(None) else: fdf = fdf.iloc[-1] pel.append(fdf["pe"]) pbl.append(fdf["pb"]) except (KeyError, TypeError, IndexError) as e: logger.warning( "%s: 获取历史估值出现问题: %s, 可能由于网站故障或股票代码非中美市场" % (r["scode"], e.args[0]) ) pel.append(None) pbl.append(None) df["pe"] = pel df["pb"] = pbl r = {} pedf = df[~pd.isna(df["pe"])] pbdf = df[~pd.isna(df["pb"])] if len(pbdf) < 0.5 * len(df): # 有时候会有个别标的有pb值 r["pb"] = None else: pbdf["b"] = pbdf["ratio"] / (pbdf["pb"] + 0.000001) r["pb"] = pbdf.ratio.sum() / pbdf.b.sum() if len(pedf) == 0: r["pe"] = None else: pedf["e"] = pedf["ratio"] / (pedf["pe"] + 0.000001) r["pe"] = pedf.ratio.sum() / pedf.e.sum() return r def get_fund_peb_range(code, start, end): """ 获取一段时间的基金历史估值,每周五为频率 :param code: :param start: :param end: :return: """ if code.startswith("F"): code = code[1:] data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) r = get_fund_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def set_backend(**ioconf): """ 设定 xalpha get_daily 函数的缓存后端,默认为内存。 ioconf 参数设置可参考 :func:`cachedio` :param ioconf: :return: None. """ if not ioconf: ioconf = {"backend": "memory"} get_daily = cachedio(**ioconf)(_get_daily) prefix = ioconf.get("prefix", "") ioconf["prefix"] = "iw-" + prefix get_index_weight_range = cachedio(**ioconf)(_get_index_weight_range) ioconf["prefix"] = "peb-" + prefix get_peb_range = cachedio(**ioconf)(_get_peb_range) setattr(thismodule, "get_daily", get_daily) setattr(xamodule, "get_daily", get_daily) setattr(thismodule, "get_index_weight_range", get_index_weight_range) setattr(thismodule, "get_peb_range", get_peb_range) ioconf["prefix"] = prefix setattr(thismodule, "ioconf", ioconf) set_backend() @data_source("jq") def get_peb(index, date=None, table=False): """ 获取指数在指定日期的 pe 和 pb。采用当时各公司的最新财报和当时的指数成分股权重加权计算。 :param index: str. 聚宽形式的指数代码。 :param date: str. %Y-%m-%d :param table: Optioanl[bool], default False. True 时返回整个计算的 DataFrame,用于 debug。 :return: Dict[str, float]. 包含 pe 和 pb 值的字典。 """ if len(index.split(".")) == 2: index = _convert_code(index) middle = dt.datetime.strptime( date.replace("/", "").replace("-", ""), "%Y%m%d" ).replace(day=1) iwdf = get_index_weight_range( index, start=(middle - dt.timedelta(days=10)).strftime("%Y-%m-%d"), end=(middle + dt.timedelta(days=6)).strftime("%Y-%m-%d"), ) q = query(valuation).filter(valuation.code.in_(list(iwdf.code))) logger.debug("get_fundamentals on %s" % (date)) df = get_fundamentals(q, date=date) df = df.merge(iwdf, on="code") df["e"] = df["weight"] / df["pe_ratio"] df["b"] = df["weight"] / df["pb_ratio"] df["p"] = df["weight"] tote = df.e.sum() totb = df.b.sum() if table: return df return { "pe": (round(100.0 / tote, 3) if tote != 0 else np.inf), "pb": (round(100.0 / totb, 3) if totb != 0 else np.inf), } @data_source("jq") def get_sw_from_jq(code, start=None, end=None, **kws): """ :param code: str. eg. 801180 申万行业指数 :param start: :param end: :param kws: :return: """ logger.debug("get sw data of %s" % code) df = finance.run_query( query(finance.SW1_DAILY_VALUATION) .filter(finance.SW1_DAILY_VALUATION.date >= start) .filter(finance.SW1_DAILY_VALUATION.date <= end) .filter(finance.SW1_DAILY_VALUATION.code == code) .order_by(finance.SW1_DAILY_VALUATION.date.asc()) ) df["date"] = pd.to_datetime(df["date"]) return df @data_source("jq") def get_teb(code, date): if len(code.split(".")) != 2: code = _inverse_convert_code(code) sl = get_index_stocks(code, date=date) logger.debug("get fundamentals from jq for %s" % code) df = get_fundamentals(query(valuation).filter(valuation.code.in_(sl)), date=date) df["e"] = df["market_cap"] / df["pe_ratio"] df["b"] = df["market_cap"] / df["pb_ratio"] return {"e": df["e"].sum(), "b": df["b"].sum(), "m": df["market_cap"].sum()} # 亿人民币 def get_teb_range(code, start, end, freq="W-FRI"): if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "e": [], "b": [], "m": []} for d in pd.date_range(start, end, freq=freq): data["date"].append(d) r = get_teb(code, d.strftime("%Y-%m-%d")) data["e"].append(r["e"]) data["b"].append(r["b"]) data["m"].append(r["m"]) df = pd.DataFrame(data) return df def _convert_code(code): """ 将聚宽形式的代码转化为 xalpha 形式 :param code: :return: """ no, mk = code.split(".") if mk == "XSHG": return "SH" + no elif mk == "XSHE": return "SZ" + no def _inverse_convert_code(code): """ 将 xalpha 形式的代码转化为聚宽形式 :param code: :return: """ if code.startswith("SH"): return code[2:] + ".XSHG" elif code.startswith("SZ"): return code[2:] + ".XSHE" @lru_cache_time(ttl=60, maxsize=512) def get_bar( code, prev=24, interval=3600, _from=None, handler=True, start=None, end=None ): """ :param code: str. 支持雪球和英为的代码 :param prev: points of data from now to back, often limited by API around several hundreds :param interval: float, seconds. need to match the corresponding API, typical values include 60, 300, 3600, 86400, 86400*7 :param handler: bool. Default True. 若为 False,则 handler 钩子失效,用于钩子函数中的嵌套。 :return: pd.DataFrame """ if handler: if getattr(thismodule, "get_bar_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_bar_handler") fr = f(**args.locals) if fr is not None: return fr if not _from: if ( (start is not None) and (end is not None) and (code.startswith("SH") or code.startswith("SZ")) ): _from = "jq" elif code.startswith("SH") or code.startswith("SZ"): _from = "xueqiu" elif code.isdigit(): _from = "cninvesting" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code.split("/")) > 1: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股 if _from in ["xq", "xueqiu", "XQ"]: return get_bar_fromxq(code, prev, interval) elif _from in ["IN", "cninvesting", "investing"]: return get_bar_frominvesting(code, prev, interval) elif _from in ["INA"]: return get_bar_frominvesting(code, prev, interval) # 这里 investing app 源是 404,只能用网页源 elif _from in ["jq"]: code, type_ = decouple_code(code) # 关于复权,聚宽各个时间密度的数据都有复权,雪球源日线以上的高频数据没有复权 type_map = {"after": "post", "before": "pre", "normal": None} return get_bar_fromjq( code, start=start, end=end, interval=interval, fq=type_map[type_] ) elif _from in ["wsj"]: return get_bar_fromwsj(code, interval=interval)[-prev:] else: raise ParserFailure("unrecoginized _from %s" % _from) @data_source("jq") def get_bar_fromjq(code, start, end, interval, fq="pre"): code = _inverse_convert_code(code) trans = { "60": "1m", "120": "2m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "daily", } interval = trans.get(str(interval), interval) logger.debug("calling ``get_price`` from jq with %s" % code) return get_price(code, start_date=start, end_date=end, frequency=interval, fq=fq) def get_bar_frominvesting(code, prev=120, interval=3600): """ get bar data beyond daily bar :param code: str. investing id or url :param prev: int, data points from now, max might be around 500, if exceed, only None is returnd :param interval: default 3600. optional 60, 300, 900, 1800, 18000, 86400, "week", "month" :return: pd.DataFrame or None if prev and interval unmatch the API """ if interval == "day": interval = 86400 elif interval == "hour": interval = 3600 elif interval == "minute": interval = 60 elif interval == 86400 * 7: interval = "week" elif interval == 86400 * 30: interval = "month" if len(code.split("/")) == 2: code = get_investing_id(code) url = "https://cn.investing.com" headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "Referer": "https://cn.investing.com/commodities/", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "X-Requested-With": "XMLHttpRequest", } r = rget( url + "/common/modules/js_instrument_chart/api/data.php?pair_id={code}&pair_id_for_news={code}\ &chart_type=area&pair_interval={interval}&candle_count={prev}&events=yes&volume_series=yes&period=".format( code=code, prev=str(prev), interval=str(interval) ), headers=headers, ) if not r.text: return # None r = r.json() df = pd.DataFrame(r["candles"], columns=["date", "close", "0", "1"]) df = df.drop(["0", "1"], axis=1) df["date"] = df["date"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) return df def get_bar_fromxq(code, prev, interval=3600): """ :param code: :param prev: :param interval: 1m, 5m, 15m, 30m, 60m, 120m, month, quarter, year, week, day :return: """ # max interval is also around 500 trans = { "60": "1m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "day", "604800": "week", "2592000": "month", } code, type_ = decouple_code(code) interval = trans.get(str(interval), interval) url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period={interval}&type={type_}\ &count=-{prev}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance".format( code=code, tomorrow=int(tomorrow_ts() * 1000), prev=prev, interval=interval, type_=type_, ) r = rget( url, headers={"user-agent": "Mozilla/5.0"}, cookies={"xq_a_token": get_token()} ) if not r.text: return # None else: df = pd.DataFrame(r.json()["data"]["item"], columns=r.json()["data"]["column"]) df["date"] = df["timestamp"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) df = df[ [ "date", "open", "high", "low", "close", "volume", "turnoverrate", "percent", ] ] return df def get_bar_fromwsj(code, token=None, interval=3600): # proxy required # code = "FUTURE/US/XNYM/CLM20" # TODO: also not explore the code format here extensively trans = {"3600": "1H"} # TODO: there is other freq tags, but I have no time to explore them, contributions are welcome:) freq = trans.get(str(interval), interval) if not token: token = "cecc4267a0194af89ca343805a3e57af" # the thing I am concerned here is whether token is refreshed params = { "json": '{"Step":"PT%s","TimeFrame":"D5","EntitlementToken":"%s",\ "IncludeMockTick":true,"FilterNullSlots":false,"FilterClosedPoints":true,"IncludeClosedSlots":false,\ "IncludeOfficialClose":true,"InjectOpen":false,"ShowPreMarket":false,"ShowAfterHours":false,\ "UseExtendedTimeFrame":false,"WantPriorClose":true,"IncludeCurrentQuotes":false,\ "ResetTodaysAfterHoursPercentChange":false,\ "Series":[{"Key":"%s","Dialect":"Charting","Kind":"Ticker","SeriesId":"s1","DataTypes":["Last"]}]}' % (freq, token, code), "ckey": token[:10], } r = rget_json( "https://api-secure.wsj.net/api/michelangelo/timeseries/history", params=params, headers={ "user-agent": "Mozilla/5.0", "Accept": "application/json, text/javascript, */*; q=0.01", "Dylan2010.EntitlementToken": token, "Host": "api-secure.wsj.net", "Origin": "https://www.marketwatch.com", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site", }, ) df = pd.DataFrame( { "date": r["TimeInfo"]["Ticks"], "close": [n[0] for n in r["Series"][0]["DataPoints"]], } ) df["date"] = pd.to_datetime(df["date"] * 1000000) + pd.Timedelta(hours=8) df = df[df["close"] > -100.0] # 存在未来数据占位符需要排除 return df class vinfo(basicinfo, indicator): """ vinfo is an info like class wrapper for get_daily, it behaves like info """ def __init__( self, code, name=None, start=None, end=None, rate=0, col="close", normalization=True, **kws ): if not name: try: name = get_rt(code)["name"] except: name = code self.name = name self.code = code self.start = start # None is one year ago self.end = end # None is yesterday df = get_daily(code, start=start, end=end) df[col] = pd.to_numeric(df[col]) # in case the col is not float df["totvalue"] = df[col] if normalization: df["netvalue"] = df[col] / df.iloc[0][col] else: df["netvalue"] = df[col] self.price = df self.round_label = kws.get("round_label", 0) self.dividend_label = kws.get("dividend_label", 0) self.value_label = kws.get("value_label", 1) # 默认按金额赎回 self.specialdate = [] self.fenhongdate = [] self.zhesuandate = [] self.rate = rate VInfo = vinfo
33.522752
277
0.544876
import os import sys import time import datetime as dt import numpy as np import pandas as pd import logging import inspect from bs4 import BeautifulSoup from functools import wraps, lru_cache from uuid import uuid4 from sqlalchemy import exc from dateutil.relativedelta import relativedelta try: from jqdatasdk import ( get_index_weights, query, get_fundamentals, valuation, get_query_count, finance, get_index_stocks, macro, get_price, ) except ImportError: try: from jqdata import finance, macro except ImportError: pass from xalpha.info import basicinfo, fundinfo, mfundinfo, get_fund_holdings from xalpha.indicator import indicator from xalpha.cons import ( rget, rpost, rget_json, rpost_json, tz_bj, last_onday, region_trans, today_obj, _float, ) from xalpha.provider import data_source from xalpha.exceptions import DataPossiblyWrong, ParserFailure pd.options.mode.chained_assignment = None thismodule = sys.modules[__name__] xamodule = sys.modules["xalpha"] logger = logging.getLogger(__name__) def tomorrow_ts(): dto = dt.datetime.now() + dt.timedelta(1) return dto.timestamp() def has_weekday(start, end): for d in pd.date_range(start, end): if d.weekday() < 5: return True return False def ts2pdts(ts): dto = dt.datetime.fromtimestamp(ts / 1000, tz=tz_bj).replace(tzinfo=None) return dto.replace( hour=0, minute=0, second=0, microsecond=0 ) def decouple_code(code): if len(code[1:].split(".")) > 1: type_ = code.split(".")[-1] code = ".".join(code.split(".")[:-1]) if type_.startswith("b") or type_.startswith("B"): type_ = "before" elif type_.startswith("a") or type_.startswith("A"): type_ = "after" elif type_.startswith("n") or type_.startswith("N"): type_ = "normal" else: logger.warning( "unrecoginzed flag for adjusted factor %s, use default" % type_ ) type_ = "before" else: type_ = "before" return code, type_ def lru_cache_time(ttl=None, maxsize=None): def wrapper(func): @lru_cache(maxsize) def time_aware(_ttl, *args, **kwargs): return func(*args, **kwargs) setattr(thismodule, func.__name__ + "_ttl", time_aware) @wraps(func) def newfunc(*args, **kwargs): ttl_hash = round(time.time() / ttl) f_ttl = getattr(thismodule, func.__name__ + "_ttl") return f_ttl(ttl_hash, *args, **kwargs) return newfunc return wrapper @lru_cache_time(ttl=300) def get_token(): r = rget("https://xueqiu.com", headers={"user-agent": "Mozilla"}) return r.cookies["xq_a_token"] def get_historical_fromxq(code, count, type_="before", full=False): url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period=day&type={type_}&count=-{count}" if full: url += "&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance" r = rget_json( url.format( code=code, tomorrow=int(tomorrow_ts() * 1000), count=count, type_=type_ ), cookies={"xq_a_token": get_token()}, headers={"user-agent": "Mozilla/5.0"}, ) df = pd.DataFrame(data=r["data"]["item"], columns=r["data"]["column"]) df["date"] = (df["timestamp"]).apply(ts2pdts) return df @lru_cache() def get_industry_fromxq(code): url = ( "https://xueqiu.com/stock/industry/stockList.json?code=%s&type=1&size=100" % code ) r = rget_json(url, cookies={"xq_a_token": get_token()}) return r def get_historical_fromcninvesting(curr_id, st_date, end_date, app=False): data = { "curr_id": curr_id, "interval_sec": "Daily", "sort_col": "date", "sort_ord": "DESC", "action": "historical_data", } if not app: # fetch from web api r = rpost( "https://cn.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) else: # fetch from app api r = rpost( "https://cnappapi.investing.com/instruments/HistoricalDataAjax", data=data, headers={ "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", }, ) s = BeautifulSoup(r.text, "lxml") dfdict = {} cols = [] for col in s.find_all("th"): dfdict[str(col.contents[0])] = [] cols.append(str(col.contents[0])) num_cols = len(cols) for i, td in enumerate(s.find_all("td")[:-5]): if cols[i % num_cols] == "日期": dfdict[cols[i % num_cols]].append( dt.datetime.strptime(str(td.string), "%Y年%m月%d日") ) else: dfdict[cols[i % num_cols]].append(str(td.string)) return pd.DataFrame(dfdict) def prettify(df): _map = { "日期": "date", "收盘": "close", "开盘": "open", "高": "high", "低": "low", "涨跌幅": "percent", "交易量": "volume", } df.rename(_map, axis=1, inplace=True) if len(df) > 1 and df.iloc[1]["date"] < df.iloc[0]["date"]: df = df[::-1] # df = df[["date", "open", "close", "high", "low", "percent"]] df1 = df[["date"]] for k in ["open", "close", "high", "low", "volume"]: if k in df.columns: df1[k] = df[k].apply(_float) df1["percent"] = df["percent"] return df1 def dstr2dobj(dstr): if len(dstr.split("/")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y/%m/%d") elif len(dstr.split(".")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y.%m.%d") elif len(dstr.split("-")) > 1: d_obj = dt.datetime.strptime(dstr, "%Y-%m-%d") else: d_obj = dt.datetime.strptime(dstr, "%Y%m%d") return d_obj @lru_cache(maxsize=1024) def get_investing_id(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") pid = s.find("span", id="last_last")["class"][-1].split("-")[1] return pid def _variate_ua(): last = 20 + np.random.randint(20) ua = [] ua.append( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)" ) ua.append( "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) choice = np.random.randint(2) return ua[choice][:last] @lru_cache_time(ttl=120, maxsize=128) def get_rmb(start=None, end=None, prev=360, currency="USD/CNY"): bl = ["USD", "EUR", "100JPY", "HKD", "GBP", "AUD", "NZD", "SGD", "CHF", "CAD"] al = [ "MYR", "RUB", "ZAR", "KRW", "AED", "SAR", "HUF", "PLN", "DKK", "SEK", "NOK", "TRY", "MXN", "THB", ] is_inverse = False if (currency[:3] in al) or (currency[4:] in bl): is_inverse = True currency = currency[4:] + "/" + currency[:3] url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={start_str}&endDate={end_str}&currency={currency}&pageNum=1&pageSize=300" if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y-%m-%d") end_str = end_obj.strftime("%Y-%m-%d") count = (end_obj - start_obj).days + 1 rl = [] # API 很奇怪,需要经常变 UA 才好用 headers = { "Referer": "http://www.chinamoney.com.cn/chinese/bkccpr/", "Origin": "http://www.chinamoney.com.cn", "Host": "www.chinamoney.com.cn", "X-Requested-With": "XMLHttpRequest", } if count <= 360: headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format(start_str=start_str, end_str=end_str, currency=currency), headers=headers, ) rl.extend(r["records"]) else: # data more than 1 year cannot be fetched once due to API limitation sepo_obj = end_obj sepn_obj = sepo_obj - dt.timedelta(360) # sep0_obj = end_obj - dt.timedelta(361) while sepn_obj > start_obj: # [sepn sepo] headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=sepn_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) sepo_obj = sepn_obj - dt.timedelta(1) sepn_obj = sepo_obj - dt.timedelta(360) headers.update({"user-agent": _variate_ua()}) r = rpost_json( url.format( start_str=start_obj.strftime("%Y-%m-%d"), end_str=sepo_obj.strftime("%Y-%m-%d"), currency=currency, ), headers=headers, ) rl.extend(r["records"]) data = {"date": [], "close": []} for d in rl: data["date"].append(pd.Timestamp(d["date"])) data["close"].append(d["values"][0]) df = pd.DataFrame(data) df = df[::-1] df["close"] = pd.to_numeric(df["close"]) if is_inverse: df["close"] = 1 / df["close"] return df def get_fund(code): # 随意设置非空 path,防止嵌套缓存到 fundinfo if code[0] == "F": if code.startswith("F96"): return get_historical_from_ttjj_oversea(code) else: df = fundinfo(code[1:], path="nobackend", priceonly=True).price elif code[0] == "T": df = fundinfo(code[1:], path="nobackend", priceonly=True).price df["netvalue"] = df["totvalue"] elif code[0] == "M": df = mfundinfo(code[1:], path="nobackend").price else: raise ParserFailure("Unknown fund code %s" % code) df["close"] = df["netvalue"] return df[["date", "close"]] def get_historical_from_ttjj_oversea(code, start=None, end=None): if code.startswith("F"): code = code[1:] pagesize = ( dt.datetime.strptime(end, "%Y%m%d") - dt.datetime.strptime(start, "%Y%m%d") ).days + 1 r = rget_json( "http://overseas.1234567.com.cn/overseasapi/OpenApiHander.ashx?api=HKFDApi&m=MethodJZ&hkfcode={hkfcode}&action=2&pageindex=0&pagesize={pagesize}&date1={startdash}&date2={enddash}&callback=".format( hkfcode=get_hkfcode(code), pagesize=pagesize, startdash=start[:4] + "-" + start[4:6] + "-" + start[6:], enddash=end[:4] + "-" + end[4:6] + "-" + end[6:], ) ) datalist = {"date": [], "close": []} for dd in r["Data"]: datalist["date"].append(pd.to_datetime(dd["PDATE"])) datalist["close"].append(dd["NAV"]) df = pd.DataFrame(datalist) df = df[df["date"] <= end] df = df[df["date"] >= start] df = df.sort_values("date", ascending=True) return df def get_portfolio_fromttjj(code, start=None, end=None): startobj = dt.datetime.strptime(start, "%Y%m%d") endobj = dt.datetime.strptime(end, "%Y%m%d") if (endobj - startobj).days < 90: return None # note start is always 1.1 4.1 7.1 10.1 in incremental updates if code.startswith("F"): code = code[1:] r = rget("http://fundf10.eastmoney.com/zcpz_{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") table = s.find("table", class_="tzxq") df = pd.read_html(str(table))[0] df["date"] = pd.to_datetime(df["报告期"]) df["stock_ratio"] = df["股票占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["bond_ratio"] = df["债券占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) df["cash_ratio"] = df["现金占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1])) # df["dr_ratio"] = df["存托凭证占净比"].replace("---", "0%").apply(lambda s: xa.cons._float(s[:-1])) df["assets"] = df["净资产(亿元)"] df = df[::-1] return df[["date", "stock_ratio", "bond_ratio", "cash_ratio", "assets"]] # this is the most elegant approach to dispatch get_daily, the definition can be such simple # you actually don't need to bother on start end blah, everything is taken care of by ``cahcedio`` @data_source("jq") def get_fundshare_byjq(code, **kws): code = _inverse_convert_code(code) df = finance.run_query( query(finance.FUND_SHARE_DAILY) .filter(finance.FUND_SHARE_DAILY.code == code) .filter(finance.FUND_SHARE_DAILY.date >= kws["start"]) .filter(finance.FUND_SHARE_DAILY.date <= kws["end"]) .order_by(finance.FUND_SHARE_DAILY.date) ) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "shares"]] return df @lru_cache(maxsize=1024) def get_futu_id(code): r = rget("https://www.futunn.com/stock/{code}".format(code=code)) sind = r.text.find("securityId") futuid = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip(" ").strip("'") sind = r.text.find("marketType") market = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip().strip("''") return futuid, market def get_futu_historical(code, start=None, end=None): fid, market = get_futu_id(code) r = rget( "https://www.futunn.com/new-quote/kline?security_id={fid}&type=2&market_type={market}".format( fid=fid, market=market ) ) df = pd.DataFrame(r.json()["data"]["list"]) df["date"] = df["k"].map( lambda s: dt.datetime.fromtimestamp(s) .replace(hour=0, minute=0, second=0, microsecond=0) .replace(tzinfo=None) ) df["open"] = df["o"] / 1000 df["close"] = df["c"] / 1000 df["high"] = df["h"] / 1000 df["low"] = df["l"] / 1000 df["volume"] = df["v"] df = df.drop(["k", "t", "o", "c", "h", "l", "v"], axis=1) return df def get_historical_fromsp(code, start=None, end=None, region="us", **kws): if code.startswith("SP"): code = code[2:] if len(code.split(".")) > 1: col = code.split(".")[1] code = code.split(".")[0] else: col = "1" start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 300: flag = "one" elif fromnow < 1000: flag = "three" else: flag = "ten" url = "https://{region}.spindices.com/idsexport/file.xls?\ selectedModule=PerformanceGraphView&selectedSubModule=Graph\ &yearFlag={flag}YearFlag&indexId={code}".format( region=region, flag=flag, code=code ) r = rget( url, headers={ "sec-fetch-dest": "document", "sec-fetch-mode": "navigate", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1", "upgrade-insecure-requests": "1", }, ) df = pd.read_excel(r.content, engine="xlrd") # print(df.iloc[:10]) df = df.iloc[6:] df = df.dropna() df["close"] = df["Unnamed: " + col] df["date"] = pd.to_datetime(df["Unnamed: 0"]) df = df[["date", "close"]] return df def get_historical_frombb(code, start=None, end=None, **kws): if code.startswith("BB-"): code = code[3:] # end_obj = dt.datetime.strptime(end, "%Y%m%d") start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: years = "1_MONTH" elif fromnow < 300: years = "1_YEAR" else: years = "5_YEAR" url = "https://www.bloomberg.com/markets2/api/history/{code}/PX_LAST?\ timeframe={years}&period=daily&volumePeriod=daily".format( years=years, code=code ) r = rget_json( url, headers={ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)", "referer": "https://www.bloomberg.com/quote/{code}".format(code=code), "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "accept": "*/*", }, ) df = pd.DataFrame(r[0]["price"]) df["close"] = df["value"] df["date"] = pd.to_datetime(df["dateTime"]) df = df[["date", "close"]] return df def get_historical_fromft(code, start, end, _type="indices"): if not code.isdigit(): code = get_ft_id(code, _type=_type) start = start.replace("/", "").replace("-", "") end = end.replace("/", "").replace("-", "") start = start[:4] + "/" + start[4:6] + "/" + start[6:] end = end[:4] + "/" + end[4:6] + "/" + end[6:] url = "https://markets.ft.com/data/equities/ajax/\ get-historical-prices?startDate={start}&endDate={end}&symbol={code}".format( code=code, start=start, end=end ) r = rget_json(url, headers={"user-agent": "Mozilla/5.0"}) b = BeautifulSoup(r["html"], "lxml") data = {"date": [], "open": [], "close": [], "high": [], "low": []} for i, td in enumerate(b.findAll("td")): if i % 6 == 0: s = td.find("span").string.split(",")[1:] s = ",".join(s) data["date"].append(dt.datetime.strptime(s, " %B %d, %Y")) elif i % 6 == 1: data["open"].append(_float(td.string)) elif i % 6 == 2: data["high"].append(_float(td.string)) elif i % 6 == 3: data["low"].append(_float(td.string)) elif i % 6 == 4: data["close"].append(_float(td.string)) df = pd.DataFrame(data) df = df.iloc[::-1] return df def get_historical_fromyh(code, start=None, end=None): if code.startswith("YH-"): code = code[3:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: range_ = "1mo" elif fromnow < 50: range_ = "3mo" elif fromnow < 150: range_ = "6mo" elif fromnow < 300: range_ = "1y" elif fromnow < 600: range_ = "2y" elif fromnow < 1500: range_ = "5y" else: range_ = "10y" url = "https://query1.finance.yahoo.com/v8\ /finance/chart/{code}?region=US&lang=en-US&includePrePost=false\ &interval=1d&range={range_}&corsDomain=finance.yahoo.com&.tsrc=finance".format( code=code, range_=range_ ) # 该 API 似乎也支持起止时间选择参数,period1=1427500800&period2=1585353600 # 也可直接从历史数据页面爬取: https://finance.yahoo.com/quote/CSGOLD.SW/history?period1=1427500800&period2=1585353600&interval=1d&filter=history&frequency=1d r = rget_json(url) data = {} datel = [] for t in r["chart"]["result"][0]["timestamp"]: t = dt.datetime.fromtimestamp(t) if t.second != 0: t -= dt.timedelta(hours=8) datel.append(t.replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)) data["date"] = datel for k in ["close", "open", "high", "low"]: data[k] = r["chart"]["result"][0]["indicators"]["quote"][0][k] df = pd.DataFrame(data) return df def get_historical_fromzzindex(code, start, end=None): if code.startswith("ZZ"): code = code[2:] start_obj = dt.datetime.strptime(start, "%Y%m%d") fromnow = (today_obj() - start_obj).days if fromnow < 20: flag = "1%E4%B8%AA%E6%9C%88" elif fromnow < 60: flag = "3%E4%B8%AA%E6%9C%88" # 个月 elif fromnow < 200: flag = "1%E5%B9%B4" # 年 else: flag = "5%E5%B9%B4" r = rget_json( "http://www.csindex.com.cn/zh-CN/indices/index-detail/\ {code}?earnings_performance={flag}&data_type=json".format( code=code, flag=flag ), headers={ "Host": "www.csindex.com.cn", "Referer": "http://www.csindex.com.cn/zh-CN/indices/index-detail/{code}".format( code=code ), "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36", "X-Requested-With": "XMLHttpRequest", "Accept": "application/json, text/javascript, */*; q=0.01", }, ) df = pd.DataFrame(r) df["date"] = pd.to_datetime(df["tradedate"]) df["close"] = df["tclose"].apply(_float) return df[["date", "close"]] def get_historical_fromgzindex(code, start, end): if code.startswith("GZ"): code = code[2:] start = start[:4] + "-" + start[4:6] + "-" + start[6:] end = end[:4] + "-" + end[4:6] + "-" + end[6:] params = { "indexCode": code, "startDate": start, "endDate": end, "frequency": "Day", } r = rget_json( "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat", params=params, ) df = pd.DataFrame(r["data"]["data"], columns=r["data"]["item"]) df["date"] = pd.to_datetime(df["timestamp"]) df = df[["date", "close", "open", "low", "high", "percent", "amount", "volume"]] # TODO: 是否有这些列不全的国证指数? df = df[::-1] return df def get_historical_fromhzindex(code, start, end): if code.startswith("HZ"): code = code[2:] r = rget_json( "http://www.chindices.com/index/values.val?code={code}".format(code=code) ) df = pd.DataFrame(r["data"]) df["date"] = pd.to_datetime(df["date"]) df = df[["date", "price", "pctChange"]] df.rename(columns={"price": "close", "pctChange": "percent"}, inplace=True) df = df[::-1] return df def get_historical_fromesunny(code, start=None, end=None): # code if code.startswith("ESCI"): code = code[4:] + ".ESCI" r = rget( "http://www.esunny.com.cn/chartES/csv/shareday/day_易盛指数_{code}.es".format( code=code ) ) data = [] for l in r.text.split("\n"): row = [s.strip() for s in l.split("|")] # 开 高 低 收 结 if len(row) > 1: data.append(row[:7]) df = pd.DataFrame( data, columns=["date", "open", "high", "low", "close", "settlement", "amount"] ) df["date"] = pd.to_datetime(df["date"]) for c in ["open", "high", "low", "close", "settlement", "amount"]: df[c] = df[c].apply(_float) return df def get_historical_fromycharts(code, start, end, category, metric): params = { "securities": "include:true,id:{code},,".format(code=code), "calcs": "include:true,id:{metric},,".format(metric=metric), "startDate": start, # %m/%d/%Y "endDate": end, # %m/%d/%Y "zoom": "custom", } r = rget_json( "https://ycharts.com/charts/fund_data.json", params=params, headers={ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "ycharts.com", "X-Requested-With": "XMLHttpRequest", "Referer": "https://ycharts.com/{category}/{code}/chart/".format( category=category, code=code ), "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", }, ) df = pd.DataFrame( data=r["chart_data"][0][0]["raw_data"], columns=["timestamp", "close"] ) df["date"] = (df["timestamp"]).apply(ts2pdts) return df[["date", "close"]] @lru_cache() def get_bond_rates(rating, date=None): rating = rating.strip() rating_uid = { "N": "2c9081e50a2f9606010a3068cae70001", # 国债 "AAA": "2c9081e50a2f9606010a309f4af50111", "AAA-": "8a8b2ca045e879bf014607ebef677f8e", "AA+": "2c908188138b62cd01139a2ee6b51e25", "AA": "2c90818812b319130112c279222836c3", "AA-": "8a8b2ca045e879bf014607f9982c7fc0", "A+": "2c9081e91b55cc84011be40946ca0925", "A": "2c9081e91e6a3313011e6d438a58000d", "A-": "8a8b2ca04142df6a014148ca880f3046", "A": "2c9081e91e6a3313011e6d438a58000d", "BBB+": "2c9081e91ea160e5011eab1f116c1a59", "BBB": "8a8b2ca0455847ac0145650780ad68fb", "BB": "8a8b2ca0455847ac0145650ba23b68ff", "B": "8a8b2ca0455847ac0145650c3d726901", } # 上边字典不全,非常欢迎贡献 :) def _fetch(date): r = rpost( "https://yield.chinabond.com.cn/cbweb-mn/yc/searchYc?\ xyzSelect=txy&&workTimes={date}&&dxbj=0&&qxll=0,&&yqqxN=N&&yqqxK=K&&\ ycDefIds={uid}&&wrjxCBFlag=0&&locale=zh_CN".format( uid=rating_uid.get(rating, rating), date=date ), ) return r if not date: date = dt.datetime.today().strftime("%Y-%m-%d") r = _fetch(date) while len(r.text.strip()) < 20: # 当天没有数据,非交易日 date = last_onday(date).strftime("%Y-%m-%d") r = _fetch(date) l = r.json()[0]["seriesData"] l = [t for t in l if t[1]] df = pd.DataFrame(l, columns=["year", "rate"]) return df def get_bond_rates_range(rating, duration=3, freq="W-FRI", start=None, end=None): l = [] if rating.startswith("B-"): rating = rating[2:] rs = rating.split(".") if len(rs) > 1: duration = float(rs[1]) rating = rs[0] for d in pd.date_range(start, end, freq=freq): df = get_bond_rates(rating, d.strftime("%Y-%m-%d")) l.append([d, df[df["year"] <= duration].iloc[-1]["rate"]]) return pd.DataFrame(l, columns=["date", "close"]) @data_source("jq") def get_macro(table, start, end, datecol="stat_year"): df = macro.run_query( query(getattr(macro, table)) .filter(getattr(getattr(macro, table), datecol) >= start) .filter(getattr(getattr(macro, table), datecol) <= end) .order_by(getattr(getattr(macro, table), datecol)) ) df[datecol] = pd.to_datetime(df[datecol]) df["date"] = df[datecol] return df def set_handler(method="daily", f=None): setattr(thismodule, "get_" + method + "_handler", f) def _get_daily( code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws ): if handler: if getattr(thismodule, "get_daily_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_daily_handler") fr = f(**args.locals) if fr is not None: return fr if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dstr2dobj(start) if not _from: if (code.startswith("SH") or code.startswith("SZ")) and code[2:8].isdigit(): _from = "xueqiu" elif code.endswith("/CNY") or code.startswith("CNY/"): _from = "zjj" elif code.isdigit(): _from = "cninvesting" elif code[0] in ["F", "M", "T"] and code[1:].isdigit(): _from = "ttjj" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif code.startswith("SP") and code[2:].split(".")[0].isdigit(): _from = "SP" elif code.startswith("SPC") and code[3:].split(".")[0].isdigit(): _from = "SPC" elif code.startswith("ZZ") and code[4:].isdigit(): # 注意中证系列指数的代码里可能包含字母! _from = "ZZ" elif code.startswith("GZ") and code[-3:].isdigit(): # 注意国证系列指数的代码里可能包含多个字母! _from = "GZ" elif code.startswith("HZ") and code[2:].isdigit(): _from = "HZ" elif code.startswith("ESCI") and code[4:].isdigit(): _from = "ES" elif code.startswith("yc-companies/") or code.startswith("yc-indices/"): _from = "ycharts" params = code.split("/") code = params[1] category = params[0].split("-")[1] if len(params) == 3: metric = params[2] else: if category == "companies": metric = "price" elif category == "indices": metric = "level" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: # peb-000807.XSHG _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code[1:].split("/")) == 2: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股代码 count = (today_obj() - start_obj).days + 1 start_str = start_obj.strftime("%Y/%m/%d") end_str = end_obj.strftime("%Y/%m/%d") if _from in ["cninvesting", "investing", "default", "IN"]: df = get_historical_fromcninvesting(code, start_str, end_str) df = prettify(df) elif _from in ["xueqiu", "xq", "snowball", "XQ"]: code, type_ = decouple_code(code) df = get_historical_fromxq(code, count, type_=type_) df = prettify(df) elif _from in ["zhongjianjia", "zjj", "chinamoney", "ZJJ"]: df = get_rmb(start, end, prev, currency=code) elif _from in ["ttjj", "tiantianjijin", "xalpha", "eastmoney"]: if code.startswith("F96"): df = get_historical_from_ttjj_oversea(code, start=start, end=end) else: df = get_fund(code) elif _from == "peb": if ( code.startswith("SH000") or code.startswith("SZ399") or code.startswith("399") or code.startswith("000") ): df = _get_peb_range(code=code, start=start_str, end=end_str) elif code.startswith("F"): df = get_fund_peb_range(code=code, start=start, end=end) else: df = get_stock_peb_range(code=code, start=start, end=end, wrapper=True) elif _from == "iw": df = _get_index_weight_range(code=code, start=start_str, end=end_str) elif _from == "fs": df = get_fundshare_byjq(code, start=start, end=end) elif _from == "SP": df = get_historical_fromsp(code, start=start, end=end) elif _from == "SPC": df = get_historical_fromsp(code[3:], start=start, end=end, region="chinese") elif _from == "BB": df = get_historical_frombb(code, start=start, end=end) elif _from == "ZZ": df = get_historical_fromzzindex(code, start=start, end=end) elif _from == "GZ": df = get_historical_fromgzindex(code, start=start, end=end) elif _from == "HZ": df = get_historical_fromhzindex(code, start=start, end=end) elif _from == "ES": df = get_historical_fromesunny(code, start=start, end=end) elif _from == "B": df = get_bond_rates_range(code, start=start, end=end) elif _from == "fu": code = code.replace(".", "-") df = get_futu_historical(code, start=start, end=end) elif _from == "ycharts": df = get_historical_fromycharts( code, start=start_obj.strftime("%m/%d/%Y"), end=end_obj.strftime("%m/%d/%Y"), category=category, metric=metric, ) elif _from == "sw": df = get_sw_from_jq(code, start=start, end=end) elif _from == "teb": df = get_teb_range(code, start=start, end=end) elif _from in ["pt", "portfolio"]: df = get_portfolio_fromttjj(code, start=start, end=end) elif _from == "YH": df = get_historical_fromyh(code, start=start, end=end) elif _from in ["FT", "FTI"]: df = get_historical_fromft(code, start=start, end=end) elif _from == "FTE": df = get_historical_fromft(code, start=start, end=end, _type="equities") elif _from == "FTB": df = get_historical_fromft(code, start=start, end=end, _type="bonds") elif _from == "FTF": df = get_historical_fromft(code, start=start, end=end, _type="funds") elif _from == "FTX": df = get_historical_fromft(code, start=start, end=end, _type="currencies") elif _from == "FTC": df = get_historical_fromft(code, start=start, end=end, _type="commodities") elif _from == "INA": # investing app code = get_investing_id(code, app=True) df = get_historical_fromcninvesting(code, start_str, end_str, app=True) df = prettify(df) elif _from == "mcy": df = get_macro(code, start=start[:4], end=end[:4], datecol="stat_year") elif _from == "mcq": df = get_macro(code, start=start, end=end, datecol="stat_quarter") elif _from == "mcm": df = get_macro(code, start=start, end=end, datecol="stat_month") elif _from == "mcd": df = get_macro(code, start=start, end=end, datecol="day") else: raise ParserFailure("no such data source: %s" % _from) if wrapper or len(df) == 0: return df else: df = df[df.date <= end_str] df = df[df.date >= start_str] return df def get_xueqiu_rt(code, token="a664afb60c7036c7947578ac1a5860c4cfb6b3b5"): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] url = "https://stock.xueqiu.com/v5/stock/quote.json?symbol={code}&extend=detail" r = rget_json( url.format(code=code), cookies={"xq_a_token": token}, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)"}, ) n = r["data"]["quote"]["name"] q = r["data"]["quote"]["current"] try: q = _float(q) except TypeError: # 针对雪球实时在9点后开盘前可能出现其他情形的fixup, 效果待 check # 现在的怀疑是在9am 到9:15 am, 雪球 API current 字段返回 Null q = _float(r["data"]["quote"]["last_close"]) q_ext = r["data"]["quote"].get("current_ext", None) percent = r["data"]["quote"]["percent"] try: percent = _float(percent) except: pass currency = r["data"]["quote"]["currency"] market = r["data"]["market"]["region"] timestr = dt.datetime.fromtimestamp(r["data"]["quote"]["time"] / 1000).strftime( "%Y-%m-%d %H:%M:%S" ) if r["data"]["quote"].get("timestamp_ext", None): time_ext = dt.datetime.fromtimestamp( r["data"]["quote"]["timestamp_ext"] / 1000 ).strftime("%Y-%m-%d %H:%M:%S") else: time_ext = None share = r["data"]["quote"]["total_shares"] fshare = r["data"]["quote"]["float_shares"] volume = r["data"]["quote"]["volume"] return { "name": n, "current": q, "percent": percent, "current_ext": _float(q_ext) if q_ext else None, "currency": currency, "market": market, # HK, US, CN "time": timestr, "time_ext": time_ext, "totshare": share, "floatshare": fshare, "volume": volume, } def get_cninvesting_rt(suburl, app=False): if not app: url = "https://cn.investing.com" else: url = "https://cnappapi.investing.com" if not suburl.startswith("/"): url += "/" url += suburl if not app: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36" } else: headers = { "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-cn", "Cache-Control": "no-cache", "Connection": "keep-alive", "User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0", "ccode": "CN", #'ccode_time': '1585551041.986028', "x-app-ver": "117", "x-meta-ver": "14", "x-os": "ios", "x-uuid": str(uuid4()), "Host": "cn.investing.com", "X-Requested-With": "XMLHttpRequest", } r = rget( url, headers=headers, ) s = BeautifulSoup(r.text, "lxml") last_last = s.find("span", id="last_last") q = _float(last_last.string) name = s.find("h1").string.strip() ind = 0 timestr = s.select('span[class*="ClockBigIcon"]+span')[0].text l = s.find("div", class_="lighterGrayFont").contents for i, c in enumerate(l): if isinstance(c, str) and c.strip() == "货币": ind = i break if ind == 0: currency = None else: currency = l[ind - 1].string percent = _float( s.find("span", attrs={"dir": "ltr", "class": "parentheses"}).string[:-1] ) panhou = s.find("div", class_="afterHoursInfo") if panhou: q_ext = _float(panhou.find("span").string) else: q_ext = None market = None for span in s.findAll("span", class_="elp"): if span.find("a") and span.find("a")["href"].startswith("/markets"): market = span.string market = region_trans.get(market, market) time_ext = s.select("div[class~=lastUpdated]") if time_ext: time_ext = time_ext[0].text.strip() else: time_ext = None d = { "name": name, "current": q, "current_ext": q_ext, "time": timestr, "time_ext": time_ext, "currency": currency, "percent": percent, "market": market, } if suburl.startswith("commodities"): # 商品期货展期日 try: d["rollover"] = s.select("span[class*=float_lang_base_2]")[10].string d["lastrollover"] = s.select("span[class*=float_lang_base_2]")[13].string except (ValueError, IndexError, AttributeError): logger.warning("%s cannot extract rollover date" % suburl) # in case some commodities with strong page structure return d def get_rt_from_sina(code): if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): tinycode = code[:2].lower() + code[2:] if code.startswith("HK"): # 港股额外要求实时 tinycode = "rt_" + tinycode else: # 美股 tinycode = "gb_" if code.startswith("."): code = code[1:] tinycode += code.lower() r = rget("https://hq.sinajs.cn/list={tinycode}".format(tinycode=tinycode)) l = r.text.split("=")[1].split(",") d = {} d["name"] = l[0].strip('"') if ( code.startswith("SH") or code.startswith("SZ") or code.startswith("HK") ) and code[2:].isdigit(): # TODO: 20200819: API seems changed a bit, index shift? # or things may get zero when the market is closed? if code.startswith("HK"): d["current"] = float(l[9]) # 英文股票名称占位 d["currency"] = "HKD" d["percent"] = round(float(l[8]), 2) d["market"] = "HK" d["time"] = l[17] + " " + l[18] d["current_ext"] = None else: # A 股 d["current"] = float(l[3]) d["currency"] = "CNY" d["percent"] = round((float(l[3]) / float(l[2]) - 1) * 100, 2) d["market"] = "CN" d["time"] = l[-4] + " " + l[-3] for i in range(10, 19)[::2]: d["buy" + str(int((i - 8) / 2))] = (l[i + 1], l[i]) for i in range(20, 29)[::2]: d["sell" + str(int((i - 18) / 2))] = (l[i + 1], l[i]) d["current_ext"] = None else: d["currency"] = "USD" d["current"] = float(l[1]) d["percent"] = float(l[2]) d["current_ext"] = _float(l[21]) if _float(l[21]) > 0 else None d["market"] = "US" d["time"] = l[3] return d def make_ft_url(code, _type="indices"): if _type == "indices": url = "https://markets.ft.com/data/indices/tearsheet/summary?s={code}".format( code=code ) elif _type == "commodities": url = ( "https://markets.ft.com/data/commodities/tearsheet/summary?c={code}".format( code=code ) ) elif _type == "currencies": url = ( "https://markets.ft.com/data/currencies/tearsheet/summary?s={code}".format( code=code ) ) elif _type == "funds": url = "https://markets.ft.com/data/funds/tearsheet/summary?s={code}".format( code=code ) elif _type == "equities": url = "https://markets.ft.com/data/equities/tearsheet/summary?s={code}".format( code=code ) elif _type == "bonds": url = "https://markets.ft.com/data/bonds/tearsheet/summary?s={code}".format( code=code ) else: raise ParserFailure("no reconginzed type for ft datasource: %s" % _type) return url @lru_cache(maxsize=1024) def get_ft_id(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") return eval( b.find("section", class_="mod-tearsheet-add-to-watchlist")["data-mod-config"] )["xid"] def get_rt_from_ft(code, _type="indices"): url = make_ft_url(code, _type=_type) r = rget(url) b = BeautifulSoup(r.text, "lxml") d = {} d["name"] = b.find("h1").string d["current"] = _float(b.find("span", class_="mod-ui-data-list__value").string) d["percent"] = _float( b.select("span[class^='mod-format--']")[0].text.split("/")[-1].strip()[:-1] ) d["current_ext"] = None d["market"] = None d["currency"] = b.find("span", class_="mod-ui-data-list__label").string.split("(")[ 1 ][:-1] d["time"] = b.find("div", class_="mod-disclaimer").string return d def get_rt_from_ycharts(code): if code.startswith("yc-"): code = code[3:] url = "https://ycharts.com/" + code r = rget(url) s = BeautifulSoup(r.text, "lxml") qdiv = s.select("div.index-rank.col-auto") # current spans = [s for s in qdiv[0].contents if s != "\n" and s.contents] d = {} d["name"] = s.select("h1,h3[class=securityName]")[0].text.strip() d["current"], d["percent"] = ( _float(spans[0].string), # current, _float(spans[1].contents[-2].string[1:-1]), # percent ) l = [ c.strip() for c in s.select("span[class=index-info]")[0].string.split("\n") if c.strip() ] d["time"] = l[1] d["currency"] = l[0].split(" ")[0].strip() d["market"] = None return d @lru_cache_time(ttl=300, maxsize=512) def get_newest_netvalue(code): code = code[1:] r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) s = BeautifulSoup(r.text, "lxml") return ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) @lru_cache(maxsize=512) def get_hkfcode(code): if code.startswith("F"): code = code[1:] page = rget("http://overseas.1234567.com.cn/{code}".format(code=code)).text page.find("hkfcode") hkfcode = ( page[page.find("hkfcode") :] .split("=")[1] .split(";")[0] .lstrip() .lstrip("'") .strip("'") ) return hkfcode def get_rt_from_ttjj_oversea(code): if code.startswith("F"): code = code[1:] if not code.startswith("96"): raise ValueError("%s is not an oversea fund" % code) r = rget("http://overseas.1234567.com.cn/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") start = s.select("dl.dataItem02")[0].text start = start.split("(")[1].split(")")[0] name = s.select("div[class='fundDetail-tit']")[0].text.split("(")[0].strip() name = name.split("(")[0].strip() value = _float(s.select("span.ui-font-large.ui-num")[0].text) date = ( s.select("dl[class='dataItem01']")[0] .find("p") .text.split("(")[-1] .split(")")[0] ) infol = [ r for r in s.select("div[class='infoOfFund']")[0].text.split("\n") if r.strip() ] return { "name": name, "time": date, "current": value, "market": "CN", "currency": None, # 很可能存在非人民币计价的互认基金 "current_ext": None, "type": infol[0].split(":")[1].strip(), "scale": infol[1].split(":")[1].strip(), "manager": infol[2].split(":")[1].strip(), "startdate": start, } @lru_cache_time(ttl=600, maxsize=512) def get_rt_from_ttjj(code): code = code[1:] if code.startswith("96"): return get_rt_from_ttjj_oversea(code) r = rget("http://fund.eastmoney.com/{code}.html".format(code=code)) r.encoding = "utf-8" s = BeautifulSoup(r.text, "lxml") name = s.select("div[style='float: left']")[0].text.split("(")[0] if s.findAll("dd", class_="dataNums")[1].find( "span", class_="ui-font-large" ): # 非货币基金 value, date = ( float( s.findAll("dd", class_="dataNums")[1] .find("span", class_="ui-font-large") .string ), str(s.findAll("dt")[1]).split("(")[1].split(")")[0][7:], ) estimate = s.select("span[id=gz_gsz]")[0].text # after loading if estimate == "--": gsz = rget( "http://fundgz.1234567.com.cn/js/{code}.js".format(code=code), headers={ "Host": "fundgz.1234567.com.cn", "Referer": "http://fund.eastmoney.com/", }, ) try: # in case eval error gsz_dict = eval(gsz.text[8:-2]) estimate = _float(gsz_dict["gsz"]) estimate_time = gsz_dict["gztime"] except: estimate = None else: try: estimate = _float(estimate) except ValueError: logger.warning("unrecognized estimate netvalue %s" % estimate) estimate = None else: value, date = ( s.findAll("dd", class_="dataNums")[1].text, str(s.findAll("dt")[1]).split("(")[1].split(")")[0], ) estimate = None status = s.select("span[class='staticCell']")[0].text.strip() tb = s.select("div.infoOfFund > table >tr>td") infol = [i.text for i in tb] try: estimate_time except NameError: estimate_time = None return { "name": name, "time": date, "current": value, "market": "CN", "currency": "CNY", "current_ext": None, "status": status, "type": infol[0].split(":")[1].split("\xa0")[0], "scale": infol[1].split(":")[1], "manager": infol[2].split(":")[1], "company": infol[4].split(":")[1], "estimate": estimate, "estimate_time": estimate_time, } # 是否有美元份额计价的基金会出问题? @lru_cache(2048) def get_fund_type(code): code = code[-6:] t = get_rt("F" + code)["type"] if t in ["联接基金", "股票指数"] or t.startswith("ETF"): return "指数基金" elif t.startswith("QDII"): return "QDII" elif t.startswith("股票"): return "股票基金" elif t.startswith("混合"): return "混合基金" elif t.startswith("债券"): return "债券基金" elif t.startswith("货币"): return "货币基金" else: return "其他" def get_rt( code, _from=None, double_check=False, double_check_threhold=0.005, handler=True ): # 对于一些标的,get_rt 的主任务可能不是 current 价格,而是去拿 market currency 这些元数据 # 现在用的新浪实时数据源延迟严重, double check 并不靠谱,港股数据似乎有15分钟延迟(已解决) # 雪球实时和新浪实时在9:00之后一段时间可能都有问题 # FT 数据源有10到20分钟的延迟 if handler: if getattr(thismodule, "get_rt_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_rt_handler") fr = f(**args.locals) if fr: return fr if not _from: # if code.startswith("HK") and code[2:].isdigit(): # _from = "xueqiu" if code.startswith("yc-"): _from = "ycharts" elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif (code.startswith("F") or code.startswith("T")) and code[1:].isdigit(): _from = "ttjj" elif len(code.split("/")) > 1: _from = "investing" else: # 默认启用雪球实时,新浪纯指数行情不完整 _from = "xueqiu" if _from in ["cninvesting", "investing"]: try: return get_cninvesting_rt(code) except Exception as e: logger.warning( "Fails due to %s, now trying app source of investing.com" % e.args[0] ) return get_cninvesting_rt(code, app=True) elif double_check and _from in ["xueqiu", "sina"]: r1 = get_xueqiu_rt(code, token=get_token()) r2 = get_rt_from_sina(code) if abs(r1["current"] / r2["current"] - 1) > double_check_threhold: raise DataPossiblyWrong("realtime data unmatch for %s" % code) return r2 elif _from in ["xueqiu", "xq", "snowball"]: try: return get_xueqiu_rt(code, token=get_token()) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from sina" % e.args[0] ) return get_rt_from_sina(code) elif _from in ["sina", "sn", "xinlang"]: try: return get_rt_from_sina(code) except (IndexError, ValueError, AttributeError, TypeError) as e: # 默认雪球实时引入备份机制 logging.warning( "Fails due to %s, now trying backup data source from xueqiu" % e.args[0] ) return get_xueqiu_rt(code, token=get_token()) elif _from in ["ttjj"]: return get_rt_from_ttjj(code) elif _from in ["FT", "ft", "FTI"]: return get_rt_from_ft(code) elif _from == "FTE": return get_rt_from_ft(code, _type="equities") elif _from == "FTB": return get_rt_from_ft(code, _type="bonds") elif _from == "FTF": return get_rt_from_ft(code, _type="funds") elif _from == "FTX": return get_rt_from_ft(code, _type="currencies") elif _from == "FTC": return get_rt_from_ft(code, _type="commodities") elif _from in ["INA"]: # investing app return get_cninvesting_rt(code, app=True) elif _from in ["yc", "ycharts"]: return get_rt_from_ycharts(code) else: raise ParserFailure("unrecoginzed _from for %s" % _from) get_realtime = get_rt get_now = get_rt _cached_data = {} def reset_cache(): global _cached_data _cached_data = {} setattr(thismodule, "cached_dict", {}) def cached(s): def cached_start(f): @wraps(f) def wrapper(*args, **kws): print("cached function is deprecated, please instead use cachedio") if args: code = args[0] else: code = kws.get("code") start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) if not prev: prev = 365 if not end: end_obj = today_obj() else: end_obj = dstr2dobj(end) if not start: start_obj = end_obj - dt.timedelta(prev) else: start_obj = dstr2dobj(start) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") kws["start"] = s kws["end"] = dt.datetime.now().strftime("%Y%m%d") global _cached_data _cached_data.setdefault(s, {}) if code not in _cached_data[s]: df = f(*args, **kws) # print("cached %s" % code) _cached_data[s][code] = df else: pass # print("directly call cache") df = _cached_data[s][code] df = df[df["date"] <= end_str] df = df[df["date"] >= start_str] return df return wrapper return cached_start def cachedio(**ioconf): def cached(f): @wraps(f) def wrapper(*args, **kws): if args: code = args[0] else: code = kws.get("code") date = ioconf.get("date", "date") # 没利用上这个栏的名字变化 precached = ioconf.get("precached", None) precached = kws.get("precached", precached) key = kws.get("key", code) key = key.replace("/", " ") key_func = ioconf.get("key_func", None) key_func = ioconf.get("keyfunc", key_func) if key_func is not None: key = key_func(key) defaultend = ioconf.get("defaultend", today_obj) defaultend = ioconf.get("default_end", defaultend) defaultprev = ioconf.get("defaultprev", 365) defaultprev = ioconf.get("default_prev", defaultprev) if isinstance(defaultend, str): defaultend = defaultend.replace("/", "").replace("-", "") defaultend = dt.datetime.strptime(defaultend, "%Y%m%d") if callable(defaultend): defaultend = defaultend() start = kws.get("start", None) end = kws.get("end", None) prev = kws.get("prev", None) prefix = ioconf.get("prefix", "") key = prefix + key if precached: precached = precached.replace("/", "").replace("-", "") precached_obj = dt.datetime.strptime(precached, "%Y%m%d") if not prev: prev = defaultprev if not end: end_obj = defaultend else: end_obj = dt.datetime.strptime( end.replace("/", "").replace("-", ""), "%Y%m%d" ) if not start: start_obj = end_obj - dt.timedelta(days=prev) else: start_obj = dt.datetime.strptime( start.replace("/", "").replace("-", ""), "%Y%m%d" ) start_str = start_obj.strftime("%Y%m%d") end_str = end_obj.strftime("%Y%m%d") backend = ioconf.get("backend") backend = kws.get("backend", backend) # if backend == "sql": # reserved for case insensitive database settings # key = key.lower() refresh = ioconf.get("refresh", False) refresh = kws.get("refresh", refresh) fetchonly = ioconf.get("fetchonly", False) fetchonly = ioconf.get("fetch_only", fetchonly) fetchonly = kws.get("fetchonly", fetchonly) fetchonly = kws.get("fetch_only", fetchonly) path = ioconf.get("path") path = kws.get("path", path) kws["start"] = start_str kws["end"] = end_str if not backend: df = f(*args, **kws) df = df[df["date"] <= kws["end"]] df = df[df["date"] >= kws["start"]] return df else: if backend == "csv": key = key + ".csv" if not getattr(thismodule, "cached_dict", None): setattr(thismodule, "cached_dict", {}) if refresh: is_changed = True df0 = f(*args, **kws) else: # non refresh try: if backend == "csv": if key in getattr(thismodule, "cached_dict"): # 即使硬盘级别的缓存,也有内存层,加快读写速度 df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": if key in getattr(thismodule, "cached_dict"): df0 = getattr(thismodule, "cached_dict")[key] else: df0 = pd.read_sql(key, path) elif backend == "memory": df0 = getattr(thismodule, "cached_dict")[key] else: raise ValueError("no %s option for backend" % backend) df0[date] = pd.to_datetime(df0[date]) # 向前延拓 is_changed = False if df0.iloc[0][date] > start_obj and not fetchonly: kws["start"] = start_str kws["end"] = ( df0.iloc[0][date] - pd.Timedelta(days=1) ).strftime("%Y%m%d") if has_weekday(kws["start"], kws["end"]): # 考虑到海外市场的不同情况,不用 opendate 判断,采取保守型判别 df1 = f(*args, **kws) if df1 is not None and len(df1) > 0: df1 = df1[df1["date"] <= kws["end"]] if df1 is not None and len(df1) > 0: is_changed = True df0 = df1.append(df0, ignore_index=True, sort=False) # 向后延拓 if df0.iloc[-1][date] < end_obj and not fetchonly: nextday_str = ( df0.iloc[-1][date] + dt.timedelta(days=1) ).strftime("%Y%m%d") if len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1: kws["start"] = (df0.iloc[-1][date]).strftime("%Y%m%d") else: # 单日多行的表默认最后一日是准确的,不再刷新了 kws["start"] = nextday_str kws["end"] = end_str if has_weekday(nextday_str, kws["end"]): # 新更新的日期里有工作日 df2 = f(*args, **kws) if df2 is not None and len(df2) > 0: df2 = df2[df2["date"] >= kws["start"]] if df2 is not None and len(df2) > 0: is_changed = True if ( len(df0[df0["date"] == df0.iloc[-1]["date"]]) == 1 ): df0 = df0.iloc[:-1] df0 = df0.append(df2, ignore_index=True, sort=False) # 注意这里抹去更新了原有最后一天的缓存,这是因为日线最新一天可能有实时数据污染 except (FileNotFoundError, exc.ProgrammingError, KeyError) as e: if fetchonly: logger.error( "no cache in backend for %s but you insist `fetchonly`" % code ) raise e if precached: if start_obj > precached_obj: kws["start"] = precached if end_obj < today_obj(): kws["end"] = ( today_obj() - dt.timedelta(days=1) ).strftime("%Y%m%d") is_changed = True df0 = f(*args, **kws) if df0 is not None and len(df0) > 0 and is_changed: if backend == "csv": df0.to_csv(os.path.join(path, key), index=False) elif backend == "sql": df0.to_sql(key, con=path, if_exists="replace", index=False) # elif backend == "memory": # 总是刷新内存层,即使是硬盘缓存 d = getattr(thismodule, "cached_dict") d[key] = df0 if df0 is not None and len(df0) > 0: df0 = df0[df0["date"] <= end_str] df0 = df0[df0["date"] >= start_str] return df0 return wrapper return cached def fetch_backend(key): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" try: if backend == "csv": df0 = pd.read_csv(os.path.join(path, key)) elif backend == "sql": df0 = pd.read_sql(key, path) else: raise ValueError("no %s option for backend" % backend) return df0 except (FileNotFoundError, exc.ProgrammingError, KeyError): return None def save_backend(key, df, mode="a", header=False): prefix = ioconf.get("prefix", "") key = prefix + key backend = ioconf.get("backend") path = ioconf.get("path") if backend == "csv": key = key + ".csv" if backend == "csv": if mode == "a": df.to_csv(os.path.join(path, key), index=False, header=header, mode=mode) else: df.to_csv(os.path.join(path, key), index=False, mode=mode) elif backend == "sql": if mode == "a": mode = "append" else: mode = "replace" df.to_sql(key, con=path, if_exists=mode, index=False) else: raise ValueError("no %s option for backend" % backend) logger.debug("%s saved into backend successfully" % key) def check_cache(*args, omit_lines=0, **kws): if omit_lines == 0: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True) .equals(get_daily(*args, **kws).reset_index(drop=True)) ) else: assert ( _get_daily(*args, wrapper=False, **kws) .reset_index(drop=True)[:-omit_lines] .equals(get_daily(*args, **kws).reset_index(drop=True)[:-omit_lines]) ) @data_source("jq") def _get_index_weight_range(code, start, end): if len(code.split(".")) != 2: code = _inverse_convert_code(code) start_obj = dt.datetime.strptime(start.replace("-", "").replace("/", ""), "%Y%m%d") end_obj = dt.datetime.strptime(end.replace("-", "").replace("/", ""), "%Y%m%d") start_m = start_obj.replace(day=1) if start_m < start_obj: start_m = start_m + relativedelta(months=1) end_m = end_obj.replace(day=1) if end_obj < end_m: end_m = end_m - relativedelta(months=1) d = start_m df = pd.DataFrame({"code": [], "weight": [], "display_name": [], "date": []}) while True: if d > end_m: df["date"] = pd.to_datetime(df["date"]) return df logger.debug("fetch index weight on %s for %s" % (d, code)) df0 = get_index_weights(index_id=code, date=d.strftime("%Y-%m-%d")) df0["code"] = df0.index df = df.append(df0, ignore_index=True, sort=False) d = d + relativedelta(months=1) @data_source("jq") def _get_peb_range(code, start, end): # 盈利,净资产,总市值 if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) logger.debug("compute pe pb on %s" % d) r = get_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def get_stock_peb_range(code, start, end, wrapper=False): if code.startswith("HK") and code[2:].isdigit(): code = code[2:] count = (today_obj() - dt.datetime.strptime(start, "%Y%m%d")).days df = get_historical_fromxq(code, count, full=True) df = df[["date", "pe", "pb", "ps"]] if not wrapper: df = df[df["date"] >= start] df = df[df["date"] <= end] return df @lru_cache() def ttjjcode(code): code = code.strip() if code.endswith(".HK"): return "HK" + code[:-3] elif code.endswith(".US"): return code[:-3] elif code.isdigit() and len(code) == 5: return "HK" + code elif code.isdigit() and len(code) == 6: if ( code.startswith("16") or code.startswith("15") or code.startswith("12") or code.startswith("0") or code.startswith("3") ): # 注意这里只能对应个股,指数代码有重叠没有办法的事 return "SZ" + code elif code.startswith("5") or code.startswith("6") or code.startswith("11"): return "SH" + code else: logger.warning("unrecognized code format %s" % code) return "0" else: logger.info("not so sure about code format %s, taken as US stock" % code) return code def get_fund_peb(code, date, threhold=0.3): if code.startswith("F"): code = code[1:] date = date.replace("/", "").replace("-", "") d = dt.datetime.strptime(date, "%Y%m%d") if d.month > 3 and d.month < 8: year = d.year - 1 season = 4 elif d.month <= 3: year = d.year - 1 season = 2 else: year = d.year season = 2 # season 只选 2,4, 具有更详细的持仓信息 df = get_fund_holdings(code, year, season) if df is None: if season == 4: season = 2 else: year -= 1 season = 4 df = get_fund_holdings(code, year, season) if df is None: logger.warning("%s seems has no holdings data in this time %s" % (code, year)) return {"pe": None, "pb": None} df = df[df["ratio"] >= threhold] df["scode"] = df["code"].apply(ttjjcode) df = df[df["scode"] != "0"] if len(df) == 0: return {"pe": None, "pb": None} pel, pbl = [], [] for i, r in df.iterrows(): try: fdf = get_daily("peb-" + r["scode"], end=date, prev=60) if len(fdf) == 0: # 已退市或改名 logger.warning("%s: 无法获取,可能已退市,当时休市或改名" % r["scode"]) pel.append(None) pbl.append(None) else: fdf = fdf.iloc[-1] pel.append(fdf["pe"]) pbl.append(fdf["pb"]) except (KeyError, TypeError, IndexError) as e: logger.warning( "%s: 获取历史估值出现问题: %s, 可能由于网站故障或股票代码非中美市场" % (r["scode"], e.args[0]) ) pel.append(None) pbl.append(None) df["pe"] = pel df["pb"] = pbl r = {} pedf = df[~pd.isna(df["pe"])] pbdf = df[~pd.isna(df["pb"])] if len(pbdf) < 0.5 * len(df): # 有时候会有个别标的有pb值 r["pb"] = None else: pbdf["b"] = pbdf["ratio"] / (pbdf["pb"] + 0.000001) r["pb"] = pbdf.ratio.sum() / pbdf.b.sum() if len(pedf) == 0: r["pe"] = None else: pedf["e"] = pedf["ratio"] / (pedf["pe"] + 0.000001) r["pe"] = pedf.ratio.sum() / pedf.e.sum() return r def get_fund_peb_range(code, start, end): if code.startswith("F"): code = code[1:] data = {"date": [], "pe": [], "pb": []} for d in pd.date_range(start=start, end=end, freq="W-FRI"): data["date"].append(d) r = get_fund_peb(code, date=d.strftime("%Y-%m-%d")) data["pe"].append(r["pe"]) data["pb"].append(r["pb"]) return pd.DataFrame(data) def set_backend(**ioconf): if not ioconf: ioconf = {"backend": "memory"} get_daily = cachedio(**ioconf)(_get_daily) prefix = ioconf.get("prefix", "") ioconf["prefix"] = "iw-" + prefix get_index_weight_range = cachedio(**ioconf)(_get_index_weight_range) ioconf["prefix"] = "peb-" + prefix get_peb_range = cachedio(**ioconf)(_get_peb_range) setattr(thismodule, "get_daily", get_daily) setattr(xamodule, "get_daily", get_daily) setattr(thismodule, "get_index_weight_range", get_index_weight_range) setattr(thismodule, "get_peb_range", get_peb_range) ioconf["prefix"] = prefix setattr(thismodule, "ioconf", ioconf) set_backend() @data_source("jq") def get_peb(index, date=None, table=False): if len(index.split(".")) == 2: index = _convert_code(index) middle = dt.datetime.strptime( date.replace("/", "").replace("-", ""), "%Y%m%d" ).replace(day=1) iwdf = get_index_weight_range( index, start=(middle - dt.timedelta(days=10)).strftime("%Y-%m-%d"), end=(middle + dt.timedelta(days=6)).strftime("%Y-%m-%d"), ) q = query(valuation).filter(valuation.code.in_(list(iwdf.code))) logger.debug("get_fundamentals on %s" % (date)) df = get_fundamentals(q, date=date) df = df.merge(iwdf, on="code") df["e"] = df["weight"] / df["pe_ratio"] df["b"] = df["weight"] / df["pb_ratio"] df["p"] = df["weight"] tote = df.e.sum() totb = df.b.sum() if table: return df return { "pe": (round(100.0 / tote, 3) if tote != 0 else np.inf), "pb": (round(100.0 / totb, 3) if totb != 0 else np.inf), } @data_source("jq") def get_sw_from_jq(code, start=None, end=None, **kws): logger.debug("get sw data of %s" % code) df = finance.run_query( query(finance.SW1_DAILY_VALUATION) .filter(finance.SW1_DAILY_VALUATION.date >= start) .filter(finance.SW1_DAILY_VALUATION.date <= end) .filter(finance.SW1_DAILY_VALUATION.code == code) .order_by(finance.SW1_DAILY_VALUATION.date.asc()) ) df["date"] = pd.to_datetime(df["date"]) return df @data_source("jq") def get_teb(code, date): if len(code.split(".")) != 2: code = _inverse_convert_code(code) sl = get_index_stocks(code, date=date) logger.debug("get fundamentals from jq for %s" % code) df = get_fundamentals(query(valuation).filter(valuation.code.in_(sl)), date=date) df["e"] = df["market_cap"] / df["pe_ratio"] df["b"] = df["market_cap"] / df["pb_ratio"] return {"e": df["e"].sum(), "b": df["b"].sum(), "m": df["market_cap"].sum()} # 亿人民币 def get_teb_range(code, start, end, freq="W-FRI"): if len(code.split(".")) != 2: code = _inverse_convert_code(code) data = {"date": [], "e": [], "b": [], "m": []} for d in pd.date_range(start, end, freq=freq): data["date"].append(d) r = get_teb(code, d.strftime("%Y-%m-%d")) data["e"].append(r["e"]) data["b"].append(r["b"]) data["m"].append(r["m"]) df = pd.DataFrame(data) return df def _convert_code(code): no, mk = code.split(".") if mk == "XSHG": return "SH" + no elif mk == "XSHE": return "SZ" + no def _inverse_convert_code(code): if code.startswith("SH"): return code[2:] + ".XSHG" elif code.startswith("SZ"): return code[2:] + ".XSHE" @lru_cache_time(ttl=60, maxsize=512) def get_bar( code, prev=24, interval=3600, _from=None, handler=True, start=None, end=None ): if handler: if getattr(thismodule, "get_bar_handler", None): args = inspect.getargvalues(inspect.currentframe()) f = getattr(thismodule, "get_bar_handler") fr = f(**args.locals) if fr is not None: return fr if not _from: if ( (start is not None) and (end is not None) and (code.startswith("SH") or code.startswith("SZ")) ): _from = "jq" elif code.startswith("SH") or code.startswith("SZ"): _from = "xueqiu" elif code.isdigit(): _from = "cninvesting" elif code.startswith("HK") and code[2:7].isdigit(): _from = "xueqiu" code = code[2:] elif len(code.split("-")) >= 2 and len(code.split("-")[0]) <= 3: _from = code.split("-")[0] code = "-".join(code.split("-")[1:]) elif len(code.split("/")) > 1: _from = "cninvesting" code = get_investing_id(code) else: _from = "xueqiu" # 美股 if _from in ["xq", "xueqiu", "XQ"]: return get_bar_fromxq(code, prev, interval) elif _from in ["IN", "cninvesting", "investing"]: return get_bar_frominvesting(code, prev, interval) elif _from in ["INA"]: return get_bar_frominvesting(code, prev, interval) # 这里 investing app 源是 404,只能用网页源 elif _from in ["jq"]: code, type_ = decouple_code(code) # 关于复权,聚宽各个时间密度的数据都有复权,雪球源日线以上的高频数据没有复权 type_map = {"after": "post", "before": "pre", "normal": None} return get_bar_fromjq( code, start=start, end=end, interval=interval, fq=type_map[type_] ) elif _from in ["wsj"]: return get_bar_fromwsj(code, interval=interval)[-prev:] else: raise ParserFailure("unrecoginized _from %s" % _from) @data_source("jq") def get_bar_fromjq(code, start, end, interval, fq="pre"): code = _inverse_convert_code(code) trans = { "60": "1m", "120": "2m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "daily", } interval = trans.get(str(interval), interval) logger.debug("calling ``get_price`` from jq with %s" % code) return get_price(code, start_date=start, end_date=end, frequency=interval, fq=fq) def get_bar_frominvesting(code, prev=120, interval=3600): if interval == "day": interval = 86400 elif interval == "hour": interval = 3600 elif interval == "minute": interval = 60 elif interval == 86400 * 7: interval = "week" elif interval == 86400 * 30: interval = "month" if len(code.split("/")) == 2: code = get_investing_id(code) url = "https://cn.investing.com" headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\ AppleWebKit/537.36 (KHTML, like Gecko)", "Host": "cn.investing.com", "Referer": "https://cn.investing.com/commodities/", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "X-Requested-With": "XMLHttpRequest", } r = rget( url + "/common/modules/js_instrument_chart/api/data.php?pair_id={code}&pair_id_for_news={code}\ &chart_type=area&pair_interval={interval}&candle_count={prev}&events=yes&volume_series=yes&period=".format( code=code, prev=str(prev), interval=str(interval) ), headers=headers, ) if not r.text: return # None r = r.json() df = pd.DataFrame(r["candles"], columns=["date", "close", "0", "1"]) df = df.drop(["0", "1"], axis=1) df["date"] = df["date"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) return df def get_bar_fromxq(code, prev, interval=3600): # max interval is also around 500 trans = { "60": "1m", "300": "5m", "900": "15m", "1800": "30m", "3600": "60m", "7200": "120m", "86400": "day", "604800": "week", "2592000": "month", } code, type_ = decouple_code(code) interval = trans.get(str(interval), interval) url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period={interval}&type={type_}\ &count=-{prev}&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance".format( code=code, tomorrow=int(tomorrow_ts() * 1000), prev=prev, interval=interval, type_=type_, ) r = rget( url, headers={"user-agent": "Mozilla/5.0"}, cookies={"xq_a_token": get_token()} ) if not r.text: return # None else: df = pd.DataFrame(r.json()["data"]["item"], columns=r.json()["data"]["column"]) df["date"] = df["timestamp"].apply( lambda t: dt.datetime.fromtimestamp(t / 1000, tz=tz_bj).replace(tzinfo=None) ) df = df[ [ "date", "open", "high", "low", "close", "volume", "turnoverrate", "percent", ] ] return df def get_bar_fromwsj(code, token=None, interval=3600): # proxy required # code = "FUTURE/US/XNYM/CLM20" # TODO: also not explore the code format here extensively trans = {"3600": "1H"} # TODO: there is other freq tags, but I have no time to explore them, contributions are welcome:) freq = trans.get(str(interval), interval) if not token: token = "cecc4267a0194af89ca343805a3e57af" # the thing I am concerned here is whether token is refreshed params = { "json": '{"Step":"PT%s","TimeFrame":"D5","EntitlementToken":"%s",\ "IncludeMockTick":true,"FilterNullSlots":false,"FilterClosedPoints":true,"IncludeClosedSlots":false,\ "IncludeOfficialClose":true,"InjectOpen":false,"ShowPreMarket":false,"ShowAfterHours":false,\ "UseExtendedTimeFrame":false,"WantPriorClose":true,"IncludeCurrentQuotes":false,\ "ResetTodaysAfterHoursPercentChange":false,\ "Series":[{"Key":"%s","Dialect":"Charting","Kind":"Ticker","SeriesId":"s1","DataTypes":["Last"]}]}' % (freq, token, code), "ckey": token[:10], } r = rget_json( "https://api-secure.wsj.net/api/michelangelo/timeseries/history", params=params, headers={ "user-agent": "Mozilla/5.0", "Accept": "application/json, text/javascript, */*; q=0.01", "Dylan2010.EntitlementToken": token, "Host": "api-secure.wsj.net", "Origin": "https://www.marketwatch.com", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site", }, ) df = pd.DataFrame( { "date": r["TimeInfo"]["Ticks"], "close": [n[0] for n in r["Series"][0]["DataPoints"]], } ) df["date"] = pd.to_datetime(df["date"] * 1000000) + pd.Timedelta(hours=8) df = df[df["close"] > -100.0] # 存在未来数据占位符需要排除 return df class vinfo(basicinfo, indicator): def __init__( self, code, name=None, start=None, end=None, rate=0, col="close", normalization=True, **kws ): if not name: try: name = get_rt(code)["name"] except: name = code self.name = name self.code = code self.start = start # None is one year ago self.end = end # None is yesterday df = get_daily(code, start=start, end=end) df[col] = pd.to_numeric(df[col]) # in case the col is not float df["totvalue"] = df[col] if normalization: df["netvalue"] = df[col] / df.iloc[0][col] else: df["netvalue"] = df[col] self.price = df self.round_label = kws.get("round_label", 0) self.dividend_label = kws.get("dividend_label", 0) self.value_label = kws.get("value_label", 1) # 默认按金额赎回 self.specialdate = [] self.fenhongdate = [] self.zhesuandate = [] self.rate = rate VInfo = vinfo
true
true
f7278b3f78adb6b6654bc60e19101d05927cea4c
1,039
py
Python
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2022-02-26T05:16:25.000Z
2022-02-26T05:16:25.000Z
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
2
2021-12-10T04:07:19.000Z
2021-12-27T20:00:03.000Z
modules/denoise/config.py
gw2cc/godot
addaa48039fff0795b99cf998a11a75a9e280850
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
def can_build(env, platform): # Thirdparty dependency OpenImage Denoise includes oneDNN library # and the version we use only supports x86_64. # It's also only relevant for tools build and desktop platforms, # as doing lightmap generation and denoising on Android or HTML5 # would be a bit far-fetched. # Note: oneDNN doesn't support ARM64, OIDN needs updating to the latest version supported_platform = platform in ["x11", "osx", "windows", "server"] supported_bits = env["bits"] == "64" supported_arch = env["arch"] != "arm64" and not env["arch"].startswith("rv") # Hack to disable on Linux arm64. This won't work well for cross-compilation (checks # host, not target) and would need a more thorough fix by refactoring our arch and # bits-handling code. from platform import machine if platform == "x11" and machine() != "x86_64": supported_arch = False return env["tools"] and supported_platform and supported_bits and supported_arch def configure(env): pass
41.56
88
0.704524
def can_build(env, platform): # as doing lightmap generation and denoising on Android or HTML5 # would be a bit far-fetched. # Note: oneDNN doesn't support ARM64, OIDN needs updating to the latest version supported_platform = platform in ["x11", "osx", "windows", "server"] supported_bits = env["bits"] == "64" supported_arch = env["arch"] != "arm64" and not env["arch"].startswith("rv") # host, not target) and would need a more thorough fix by refactoring our arch and # bits-handling code. from platform import machine if platform == "x11" and machine() != "x86_64": supported_arch = False return env["tools"] and supported_platform and supported_bits and supported_arch def configure(env): pass
true
true
f7278bb2aaab500d948340fdddc1c5f836645f0b
97,520
py
Python
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wordlist.py
Finoozer/pypassgen
37a129f0917871f8ea6680e7820a110df779f5f2
[ "MIT" ]
null
null
null
wl = ["aah", "aaron", "aba", "ababa", "aback", "abase", "abash", "abate", "abbas", "abbe", "abbey", "abbot", "abbott", "abc", "abe", "abed", "abel", "abet", "abide", "abject", "ablaze", "able", "abner", "abo", "abode", "abort", "about", "above", "abrade", "abram", "absorb", "abuse", "abut", "abyss", "acadia", "accra", "accrue", "ace", "acetic", "ache", "acid", "acidic", "acm", "acme", "acorn", "acre", "acrid", "act", "acton", "actor", "acts", "acuity", "acute", "ada", "adage", "adagio", "adair", "adam", "adams", "adapt", "add", "added", "addict", "addis", "addle", "adele", "aden", "adept", "adieu", "adjust", "adler", "admit", "admix", "ado", "adobe", "adonis", "adopt", "adore", "adorn", "adult", "advent", "advert", "advise", "aegis", "aeneid", "afar", "affair", "affine", "affix", "afire", "afoot", "afraid", "africa", "afro", "aft", "again", "agate", "agave", "age", "age", "agenda", "agent", "agile", "aging", "agnes", "agnew", "ago", "agone", "agony", "agree", "ague", "agway", "ahead", "ahem", "ahoy", "aid", "aida", "aide", "aides", "aiken", "ail", "aile", "aim", "ainu", "air", "aires", "airman", "airway", "airy", "aisle", "ajar", "ajax", "akers", "akin", "akron", "ala", "alai", "alamo", "alan", "alarm", "alaska", "alb", "alba", "album", "alcoa", "alden", "alder", "ale", "alec", "aleck", "aleph", "alert", "alex", "alexei", "alga", "algae", "algal", "alger", "algol", "ali", "alia", "alias", "alibi", "alice", "alien", "alight", "align", "alike", "alive", "all", "allah", "allan", "allay", "allen", "alley", "allied", "allis", "allot", "allow", "alloy", "allure", "ally", "allyl", "allyn", "alma", "almost", "aloe", "aloft", "aloha", "alone", "along", "aloof", "aloud", "alp", "alpha", "alps", "also", "alsop", "altair", "altar", "alter", "alto", "alton", "alum", "alumni", "alva", "alvin", "alway", "ama", "amass", "amaze", "amber", "amble", "ambush", "amen", "amend", "ames", "ami", "amid", "amide", "amigo", "amino", "amiss", "amity", "amman", "ammo", "amoco", "amok", "among", "amort", "amos", "amp", "ampere", "ampex", "ample", "amply", "amra", "amulet", "amuse", "amy", "ana", "and", "andes", "andre", "andrew", "andy", "anent", "anew", "angel", "angelo", "anger", "angie", "angle", "anglo", "angola", "angry", "angst", "angus", "ani", "anion", "anise", "anita", "ankle", "ann", "anna", "annal", "anne", "annex", "annie", "annoy", "annul", "annuli", "annum", "anode", "ansi", "answer", "ant", "ante", "anti", "antic", "anton", "anus", "anvil", "any", "anyhow", "anyway", "aok", "aorta", "apart", "apathy", "ape", "apex", "aphid", "aplomb", "appeal", "append", "apple", "apply", "april", "apron", "apse", "apt", "aqua", "arab", "araby", "arc", "arcana", "arch", "archer", "arden", "ardent", "are", "area", "arena", "ares", "argive", "argo", "argon", "argot", "argue", "argus", "arhat", "arid", "aries", "arise", "ark", "arlen", "arlene", "arm", "armco", "army", "arnold", "aroma", "arose", "arpa", "array", "arrear", "arrow", "arson", "art", "artery", "arthur", "artie", "arty", "aruba", "arum", "aryl", "ascend", "ash", "ashen", "asher", "ashley", "ashy", "asia", "aside", "ask", "askew", "asleep", "aspen", "aspire", "ass", "assai", "assam", "assay", "asset", "assort", "assure", "aster", "astm", "astor", "astral", "ate", "athens", "atlas", "atom", "atomic", "atone", "atop", "attic", "attire", "aubrey", "audio", "audit", "aug", "auger", "augur", "august", "auk", "aunt", "aura", "aural", "auric", "austin", "auto", "autumn", "avail", "ave", "aver", "avert", "avery", "aviate", "avid", "avis", "aviv", "avoid", "avon", "avow", "await", "awake", "award", "aware", "awash", "away", "awe", "awful", "awl", "awn", "awoke", "awry", "axe", "axes", "axial", "axiom", "axis", "axle", "axon", "aye", "ayers", "aztec", "azure", "babe", "babel", "baby", "bach", "back", "backup", "bacon", "bad", "bade", "baden", "badge", "baffle", "bag", "baggy", "bah", "bahama", "bail", "baird", "bait", "bake", "baku", "bald", "baldy", "bale", "bali", "balk", "balkan", "balky", "ball", "balled", "ballot", "balm", "balmy", "balsa", "bam", "bambi", "ban", "banal", "band", "bandit", "bandy", "bane", "bang", "banish", "banjo", "bank", "banks", "bantu", "bar", "barb", "bard", "bare", "barfly", "barge", "bark", "barley", "barn", "barnes", "baron", "barony", "barr", "barre", "barry", "barter", "barth", "barton", "basal", "base", "basel", "bash", "basic", "basil", "basin", "basis", "bask", "bass", "bassi", "basso", "baste", "bat", "batch", "bate", "bater", "bates", "bath", "bathe", "batik", "baton", "bator", "batt", "bauble", "baud", "bauer", "bawd", "bawdy", "bawl", "baxter", "bay", "bayda", "bayed", "bayou", "bazaar", "bbb", "bbbb", "bcd", "beach", "bead", "beady", "beak", "beam", "bean", "bear", "beard", "beast", "beat", "beau", "beauty", "beaux", "bebop", "becalm", "beck", "becker", "becky", "bed", "bedim", "bee", "beebe", "beech", "beef", "beefy", "been", "beep", "beer", "beet", "befall", "befit", "befog", "beg", "began", "beget", "beggar", "begin", "begun", "behind", "beige", "being", "beirut", "bel", "bela", "belch", "belfry", "belie", "bell", "bella", "belle", "belly", "below", "belt", "bema", "beman", "bemoan", "ben", "bench", "bend", "bender", "benny", "bent", "benz", "berea", "bereft", "beret", "berg", "berlin", "bern", "berne", "bernet", "berra", "berry", "bert", "berth", "beryl", "beset", "bess", "bessel", "best", "bestir", "bet", "beta", "betel", "beth", "bethel", "betsy", "bette", "betty", "bevel", "bevy", "beware", "bey", "bezel", "bhoy", "bias", "bib", "bibb", "bible", "bicep", "biceps", "bid", "biddy", "bide", "bien", "big", "biggs", "bigot", "bile", "bilge", "bilk", "bill", "billow", "billy", "bin", "binary", "bind", "bing", "binge", "bingle", "bini", "biota", "birch", "bird", "birdie", "birth", "bison", "bisque", "bit", "bitch", "bite", "bitt", "bitten", "biz", "bizet", "blab", "black", "blade", "blair", "blake", "blame", "blanc", "bland", "blank", "blare", "blast", "blat", "blatz", "blaze", "bleak", "bleat", "bled", "bleed", "blend", "bless", "blest", "blew", "blimp", "blind", "blink", "blinn", "blip", "bliss", "blithe", "blitz", "bloat", "blob", "bloc", "bloch", "block", "bloke", "blond", "blonde", "blood", "bloom", "bloop", "blot", "blotch", "blow", "blown", "blue", "bluet", "bluff", "blum", "blunt", "blur", "blurt", "blush", "blvd", "blythe", "bmw", "boa", "boar", "board", "boast", "boat", "bob", "bobbin", "bobby", "bobcat", "boca", "bock", "bode", "body", "bog", "bogey", "boggy", "bogus", "bogy", "bohr", "boil", "bois", "boise", "bold", "bole", "bolo", "bolt", "bomb", "bombay", "bon", "bona", "bond", "bone", "bong", "bongo", "bonn", "bonus", "bony", "bonze", "boo", "booby", "boogie", "book", "booky", "boom", "boon", "boone", "boor", "boost", "boot", "booth", "booty", "booze", "bop", "borax", "border", "bore", "borg", "boric", "boris", "born", "borne", "borneo", "boron", "bosch", "bose", "bosom", "boson", "boss", "boston", "botch", "both", "bottle", "bough", "bouncy", "bound", "bourn", "bout", "bovine", "bow", "bowel", "bowen", "bowie", "bowl", "box", "boxy", "boy", "boyar", "boyce", "boyd", "boyle", "brace", "bract", "brad", "brady", "brae", "brag", "bragg", "braid", "brain", "brainy", "brake", "bran", "brand", "brandt", "brant", "brash", "brass", "brassy", "braun", "brave", "bravo", "brawl", "bray", "bread", "break", "bream", "breath", "bred", "breed", "breeze", "bremen", "brent", "brest", "brett", "breve", "brew", "brian", "briar", "bribe", "brice", "brick", "bride", "brief", "brig", "briggs", "brim", "brine", "bring", "brink", "briny", "brisk", "broad", "brock", "broil", "broke", "broken", "bronx", "brood", "brook", "brooke", "broom", "broth", "brow", "brown", "browse", "bruce", "bruit", "brunch", "bruno", "brunt", "brush", "brute", "bryan", "bryant", "bryce", "bryn", "bstj", "btl", "bub", "buck", "bud", "budd", "buddy", "budge", "buena", "buenos", "buff", "bug", "buggy", "bugle", "buick", "build", "built", "bulb", "bulge", "bulk", "bulky", "bull", "bully", "bum", "bump", "bun", "bunch", "bundy", "bunk", "bunny", "bunt", "bunyan", "buoy", "burch", "bureau", "buret", "burg", "buried", "burke", "burl", "burly", "burma", "burn", "burnt", "burp", "burr", "burro", "burst", "burt", "burton", "burtt", "bury", "bus", "busch", "bush", "bushel", "bushy", "buss", "bust", "busy", "but", "butane", "butch", "buteo", "butt", "butte", "butyl", "buxom", "buy", "buyer", "buzz", "buzzy", "bye", "byers", "bylaw", "byline", "byrd", "byrne", "byron", "byte", "byway", "byword", "cab", "cabal", "cabin", "cable", "cabot", "cacao", "cache", "cacm", "cacti", "caddy", "cadent", "cadet", "cadre", "cady", "cafe", "cage", "cagey", "cahill", "caiman", "cain", "caine", "cairn", "cairo", "cake", "cal", "calder", "caleb", "calf", "call", "calla", "callus", "calm", "calve", "cam", "camber", "came", "camel", "cameo", "camp", "can", "canal", "canary", "cancer", "candle", "candy", "cane", "canis", "canna", "cannot", "canny", "canoe", "canon", "canopy", "cant", "canto", "canton", "cap", "cape", "caper", "capo", "car", "carbon", "card", "care", "caress", "caret", "carey", "cargo", "carib", "carl", "carla", "carlo", "carne", "carob", "carol", "carp", "carpet", "carr", "carrie", "carry", "carson", "cart", "carte", "caruso", "carve", "case", "casey", "cash", "cashew", "cask", "casket", "cast", "caste", "cat", "catch", "cater", "cathy", "catkin", "catsup", "cauchy", "caulk", "cause", "cave", "cavern", "cavil", "cavort", "caw", "cayuga", "cbs", "ccc", "cccc", "cdc", "cease", "cecil", "cedar", "cede", "ceil", "celia", "cell", "census", "cent", "ceres", "cern", "cetera", "cetus", "chad", "chafe", "chaff", "chai", "chain", "chair", "chalk", "champ", "chance", "chang", "chant", "chao", "chaos", "chap", "chapel", "char", "chard", "charm", "chart", "chase", "chasm", "chaste", "chat", "chaw", "cheap", "cheat", "check", "cheek", "cheeky", "cheer", "chef", "chen", "chert", "cherub", "chess", "chest", "chevy", "chew", "chi", "chic", "chick", "chide", "chief", "child", "chile", "chili", "chill", "chilly", "chime", "chin", "china", "chine", "chink", "chip", "chirp", "chisel", "chit", "chive", "chock", "choir", "choke", "chomp", "chop", "chopin", "choral", "chord", "chore", "chose", "chosen", "chou", "chow", "chris", "chub", "chuck", "chuff", "chug", "chum", "chump", "chunk", "churn", "chute", "cia", "cicada", "cider", "cigar", "cilia", "cinch", "cindy", "cipher", "circa", "circe", "cite", "citrus", "city", "civet", "civic", "civil", "clad", "claim", "clam", "clammy", "clamp", "clan", "clang", "clank", "clap", "clara", "clare", "clark", "clarke", "clash", "clasp", "class", "claus", "clause", "claw", "clay", "clean", "clear", "cleat", "cleft", "clerk", "cliche", "click", "cliff", "climb", "clime", "cling", "clink", "clint", "clio", "clip", "clive", "cloak", "clock", "clod", "clog", "clomp", "clone", "close", "closet", "clot", "cloth", "cloud", "clout", "clove", "clown", "cloy", "club", "cluck", "clue", "cluj", "clump", "clumsy", "clung", "clyde", "coach", "coal", "coast", "coat", "coax", "cobb", "cobble", "cobol", "cobra", "coca", "cock", "cockle", "cocky", "coco", "cocoa", "cod", "coda", "coddle", "code", "codon", "cody", "coed", "cog", "cogent", "cohen", "cohn", "coil", "coin", "coke", "col", "cola", "colby", "cold", "cole", "colon", "colony", "colt", "colza", "coma", "comb", "combat", "come", "comet", "cometh", "comic", "comma", "con", "conch", "cone", "coney", "congo", "conic", "conn", "conner", "conway", "cony", "coo", "cook", "cooke", "cooky", "cool", "cooley", "coon", "coop", "coors", "coot", "cop", "cope", "copra", "copy", "coral", "corbel", "cord", "core", "corey", "cork", "corn", "corny", "corp", "corps", "corvus", "cos", "cosec", "coset", "cosh", "cost", "costa", "cosy", "cot", "cotta", "cotty", "couch", "cough", "could", "count", "coup", "coupe", "court", "cousin", "cove", "coven", "cover", "covet", "cow", "cowan", "cowl", "cowman", "cowry", "cox", "coy", "coyote", "coypu", "cozen", "cozy", "cpa", "crab", "crack", "craft", "crag", "craig", "cram", "cramp", "crane", "crank", "crap", "crash", "crass", "crate", "crater", "crave", "craw", "crawl", "craze", "crazy", "creak", "cream", "credit", "credo", "creed", "creek", "creep", "creole", "creon", "crepe", "crept", "cress", "crest", "crete", "crew", "crib", "cried", "crime", "crimp", "crisp", "criss", "croak", "crock", "crocus", "croft", "croix", "crone", "crony", "crook", "croon", "crop", "cross", "crow", "crowd", "crown", "crt", "crud", "crude", "cruel", "crumb", "crump", "crush", "crust", "crux", "cruz", "cry", "crypt", "cub", "cuba", "cube", "cubic", "cud", "cuddle", "cue", "cuff", "cull", "culpa", "cult", "cumin", "cuny", "cup", "cupful", "cupid", "cur", "curb", "curd", "cure", "curfew", "curia", "curie", "curio", "curl", "curry", "curse", "curt", "curve", "cusp", "cut", "cute", "cutlet", "cycad", "cycle", "cynic", "cyril", "cyrus", "cyst", "czar", "czech", "dab", "dacca", "dactyl", "dad", "dada", "daddy", "dade", "daffy", "dahl", "dahlia", "dairy", "dais", "daisy", "dakar", "dale", "daley", "dally", "daly", "dam", "dame", "damn", "damon", "damp", "damsel", "dan", "dana", "dance", "dandy", "dane", "dang", "dank", "danny", "dante", "dar", "dare", "dark", "darken", "darn", "darry", "dart", "dash", "data", "date", "dater", "datum", "daub", "daunt", "dave", "david", "davis", "davit", "davy", "dawn", "dawson", "day", "daze", "ddd", "dddd", "deacon", "dead", "deaf", "deal", "dealt", "dean", "deane", "dear", "death", "debar", "debby", "debit", "debra", "debris", "debt", "debug", "debut", "dec", "decal", "decay", "decca", "deck", "decker", "decor", "decree", "decry", "dee", "deed", "deem", "deep", "deer", "deere", "def", "defer", "deform", "deft", "defy", "degas", "degum", "deify", "deign", "deity", "deja", "del", "delay", "delft", "delhi", "delia", "dell", "della", "delta", "delve", "demark", "demit", "demon", "demur", "den", "deneb", "denial", "denny", "dense", "dent", "denton", "deny", "depot", "depth", "depute", "derby", "derek", "des", "desist", "desk", "detach", "deter", "deuce", "deus", "devil", "devoid", "devon", "dew", "dewar", "dewey", "dewy", "dey", "dhabi", "dial", "diana", "diane", "diary", "dibble", "dice", "dick", "dicta", "did", "dido", "die", "died", "diego", "diem", "diesel", "diet", "diety", "dietz", "dig", "digit", "dilate", "dill", "dim", "dime", "din", "dinah", "dine", "ding", "dingo", "dingy", "dint", "diode", "dip", "dirac", "dire", "dirge", "dirt", "dirty", "dis", "disc", "dish", "disk", "disney", "ditch", "ditto", "ditty", "diva", "divan", "dive", "dixie", "dixon", "dizzy", "dna", "dobbs", "dobson", "dock", "docket", "dod", "dodd", "dodge", "dodo", "doe", "doff", "dog", "doge", "dogma", "dolan", "dolce", "dole", "doll", "dolly", "dolt", "dome", "don", "done", "doneck", "donna", "donor", "doom", "door", "dope", "dora", "doria", "doric", "doris", "dose", "dot", "dote", "double", "doubt", "douce", "doug", "dough", "dour", "douse", "dove", "dow", "dowel", "down", "downs", "dowry", "doyle", "doze", "dozen", "drab", "draco", "draft", "drag", "drain", "drake", "dram", "drama", "drank", "drape", "draw", "drawl", "drawn", "dread", "dream", "dreamy", "dreg", "dress", "dressy", "drew", "drib", "dried", "drier", "drift", "drill", "drink", "drip", "drive", "droll", "drone", "drool", "droop", "drop", "dross", "drove", "drown", "drub", "drug", "druid", "drum", "drunk", "drury", "dry", "dryad", "dual", "duane", "dub", "dubhe", "dublin", "ducat", "duck", "duct", "dud", "due", "duel", "duet", "duff", "duffy", "dug", "dugan", "duke", "dull", "dully", "dulse", "duly", "duma", "dumb", "dummy", "dump", "dumpy", "dun", "dunce", "dune", "dung", "dunham", "dunk", "dunlop", "dunn", "dupe", "durer", "dusk", "dusky", "dust", "dusty", "dutch", "duty", "dwarf", "dwell", "dwelt", "dwight", "dwyer", "dyad", "dye", "dyer", "dying", "dyke", "dylan", "dyne", "each", "eagan", "eager", "eagle", "ear", "earl", "earn", "earth", "ease", "easel", "east", "easy", "eat", "eaten", "eater", "eaton", "eave", "ebb", "eben", "ebony", "echo", "eclat", "ecole", "eddie", "eddy", "eden", "edgar", "edge", "edgy", "edict", "edify", "edit", "edith", "editor", "edna", "edt", "edwin", "eee", "eeee", "eel", "eeoc", "eerie", "efface", "effie", "efg", "eft", "egan", "egg", "ego", "egress", "egret", "egypt", "eider", "eight", "eire", "eject", "eke", "elan", "elate", "elba", "elbow", "elder", "eldon", "elect", "elegy", "elena", "eleven", "elfin", "elgin", "eli", "elide", "eliot", "elite", "elk", "ell", "ella", "ellen", "ellis", "elm", "elmer", "elope", "else", "elsie", "elton", "elude", "elute", "elves", "ely", "embalm", "embark", "embed", "ember", "emcee", "emery", "emil", "emile", "emily", "emit", "emma", "emory", "empty", "enact", "enamel", "end", "endow", "enemy", "eng", "engel", "engle", "engulf", "enid", "enjoy", "enmity", "enoch", "enol", "enos", "enrico", "ensue", "enter", "entrap", "entry", "envoy", "envy", "epa", "epic", "epoch", "epoxy", "epsom", "equal", "equip", "era", "erase", "erato", "erda", "ere", "erect", "erg", "eric", "erich", "erie", "erik", "ernest", "ernie", "ernst", "erode", "eros", "err", "errand", "errol", "error", "erupt", "ervin", "erwin", "essay", "essen", "essex", "est", "ester", "estes", "estop", "eta", "etc", "etch", "ethan", "ethel", "ether", "ethic", "ethos", "ethyl", "etude", "eucre", "euler", "eureka", "eva", "evade", "evans", "eve", "even", "event", "every", "evict", "evil", "evoke", "evolve", "ewe", "ewing", "exact", "exalt", "exam", "excel", "excess", "exert", "exile", "exist", "exit", "exodus", "expel", "extant", "extent", "extol", "extra", "exude", "exult", "exxon", "eye", "eyed", "ezra", "faa", "faber", "fable", "face", "facet", "facile", "fact", "facto", "fad", "fade", "faery", "fag", "fahey", "fail", "fain", "faint", "fair", "fairy", "faith", "fake", "fall", "false", "fame", "fan", "fancy", "fang", "fanny", "fanout", "far", "farad", "farce", "fare", "fargo", "farley", "farm", "faro", "fast", "fat", "fatal", "fate", "fatty", "fault", "faun", "fauna", "faust", "fawn", "fay", "faze", "fbi", "fcc", "fda", "fear", "feast", "feat", "feb", "fed", "fee", "feed", "feel", "feet", "feign", "feint", "felice", "felix", "fell", "felon", "felt", "femur", "fence", "fend", "fermi", "fern", "ferric", "ferry", "fest", "fetal", "fetch", "fete", "fetid", "fetus", "feud", "fever", "few", "fff", "ffff", "fgh", "fiat", "fib", "fibrin", "fiche", "fide", "fief", "field", "fiend", "fiery", "fife", "fifo", "fifth", "fifty", "fig", "fight", "filch", "file", "filet", "fill", "filler", "filly", "film", "filmy", "filth", "fin", "final", "finale", "finch", "find", "fine", "finite", "fink", "finn", "finny", "fir", "fire", "firm", "first", "fish", "fishy", "fisk", "fiske", "fist", "fit", "fitch", "five", "fix", "fjord", "flack", "flag", "flail", "flair", "flak", "flake", "flaky", "flam", "flame", "flank", "flap", "flare", "flash", "flask", "flat", "flatus", "flaw", "flax", "flea", "fleck", "fled", "flee", "fleet", "flesh", "flew", "flex", "flick", "flier", "flinch", "fling", "flint", "flip", "flirt", "flit", "flo", "float", "floc", "flock", "floe", "flog", "flood", "floor", "flop", "floppy", "flora", "flour", "flout", "flow", "flown", "floyd", "flu", "flub", "flue", "fluff", "fluid", "fluke", "flung", "flush", "flute", "flux", "fly", "flyer", "flynn", "fmc", "foal", "foam", "foamy", "fob", "focal", "foci", "focus", "fodder", "foe", "fog", "foggy", "fogy", "foil", "foist", "fold", "foley", "folio", "folk", "folly", "fond", "font", "food", "fool", "foot", "foote", "fop", "for", "foray", "force", "ford", "fore", "forge", "forgot", "fork", "form", "fort", "forte", "forth", "forty", "forum", "foss", "fossil", "foul", "found", "fount", "four", "fovea", "fowl", "fox", "foxy", "foyer", "fpc", "frail", "frame", "fran", "franc", "franca", "frank", "franz", "frau", "fraud", "fray", "freak", "fred", "free", "freed", "freer", "frenzy", "freon", "fresh", "fret", "freud", "frey", "freya", "friar", "frick", "fried", "frill", "frilly", "frisky", "fritz", "fro", "frock", "frog", "from", "front", "frost", "froth", "frown", "froze", "fruit", "fry", "frye", "ftc", "fuchs", "fudge", "fuel", "fugal", "fugue", "fuji", "full", "fully", "fum", "fume", "fun", "fund", "fungal", "fungi", "funk", "funny", "fur", "furl", "furry", "fury", "furze", "fuse", "fuss", "fussy", "fusty", "fuzz", "fuzzy", "gab", "gable", "gabon", "gad", "gadget", "gaff", "gaffe", "gag", "gage", "gail", "gain", "gait", "gal", "gala", "galaxy", "gale", "galen", "gall", "gallop", "galt", "gam", "game", "gamin", "gamma", "gamut", "gander", "gang", "gao", "gap", "gape", "gar", "garb", "garish", "garner", "garry", "garth", "gary", "gas", "gash", "gasp", "gassy", "gate", "gates", "gator", "gauche", "gaudy", "gauge", "gaul", "gaunt", "gaur", "gauss", "gauze", "gave", "gavel", "gavin", "gawk", "gawky", "gay", "gaze", "gear", "gecko", "gee", "geese", "geigy", "gel", "geld", "gem", "gemma", "gene", "genie", "genii", "genoa", "genre", "gent", "gentry", "genus", "gerbil", "germ", "gerry", "get", "getty", "ggg", "gggg", "ghana", "ghent", "ghetto", "ghi", "ghost", "ghoul", "giant", "gibbs", "gibby", "gibe", "giddy", "gift", "gig", "gil", "gila", "gild", "giles", "gill", "gilt", "gimbal", "gimpy", "gin", "gina", "ginn", "gino", "gird", "girl", "girth", "gist", "give", "given", "glad", "gladdy", "glade", "glamor", "gland", "glans", "glare", "glass", "glaze", "gleam", "glean", "glee", "glen", "glenn", "glib", "glide", "glint", "gloat", "glob", "globe", "glom", "gloom", "glory", "gloss", "glove", "glow", "glue", "glued", "gluey", "gluing", "glum", "glut", "glyph", "gmt", "gnarl", "gnash", "gnat", "gnaw", "gnome", "gnp", "gnu", "goa", "goad", "goal", "goat", "gob", "goer", "goes", "goff", "gog", "goggle", "gogh", "gogo", "gold", "golf", "golly", "gone", "gong", "goo", "good", "goode", "goody", "goof", "goofy", "goose", "gop", "gordon", "gore", "goren", "gorge", "gorky", "gorse", "gory", "gosh", "gospel", "got", "gouda", "gouge", "gould", "gourd", "gout", "gown", "gpo", "grab", "grace", "grad", "grade", "grady", "graff", "graft", "grail", "grain", "grand", "grant", "grape", "graph", "grasp", "grass", "grata", "grate", "grater", "grave", "gravy", "gray", "graze", "great", "grebe", "greed", "greedy", "greek", "green", "greer", "greet", "greg", "gregg", "greta", "grew", "grey", "grid", "grief", "grieve", "grill", "grim", "grime", "grimm", "grin", "grind", "grip", "gripe", "grist", "grit", "groan", "groat", "groin", "groom", "grope", "gross", "groton", "group", "grout", "grove", "grow", "growl", "grown", "grub", "gruff", "grunt", "gsa", "guam", "guano", "guard", "guess", "guest", "guide", "guild", "guile", "guilt", "guise", "guitar", "gules", "gulf", "gull", "gully", "gulp", "gum", "gumbo", "gummy", "gun", "gunk", "gunky", "gunny", "gurgle", "guru", "gus", "gush", "gust", "gusto", "gusty", "gut", "gutsy", "guy", "guyana", "gwen", "gwyn", "gym", "gyp", "gypsy", "gyro", "haag", "haas", "habib", "habit", "hack", "had", "hades", "hadron", "hagen", "hager", "hague", "hahn", "haifa", "haiku", "hail", "hair", "hairy", "haiti", "hal", "hale", "haley", "half", "hall", "halma", "halo", "halt", "halvah", "halve", "ham", "hamal", "hamlin", "han", "hand", "handy", "haney", "hang", "hank", "hanna", "hanoi", "hans", "hansel", "hap", "happy", "hard", "hardy", "hare", "harem", "hark", "harley", "harm", "harp", "harpy", "harry", "harsh", "hart", "harvey", "hash", "hasp", "hast", "haste", "hasty", "hat", "hatch", "hate", "hater", "hath", "hatred", "haul", "haunt", "have", "haven", "havoc", "haw", "hawk", "hay", "haydn", "hayes", "hays", "hazard", "haze", "hazel", "hazy", "head", "heady", "heal", "healy", "heap", "hear", "heard", "heart", "heat", "heath", "heave", "heavy", "hebe", "hebrew", "heck", "heckle", "hedge", "heed", "heel", "heft", "hefty", "heigh", "heine", "heinz", "heir", "held", "helen", "helga", "helix", "hell", "hello", "helm", "helmut", "help", "hem", "hemp", "hen", "hence", "henri", "henry", "her", "hera", "herb", "herd", "here", "hero", "heroic", "heron", "herr", "hertz", "hess", "hesse", "hettie", "hetty", "hew", "hewitt", "hewn", "hex", "hey", "hhh", "hhhh", "hiatt", "hick", "hicks", "hid", "hide", "high", "hij", "hike", "hill", "hilly", "hilt", "hilum", "him", "hind", "hindu", "hines", "hinge", "hint", "hip", "hippo", "hippy", "hiram", "hire", "hirsch", "his", "hiss", "hit", "hitch", "hive", "hoagy", "hoar", "hoard", "hob", "hobbs", "hobby", "hobo", "hoc", "hock", "hodge", "hodges", "hoe", "hoff", "hog", "hogan", "hoi", "hokan", "hold", "holdup", "hole", "holly", "holm", "holst", "holt", "home", "homo", "honda", "hondo", "hone", "honey", "hong", "honk", "hooch", "hood", "hoof", "hook", "hookup", "hoop", "hoot", "hop", "hope", "horde", "horn", "horny", "horse", "horus", "hose", "host", "hot", "hotbox", "hotel", "hough", "hound", "hour", "house", "hove", "hovel", "hover", "how", "howdy", "howe", "howl", "hoy", "hoyt", "hub", "hubbub", "hubby", "huber", "huck", "hue", "hued", "huff", "hug", "huge", "hugh", "hughes", "hugo", "huh", "hulk", "hull", "hum", "human", "humid", "hump", "humus", "hun", "hunch", "hung", "hunk", "hunt", "hurd", "hurl", "huron", "hurrah", "hurry", "hurst", "hurt", "hurty", "hush", "husky", "hut", "hutch", "hyde", "hydra", "hydro", "hyena", "hying", "hyman", "hymen", "hymn", "hymnal", "iambic", "ian", "ibex", "ibid", "ibis", "ibm", "ibn", "icc", "ice", "icing", "icky", "icon", "icy", "ida", "idaho", "idea", "ideal", "idiom", "idiot", "idle", "idol", "idyll", "ieee", "iffy", "ifni", "igloo", "igor", "iii", "iiii", "ijk", "ike", "ileum", "iliac", "iliad", "ill", "illume", "ilona", "image", "imbue", "imp", "impel", "import", "impute", "inane", "inapt", "inc", "inca", "incest", "inch", "incur", "index", "india", "indies", "indy", "inept", "inert", "infect", "infer", "infima", "infix", "infra", "ingot", "inhere", "injun", "ink", "inlay", "inlet", "inman", "inn", "inner", "input", "insect", "inset", "insult", "intend", "inter", "into", "inure", "invoke", "ion", "ionic", "iota", "iowa", "ipso", "ira", "iran", "iraq", "irate", "ire", "irene", "iris", "irish", "irk", "irma", "iron", "irony", "irs", "irvin", "irwin", "isaac", "isabel", "ising", "isis", "islam", "island", "isle", "israel", "issue", "italy", "itch", "item", "ito", "itt", "ivan", "ive", "ivory", "ivy", "jab", "jack", "jacky", "jacm", "jacob", "jacobi", "jade", "jag", "jail", "jaime", "jake", "jam", "james", "jan", "jane", "janet", "janos", "janus", "japan", "jar", "jason", "java", "jaw", "jay", "jazz", "jazzy", "jean", "jed", "jeep", "jeff", "jejune", "jelly", "jenny", "jeres", "jerk", "jerky", "jerry", "jersey", "jess", "jesse", "jest", "jesus", "jet", "jew", "jewel", "jewett", "jewish", "jibe", "jiffy", "jig", "jill", "jilt", "jim", "jimmy", "jinx", "jive", "jjj", "jjjj", "jkl", "joan", "job", "jock", "jockey", "joe", "joel", "joey", "jog", "john", "johns", "join", "joint", "joke", "jolla", "jolly", "jolt", "jon", "jonas", "jones", "jorge", "jose", "josef", "joshua", "joss", "jostle", "jot", "joule", "joust", "jove", "jowl", "jowly", "joy", "joyce", "juan", "judas", "judd", "jude", "judge", "judo", "judy", "jug", "juggle", "juice", "juicy", "juju", "juke", "jukes", "julep", "jules", "julia", "julie", "julio", "july", "jumbo", "jump", "jumpy", "junco", "june", "junk", "junky", "juno", "junta", "jura", "jure", "juror", "jury", "just", "jut", "jute", "kabul", "kafka", "kahn", "kajar", "kale", "kalmia", "kane", "kant", "kapok", "kappa", "karate", "karen", "karl", "karma", "karol", "karp", "kate", "kathy", "katie", "katz", "kava", "kay", "kayo", "kazoo", "keats", "keel", "keen", "keep", "keg", "keith", "keller", "kelly", "kelp", "kemp", "ken", "keno", "kent", "kenya", "kepler", "kept", "kern", "kerr", "kerry", "ketch", "kevin", "key", "keyed", "keyes", "keys", "khaki", "khan", "khmer", "kick", "kid", "kidde", "kidney", "kiev", "kigali", "kill", "kim", "kin", "kind", "king", "kink", "kinky", "kiosk", "kiowa", "kirby", "kirk", "kirov", "kiss", "kit", "kite", "kitty", "kiva", "kivu", "kiwi", "kkk", "kkkk", "klan", "klaus", "klein", "kline", "klm", "klux", "knack", "knapp", "knauer", "knead", "knee", "kneel", "knelt", "knew", "knick", "knife", "knit", "knob", "knock", "knoll", "knot", "knott", "know", "known", "knox", "knurl", "koala", "koch", "kodak", "kola", "kombu", "kong", "koran", "korea", "kraft", "krause", "kraut", "krebs", "kruse", "kudo", "kudzu", "kuhn", "kulak", "kurd", "kurt", "kyle", "kyoto", "lab", "laban", "label", "labia", "labile", "lac", "lace", "lack", "lacy", "lad", "laden", "ladle", "lady", "lag", "lager", "lagoon", "lagos", "laid", "lain", "lair", "laity", "lake", "lam", "lamar", "lamb", "lame", "lamp", "lana", "lance", "land", "lane", "lang", "lange", "lanka", "lanky", "lao", "laos", "lap", "lapel", "lapse", "larch", "lard", "lares", "large", "lark", "larkin", "larry", "lars", "larva", "lase", "lash", "lass", "lasso", "last", "latch", "late", "later", "latest", "latex", "lath", "lathe", "latin", "latus", "laud", "laue", "laugh", "launch", "laura", "lava", "law", "lawn", "lawson", "lax", "lay", "layup", "laze", "lazy", "lea", "leach", "lead", "leaf", "leafy", "leak", "leaky", "lean", "leap", "leapt", "lear", "learn", "lease", "leash", "least", "leave", "led", "ledge", "lee", "leech", "leeds", "leek", "leer", "leery", "leeway", "left", "lefty", "leg", "legal", "leggy", "legion", "leigh", "leila", "leland", "lemma", "lemon", "len", "lena", "lend", "lenin", "lenny", "lens", "lent", "leo", "leon", "leona", "leone", "leper", "leroy", "less", "lessee", "lest", "let", "lethe", "lev", "levee", "level", "lever", "levi", "levin", "levis", "levy", "lew", "lewd", "lewis", "leyden", "liar", "libel", "libido", "libya", "lice", "lick", "lid", "lie", "lied", "lien", "lieu", "life", "lifo", "lift", "light", "like", "liken", "lila", "lilac", "lilly", "lilt", "lily", "lima", "limb", "limbo", "lime", "limit", "limp", "lin", "lind", "linda", "linden", "line", "linen", "lingo", "link", "lint", "linus", "lion", "lip", "lipid", "lisa", "lise", "lisle", "lisp", "list", "listen", "lit", "lithe", "litton", "live", "liven", "livid", "livre", "liz", "lizzie", "lll", "llll", "lloyd", "lmn", "load", "loaf", "loam", "loamy", "loan", "loath", "lob", "lobar", "lobby", "lobe", "lobo", "local", "loci", "lock", "locke", "locus", "lodge", "loeb", "loess", "loft", "lofty", "log", "logan", "loge", "logic", "loin", "loire", "lois", "loiter", "loki", "lola", "loll", "lolly", "lomb", "lome", "lone", "long", "look", "loom", "loon", "loop", "loose", "loot", "lop", "lope", "lopez", "lord", "lore", "loren", "los", "lose", "loss", "lossy", "lost", "lot", "lotte", "lotus", "lou", "loud", "louis", "louise", "louse", "lousy", "louver", "love", "low", "lowe", "lower", "lowry", "loy", "loyal", "lsi", "ltv", "lucas", "lucia", "lucid", "luck", "lucky", "lucre", "lucy", "lug", "luge", "luger", "luis", "luke", "lull", "lulu", "lumbar", "lumen", "lump", "lumpy", "lunar", "lunch", "lund", "lung", "lunge", "lura", "lurch", "lure", "lurid", "lurk", "lush", "lust", "lusty", "lute", "lutz", "lux", "luxe", "luzon", "lydia", "lye", "lying", "lykes", "lyle", "lyman", "lymph", "lynch", "lynn", "lynx", "lyon", "lyons", "lyra", "lyric", "mabel", "mac", "mace", "mach", "macho", "mack", "mackey", "macon", "macro", "mad", "madam", "made", "madman", "madsen", "mae", "magi", "magic", "magma", "magna", "magog", "maid", "maier", "mail", "maim", "main", "maine", "major", "make", "malady", "malay", "male", "mali", "mall", "malt", "malta", "mambo", "mamma", "mammal", "man", "mana", "manama", "mane", "mange", "mania", "manic", "mann", "manna", "manor", "mans", "manse", "mantle", "many", "mao", "maori", "map", "maple", "mar", "marc", "march", "marco", "marcy", "mardi", "mare", "margo", "maria", "marie", "marin", "marine", "mario", "mark", "marks", "marlin", "marrow", "marry", "mars", "marsh", "mart", "marty", "marx", "mary", "maser", "mash", "mask", "mason", "masque", "mass", "mast", "mat", "match", "mate", "mateo", "mater", "math", "matte", "maul", "mauve", "mavis", "maw", "mawr", "max", "maxim", "maxima", "may", "maya", "maybe", "mayer", "mayhem", "mayo", "mayor", "mayst", "mazda", "maze", "mba", "mccoy", "mcgee", "mckay", "mckee", "mcleod", "mead", "meal", "mealy", "mean", "meant", "meat", "meaty", "mecca", "mecum", "medal", "medea", "media", "medic", "medley", "meek", "meet", "meg", "mega", "meier", "meir", "mel", "meld", "melee", "mellow", "melon", "melt", "memo", "memoir", "men", "mend", "menlo", "menu", "merck", "mercy", "mere", "merge", "merit", "merle", "merry", "mesa", "mescal", "mesh", "meson", "mess", "messy", "met", "metal", "mete", "meter", "metro", "mew", "meyer", "meyers", "mezzo", "miami", "mica", "mice", "mickey", "micky", "micro", "mid", "midas", "midge", "midst", "mien", "miff", "mig", "might", "mike", "mila", "milan", "milch", "mild", "mildew", "mile", "miles", "milk", "milky", "mill", "mills", "milt", "mimi", "mimic", "mince", "mind", "mine", "mini", "minim", "mink", "minnow", "minor", "minos", "minot", "minsk", "mint", "minus", "mira", "mirage", "mire", "mirth", "miser", "misery", "miss", "missy", "mist", "misty", "mit", "mite", "mitre", "mitt", "mix", "mixup", "mizar", "mmm", "mmmm", "mno", "moan", "moat", "mob", "mobil", "mock", "modal", "mode", "model", "modem", "modish", "moe", "moen", "mohr", "moire", "moist", "molal", "molar", "mold", "mole", "moll", "mollie", "molly", "molt", "molten", "mommy", "mona", "monad", "mondo", "monel", "money", "monic", "monk", "mont", "monte", "month", "monty", "moo", "mood", "moody", "moon", "moor", "moore", "moose", "moot", "mop", "moral", "morale", "moran", "more", "morel", "morn", "moron", "morse", "morsel", "mort", "mosaic", "moser", "moses", "moss", "mossy", "most", "mot", "motel", "motet", "moth", "mother", "motif", "motor", "motto", "mould", "mound", "mount", "mourn", "mouse", "mousy", "mouth", "move", "movie", "mow", "moyer", "mph", "mrs", "much", "muck", "mucus", "mud", "mudd", "muddy", "muff", "muffin", "mug", "muggy", "mugho", "muir", "mulch", "mulct", "mule", "mull", "multi", "mum", "mummy", "munch", "mung", "munson", "muon", "muong", "mural", "muriel", "murk", "murky", "murre", "muse", "mush", "mushy", "music", "musk", "muslim", "must", "musty", "mute", "mutt", "muzak", "muzo", "myel", "myers", "mylar", "mynah", "myopia", "myra", "myron", "myrrh", "myself", "myth", "naacp", "nab", "nadir", "nag", "nagoya", "nagy", "naiad", "nail", "nair", "naive", "naked", "name", "nan", "nancy", "naomi", "nap", "nary", "nasa", "nasal", "nash", "nasty", "nat", "natal", "nate", "nato", "natty", "nature", "naval", "nave", "navel", "navy", "nay", "nazi", "nbc", "nbs", "ncaa", "ncr", "neal", "near", "neat", "neath", "neck", "ned", "nee", "need", "needy", "neff", "negate", "negro", "nehru", "neil", "nell", "nelsen", "neon", "nepal", "nero", "nerve", "ness", "nest", "net", "neuron", "neva", "neve", "new", "newel", "newt", "next", "nib", "nibs", "nice", "nicety", "niche", "nick", "niece", "niger", "nigh", "night", "nih", "nikko", "nil", "nile", "nimbus", "nimh", "nina", "nine", "ninth", "niobe", "nip", "nit", "nitric", "nitty", "nixon", "nnn", "nnnn", "noaa", "noah", "nob", "nobel", "noble", "nod", "nodal", "node", "noel", "noise", "noisy", "nolan", "noll", "nolo", "nomad", "non", "nonce", "none", "nook", "noon", "noose", "nop", "nor", "nora", "norm", "norma", "north", "norway", "nose", "not", "notch", "note", "notre", "noun", "nov", "nova", "novak", "novel", "novo", "now", "nrc", "nsf", "ntis", "nuance", "nubia", "nuclei", "nude", "nudge", "null", "numb", "nun", "nurse", "nut", "nyc", "nylon", "nymph", "nyu", "oaf", "oak", "oaken", "oakley", "oar", "oases", "oasis", "oat", "oath", "obese", "obey", "objet", "oboe", "occur", "ocean", "oct", "octal", "octave", "octet", "odd", "ode", "odin", "odium", "off", "offal", "offend", "offer", "oft", "often", "ogden", "ogle", "ogre", "ohio", "ohm", "ohmic", "oil", "oily", "oint", "okay", "olaf", "olav", "old", "olden", "oldy", "olga", "olin", "olive", "olsen", "olson", "omaha", "oman", "omega", "omen", "omit", "once", "one", "onion", "only", "onset", "onto", "onus", "onward", "onyx", "ooo", "oooo", "ooze", "opal", "opec", "opel", "open", "opera", "opium", "opt", "optic", "opus", "oral", "orate", "orb", "orbit", "orchid", "ordain", "order", "ore", "organ", "orgy", "orin", "orion", "ornery", "orono", "orr", "osaka", "oscar", "osier", "oslo", "other", "otis", "ott", "otter", "otto", "ouch", "ought", "ounce", "our", "oust", "out", "ouvre", "ouzel", "ouzo", "ova", "oval", "ovary", "ovate", "oven", "over", "overt", "ovid", "owe", "owens", "owing", "owl", "owly", "own", "oxen", "oxeye", "oxide", "oxnard", "ozark", "ozone", "pablo", "pabst", "pace", "pack", "packet", "pact", "pad", "paddy", "padre", "paean", "pagan", "page", "paid", "pail", "pain", "paine", "paint", "pair", "pal", "pale", "pall", "palm", "palo", "palsy", "pam", "pampa", "pan", "panama", "panda", "pane", "panel", "pang", "panic", "pansy", "pant", "panty", "paoli", "pap", "papa", "papal", "papaw", "paper", "pappy", "papua", "par", "parch", "pardon", "pare", "pareto", "paris", "park", "parke", "parks", "parr", "parry", "parse", "part", "party", "pascal", "pasha", "paso", "pass", "passe", "past", "paste", "pasty", "pat", "patch", "pate", "pater", "path", "patio", "patsy", "patti", "patton", "patty", "paul", "paula", "pauli", "paulo", "pause", "pave", "paw", "pawn", "pax", "pay", "payday", "payne", "paz", "pbs", "pea", "peace", "peach", "peak", "peaky", "peal", "peale", "pear", "pearl", "pease", "peat", "pebble", "pecan", "peck", "pecos", "pedal", "pedro", "pee", "peed", "peek", "peel", "peep", "peepy", "peer", "peg", "peggy", "pelt", "pen", "penal", "pence", "pencil", "pend", "penh", "penn", "penna", "penny", "pent", "peony", "pep", "peppy", "pepsi", "per", "perch", "percy", "perez", "peril", "perk", "perky", "perle", "perry", "persia", "pert", "perth", "peru", "peruse", "pest", "peste", "pet", "petal", "pete", "peter", "petit", "petri", "petty", "pew", "pewee", "phage", "phase", "phd", "phenol", "phi", "phil", "phlox", "phon", "phone", "phony", "photo", "phyla", "physic", "piano", "pica", "pick", "pickup", "picky", "pie", "piece", "pier", "pierce", "piety", "pig", "piggy", "pike", "pile", "pill", "pilot", "pimp", "pin", "pinch", "pine", "ping", "pinion", "pink", "pint", "pinto", "pion", "piotr", "pious", "pip", "pipe", "piper", "pique", "pit", "pitch", "pith", "pithy", "pitney", "pitt", "pity", "pius", "pivot", "pixel", "pixy", "pizza", "place", "plague", "plaid", "plain", "plan", "plane", "plank", "plant", "plasm", "plat", "plate", "plato", "play", "playa", "plaza", "plea", "plead", "pleat", "pledge", "pliny", "plod", "plop", "plot", "plow", "pluck", "plug", "plum", "plumb", "plume", "plump", "plunk", "plus", "plush", "plushy", "pluto", "ply", "poach", "pobox", "pod", "podge", "podia", "poe", "poem", "poesy", "poet", "poetry", "pogo", "poi", "point", "poise", "poke", "pol", "polar", "pole", "police", "polio", "polis", "polk", "polka", "poll", "polo", "pomona", "pomp", "ponce", "pond", "pong", "pont", "pony", "pooch", "pooh", "pool", "poole", "poop", "poor", "pop", "pope", "poppy", "porch", "pore", "pork", "porous", "port", "porte", "portia", "porto", "pose", "posey", "posh", "posit", "posse", "post", "posy", "pot", "potts", "pouch", "pound", "pour", "pout", "pow", "powder", "power", "ppm", "ppp", "pppp", "pqr", "prado", "pram", "prank", "pratt", "pray", "preen", "prefix", "prep", "press", "prexy", "prey", "priam", "price", "prick", "pride", "prig", "prim", "prima", "prime", "primp", "prince", "print", "prior", "prism", "prissy", "privy", "prize", "pro", "probe", "prod", "prof", "prom", "prone", "prong", "proof", "prop", "propyl", "prose", "proud", "prove", "prow", "prowl", "proxy", "prune", "pry", "psalm", "psi", "psych", "pta", "pub", "puck", "puddly", "puerto", "puff", "puffy", "pug", "pugh", "puke", "pull", "pulp", "pulse", "puma", "pump", "pun", "punch", "punic", "punish", "punk", "punky", "punt", "puny", "pup", "pupal", "pupil", "puppy", "pure", "purge", "purl", "purr", "purse", "pus", "pusan", "pusey", "push", "pussy", "put", "putt", "putty", "pvc", "pygmy", "pyle", "pyre", "pyrex", "pyrite", "qatar", "qed", "qqq", "qqqq", "qrs", "qua", "quack", "quad", "quaff", "quail", "quake", "qualm", "quark", "quarry", "quart", "quash", "quasi", "quay", "queasy", "queen", "queer", "quell", "query", "quest", "queue", "quick", "quid", "quiet", "quill", "quilt", "quinn", "quint", "quip", "quirk", "quirt", "quit", "quite", "quito", "quiz", "quo", "quod", "quota", "quote", "rabat", "rabbi", "rabbit", "rabid", "rabin", "race", "rack", "racy", "radar", "radii", "radio", "radium", "radix", "radon", "rae", "rafael", "raft", "rag", "rage", "raid", "rail", "rain", "rainy", "raise", "raj", "rajah", "rake", "rally", "ralph", "ram", "raman", "ramo", "ramp", "ramsey", "ran", "ranch", "rand", "randy", "rang", "range", "rangy", "rank", "rant", "raoul", "rap", "rape", "rapid", "rapt", "rare", "rasa", "rascal", "rash", "rasp", "rat", "rata", "rate", "rater", "ratio", "rattle", "raul", "rave", "ravel", "raven", "raw", "ray", "raze", "razor", "rca", "reach", "read", "ready", "reagan", "real", "realm", "ream", "reap", "rear", "reave", "reb", "rebel", "rebut", "recipe", "reck", "recur", "red", "redeem", "reduce", "reed", "reedy", "reef", "reek", "reel", "reese", "reeve", "refer", "regal", "regina", "regis", "reich", "reid", "reign", "rein", "relax", "relay", "relic", "reman", "remedy", "remit", "remus", "rena", "renal", "rend", "rene", "renown", "rent", "rep", "repel", "repent", "resin", "resort", "rest", "ret", "retch", "return", "reub", "rev", "reveal", "revel", "rever", "revet", "revved", "rex", "rhea", "rheum", "rhine", "rhino", "rho", "rhoda", "rhode", "rhyme", "rib", "rica", "rice", "rich", "rick", "rico", "rid", "ride", "ridge", "rifle", "rift", "rig", "riga", "rigel", "riggs", "right", "rigid", "riley", "rill", "rilly", "rim", "rime", "rimy", "ring", "rink", "rinse", "rio", "riot", "rip", "ripe", "ripen", "ripley", "rise", "risen", "risk", "risky", "rite", "ritz", "rival", "riven", "river", "rivet", "riyadh", "roach", "road", "roam", "roar", "roast", "rob", "robe", "robin", "robot", "rock", "rocket", "rocky", "rod", "rode", "rodeo", "roe", "roger", "rogue", "roil", "role", "roll", "roman", "rome", "romeo", "romp", "ron", "rondo", "rood", "roof", "rook", "rookie", "rooky", "room", "roomy", "roost", "root", "rope", "rosa", "rose", "rosen", "ross", "rosy", "rot", "rotc", "roth", "rotor", "rouge", "rough", "round", "rouse", "rout", "route", "rove", "row", "rowdy", "rowe", "roy", "royal", "royce", "rpm", "rrr", "rrrr", "rst", "rsvp", "ruanda", "rub", "rube", "ruben", "rubin", "rubric", "ruby", "ruddy", "rude", "rudy", "rue", "rufus", "rug", "ruin", "rule", "rum", "rumen", "rummy", "rump", "rumpus", "run", "rune", "rung", "runge", "runic", "runt", "runty", "rupee", "rural", "ruse", "rush", "rusk", "russ", "russo", "rust", "rusty", "rut", "ruth", "rutty", "ryan", "ryder", "rye", "sabine", "sable", "sabra", "sac", "sachs", "sack", "sad", "saddle", "sadie", "safari", "safe", "sag", "saga", "sage", "sago", "said", "sail", "saint", "sake", "sal", "salad", "sale", "salem", "saline", "salk", "salle", "sally", "salon", "salt", "salty", "salve", "salvo", "sam", "samba", "same", "sammy", "samoa", "samuel", "san", "sana", "sand", "sandal", "sandy", "sane", "sang", "sank", "sans", "santa", "santo", "sao", "sap", "sappy", "sara", "sarah", "saran", "sari", "sash", "sat", "satan", "satin", "satyr", "sauce", "saucy", "saud", "saudi", "saul", "sault", "saute", "save", "savoy", "savvy", "saw", "sawyer", "sax", "saxon", "say", "scab", "scala", "scald", "scale", "scalp", "scam", "scamp", "scan", "scant", "scar", "scare", "scarf", "scary", "scat", "scaup", "scene", "scent", "school", "scion", "scm", "scoff", "scold", "scoop", "scoot", "scope", "scops", "score", "scoria", "scorn", "scot", "scott", "scour", "scout", "scowl", "scram", "scrap", "scrape", "screw", "scrim", "scrub", "scuba", "scud", "scuff", "scull", "scum", "scurry", "sea", "seal", "seam", "seamy", "sean", "sear", "sears", "season", "seat", "sec", "secant", "sect", "sedan", "seder", "sedge", "see", "seed", "seedy", "seek", "seem", "seen", "seep", "seethe", "seize", "self", "sell", "selma", "semi", "sen", "send", "seneca", "senor", "sense", "sent", "sentry", "seoul", "sepal", "sepia", "sepoy", "sept", "septa", "sequin", "sera", "serf", "serge", "serif", "serum", "serve", "servo", "set", "seth", "seton", "setup", "seven", "sever", "severe", "sew", "sewn", "sex", "sexy", "shack", "shad", "shade", "shady", "shafer", "shaft", "shag", "shah", "shake", "shaken", "shako", "shaky", "shale", "shall", "sham", "shame", "shank", "shape", "shard", "share", "shari", "shark", "sharp", "shave", "shaw", "shawl", "shay", "she", "shea", "sheaf", "shear", "sheath", "shed", "sheen", "sheep", "sheer", "sheet", "sheik", "shelf", "shell", "shied", "shift", "shill", "shim", "shin", "shine", "shinto", "shiny", "ship", "shire", "shirk", "shirt", "shish", "shiv", "shoal", "shock", "shod", "shoe", "shoji", "shone", "shoo", "shook", "shoot", "shop", "shore", "short", "shot", "shout", "shove", "show", "shown", "showy", "shrank", "shred", "shrew", "shrike", "shrub", "shrug", "shu", "shuck", "shun", "shunt", "shut", "shy", "sial", "siam", "sian", "sib", "sibley", "sibyl", "sic", "sick", "side", "sidle", "siege", "siena", "sieve", "sift", "sigh", "sight", "sigma", "sign", "signal", "signor", "silas", "silk", "silky", "sill", "silly", "silo", "silt", "silty", "sima", "simon", "simons", "sims", "sin", "sinai", "since", "sine", "sinew", "sing", "singe", "sinh", "sink", "sinus", "sioux", "sip", "sir", "sire", "siren", "sis", "sisal", "sit", "site", "situ", "situs", "siva", "six", "sixgun", "sixth", "sixty", "size", "skat", "skate", "skeet", "skew", "ski", "skid", "skied", "skiff", "skill", "skim", "skimp", "skimpy", "skin", "skip", "skirt", "skit", "skulk", "skull", "skunk", "sky", "skye", "slab", "slack", "slag", "slain", "slake", "slam", "slang", "slant", "slap", "slash", "slat", "slate", "slater", "slav", "slave", "slay", "sled", "sleek", "sleep", "sleet", "slept", "slew", "slice", "slick", "slid", "slide", "slim", "slime", "slimy", "sling", "slip", "slit", "sliver", "sloan", "slob", "sloe", "slog", "sloop", "slop", "slope", "slosh", "slot", "sloth", "slow", "slug", "sluice", "slum", "slump", "slung", "slur", "slurp", "sly", "smack", "small", "smart", "smash", "smear", "smell", "smelt", "smile", "smirk", "smith", "smithy", "smog", "smoke", "smoky", "smug", "smut", "snack", "snafu", "snag", "snail", "snake", "snap", "snare", "snark", "snarl", "snatch", "sneak", "sneer", "snell", "snick", "sniff", "snip", "snipe", "snob", "snook", "snoop", "snore", "snort", "snout", "snow", "snowy", "snub", "snuff", "snug", "soak", "soap", "soapy", "soar", "sob", "sober", "social", "sock", "sod", "soda", "sofa", "sofia", "soft", "soften", "soggy", "soil", "sol", "solar", "sold", "sole", "solemn", "solid", "solo", "solon", "solve", "soma", "somal", "some", "son", "sonar", "song", "sonic", "sonny", "sonora", "sony", "soon", "soot", "sooth", "sop", "sora", "sorb", "sore", "sorry", "sort", "sos", "sou", "sough", "soul", "sound", "soup", "sour", "source", "sousa", "south", "sow", "sown", "soy", "soya", "spa", "space", "spade", "spain", "span", "spar", "spare", "sparge", "spark", "spasm", "spat", "spate", "spawn", "spay", "speak", "spear", "spec", "speck", "sped", "speed", "spell", "spend", "spent", "sperm", "sperry", "spew", "spica", "spice", "spicy", "spike", "spiky", "spill", "spilt", "spin", "spine", "spiny", "spire", "spiro", "spit", "spite", "spitz", "splat", "splay", "spline", "split", "spoil", "spoke", "spoof", "spook", "spooky", "spool", "spoon", "spore", "sport", "spot", "spout", "sprain", "spray", "spree", "sprig", "spruce", "sprue", "spud", "spume", "spun", "spunk", "spur", "spurn", "spurt", "spy", "squad", "squat", "squaw", "squibb", "squid", "squint", "sri", "sss", "ssss", "sst", "st.", "stab", "stack", "stacy", "staff", "stag", "stage", "stagy", "stahl", "staid", "stain", "stair", "stake", "stale", "stalk", "stall", "stamp", "stan", "stance", "stand", "stank", "staph", "star", "stare", "stark", "starr", "start", "stash", "state", "statue", "stave", "stay", "stead", "steak", "steal", "steam", "steed", "steel", "steele", "steen", "steep", "steer", "stein", "stella", "stem", "step", "stern", "steve", "stew", "stick", "stiff", "stile", "still", "stilt", "sting", "stingy", "stink", "stint", "stir", "stock", "stoic", "stoke", "stole", "stomp", "stone", "stony", "stood", "stool", "stoop", "stop", "store", "storey", "stork", "storm", "story", "stout", "stove", "stow", "strafe", "strap", "straw", "stray", "strewn", "strip", "stroll", "strom", "strop", "strum", "strut", "stu", "stuart", "stub", "stuck", "stud", "study", "stuff", "stuffy", "stump", "stun", "stung", "stunk", "stunt", "sturm", "style", "styli", "styx", "suave", "sub", "subtly", "such", "suck", "sud", "sudan", "suds", "sue", "suey", "suez", "sugar", "suit", "suite", "sulfa", "sulk", "sulky", "sully", "sultry", "sum", "sumac", "summon", "sun", "sung", "sunk", "sunny", "sunset", "suny", "sup", "super", "supra", "sure", "surf", "surge", "sus", "susan", "sushi", "susie", "sutton", "swab", "swag", "swain", "swam", "swami", "swamp", "swampy", "swan", "swank", "swap", "swarm", "swart", "swat", "swath", "sway", "swear", "sweat", "sweaty", "swede", "sweep", "sweet", "swell", "swelt", "swept", "swift", "swig", "swim", "swine", "swing", "swipe", "swirl", "swish", "swiss", "swoop", "sword", "swore", "sworn", "swum", "swung", "sybil", "sykes", "sylow", "sylvan", "synge", "synod", "syria", "syrup", "tab", "table", "taboo", "tabu", "tabula", "tacit", "tack", "tacky", "tacoma", "tact", "tad", "taffy", "taft", "tag", "tahoe", "tail", "taint", "take", "taken", "talc", "tale", "talk", "talky", "tall", "tallow", "tally", "talon", "talus", "tam", "tame", "tamp", "tampa", "tan", "tang", "tango", "tangy", "tanh", "tank", "tansy", "tanya", "tao", "taos", "tap", "tapa", "tape", "taper", "tapir", "tapis", "tappa", "tar", "tara", "tardy", "tariff", "tarry", "tart", "task", "tass", "taste", "tasty", "tat", "tate", "tater", "tattle", "tatty", "tau", "taunt", "taut", "tavern", "tawny", "tax", "taxi", "tea", "teach", "teal", "team", "tear", "tease", "teat", "tech", "tecum", "ted", "teddy", "tee", "teem", "teen", "teensy", "teet", "teeth", "telex", "tell", "tempo", "tempt", "ten", "tend", "tenet", "tenney", "tenon", "tenor", "tense", "tensor", "tent", "tenth", "tepee", "tepid", "term", "tern", "terra", "terre", "terry", "terse", "tess", "test", "testy", "tete", "texan", "texas", "text", "thai", "than", "thank", "that", "thaw", "the", "thea", "thee", "theft", "their", "them", "theme", "then", "there", "these", "theta", "they", "thick", "thief", "thigh", "thin", "thine", "thing", "think", "third", "this", "thong", "thor", "thorn", "thorny", "those", "thou", "thread", "three", "threw", "throb", "throes", "throw", "thrum", "thud", "thug", "thule", "thumb", "thump", "thus", "thy", "thyme", "tiber", "tibet", "tibia", "tic", "tick", "ticket", "tid", "tidal", "tidbit", "tide", "tidy", "tie", "tied", "tier", "tift", "tiger", "tight", "til", "tilde", "tile", "till", "tilt", "tilth", "tim", "time", "timex", "timid", "timon", "tin", "tina", "tine", "tinge", "tint", "tiny", "tioga", "tip", "tipoff", "tippy", "tipsy", "tire", "tit", "titan", "tithe", "title", "titus", "tnt", "toad", "toady", "toast", "toby", "today", "todd", "toe", "tofu", "tog", "togo", "togs", "toil", "toilet", "token", "tokyo", "told", "toll", "tom", "tomb", "tome", "tommy", "ton", "tonal", "tone", "tong", "toni", "tonic", "tonk", "tonsil", "tony", "too", "took", "tool", "toot", "tooth", "top", "topaz", "topic", "topple", "topsy", "tor", "torah", "torch", "tore", "tori", "torn", "torr", "torso", "tort", "torus", "tory", "toss", "tot", "total", "tote", "totem", "touch", "tough", "tour", "tout", "tow", "towel", "tower", "town", "toxic", "toxin", "toy", "trace", "track", "tract", "tracy", "trade", "trag", "trail", "train", "trait", "tram", "tramp", "trap", "trash", "trawl", "tread", "treat", "treble", "tree", "trek", "trench", "trend", "tress", "triad", "trial", "tribe", "trick", "tried", "trig", "trill", "trim", "trio", "trip", "tripe", "trite", "triton", "trod", "troll", "troop", "trot", "trout", "troy", "truce", "truck", "trudge", "trudy", "true", "truly", "trump", "trunk", "truss", "trust", "truth", "trw", "try", "tsar", "ttl", "ttt", "tttt", "tty", "tub", "tuba", "tube", "tuck", "tudor", "tuff", "tuft", "tug", "tulane", "tulip", "tulle", "tulsa", "tum", "tun", "tuna", "tune", "tung", "tunic", "tunis", "tunnel", "tuple", "turf", "turin", "turk", "turn", "turvy", "tusk", "tussle", "tutor", "tutu", "tuv", "tva", "twa", "twain", "tweak", "tweed", "twice", "twig", "twill", "twin", "twine", "twirl", "twist", "twisty", "twit", "two", "twx", "tyburn", "tying", "tyler", "type", "typic", "typo", "tyson", "ucla", "ugh", "ugly", "ulan", "ulcer", "ultra", "umber", "umbra", "umpire", "unary", "uncle", "under", "unify", "union", "unit", "unite", "unity", "unix", "until", "upend", "uphold", "upon", "upper", "uproar", "upset", "uptake", "upton", "urban", "urbane", "urea", "urge", "uri", "urine", "uris", "urn", "ursa", "usa", "usaf", "usage", "usc", "usda", "use", "useful", "usgs", "usher", "usia", "usn", "usps", "ussr", "usual", "usurp", "usury", "utah", "utica", "utile", "utmost", "utter", "uuu", "uuuu", "uvw", "vacua", "vacuo", "vade", "vaduz", "vague", "vail", "vain", "vale", "valet", "valeur", "valid", "value", "valve", "vamp", "van", "vance", "vane", "vary", "vase", "vast", "vat", "vault", "veal", "veda", "vee", "veer", "veery", "vega", "veil", "vein", "velar", "veldt", "vella", "vellum", "venal", "vend", "venial", "venom", "vent", "venus", "vera", "verb", "verde", "verdi", "verge", "verity", "verna", "verne", "versa", "verse", "verve", "very", "vessel", "vest", "vet", "vetch", "veto", "vex", "via", "vial", "vicar", "vice", "vichy", "vicky", "vida", "video", "vie", "viet", "view", "vigil", "vii", "viii", "vile", "villa", "vine", "vinyl", "viola", "violet", "virgil", "virgo", "virus", "vis", "visa", "vise", "visit", "visor", "vista", "vita", "vitae", "vital", "vito", "vitro", "viva", "vivian", "vivid", "vivo", "vixen", "viz", "vocal", "vogel", "vogue", "voice", "void", "volt", "volta", "volvo", "vomit", "von", "voss", "vote", "vouch", "vow", "vowel", "vulcan", "vvv", "vvvv", "vying", "waals", "wac", "wack", "wacke", "wacky", "waco", "wad", "wade", "wadi", "wafer", "wag", "wage", "waggle", "wah", "wahl", "wail", "waist", "wait", "waite", "waive", "wake", "waken", "waldo", "wale", "walk", "walkie", "wall", "walls", "wally", "walsh", "walt", "walton", "waltz", "wan", "wand", "wane", "wang", "want", "war", "ward", "ware", "warm", "warmth", "warn", "warp", "warren", "wart", "warty", "wary", "was", "wash", "washy", "wasp", "wast", "waste", "watch", "water", "watt", "watts", "wave", "wavy", "wax", "waxen", "waxy", "way", "wayne", "weak", "weal", "wealth", "wean", "wear", "weary", "weave", "web", "webb", "weber", "weco", "wed", "wedge", "wee", "weed", "weedy", "week", "weeks", "weep", "wehr", "wei", "weigh", "weir", "weird", "weiss", "welch", "weld", "well", "wells", "welsh", "welt", "wendy", "went", "wept", "were", "wert", "west", "wet", "whack", "whale", "wham", "wharf", "what", "wheat", "whee", "wheel", "whelk", "whelm", "whelp", "when", "where", "whet", "which", "whiff", "whig", "while", "whim", "whine", "whinny", "whip", "whir", "whirl", "whisk", "whit", "white", "whiz", "who", "whoa", "whole", "whom", "whoop", "whoosh", "whop", "whose", "whup", "why", "wick", "wide", "widen", "widow", "width", "wield", "wier", "wife", "wig", "wild", "wile", "wiley", "wilkes", "will", "willa", "wills", "wilma", "wilt", "wily", "win", "wince", "winch", "wind", "windy", "wine", "wing", "wink", "winnie", "wino", "winter", "winy", "wipe", "wire", "wiry", "wise", "wish", "wishy", "wisp", "wispy", "wit", "witch", "with", "withe", "withy", "witt", "witty", "wive", "woe", "wok", "woke", "wold", "wolf", "wolfe", "wolff", "wolve", "woman", "womb", "women", "won", "wonder", "wong", "wont", "woo", "wood", "woods", "woody", "wool", "woozy", "word", "wordy", "wore", "work", "world", "worm", "wormy", "worn", "worry", "worse", "worst", "worth", "wotan", "would", "wound", "wove", "woven", "wow", "wrack", "wrap", "wrath", "wreak", "wreck", "wrest", "wring", "wrist", "writ", "write", "writhe", "wrong", "wrote", "wry", "wuhan", "www", "wwww", "wxy", "wyatt", "wyeth", "wylie", "wyman", "wyner", "wynn", "xenon", "xerox", "xxx", "xxxx", "xylem", "xyz", "yacht", "yah", "yak", "yale", "yalta", "yam", "yamaha", "yang", "yank", "yap", "yaqui", "yard", "yarn", "yates", "yaw", "yawl", "yawn", "yea", "yeah", "year", "yearn", "yeast", "yeasty", "yeats", "yell", "yelp", "yemen", "yen", "yet", "yield", "yin", "yip", "ymca", "yodel", "yoder", "yoga", "yogi", "yoke", "yokel", "yolk", "yon", "yond", "yore", "york", "yost", "you", "young", "your", "youth", "yow", "yucca", "yuck", "yuh", "yuki", "yukon", "yule", "yves", "ywca", "yyy", "yyyy", "zag", "zaire", "zan", "zap", "zazen", "zeal", "zealot", "zebra", "zeiss", "zen", "zero", "zest", "zesty", "zeta", "zeus", "zig", "zilch", "zinc", "zing", "zion", "zip", "zloty", "zoe", "zomba", "zone", "zoo", "zoom", "zorn", "zurich", "zzz", "zzzz"]
14.535698
15
0.312151
wl = ["aah", "aaron", "aba", "ababa", "aback", "abase", "abash", "abate", "abbas", "abbe", "abbey", "abbot", "abbott", "abc", "abe", "abed", "abel", "abet", "abide", "abject", "ablaze", "able", "abner", "abo", "abode", "abort", "about", "above", "abrade", "abram", "absorb", "abuse", "abut", "abyss", "acadia", "accra", "accrue", "ace", "acetic", "ache", "acid", "acidic", "acm", "acme", "acorn", "acre", "acrid", "act", "acton", "actor", "acts", "acuity", "acute", "ada", "adage", "adagio", "adair", "adam", "adams", "adapt", "add", "added", "addict", "addis", "addle", "adele", "aden", "adept", "adieu", "adjust", "adler", "admit", "admix", "ado", "adobe", "adonis", "adopt", "adore", "adorn", "adult", "advent", "advert", "advise", "aegis", "aeneid", "afar", "affair", "affine", "affix", "afire", "afoot", "afraid", "africa", "afro", "aft", "again", "agate", "agave", "age", "age", "agenda", "agent", "agile", "aging", "agnes", "agnew", "ago", "agone", "agony", "agree", "ague", "agway", "ahead", "ahem", "ahoy", "aid", "aida", "aide", "aides", "aiken", "ail", "aile", "aim", "ainu", "air", "aires", "airman", "airway", "airy", "aisle", "ajar", "ajax", "akers", "akin", "akron", "ala", "alai", "alamo", "alan", "alarm", "alaska", "alb", "alba", "album", "alcoa", "alden", "alder", "ale", "alec", "aleck", "aleph", "alert", "alex", "alexei", "alga", "algae", "algal", "alger", "algol", "ali", "alia", "alias", "alibi", "alice", "alien", "alight", "align", "alike", "alive", "all", "allah", "allan", "allay", "allen", "alley", "allied", "allis", "allot", "allow", "alloy", "allure", "ally", "allyl", "allyn", "alma", "almost", "aloe", "aloft", "aloha", "alone", "along", "aloof", "aloud", "alp", "alpha", "alps", "also", "alsop", "altair", "altar", "alter", "alto", "alton", "alum", "alumni", "alva", "alvin", "alway", "ama", "amass", "amaze", "amber", "amble", "ambush", "amen", "amend", "ames", "ami", "amid", "amide", "amigo", "amino", "amiss", "amity", "amman", "ammo", "amoco", "amok", "among", "amort", "amos", "amp", "ampere", "ampex", "ample", "amply", "amra", "amulet", "amuse", "amy", "ana", "and", "andes", "andre", "andrew", "andy", "anent", "anew", "angel", "angelo", "anger", "angie", "angle", "anglo", "angola", "angry", "angst", "angus", "ani", "anion", "anise", "anita", "ankle", "ann", "anna", "annal", "anne", "annex", "annie", "annoy", "annul", "annuli", "annum", "anode", "ansi", "answer", "ant", "ante", "anti", "antic", "anton", "anus", "anvil", "any", "anyhow", "anyway", "aok", "aorta", "apart", "apathy", "ape", "apex", "aphid", "aplomb", "appeal", "append", "apple", "apply", "april", "apron", "apse", "apt", "aqua", "arab", "araby", "arc", "arcana", "arch", "archer", "arden", "ardent", "are", "area", "arena", "ares", "argive", "argo", "argon", "argot", "argue", "argus", "arhat", "arid", "aries", "arise", "ark", "arlen", "arlene", "arm", "armco", "army", "arnold", "aroma", "arose", "arpa", "array", "arrear", "arrow", "arson", "art", "artery", "arthur", "artie", "arty", "aruba", "arum", "aryl", "ascend", "ash", "ashen", "asher", "ashley", "ashy", "asia", "aside", "ask", "askew", "asleep", "aspen", "aspire", "ass", "assai", "assam", "assay", "asset", "assort", "assure", "aster", "astm", "astor", "astral", "ate", "athens", "atlas", "atom", "atomic", "atone", "atop", "attic", "attire", "aubrey", "audio", "audit", "aug", "auger", "augur", "august", "auk", "aunt", "aura", "aural", "auric", "austin", "auto", "autumn", "avail", "ave", "aver", "avert", "avery", "aviate", "avid", "avis", "aviv", "avoid", "avon", "avow", "await", "awake", "award", "aware", "awash", "away", "awe", "awful", "awl", "awn", "awoke", "awry", "axe", "axes", "axial", "axiom", "axis", "axle", "axon", "aye", "ayers", "aztec", "azure", "babe", "babel", "baby", "bach", "back", "backup", "bacon", "bad", "bade", "baden", "badge", "baffle", "bag", "baggy", "bah", "bahama", "bail", "baird", "bait", "bake", "baku", "bald", "baldy", "bale", "bali", "balk", "balkan", "balky", "ball", "balled", "ballot", "balm", "balmy", "balsa", "bam", "bambi", "ban", "banal", "band", "bandit", "bandy", "bane", "bang", "banish", "banjo", "bank", "banks", "bantu", "bar", "barb", "bard", "bare", "barfly", "barge", "bark", "barley", "barn", "barnes", "baron", "barony", "barr", "barre", "barry", "barter", "barth", "barton", "basal", "base", "basel", "bash", "basic", "basil", "basin", "basis", "bask", "bass", "bassi", "basso", "baste", "bat", "batch", "bate", "bater", "bates", "bath", "bathe", "batik", "baton", "bator", "batt", "bauble", "baud", "bauer", "bawd", "bawdy", "bawl", "baxter", "bay", "bayda", "bayed", "bayou", "bazaar", "bbb", "bbbb", "bcd", "beach", "bead", "beady", "beak", "beam", "bean", "bear", "beard", "beast", "beat", "beau", "beauty", "beaux", "bebop", "becalm", "beck", "becker", "becky", "bed", "bedim", "bee", "beebe", "beech", "beef", "beefy", "been", "beep", "beer", "beet", "befall", "befit", "befog", "beg", "began", "beget", "beggar", "begin", "begun", "behind", "beige", "being", "beirut", "bel", "bela", "belch", "belfry", "belie", "bell", "bella", "belle", "belly", "below", "belt", "bema", "beman", "bemoan", "ben", "bench", "bend", "bender", "benny", "bent", "benz", "berea", "bereft", "beret", "berg", "berlin", "bern", "berne", "bernet", "berra", "berry", "bert", "berth", "beryl", "beset", "bess", "bessel", "best", "bestir", "bet", "beta", "betel", "beth", "bethel", "betsy", "bette", "betty", "bevel", "bevy", "beware", "bey", "bezel", "bhoy", "bias", "bib", "bibb", "bible", "bicep", "biceps", "bid", "biddy", "bide", "bien", "big", "biggs", "bigot", "bile", "bilge", "bilk", "bill", "billow", "billy", "bin", "binary", "bind", "bing", "binge", "bingle", "bini", "biota", "birch", "bird", "birdie", "birth", "bison", "bisque", "bit", "bitch", "bite", "bitt", "bitten", "biz", "bizet", "blab", "black", "blade", "blair", "blake", "blame", "blanc", "bland", "blank", "blare", "blast", "blat", "blatz", "blaze", "bleak", "bleat", "bled", "bleed", "blend", "bless", "blest", "blew", "blimp", "blind", "blink", "blinn", "blip", "bliss", "blithe", "blitz", "bloat", "blob", "bloc", "bloch", "block", "bloke", "blond", "blonde", "blood", "bloom", "bloop", "blot", "blotch", "blow", "blown", "blue", "bluet", "bluff", "blum", "blunt", "blur", "blurt", "blush", "blvd", "blythe", "bmw", "boa", "boar", "board", "boast", "boat", "bob", "bobbin", "bobby", "bobcat", "boca", "bock", "bode", "body", "bog", "bogey", "boggy", "bogus", "bogy", "bohr", "boil", "bois", "boise", "bold", "bole", "bolo", "bolt", "bomb", "bombay", "bon", "bona", "bond", "bone", "bong", "bongo", "bonn", "bonus", "bony", "bonze", "boo", "booby", "boogie", "book", "booky", "boom", "boon", "boone", "boor", "boost", "boot", "booth", "booty", "booze", "bop", "borax", "border", "bore", "borg", "boric", "boris", "born", "borne", "borneo", "boron", "bosch", "bose", "bosom", "boson", "boss", "boston", "botch", "both", "bottle", "bough", "bouncy", "bound", "bourn", "bout", "bovine", "bow", "bowel", "bowen", "bowie", "bowl", "box", "boxy", "boy", "boyar", "boyce", "boyd", "boyle", "brace", "bract", "brad", "brady", "brae", "brag", "bragg", "braid", "brain", "brainy", "brake", "bran", "brand", "brandt", "brant", "brash", "brass", "brassy", "braun", "brave", "bravo", "brawl", "bray", "bread", "break", "bream", "breath", "bred", "breed", "breeze", "bremen", "brent", "brest", "brett", "breve", "brew", "brian", "briar", "bribe", "brice", "brick", "bride", "brief", "brig", "briggs", "brim", "brine", "bring", "brink", "briny", "brisk", "broad", "brock", "broil", "broke", "broken", "bronx", "brood", "brook", "brooke", "broom", "broth", "brow", "brown", "browse", "bruce", "bruit", "brunch", "bruno", "brunt", "brush", "brute", "bryan", "bryant", "bryce", "bryn", "bstj", "btl", "bub", "buck", "bud", "budd", "buddy", "budge", "buena", "buenos", "buff", "bug", "buggy", "bugle", "buick", "build", "built", "bulb", "bulge", "bulk", "bulky", "bull", "bully", "bum", "bump", "bun", "bunch", "bundy", "bunk", "bunny", "bunt", "bunyan", "buoy", "burch", "bureau", "buret", "burg", "buried", "burke", "burl", "burly", "burma", "burn", "burnt", "burp", "burr", "burro", "burst", "burt", "burton", "burtt", "bury", "bus", "busch", "bush", "bushel", "bushy", "buss", "bust", "busy", "but", "butane", "butch", "buteo", "butt", "butte", "butyl", "buxom", "buy", "buyer", "buzz", "buzzy", "bye", "byers", "bylaw", "byline", "byrd", "byrne", "byron", "byte", "byway", "byword", "cab", "cabal", "cabin", "cable", "cabot", "cacao", "cache", "cacm", "cacti", "caddy", "cadent", "cadet", "cadre", "cady", "cafe", "cage", "cagey", "cahill", "caiman", "cain", "caine", "cairn", "cairo", "cake", "cal", "calder", "caleb", "calf", "call", "calla", "callus", "calm", "calve", "cam", "camber", "came", "camel", "cameo", "camp", "can", "canal", "canary", "cancer", "candle", "candy", "cane", "canis", "canna", "cannot", "canny", "canoe", "canon", "canopy", "cant", "canto", "canton", "cap", "cape", "caper", "capo", "car", "carbon", "card", "care", "caress", "caret", "carey", "cargo", "carib", "carl", "carla", "carlo", "carne", "carob", "carol", "carp", "carpet", "carr", "carrie", "carry", "carson", "cart", "carte", "caruso", "carve", "case", "casey", "cash", "cashew", "cask", "casket", "cast", "caste", "cat", "catch", "cater", "cathy", "catkin", "catsup", "cauchy", "caulk", "cause", "cave", "cavern", "cavil", "cavort", "caw", "cayuga", "cbs", "ccc", "cccc", "cdc", "cease", "cecil", "cedar", "cede", "ceil", "celia", "cell", "census", "cent", "ceres", "cern", "cetera", "cetus", "chad", "chafe", "chaff", "chai", "chain", "chair", "chalk", "champ", "chance", "chang", "chant", "chao", "chaos", "chap", "chapel", "char", "chard", "charm", "chart", "chase", "chasm", "chaste", "chat", "chaw", "cheap", "cheat", "check", "cheek", "cheeky", "cheer", "chef", "chen", "chert", "cherub", "chess", "chest", "chevy", "chew", "chi", "chic", "chick", "chide", "chief", "child", "chile", "chili", "chill", "chilly", "chime", "chin", "china", "chine", "chink", "chip", "chirp", "chisel", "chit", "chive", "chock", "choir", "choke", "chomp", "chop", "chopin", "choral", "chord", "chore", "chose", "chosen", "chou", "chow", "chris", "chub", "chuck", "chuff", "chug", "chum", "chump", "chunk", "churn", "chute", "cia", "cicada", "cider", "cigar", "cilia", "cinch", "cindy", "cipher", "circa", "circe", "cite", "citrus", "city", "civet", "civic", "civil", "clad", "claim", "clam", "clammy", "clamp", "clan", "clang", "clank", "clap", "clara", "clare", "clark", "clarke", "clash", "clasp", "class", "claus", "clause", "claw", "clay", "clean", "clear", "cleat", "cleft", "clerk", "cliche", "click", "cliff", "climb", "clime", "cling", "clink", "clint", "clio", "clip", "clive", "cloak", "clock", "clod", "clog", "clomp", "clone", "close", "closet", "clot", "cloth", "cloud", "clout", "clove", "clown", "cloy", "club", "cluck", "clue", "cluj", "clump", "clumsy", "clung", "clyde", "coach", "coal", "coast", "coat", "coax", "cobb", "cobble", "cobol", "cobra", "coca", "cock", "cockle", "cocky", "coco", "cocoa", "cod", "coda", "coddle", "code", "codon", "cody", "coed", "cog", "cogent", "cohen", "cohn", "coil", "coin", "coke", "col", "cola", "colby", "cold", "cole", "colon", "colony", "colt", "colza", "coma", "comb", "combat", "come", "comet", "cometh", "comic", "comma", "con", "conch", "cone", "coney", "congo", "conic", "conn", "conner", "conway", "cony", "coo", "cook", "cooke", "cooky", "cool", "cooley", "coon", "coop", "coors", "coot", "cop", "cope", "copra", "copy", "coral", "corbel", "cord", "core", "corey", "cork", "corn", "corny", "corp", "corps", "corvus", "cos", "cosec", "coset", "cosh", "cost", "costa", "cosy", "cot", "cotta", "cotty", "couch", "cough", "could", "count", "coup", "coupe", "court", "cousin", "cove", "coven", "cover", "covet", "cow", "cowan", "cowl", "cowman", "cowry", "cox", "coy", "coyote", "coypu", "cozen", "cozy", "cpa", "crab", "crack", "craft", "crag", "craig", "cram", "cramp", "crane", "crank", "crap", "crash", "crass", "crate", "crater", "crave", "craw", "crawl", "craze", "crazy", "creak", "cream", "credit", "credo", "creed", "creek", "creep", "creole", "creon", "crepe", "crept", "cress", "crest", "crete", "crew", "crib", "cried", "crime", "crimp", "crisp", "criss", "croak", "crock", "crocus", "croft", "croix", "crone", "crony", "crook", "croon", "crop", "cross", "crow", "crowd", "crown", "crt", "crud", "crude", "cruel", "crumb", "crump", "crush", "crust", "crux", "cruz", "cry", "crypt", "cub", "cuba", "cube", "cubic", "cud", "cuddle", "cue", "cuff", "cull", "culpa", "cult", "cumin", "cuny", "cup", "cupful", "cupid", "cur", "curb", "curd", "cure", "curfew", "curia", "curie", "curio", "curl", "curry", "curse", "curt", "curve", "cusp", "cut", "cute", "cutlet", "cycad", "cycle", "cynic", "cyril", "cyrus", "cyst", "czar", "czech", "dab", "dacca", "dactyl", "dad", "dada", "daddy", "dade", "daffy", "dahl", "dahlia", "dairy", "dais", "daisy", "dakar", "dale", "daley", "dally", "daly", "dam", "dame", "damn", "damon", "damp", "damsel", "dan", "dana", "dance", "dandy", "dane", "dang", "dank", "danny", "dante", "dar", "dare", "dark", "darken", "darn", "darry", "dart", "dash", "data", "date", "dater", "datum", "daub", "daunt", "dave", "david", "davis", "davit", "davy", "dawn", "dawson", "day", "daze", "ddd", "dddd", "deacon", "dead", "deaf", "deal", "dealt", "dean", "deane", "dear", "death", "debar", "debby", "debit", "debra", "debris", "debt", "debug", "debut", "dec", "decal", "decay", "decca", "deck", "decker", "decor", "decree", "decry", "dee", "deed", "deem", "deep", "deer", "deere", "def", "defer", "deform", "deft", "defy", "degas", "degum", "deify", "deign", "deity", "deja", "del", "delay", "delft", "delhi", "delia", "dell", "della", "delta", "delve", "demark", "demit", "demon", "demur", "den", "deneb", "denial", "denny", "dense", "dent", "denton", "deny", "depot", "depth", "depute", "derby", "derek", "des", "desist", "desk", "detach", "deter", "deuce", "deus", "devil", "devoid", "devon", "dew", "dewar", "dewey", "dewy", "dey", "dhabi", "dial", "diana", "diane", "diary", "dibble", "dice", "dick", "dicta", "did", "dido", "die", "died", "diego", "diem", "diesel", "diet", "diety", "dietz", "dig", "digit", "dilate", "dill", "dim", "dime", "din", "dinah", "dine", "ding", "dingo", "dingy", "dint", "diode", "dip", "dirac", "dire", "dirge", "dirt", "dirty", "dis", "disc", "dish", "disk", "disney", "ditch", "ditto", "ditty", "diva", "divan", "dive", "dixie", "dixon", "dizzy", "dna", "dobbs", "dobson", "dock", "docket", "dod", "dodd", "dodge", "dodo", "doe", "doff", "dog", "doge", "dogma", "dolan", "dolce", "dole", "doll", "dolly", "dolt", "dome", "don", "done", "doneck", "donna", "donor", "doom", "door", "dope", "dora", "doria", "doric", "doris", "dose", "dot", "dote", "double", "doubt", "douce", "doug", "dough", "dour", "douse", "dove", "dow", "dowel", "down", "downs", "dowry", "doyle", "doze", "dozen", "drab", "draco", "draft", "drag", "drain", "drake", "dram", "drama", "drank", "drape", "draw", "drawl", "drawn", "dread", "dream", "dreamy", "dreg", "dress", "dressy", "drew", "drib", "dried", "drier", "drift", "drill", "drink", "drip", "drive", "droll", "drone", "drool", "droop", "drop", "dross", "drove", "drown", "drub", "drug", "druid", "drum", "drunk", "drury", "dry", "dryad", "dual", "duane", "dub", "dubhe", "dublin", "ducat", "duck", "duct", "dud", "due", "duel", "duet", "duff", "duffy", "dug", "dugan", "duke", "dull", "dully", "dulse", "duly", "duma", "dumb", "dummy", "dump", "dumpy", "dun", "dunce", "dune", "dung", "dunham", "dunk", "dunlop", "dunn", "dupe", "durer", "dusk", "dusky", "dust", "dusty", "dutch", "duty", "dwarf", "dwell", "dwelt", "dwight", "dwyer", "dyad", "dye", "dyer", "dying", "dyke", "dylan", "dyne", "each", "eagan", "eager", "eagle", "ear", "earl", "earn", "earth", "ease", "easel", "east", "easy", "eat", "eaten", "eater", "eaton", "eave", "ebb", "eben", "ebony", "echo", "eclat", "ecole", "eddie", "eddy", "eden", "edgar", "edge", "edgy", "edict", "edify", "edit", "edith", "editor", "edna", "edt", "edwin", "eee", "eeee", "eel", "eeoc", "eerie", "efface", "effie", "efg", "eft", "egan", "egg", "ego", "egress", "egret", "egypt", "eider", "eight", "eire", "eject", "eke", "elan", "elate", "elba", "elbow", "elder", "eldon", "elect", "elegy", "elena", "eleven", "elfin", "elgin", "eli", "elide", "eliot", "elite", "elk", "ell", "ella", "ellen", "ellis", "elm", "elmer", "elope", "else", "elsie", "elton", "elude", "elute", "elves", "ely", "embalm", "embark", "embed", "ember", "emcee", "emery", "emil", "emile", "emily", "emit", "emma", "emory", "empty", "enact", "enamel", "end", "endow", "enemy", "eng", "engel", "engle", "engulf", "enid", "enjoy", "enmity", "enoch", "enol", "enos", "enrico", "ensue", "enter", "entrap", "entry", "envoy", "envy", "epa", "epic", "epoch", "epoxy", "epsom", "equal", "equip", "era", "erase", "erato", "erda", "ere", "erect", "erg", "eric", "erich", "erie", "erik", "ernest", "ernie", "ernst", "erode", "eros", "err", "errand", "errol", "error", "erupt", "ervin", "erwin", "essay", "essen", "essex", "est", "ester", "estes", "estop", "eta", "etc", "etch", "ethan", "ethel", "ether", "ethic", "ethos", "ethyl", "etude", "eucre", "euler", "eureka", "eva", "evade", "evans", "eve", "even", "event", "every", "evict", "evil", "evoke", "evolve", "ewe", "ewing", "exact", "exalt", "exam", "excel", "excess", "exert", "exile", "exist", "exit", "exodus", "expel", "extant", "extent", "extol", "extra", "exude", "exult", "exxon", "eye", "eyed", "ezra", "faa", "faber", "fable", "face", "facet", "facile", "fact", "facto", "fad", "fade", "faery", "fag", "fahey", "fail", "fain", "faint", "fair", "fairy", "faith", "fake", "fall", "false", "fame", "fan", "fancy", "fang", "fanny", "fanout", "far", "farad", "farce", "fare", "fargo", "farley", "farm", "faro", "fast", "fat", "fatal", "fate", "fatty", "fault", "faun", "fauna", "faust", "fawn", "fay", "faze", "fbi", "fcc", "fda", "fear", "feast", "feat", "feb", "fed", "fee", "feed", "feel", "feet", "feign", "feint", "felice", "felix", "fell", "felon", "felt", "femur", "fence", "fend", "fermi", "fern", "ferric", "ferry", "fest", "fetal", "fetch", "fete", "fetid", "fetus", "feud", "fever", "few", "fff", "ffff", "fgh", "fiat", "fib", "fibrin", "fiche", "fide", "fief", "field", "fiend", "fiery", "fife", "fifo", "fifth", "fifty", "fig", "fight", "filch", "file", "filet", "fill", "filler", "filly", "film", "filmy", "filth", "fin", "final", "finale", "finch", "find", "fine", "finite", "fink", "finn", "finny", "fir", "fire", "firm", "first", "fish", "fishy", "fisk", "fiske", "fist", "fit", "fitch", "five", "fix", "fjord", "flack", "flag", "flail", "flair", "flak", "flake", "flaky", "flam", "flame", "flank", "flap", "flare", "flash", "flask", "flat", "flatus", "flaw", "flax", "flea", "fleck", "fled", "flee", "fleet", "flesh", "flew", "flex", "flick", "flier", "flinch", "fling", "flint", "flip", "flirt", "flit", "flo", "float", "floc", "flock", "floe", "flog", "flood", "floor", "flop", "floppy", "flora", "flour", "flout", "flow", "flown", "floyd", "flu", "flub", "flue", "fluff", "fluid", "fluke", "flung", "flush", "flute", "flux", "fly", "flyer", "flynn", "fmc", "foal", "foam", "foamy", "fob", "focal", "foci", "focus", "fodder", "foe", "fog", "foggy", "fogy", "foil", "foist", "fold", "foley", "folio", "folk", "folly", "fond", "font", "food", "fool", "foot", "foote", "fop", "for", "foray", "force", "ford", "fore", "forge", "forgot", "fork", "form", "fort", "forte", "forth", "forty", "forum", "foss", "fossil", "foul", "found", "fount", "four", "fovea", "fowl", "fox", "foxy", "foyer", "fpc", "frail", "frame", "fran", "franc", "franca", "frank", "franz", "frau", "fraud", "fray", "freak", "fred", "free", "freed", "freer", "frenzy", "freon", "fresh", "fret", "freud", "frey", "freya", "friar", "frick", "fried", "frill", "frilly", "frisky", "fritz", "fro", "frock", "frog", "from", "front", "frost", "froth", "frown", "froze", "fruit", "fry", "frye", "ftc", "fuchs", "fudge", "fuel", "fugal", "fugue", "fuji", "full", "fully", "fum", "fume", "fun", "fund", "fungal", "fungi", "funk", "funny", "fur", "furl", "furry", "fury", "furze", "fuse", "fuss", "fussy", "fusty", "fuzz", "fuzzy", "gab", "gable", "gabon", "gad", "gadget", "gaff", "gaffe", "gag", "gage", "gail", "gain", "gait", "gal", "gala", "galaxy", "gale", "galen", "gall", "gallop", "galt", "gam", "game", "gamin", "gamma", "gamut", "gander", "gang", "gao", "gap", "gape", "gar", "garb", "garish", "garner", "garry", "garth", "gary", "gas", "gash", "gasp", "gassy", "gate", "gates", "gator", "gauche", "gaudy", "gauge", "gaul", "gaunt", "gaur", "gauss", "gauze", "gave", "gavel", "gavin", "gawk", "gawky", "gay", "gaze", "gear", "gecko", "gee", "geese", "geigy", "gel", "geld", "gem", "gemma", "gene", "genie", "genii", "genoa", "genre", "gent", "gentry", "genus", "gerbil", "germ", "gerry", "get", "getty", "ggg", "gggg", "ghana", "ghent", "ghetto", "ghi", "ghost", "ghoul", "giant", "gibbs", "gibby", "gibe", "giddy", "gift", "gig", "gil", "gila", "gild", "giles", "gill", "gilt", "gimbal", "gimpy", "gin", "gina", "ginn", "gino", "gird", "girl", "girth", "gist", "give", "given", "glad", "gladdy", "glade", "glamor", "gland", "glans", "glare", "glass", "glaze", "gleam", "glean", "glee", "glen", "glenn", "glib", "glide", "glint", "gloat", "glob", "globe", "glom", "gloom", "glory", "gloss", "glove", "glow", "glue", "glued", "gluey", "gluing", "glum", "glut", "glyph", "gmt", "gnarl", "gnash", "gnat", "gnaw", "gnome", "gnp", "gnu", "goa", "goad", "goal", "goat", "gob", "goer", "goes", "goff", "gog", "goggle", "gogh", "gogo", "gold", "golf", "golly", "gone", "gong", "goo", "good", "goode", "goody", "goof", "goofy", "goose", "gop", "gordon", "gore", "goren", "gorge", "gorky", "gorse", "gory", "gosh", "gospel", "got", "gouda", "gouge", "gould", "gourd", "gout", "gown", "gpo", "grab", "grace", "grad", "grade", "grady", "graff", "graft", "grail", "grain", "grand", "grant", "grape", "graph", "grasp", "grass", "grata", "grate", "grater", "grave", "gravy", "gray", "graze", "great", "grebe", "greed", "greedy", "greek", "green", "greer", "greet", "greg", "gregg", "greta", "grew", "grey", "grid", "grief", "grieve", "grill", "grim", "grime", "grimm", "grin", "grind", "grip", "gripe", "grist", "grit", "groan", "groat", "groin", "groom", "grope", "gross", "groton", "group", "grout", "grove", "grow", "growl", "grown", "grub", "gruff", "grunt", "gsa", "guam", "guano", "guard", "guess", "guest", "guide", "guild", "guile", "guilt", "guise", "guitar", "gules", "gulf", "gull", "gully", "gulp", "gum", "gumbo", "gummy", "gun", "gunk", "gunky", "gunny", "gurgle", "guru", "gus", "gush", "gust", "gusto", "gusty", "gut", "gutsy", "guy", "guyana", "gwen", "gwyn", "gym", "gyp", "gypsy", "gyro", "haag", "haas", "habib", "habit", "hack", "had", "hades", "hadron", "hagen", "hager", "hague", "hahn", "haifa", "haiku", "hail", "hair", "hairy", "haiti", "hal", "hale", "haley", "half", "hall", "halma", "halo", "halt", "halvah", "halve", "ham", "hamal", "hamlin", "han", "hand", "handy", "haney", "hang", "hank", "hanna", "hanoi", "hans", "hansel", "hap", "happy", "hard", "hardy", "hare", "harem", "hark", "harley", "harm", "harp", "harpy", "harry", "harsh", "hart", "harvey", "hash", "hasp", "hast", "haste", "hasty", "hat", "hatch", "hate", "hater", "hath", "hatred", "haul", "haunt", "have", "haven", "havoc", "haw", "hawk", "hay", "haydn", "hayes", "hays", "hazard", "haze", "hazel", "hazy", "head", "heady", "heal", "healy", "heap", "hear", "heard", "heart", "heat", "heath", "heave", "heavy", "hebe", "hebrew", "heck", "heckle", "hedge", "heed", "heel", "heft", "hefty", "heigh", "heine", "heinz", "heir", "held", "helen", "helga", "helix", "hell", "hello", "helm", "helmut", "help", "hem", "hemp", "hen", "hence", "henri", "henry", "her", "hera", "herb", "herd", "here", "hero", "heroic", "heron", "herr", "hertz", "hess", "hesse", "hettie", "hetty", "hew", "hewitt", "hewn", "hex", "hey", "hhh", "hhhh", "hiatt", "hick", "hicks", "hid", "hide", "high", "hij", "hike", "hill", "hilly", "hilt", "hilum", "him", "hind", "hindu", "hines", "hinge", "hint", "hip", "hippo", "hippy", "hiram", "hire", "hirsch", "his", "hiss", "hit", "hitch", "hive", "hoagy", "hoar", "hoard", "hob", "hobbs", "hobby", "hobo", "hoc", "hock", "hodge", "hodges", "hoe", "hoff", "hog", "hogan", "hoi", "hokan", "hold", "holdup", "hole", "holly", "holm", "holst", "holt", "home", "homo", "honda", "hondo", "hone", "honey", "hong", "honk", "hooch", "hood", "hoof", "hook", "hookup", "hoop", "hoot", "hop", "hope", "horde", "horn", "horny", "horse", "horus", "hose", "host", "hot", "hotbox", "hotel", "hough", "hound", "hour", "house", "hove", "hovel", "hover", "how", "howdy", "howe", "howl", "hoy", "hoyt", "hub", "hubbub", "hubby", "huber", "huck", "hue", "hued", "huff", "hug", "huge", "hugh", "hughes", "hugo", "huh", "hulk", "hull", "hum", "human", "humid", "hump", "humus", "hun", "hunch", "hung", "hunk", "hunt", "hurd", "hurl", "huron", "hurrah", "hurry", "hurst", "hurt", "hurty", "hush", "husky", "hut", "hutch", "hyde", "hydra", "hydro", "hyena", "hying", "hyman", "hymen", "hymn", "hymnal", "iambic", "ian", "ibex", "ibid", "ibis", "ibm", "ibn", "icc", "ice", "icing", "icky", "icon", "icy", "ida", "idaho", "idea", "ideal", "idiom", "idiot", "idle", "idol", "idyll", "ieee", "iffy", "ifni", "igloo", "igor", "iii", "iiii", "ijk", "ike", "ileum", "iliac", "iliad", "ill", "illume", "ilona", "image", "imbue", "imp", "impel", "import", "impute", "inane", "inapt", "inc", "inca", "incest", "inch", "incur", "index", "india", "indies", "indy", "inept", "inert", "infect", "infer", "infima", "infix", "infra", "ingot", "inhere", "injun", "ink", "inlay", "inlet", "inman", "inn", "inner", "input", "insect", "inset", "insult", "intend", "inter", "into", "inure", "invoke", "ion", "ionic", "iota", "iowa", "ipso", "ira", "iran", "iraq", "irate", "ire", "irene", "iris", "irish", "irk", "irma", "iron", "irony", "irs", "irvin", "irwin", "isaac", "isabel", "ising", "isis", "islam", "island", "isle", "israel", "issue", "italy", "itch", "item", "ito", "itt", "ivan", "ive", "ivory", "ivy", "jab", "jack", "jacky", "jacm", "jacob", "jacobi", "jade", "jag", "jail", "jaime", "jake", "jam", "james", "jan", "jane", "janet", "janos", "janus", "japan", "jar", "jason", "java", "jaw", "jay", "jazz", "jazzy", "jean", "jed", "jeep", "jeff", "jejune", "jelly", "jenny", "jeres", "jerk", "jerky", "jerry", "jersey", "jess", "jesse", "jest", "jesus", "jet", "jew", "jewel", "jewett", "jewish", "jibe", "jiffy", "jig", "jill", "jilt", "jim", "jimmy", "jinx", "jive", "jjj", "jjjj", "jkl", "joan", "job", "jock", "jockey", "joe", "joel", "joey", "jog", "john", "johns", "join", "joint", "joke", "jolla", "jolly", "jolt", "jon", "jonas", "jones", "jorge", "jose", "josef", "joshua", "joss", "jostle", "jot", "joule", "joust", "jove", "jowl", "jowly", "joy", "joyce", "juan", "judas", "judd", "jude", "judge", "judo", "judy", "jug", "juggle", "juice", "juicy", "juju", "juke", "jukes", "julep", "jules", "julia", "julie", "julio", "july", "jumbo", "jump", "jumpy", "junco", "june", "junk", "junky", "juno", "junta", "jura", "jure", "juror", "jury", "just", "jut", "jute", "kabul", "kafka", "kahn", "kajar", "kale", "kalmia", "kane", "kant", "kapok", "kappa", "karate", "karen", "karl", "karma", "karol", "karp", "kate", "kathy", "katie", "katz", "kava", "kay", "kayo", "kazoo", "keats", "keel", "keen", "keep", "keg", "keith", "keller", "kelly", "kelp", "kemp", "ken", "keno", "kent", "kenya", "kepler", "kept", "kern", "kerr", "kerry", "ketch", "kevin", "key", "keyed", "keyes", "keys", "khaki", "khan", "khmer", "kick", "kid", "kidde", "kidney", "kiev", "kigali", "kill", "kim", "kin", "kind", "king", "kink", "kinky", "kiosk", "kiowa", "kirby", "kirk", "kirov", "kiss", "kit", "kite", "kitty", "kiva", "kivu", "kiwi", "kkk", "kkkk", "klan", "klaus", "klein", "kline", "klm", "klux", "knack", "knapp", "knauer", "knead", "knee", "kneel", "knelt", "knew", "knick", "knife", "knit", "knob", "knock", "knoll", "knot", "knott", "know", "known", "knox", "knurl", "koala", "koch", "kodak", "kola", "kombu", "kong", "koran", "korea", "kraft", "krause", "kraut", "krebs", "kruse", "kudo", "kudzu", "kuhn", "kulak", "kurd", "kurt", "kyle", "kyoto", "lab", "laban", "label", "labia", "labile", "lac", "lace", "lack", "lacy", "lad", "laden", "ladle", "lady", "lag", "lager", "lagoon", "lagos", "laid", "lain", "lair", "laity", "lake", "lam", "lamar", "lamb", "lame", "lamp", "lana", "lance", "land", "lane", "lang", "lange", "lanka", "lanky", "lao", "laos", "lap", "lapel", "lapse", "larch", "lard", "lares", "large", "lark", "larkin", "larry", "lars", "larva", "lase", "lash", "lass", "lasso", "last", "latch", "late", "later", "latest", "latex", "lath", "lathe", "latin", "latus", "laud", "laue", "laugh", "launch", "laura", "lava", "law", "lawn", "lawson", "lax", "lay", "layup", "laze", "lazy", "lea", "leach", "lead", "leaf", "leafy", "leak", "leaky", "lean", "leap", "leapt", "lear", "learn", "lease", "leash", "least", "leave", "led", "ledge", "lee", "leech", "leeds", "leek", "leer", "leery", "leeway", "left", "lefty", "leg", "legal", "leggy", "legion", "leigh", "leila", "leland", "lemma", "lemon", "len", "lena", "lend", "lenin", "lenny", "lens", "lent", "leo", "leon", "leona", "leone", "leper", "leroy", "less", "lessee", "lest", "let", "lethe", "lev", "levee", "level", "lever", "levi", "levin", "levis", "levy", "lew", "lewd", "lewis", "leyden", "liar", "libel", "libido", "libya", "lice", "lick", "lid", "lie", "lied", "lien", "lieu", "life", "lifo", "lift", "light", "like", "liken", "lila", "lilac", "lilly", "lilt", "lily", "lima", "limb", "limbo", "lime", "limit", "limp", "lin", "lind", "linda", "linden", "line", "linen", "lingo", "link", "lint", "linus", "lion", "lip", "lipid", "lisa", "lise", "lisle", "lisp", "list", "listen", "lit", "lithe", "litton", "live", "liven", "livid", "livre", "liz", "lizzie", "lll", "llll", "lloyd", "lmn", "load", "loaf", "loam", "loamy", "loan", "loath", "lob", "lobar", "lobby", "lobe", "lobo", "local", "loci", "lock", "locke", "locus", "lodge", "loeb", "loess", "loft", "lofty", "log", "logan", "loge", "logic", "loin", "loire", "lois", "loiter", "loki", "lola", "loll", "lolly", "lomb", "lome", "lone", "long", "look", "loom", "loon", "loop", "loose", "loot", "lop", "lope", "lopez", "lord", "lore", "loren", "los", "lose", "loss", "lossy", "lost", "lot", "lotte", "lotus", "lou", "loud", "louis", "louise", "louse", "lousy", "louver", "love", "low", "lowe", "lower", "lowry", "loy", "loyal", "lsi", "ltv", "lucas", "lucia", "lucid", "luck", "lucky", "lucre", "lucy", "lug", "luge", "luger", "luis", "luke", "lull", "lulu", "lumbar", "lumen", "lump", "lumpy", "lunar", "lunch", "lund", "lung", "lunge", "lura", "lurch", "lure", "lurid", "lurk", "lush", "lust", "lusty", "lute", "lutz", "lux", "luxe", "luzon", "lydia", "lye", "lying", "lykes", "lyle", "lyman", "lymph", "lynch", "lynn", "lynx", "lyon", "lyons", "lyra", "lyric", "mabel", "mac", "mace", "mach", "macho", "mack", "mackey", "macon", "macro", "mad", "madam", "made", "madman", "madsen", "mae", "magi", "magic", "magma", "magna", "magog", "maid", "maier", "mail", "maim", "main", "maine", "major", "make", "malady", "malay", "male", "mali", "mall", "malt", "malta", "mambo", "mamma", "mammal", "man", "mana", "manama", "mane", "mange", "mania", "manic", "mann", "manna", "manor", "mans", "manse", "mantle", "many", "mao", "maori", "map", "maple", "mar", "marc", "march", "marco", "marcy", "mardi", "mare", "margo", "maria", "marie", "marin", "marine", "mario", "mark", "marks", "marlin", "marrow", "marry", "mars", "marsh", "mart", "marty", "marx", "mary", "maser", "mash", "mask", "mason", "masque", "mass", "mast", "mat", "match", "mate", "mateo", "mater", "math", "matte", "maul", "mauve", "mavis", "maw", "mawr", "max", "maxim", "maxima", "may", "maya", "maybe", "mayer", "mayhem", "mayo", "mayor", "mayst", "mazda", "maze", "mba", "mccoy", "mcgee", "mckay", "mckee", "mcleod", "mead", "meal", "mealy", "mean", "meant", "meat", "meaty", "mecca", "mecum", "medal", "medea", "media", "medic", "medley", "meek", "meet", "meg", "mega", "meier", "meir", "mel", "meld", "melee", "mellow", "melon", "melt", "memo", "memoir", "men", "mend", "menlo", "menu", "merck", "mercy", "mere", "merge", "merit", "merle", "merry", "mesa", "mescal", "mesh", "meson", "mess", "messy", "met", "metal", "mete", "meter", "metro", "mew", "meyer", "meyers", "mezzo", "miami", "mica", "mice", "mickey", "micky", "micro", "mid", "midas", "midge", "midst", "mien", "miff", "mig", "might", "mike", "mila", "milan", "milch", "mild", "mildew", "mile", "miles", "milk", "milky", "mill", "mills", "milt", "mimi", "mimic", "mince", "mind", "mine", "mini", "minim", "mink", "minnow", "minor", "minos", "minot", "minsk", "mint", "minus", "mira", "mirage", "mire", "mirth", "miser", "misery", "miss", "missy", "mist", "misty", "mit", "mite", "mitre", "mitt", "mix", "mixup", "mizar", "mmm", "mmmm", "mno", "moan", "moat", "mob", "mobil", "mock", "modal", "mode", "model", "modem", "modish", "moe", "moen", "mohr", "moire", "moist", "molal", "molar", "mold", "mole", "moll", "mollie", "molly", "molt", "molten", "mommy", "mona", "monad", "mondo", "monel", "money", "monic", "monk", "mont", "monte", "month", "monty", "moo", "mood", "moody", "moon", "moor", "moore", "moose", "moot", "mop", "moral", "morale", "moran", "more", "morel", "morn", "moron", "morse", "morsel", "mort", "mosaic", "moser", "moses", "moss", "mossy", "most", "mot", "motel", "motet", "moth", "mother", "motif", "motor", "motto", "mould", "mound", "mount", "mourn", "mouse", "mousy", "mouth", "move", "movie", "mow", "moyer", "mph", "mrs", "much", "muck", "mucus", "mud", "mudd", "muddy", "muff", "muffin", "mug", "muggy", "mugho", "muir", "mulch", "mulct", "mule", "mull", "multi", "mum", "mummy", "munch", "mung", "munson", "muon", "muong", "mural", "muriel", "murk", "murky", "murre", "muse", "mush", "mushy", "music", "musk", "muslim", "must", "musty", "mute", "mutt", "muzak", "muzo", "myel", "myers", "mylar", "mynah", "myopia", "myra", "myron", "myrrh", "myself", "myth", "naacp", "nab", "nadir", "nag", "nagoya", "nagy", "naiad", "nail", "nair", "naive", "naked", "name", "nan", "nancy", "naomi", "nap", "nary", "nasa", "nasal", "nash", "nasty", "nat", "natal", "nate", "nato", "natty", "nature", "naval", "nave", "navel", "navy", "nay", "nazi", "nbc", "nbs", "ncaa", "ncr", "neal", "near", "neat", "neath", "neck", "ned", "nee", "need", "needy", "neff", "negate", "negro", "nehru", "neil", "nell", "nelsen", "neon", "nepal", "nero", "nerve", "ness", "nest", "net", "neuron", "neva", "neve", "new", "newel", "newt", "next", "nib", "nibs", "nice", "nicety", "niche", "nick", "niece", "niger", "nigh", "night", "nih", "nikko", "nil", "nile", "nimbus", "nimh", "nina", "nine", "ninth", "niobe", "nip", "nit", "nitric", "nitty", "nixon", "nnn", "nnnn", "noaa", "noah", "nob", "nobel", "noble", "nod", "nodal", "node", "noel", "noise", "noisy", "nolan", "noll", "nolo", "nomad", "non", "nonce", "none", "nook", "noon", "noose", "nop", "nor", "nora", "norm", "norma", "north", "norway", "nose", "not", "notch", "note", "notre", "noun", "nov", "nova", "novak", "novel", "novo", "now", "nrc", "nsf", "ntis", "nuance", "nubia", "nuclei", "nude", "nudge", "null", "numb", "nun", "nurse", "nut", "nyc", "nylon", "nymph", "nyu", "oaf", "oak", "oaken", "oakley", "oar", "oases", "oasis", "oat", "oath", "obese", "obey", "objet", "oboe", "occur", "ocean", "oct", "octal", "octave", "octet", "odd", "ode", "odin", "odium", "off", "offal", "offend", "offer", "oft", "often", "ogden", "ogle", "ogre", "ohio", "ohm", "ohmic", "oil", "oily", "oint", "okay", "olaf", "olav", "old", "olden", "oldy", "olga", "olin", "olive", "olsen", "olson", "omaha", "oman", "omega", "omen", "omit", "once", "one", "onion", "only", "onset", "onto", "onus", "onward", "onyx", "ooo", "oooo", "ooze", "opal", "opec", "opel", "open", "opera", "opium", "opt", "optic", "opus", "oral", "orate", "orb", "orbit", "orchid", "ordain", "order", "ore", "organ", "orgy", "orin", "orion", "ornery", "orono", "orr", "osaka", "oscar", "osier", "oslo", "other", "otis", "ott", "otter", "otto", "ouch", "ought", "ounce", "our", "oust", "out", "ouvre", "ouzel", "ouzo", "ova", "oval", "ovary", "ovate", "oven", "over", "overt", "ovid", "owe", "owens", "owing", "owl", "owly", "own", "oxen", "oxeye", "oxide", "oxnard", "ozark", "ozone", "pablo", "pabst", "pace", "pack", "packet", "pact", "pad", "paddy", "padre", "paean", "pagan", "page", "paid", "pail", "pain", "paine", "paint", "pair", "pal", "pale", "pall", "palm", "palo", "palsy", "pam", "pampa", "pan", "panama", "panda", "pane", "panel", "pang", "panic", "pansy", "pant", "panty", "paoli", "pap", "papa", "papal", "papaw", "paper", "pappy", "papua", "par", "parch", "pardon", "pare", "pareto", "paris", "park", "parke", "parks", "parr", "parry", "parse", "part", "party", "pascal", "pasha", "paso", "pass", "passe", "past", "paste", "pasty", "pat", "patch", "pate", "pater", "path", "patio", "patsy", "patti", "patton", "patty", "paul", "paula", "pauli", "paulo", "pause", "pave", "paw", "pawn", "pax", "pay", "payday", "payne", "paz", "pbs", "pea", "peace", "peach", "peak", "peaky", "peal", "peale", "pear", "pearl", "pease", "peat", "pebble", "pecan", "peck", "pecos", "pedal", "pedro", "pee", "peed", "peek", "peel", "peep", "peepy", "peer", "peg", "peggy", "pelt", "pen", "penal", "pence", "pencil", "pend", "penh", "penn", "penna", "penny", "pent", "peony", "pep", "peppy", "pepsi", "per", "perch", "percy", "perez", "peril", "perk", "perky", "perle", "perry", "persia", "pert", "perth", "peru", "peruse", "pest", "peste", "pet", "petal", "pete", "peter", "petit", "petri", "petty", "pew", "pewee", "phage", "phase", "phd", "phenol", "phi", "phil", "phlox", "phon", "phone", "phony", "photo", "phyla", "physic", "piano", "pica", "pick", "pickup", "picky", "pie", "piece", "pier", "pierce", "piety", "pig", "piggy", "pike", "pile", "pill", "pilot", "pimp", "pin", "pinch", "pine", "ping", "pinion", "pink", "pint", "pinto", "pion", "piotr", "pious", "pip", "pipe", "piper", "pique", "pit", "pitch", "pith", "pithy", "pitney", "pitt", "pity", "pius", "pivot", "pixel", "pixy", "pizza", "place", "plague", "plaid", "plain", "plan", "plane", "plank", "plant", "plasm", "plat", "plate", "plato", "play", "playa", "plaza", "plea", "plead", "pleat", "pledge", "pliny", "plod", "plop", "plot", "plow", "pluck", "plug", "plum", "plumb", "plume", "plump", "plunk", "plus", "plush", "plushy", "pluto", "ply", "poach", "pobox", "pod", "podge", "podia", "poe", "poem", "poesy", "poet", "poetry", "pogo", "poi", "point", "poise", "poke", "pol", "polar", "pole", "police", "polio", "polis", "polk", "polka", "poll", "polo", "pomona", "pomp", "ponce", "pond", "pong", "pont", "pony", "pooch", "pooh", "pool", "poole", "poop", "poor", "pop", "pope", "poppy", "porch", "pore", "pork", "porous", "port", "porte", "portia", "porto", "pose", "posey", "posh", "posit", "posse", "post", "posy", "pot", "potts", "pouch", "pound", "pour", "pout", "pow", "powder", "power", "ppm", "ppp", "pppp", "pqr", "prado", "pram", "prank", "pratt", "pray", "preen", "prefix", "prep", "press", "prexy", "prey", "priam", "price", "prick", "pride", "prig", "prim", "prima", "prime", "primp", "prince", "print", "prior", "prism", "prissy", "privy", "prize", "pro", "probe", "prod", "prof", "prom", "prone", "prong", "proof", "prop", "propyl", "prose", "proud", "prove", "prow", "prowl", "proxy", "prune", "pry", "psalm", "psi", "psych", "pta", "pub", "puck", "puddly", "puerto", "puff", "puffy", "pug", "pugh", "puke", "pull", "pulp", "pulse", "puma", "pump", "pun", "punch", "punic", "punish", "punk", "punky", "punt", "puny", "pup", "pupal", "pupil", "puppy", "pure", "purge", "purl", "purr", "purse", "pus", "pusan", "pusey", "push", "pussy", "put", "putt", "putty", "pvc", "pygmy", "pyle", "pyre", "pyrex", "pyrite", "qatar", "qed", "qqq", "qqqq", "qrs", "qua", "quack", "quad", "quaff", "quail", "quake", "qualm", "quark", "quarry", "quart", "quash", "quasi", "quay", "queasy", "queen", "queer", "quell", "query", "quest", "queue", "quick", "quid", "quiet", "quill", "quilt", "quinn", "quint", "quip", "quirk", "quirt", "quit", "quite", "quito", "quiz", "quo", "quod", "quota", "quote", "rabat", "rabbi", "rabbit", "rabid", "rabin", "race", "rack", "racy", "radar", "radii", "radio", "radium", "radix", "radon", "rae", "rafael", "raft", "rag", "rage", "raid", "rail", "rain", "rainy", "raise", "raj", "rajah", "rake", "rally", "ralph", "ram", "raman", "ramo", "ramp", "ramsey", "ran", "ranch", "rand", "randy", "rang", "range", "rangy", "rank", "rant", "raoul", "rap", "rape", "rapid", "rapt", "rare", "rasa", "rascal", "rash", "rasp", "rat", "rata", "rate", "rater", "ratio", "rattle", "raul", "rave", "ravel", "raven", "raw", "ray", "raze", "razor", "rca", "reach", "read", "ready", "reagan", "real", "realm", "ream", "reap", "rear", "reave", "reb", "rebel", "rebut", "recipe", "reck", "recur", "red", "redeem", "reduce", "reed", "reedy", "reef", "reek", "reel", "reese", "reeve", "refer", "regal", "regina", "regis", "reich", "reid", "reign", "rein", "relax", "relay", "relic", "reman", "remedy", "remit", "remus", "rena", "renal", "rend", "rene", "renown", "rent", "rep", "repel", "repent", "resin", "resort", "rest", "ret", "retch", "return", "reub", "rev", "reveal", "revel", "rever", "revet", "revved", "rex", "rhea", "rheum", "rhine", "rhino", "rho", "rhoda", "rhode", "rhyme", "rib", "rica", "rice", "rich", "rick", "rico", "rid", "ride", "ridge", "rifle", "rift", "rig", "riga", "rigel", "riggs", "right", "rigid", "riley", "rill", "rilly", "rim", "rime", "rimy", "ring", "rink", "rinse", "rio", "riot", "rip", "ripe", "ripen", "ripley", "rise", "risen", "risk", "risky", "rite", "ritz", "rival", "riven", "river", "rivet", "riyadh", "roach", "road", "roam", "roar", "roast", "rob", "robe", "robin", "robot", "rock", "rocket", "rocky", "rod", "rode", "rodeo", "roe", "roger", "rogue", "roil", "role", "roll", "roman", "rome", "romeo", "romp", "ron", "rondo", "rood", "roof", "rook", "rookie", "rooky", "room", "roomy", "roost", "root", "rope", "rosa", "rose", "rosen", "ross", "rosy", "rot", "rotc", "roth", "rotor", "rouge", "rough", "round", "rouse", "rout", "route", "rove", "row", "rowdy", "rowe", "roy", "royal", "royce", "rpm", "rrr", "rrrr", "rst", "rsvp", "ruanda", "rub", "rube", "ruben", "rubin", "rubric", "ruby", "ruddy", "rude", "rudy", "rue", "rufus", "rug", "ruin", "rule", "rum", "rumen", "rummy", "rump", "rumpus", "run", "rune", "rung", "runge", "runic", "runt", "runty", "rupee", "rural", "ruse", "rush", "rusk", "russ", "russo", "rust", "rusty", "rut", "ruth", "rutty", "ryan", "ryder", "rye", "sabine", "sable", "sabra", "sac", "sachs", "sack", "sad", "saddle", "sadie", "safari", "safe", "sag", "saga", "sage", "sago", "said", "sail", "saint", "sake", "sal", "salad", "sale", "salem", "saline", "salk", "salle", "sally", "salon", "salt", "salty", "salve", "salvo", "sam", "samba", "same", "sammy", "samoa", "samuel", "san", "sana", "sand", "sandal", "sandy", "sane", "sang", "sank", "sans", "santa", "santo", "sao", "sap", "sappy", "sara", "sarah", "saran", "sari", "sash", "sat", "satan", "satin", "satyr", "sauce", "saucy", "saud", "saudi", "saul", "sault", "saute", "save", "savoy", "savvy", "saw", "sawyer", "sax", "saxon", "say", "scab", "scala", "scald", "scale", "scalp", "scam", "scamp", "scan", "scant", "scar", "scare", "scarf", "scary", "scat", "scaup", "scene", "scent", "school", "scion", "scm", "scoff", "scold", "scoop", "scoot", "scope", "scops", "score", "scoria", "scorn", "scot", "scott", "scour", "scout", "scowl", "scram", "scrap", "scrape", "screw", "scrim", "scrub", "scuba", "scud", "scuff", "scull", "scum", "scurry", "sea", "seal", "seam", "seamy", "sean", "sear", "sears", "season", "seat", "sec", "secant", "sect", "sedan", "seder", "sedge", "see", "seed", "seedy", "seek", "seem", "seen", "seep", "seethe", "seize", "self", "sell", "selma", "semi", "sen", "send", "seneca", "senor", "sense", "sent", "sentry", "seoul", "sepal", "sepia", "sepoy", "sept", "septa", "sequin", "sera", "serf", "serge", "serif", "serum", "serve", "servo", "set", "seth", "seton", "setup", "seven", "sever", "severe", "sew", "sewn", "sex", "sexy", "shack", "shad", "shade", "shady", "shafer", "shaft", "shag", "shah", "shake", "shaken", "shako", "shaky", "shale", "shall", "sham", "shame", "shank", "shape", "shard", "share", "shari", "shark", "sharp", "shave", "shaw", "shawl", "shay", "she", "shea", "sheaf", "shear", "sheath", "shed", "sheen", "sheep", "sheer", "sheet", "sheik", "shelf", "shell", "shied", "shift", "shill", "shim", "shin", "shine", "shinto", "shiny", "ship", "shire", "shirk", "shirt", "shish", "shiv", "shoal", "shock", "shod", "shoe", "shoji", "shone", "shoo", "shook", "shoot", "shop", "shore", "short", "shot", "shout", "shove", "show", "shown", "showy", "shrank", "shred", "shrew", "shrike", "shrub", "shrug", "shu", "shuck", "shun", "shunt", "shut", "shy", "sial", "siam", "sian", "sib", "sibley", "sibyl", "sic", "sick", "side", "sidle", "siege", "siena", "sieve", "sift", "sigh", "sight", "sigma", "sign", "signal", "signor", "silas", "silk", "silky", "sill", "silly", "silo", "silt", "silty", "sima", "simon", "simons", "sims", "sin", "sinai", "since", "sine", "sinew", "sing", "singe", "sinh", "sink", "sinus", "sioux", "sip", "sir", "sire", "siren", "sis", "sisal", "sit", "site", "situ", "situs", "siva", "six", "sixgun", "sixth", "sixty", "size", "skat", "skate", "skeet", "skew", "ski", "skid", "skied", "skiff", "skill", "skim", "skimp", "skimpy", "skin", "skip", "skirt", "skit", "skulk", "skull", "skunk", "sky", "skye", "slab", "slack", "slag", "slain", "slake", "slam", "slang", "slant", "slap", "slash", "slat", "slate", "slater", "slav", "slave", "slay", "sled", "sleek", "sleep", "sleet", "slept", "slew", "slice", "slick", "slid", "slide", "slim", "slime", "slimy", "sling", "slip", "slit", "sliver", "sloan", "slob", "sloe", "slog", "sloop", "slop", "slope", "slosh", "slot", "sloth", "slow", "slug", "sluice", "slum", "slump", "slung", "slur", "slurp", "sly", "smack", "small", "smart", "smash", "smear", "smell", "smelt", "smile", "smirk", "smith", "smithy", "smog", "smoke", "smoky", "smug", "smut", "snack", "snafu", "snag", "snail", "snake", "snap", "snare", "snark", "snarl", "snatch", "sneak", "sneer", "snell", "snick", "sniff", "snip", "snipe", "snob", "snook", "snoop", "snore", "snort", "snout", "snow", "snowy", "snub", "snuff", "snug", "soak", "soap", "soapy", "soar", "sob", "sober", "social", "sock", "sod", "soda", "sofa", "sofia", "soft", "soften", "soggy", "soil", "sol", "solar", "sold", "sole", "solemn", "solid", "solo", "solon", "solve", "soma", "somal", "some", "son", "sonar", "song", "sonic", "sonny", "sonora", "sony", "soon", "soot", "sooth", "sop", "sora", "sorb", "sore", "sorry", "sort", "sos", "sou", "sough", "soul", "sound", "soup", "sour", "source", "sousa", "south", "sow", "sown", "soy", "soya", "spa", "space", "spade", "spain", "span", "spar", "spare", "sparge", "spark", "spasm", "spat", "spate", "spawn", "spay", "speak", "spear", "spec", "speck", "sped", "speed", "spell", "spend", "spent", "sperm", "sperry", "spew", "spica", "spice", "spicy", "spike", "spiky", "spill", "spilt", "spin", "spine", "spiny", "spire", "spiro", "spit", "spite", "spitz", "splat", "splay", "spline", "split", "spoil", "spoke", "spoof", "spook", "spooky", "spool", "spoon", "spore", "sport", "spot", "spout", "sprain", "spray", "spree", "sprig", "spruce", "sprue", "spud", "spume", "spun", "spunk", "spur", "spurn", "spurt", "spy", "squad", "squat", "squaw", "squibb", "squid", "squint", "sri", "sss", "ssss", "sst", "st.", "stab", "stack", "stacy", "staff", "stag", "stage", "stagy", "stahl", "staid", "stain", "stair", "stake", "stale", "stalk", "stall", "stamp", "stan", "stance", "stand", "stank", "staph", "star", "stare", "stark", "starr", "start", "stash", "state", "statue", "stave", "stay", "stead", "steak", "steal", "steam", "steed", "steel", "steele", "steen", "steep", "steer", "stein", "stella", "stem", "step", "stern", "steve", "stew", "stick", "stiff", "stile", "still", "stilt", "sting", "stingy", "stink", "stint", "stir", "stock", "stoic", "stoke", "stole", "stomp", "stone", "stony", "stood", "stool", "stoop", "stop", "store", "storey", "stork", "storm", "story", "stout", "stove", "stow", "strafe", "strap", "straw", "stray", "strewn", "strip", "stroll", "strom", "strop", "strum", "strut", "stu", "stuart", "stub", "stuck", "stud", "study", "stuff", "stuffy", "stump", "stun", "stung", "stunk", "stunt", "sturm", "style", "styli", "styx", "suave", "sub", "subtly", "such", "suck", "sud", "sudan", "suds", "sue", "suey", "suez", "sugar", "suit", "suite", "sulfa", "sulk", "sulky", "sully", "sultry", "sum", "sumac", "summon", "sun", "sung", "sunk", "sunny", "sunset", "suny", "sup", "super", "supra", "sure", "surf", "surge", "sus", "susan", "sushi", "susie", "sutton", "swab", "swag", "swain", "swam", "swami", "swamp", "swampy", "swan", "swank", "swap", "swarm", "swart", "swat", "swath", "sway", "swear", "sweat", "sweaty", "swede", "sweep", "sweet", "swell", "swelt", "swept", "swift", "swig", "swim", "swine", "swing", "swipe", "swirl", "swish", "swiss", "swoop", "sword", "swore", "sworn", "swum", "swung", "sybil", "sykes", "sylow", "sylvan", "synge", "synod", "syria", "syrup", "tab", "table", "taboo", "tabu", "tabula", "tacit", "tack", "tacky", "tacoma", "tact", "tad", "taffy", "taft", "tag", "tahoe", "tail", "taint", "take", "taken", "talc", "tale", "talk", "talky", "tall", "tallow", "tally", "talon", "talus", "tam", "tame", "tamp", "tampa", "tan", "tang", "tango", "tangy", "tanh", "tank", "tansy", "tanya", "tao", "taos", "tap", "tapa", "tape", "taper", "tapir", "tapis", "tappa", "tar", "tara", "tardy", "tariff", "tarry", "tart", "task", "tass", "taste", "tasty", "tat", "tate", "tater", "tattle", "tatty", "tau", "taunt", "taut", "tavern", "tawny", "tax", "taxi", "tea", "teach", "teal", "team", "tear", "tease", "teat", "tech", "tecum", "ted", "teddy", "tee", "teem", "teen", "teensy", "teet", "teeth", "telex", "tell", "tempo", "tempt", "ten", "tend", "tenet", "tenney", "tenon", "tenor", "tense", "tensor", "tent", "tenth", "tepee", "tepid", "term", "tern", "terra", "terre", "terry", "terse", "tess", "test", "testy", "tete", "texan", "texas", "text", "thai", "than", "thank", "that", "thaw", "the", "thea", "thee", "theft", "their", "them", "theme", "then", "there", "these", "theta", "they", "thick", "thief", "thigh", "thin", "thine", "thing", "think", "third", "this", "thong", "thor", "thorn", "thorny", "those", "thou", "thread", "three", "threw", "throb", "throes", "throw", "thrum", "thud", "thug", "thule", "thumb", "thump", "thus", "thy", "thyme", "tiber", "tibet", "tibia", "tic", "tick", "ticket", "tid", "tidal", "tidbit", "tide", "tidy", "tie", "tied", "tier", "tift", "tiger", "tight", "til", "tilde", "tile", "till", "tilt", "tilth", "tim", "time", "timex", "timid", "timon", "tin", "tina", "tine", "tinge", "tint", "tiny", "tioga", "tip", "tipoff", "tippy", "tipsy", "tire", "tit", "titan", "tithe", "title", "titus", "tnt", "toad", "toady", "toast", "toby", "today", "todd", "toe", "tofu", "tog", "togo", "togs", "toil", "toilet", "token", "tokyo", "told", "toll", "tom", "tomb", "tome", "tommy", "ton", "tonal", "tone", "tong", "toni", "tonic", "tonk", "tonsil", "tony", "too", "took", "tool", "toot", "tooth", "top", "topaz", "topic", "topple", "topsy", "tor", "torah", "torch", "tore", "tori", "torn", "torr", "torso", "tort", "torus", "tory", "toss", "tot", "total", "tote", "totem", "touch", "tough", "tour", "tout", "tow", "towel", "tower", "town", "toxic", "toxin", "toy", "trace", "track", "tract", "tracy", "trade", "trag", "trail", "train", "trait", "tram", "tramp", "trap", "trash", "trawl", "tread", "treat", "treble", "tree", "trek", "trench", "trend", "tress", "triad", "trial", "tribe", "trick", "tried", "trig", "trill", "trim", "trio", "trip", "tripe", "trite", "triton", "trod", "troll", "troop", "trot", "trout", "troy", "truce", "truck", "trudge", "trudy", "true", "truly", "trump", "trunk", "truss", "trust", "truth", "trw", "try", "tsar", "ttl", "ttt", "tttt", "tty", "tub", "tuba", "tube", "tuck", "tudor", "tuff", "tuft", "tug", "tulane", "tulip", "tulle", "tulsa", "tum", "tun", "tuna", "tune", "tung", "tunic", "tunis", "tunnel", "tuple", "turf", "turin", "turk", "turn", "turvy", "tusk", "tussle", "tutor", "tutu", "tuv", "tva", "twa", "twain", "tweak", "tweed", "twice", "twig", "twill", "twin", "twine", "twirl", "twist", "twisty", "twit", "two", "twx", "tyburn", "tying", "tyler", "type", "typic", "typo", "tyson", "ucla", "ugh", "ugly", "ulan", "ulcer", "ultra", "umber", "umbra", "umpire", "unary", "uncle", "under", "unify", "union", "unit", "unite", "unity", "unix", "until", "upend", "uphold", "upon", "upper", "uproar", "upset", "uptake", "upton", "urban", "urbane", "urea", "urge", "uri", "urine", "uris", "urn", "ursa", "usa", "usaf", "usage", "usc", "usda", "use", "useful", "usgs", "usher", "usia", "usn", "usps", "ussr", "usual", "usurp", "usury", "utah", "utica", "utile", "utmost", "utter", "uuu", "uuuu", "uvw", "vacua", "vacuo", "vade", "vaduz", "vague", "vail", "vain", "vale", "valet", "valeur", "valid", "value", "valve", "vamp", "van", "vance", "vane", "vary", "vase", "vast", "vat", "vault", "veal", "veda", "vee", "veer", "veery", "vega", "veil", "vein", "velar", "veldt", "vella", "vellum", "venal", "vend", "venial", "venom", "vent", "venus", "vera", "verb", "verde", "verdi", "verge", "verity", "verna", "verne", "versa", "verse", "verve", "very", "vessel", "vest", "vet", "vetch", "veto", "vex", "via", "vial", "vicar", "vice", "vichy", "vicky", "vida", "video", "vie", "viet", "view", "vigil", "vii", "viii", "vile", "villa", "vine", "vinyl", "viola", "violet", "virgil", "virgo", "virus", "vis", "visa", "vise", "visit", "visor", "vista", "vita", "vitae", "vital", "vito", "vitro", "viva", "vivian", "vivid", "vivo", "vixen", "viz", "vocal", "vogel", "vogue", "voice", "void", "volt", "volta", "volvo", "vomit", "von", "voss", "vote", "vouch", "vow", "vowel", "vulcan", "vvv", "vvvv", "vying", "waals", "wac", "wack", "wacke", "wacky", "waco", "wad", "wade", "wadi", "wafer", "wag", "wage", "waggle", "wah", "wahl", "wail", "waist", "wait", "waite", "waive", "wake", "waken", "waldo", "wale", "walk", "walkie", "wall", "walls", "wally", "walsh", "walt", "walton", "waltz", "wan", "wand", "wane", "wang", "want", "war", "ward", "ware", "warm", "warmth", "warn", "warp", "warren", "wart", "warty", "wary", "was", "wash", "washy", "wasp", "wast", "waste", "watch", "water", "watt", "watts", "wave", "wavy", "wax", "waxen", "waxy", "way", "wayne", "weak", "weal", "wealth", "wean", "wear", "weary", "weave", "web", "webb", "weber", "weco", "wed", "wedge", "wee", "weed", "weedy", "week", "weeks", "weep", "wehr", "wei", "weigh", "weir", "weird", "weiss", "welch", "weld", "well", "wells", "welsh", "welt", "wendy", "went", "wept", "were", "wert", "west", "wet", "whack", "whale", "wham", "wharf", "what", "wheat", "whee", "wheel", "whelk", "whelm", "whelp", "when", "where", "whet", "which", "whiff", "whig", "while", "whim", "whine", "whinny", "whip", "whir", "whirl", "whisk", "whit", "white", "whiz", "who", "whoa", "whole", "whom", "whoop", "whoosh", "whop", "whose", "whup", "why", "wick", "wide", "widen", "widow", "width", "wield", "wier", "wife", "wig", "wild", "wile", "wiley", "wilkes", "will", "willa", "wills", "wilma", "wilt", "wily", "win", "wince", "winch", "wind", "windy", "wine", "wing", "wink", "winnie", "wino", "winter", "winy", "wipe", "wire", "wiry", "wise", "wish", "wishy", "wisp", "wispy", "wit", "witch", "with", "withe", "withy", "witt", "witty", "wive", "woe", "wok", "woke", "wold", "wolf", "wolfe", "wolff", "wolve", "woman", "womb", "women", "won", "wonder", "wong", "wont", "woo", "wood", "woods", "woody", "wool", "woozy", "word", "wordy", "wore", "work", "world", "worm", "wormy", "worn", "worry", "worse", "worst", "worth", "wotan", "would", "wound", "wove", "woven", "wow", "wrack", "wrap", "wrath", "wreak", "wreck", "wrest", "wring", "wrist", "writ", "write", "writhe", "wrong", "wrote", "wry", "wuhan", "www", "wwww", "wxy", "wyatt", "wyeth", "wylie", "wyman", "wyner", "wynn", "xenon", "xerox", "xxx", "xxxx", "xylem", "xyz", "yacht", "yah", "yak", "yale", "yalta", "yam", "yamaha", "yang", "yank", "yap", "yaqui", "yard", "yarn", "yates", "yaw", "yawl", "yawn", "yea", "yeah", "year", "yearn", "yeast", "yeasty", "yeats", "yell", "yelp", "yemen", "yen", "yet", "yield", "yin", "yip", "ymca", "yodel", "yoder", "yoga", "yogi", "yoke", "yokel", "yolk", "yon", "yond", "yore", "york", "yost", "you", "young", "your", "youth", "yow", "yucca", "yuck", "yuh", "yuki", "yukon", "yule", "yves", "ywca", "yyy", "yyyy", "zag", "zaire", "zan", "zap", "zazen", "zeal", "zealot", "zebra", "zeiss", "zen", "zero", "zest", "zesty", "zeta", "zeus", "zig", "zilch", "zinc", "zing", "zion", "zip", "zloty", "zoe", "zomba", "zone", "zoo", "zoom", "zorn", "zurich", "zzz", "zzzz"]
true
true
f7278c9a625b2d1059e2cfccec2d387b369c5723
3,269
py
Python
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
test_src/Tests/test07_scroll_list/test_TC09.py
BJanos87/Vizsgaremek-conduit-app
1ffb309389b0cbe68aca56bfde50ba8b17219d03
[ "MIT" ]
null
null
null
from test_src.Tests.test07_scroll_list.conftest import PyFix from test_src.Pages.HomePage import HomePage from test_src.Pages.LoginPage import LoginPage from test_src.Pages.MainPage import MainPage from test_src.Data.test_data import TestData import time class TestScrollList(PyFix): """this used to check the title of the loaded url, and check the Sign In button""" def test_homepage(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True self.HomePage.click_sign_in_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check the elements of the Login Page""" """Login an existing user""" def test_check_login_form(self): try: self.LoginPage = LoginPage(self.driver) assert self.LoginPage.is_inputs_displayed() is True assert self.LoginPage.is_inputs_placeholder() is True assert self.LoginPage.is_password_type() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to fill Login Page and sign in to app""" def test_login_exist_user(self): try: self.LoginPage = LoginPage(self.driver) self.LoginPage.fill_login_existed_email() assert self.LoginPage.is_sign_in_btn_displayed() is True self.LoginPage.click_sign_in_btn() time.sleep(3) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check scroll in the list""" def test_check_scroll_in_the_list(self): try: self.MainPage = MainPage(self.driver) assert self.MainPage.is_username_displayed() == TestData.reg_test_valid[0] assert self.MainPage.count_post_fields() == 11 self.MainPage.scroll_to_bottom_of_the_main_page() assert self.MainPage.is_next_btn_displayed() is True assert self.MainPage.is_next_btn_selected() is False self.MainPage.click_next_btn_topic_list() time.sleep(3) # assert self.MainPage.is_next_btn_selected() is True assert self.MainPage.count_post_fields() == 1 assert self.MainPage.is_log_out_btn_displayed() is True self.MainPage.click_log_out_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) """this used to check successful navigate to home page""" def test_homepage_is_displayed(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err))
44.780822
86
0.674824
from test_src.Tests.test07_scroll_list.conftest import PyFix from test_src.Pages.HomePage import HomePage from test_src.Pages.LoginPage import LoginPage from test_src.Pages.MainPage import MainPage from test_src.Data.test_data import TestData import time class TestScrollList(PyFix): def test_homepage(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True self.HomePage.click_sign_in_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_check_login_form(self): try: self.LoginPage = LoginPage(self.driver) assert self.LoginPage.is_inputs_displayed() is True assert self.LoginPage.is_inputs_placeholder() is True assert self.LoginPage.is_password_type() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_login_exist_user(self): try: self.LoginPage = LoginPage(self.driver) self.LoginPage.fill_login_existed_email() assert self.LoginPage.is_sign_in_btn_displayed() is True self.LoginPage.click_sign_in_btn() time.sleep(3) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_check_scroll_in_the_list(self): try: self.MainPage = MainPage(self.driver) assert self.MainPage.is_username_displayed() == TestData.reg_test_valid[0] assert self.MainPage.count_post_fields() == 11 self.MainPage.scroll_to_bottom_of_the_main_page() assert self.MainPage.is_next_btn_displayed() is True assert self.MainPage.is_next_btn_selected() is False self.MainPage.click_next_btn_topic_list() time.sleep(3) assert self.MainPage.count_post_fields() == 1 assert self.MainPage.is_log_out_btn_displayed() is True self.MainPage.click_log_out_btn() time.sleep(1) except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err)) def test_homepage_is_displayed(self): try: self.HomePage = HomePage(self.driver) assert self.HomePage.get_home_page_url() == TestData.BASE_URL assert self.HomePage.get_home_page_title() == TestData.HOME_PAGE_TITLE assert self.HomePage.is_sign_in_btn_displayed() is True except AssertionError as err: self.pytest.fail(print(TestData.assert_error_msg, err))
true
true
f7278cd33f1012970fa1eafccf108f1db2ee92aa
1,387
py
Python
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
14
2018-04-19T09:53:56.000Z
2022-01-27T06:05:48.000Z
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
15
2018-09-11T05:39:54.000Z
2021-07-02T12:38:02.000Z
python_code/vnev/Lib/site-packages/jdcloud_sdk/services/kubernetes/apis/SetAutoRepairRequest.py
Ureimu/weather-robot
7634195af388538a566ccea9f8a8534c5fb0f4b6
[ "MIT" ]
33
2018-04-20T05:29:16.000Z
2022-02-17T09:10:05.000Z
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class SetAutoRepairRequest(JDCloudRequest): """ 设置工作节点组的自动修复 """ def __init__(self, parameters, header=None, version="v1"): super(SetAutoRepairRequest, self).__init__( '/regions/{regionId}/nodeGroups/{nodeGroupId}:setAutoRepair', 'POST', header, version) self.parameters = parameters class SetAutoRepairParameters(object): def __init__(self, regionId, nodeGroupId, enabled): """ :param regionId: 地域 ID :param nodeGroupId: 工作节点组 ID :param enabled: 是否开启自动修复 """ self.regionId = regionId self.nodeGroupId = nodeGroupId self.enabled = enabled
30.152174
98
0.708724
from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class SetAutoRepairRequest(JDCloudRequest): def __init__(self, parameters, header=None, version="v1"): super(SetAutoRepairRequest, self).__init__( '/regions/{regionId}/nodeGroups/{nodeGroupId}:setAutoRepair', 'POST', header, version) self.parameters = parameters class SetAutoRepairParameters(object): def __init__(self, regionId, nodeGroupId, enabled): self.regionId = regionId self.nodeGroupId = nodeGroupId self.enabled = enabled
true
true
f7278cfa86311c10a1c661a6f7e11feef1b88341
97,964
py
Python
nova/tests/unit/virt/xenapi/test_vm_utils.py
NxtCloud/nova
6f6c3bcc1fea805ece40d64b092eb836ee21c006
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/virt/xenapi/test_vm_utils.py
NxtCloud/nova
6f6c3bcc1fea805ece40d64b092eb836ee21c006
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/virt/xenapi/test_vm_utils.py
NxtCloud/nova
6f6c3bcc1fea805ece40d64b092eb836ee21c006
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 OpenStack Foundation # 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. import contextlib import uuid from eventlet import greenthread import fixtures import mock from mox3 import mox from oslo.config import cfg from oslo.config import fixture as config_fixture from oslo.utils import timeutils from oslo.utils import units from oslo_concurrency import lockutils from oslo_concurrency import processutils import six from nova.compute import flavors from nova.compute import power_state from nova.compute import vm_mode from nova import context from nova import exception from nova.i18n import _ from nova import objects from nova import test from nova.tests.unit.objects import test_flavor from nova.tests.unit.virt.xenapi import stubs from nova.tests.unit.virt.xenapi import test_xenapi from nova import utils from nova.virt import hardware from nova.virt.xenapi.client import session as xenapi_session from nova.virt.xenapi import driver as xenapi_conn from nova.virt.xenapi import fake from nova.virt.xenapi import vm_utils CONF = cfg.CONF XENSM_TYPE = 'xensm' ISCSI_TYPE = 'iscsi' def get_fake_connection_data(sr_type): fakes = {XENSM_TYPE: {'sr_uuid': 'falseSR', 'name_label': 'fake_storage', 'name_description': 'test purposes', 'server': 'myserver', 'serverpath': '/local/scratch/myname', 'sr_type': 'nfs', 'introduce_sr_keys': ['server', 'serverpath', 'sr_type'], 'vdi_uuid': 'falseVDI'}, ISCSI_TYPE: {'volume_id': 'fake_volume_id', 'target_lun': 1, 'target_iqn': 'fake_iqn:volume-fake_volume_id', 'target_portal': u'localhost:3260', 'target_discovered': False}, } return fakes[sr_type] def _get_fake_session(error=None): session = mock.Mock() xenapi_session.apply_session_helpers(session) if error is not None: class FakeException(Exception): details = [error, "a", "b", "c"] session.XenAPI.Failure = FakeException session.call_xenapi.side_effect = FakeException return session @contextlib.contextmanager def contextified(result): yield result def _fake_noop(*args, **kwargs): return class VMUtilsTestBase(stubs.XenAPITestBaseNoDB): pass class LookupTestCase(VMUtilsTestBase): def setUp(self): super(LookupTestCase, self).setUp() self.session = self.mox.CreateMockAnything('Fake Session') self.name_label = 'my_vm' def _do_mock(self, result): self.session.call_xenapi( "VM.get_by_name_label", self.name_label).AndReturn(result) self.mox.ReplayAll() def test_normal(self): self._do_mock(['x']) result = vm_utils.lookup(self.session, self.name_label) self.assertEqual('x', result) def test_no_result(self): self._do_mock([]) result = vm_utils.lookup(self.session, self.name_label) self.assertIsNone(result) def test_too_many(self): self._do_mock(['a', 'b']) self.assertRaises(exception.InstanceExists, vm_utils.lookup, self.session, self.name_label) def test_rescue_none(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn([]) self._do_mock(['x']) result = vm_utils.lookup(self.session, self.name_label, check_rescue=True) self.assertEqual('x', result) def test_rescue_found(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn(['y']) self.mox.ReplayAll() result = vm_utils.lookup(self.session, self.name_label, check_rescue=True) self.assertEqual('y', result) def test_rescue_too_many(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn(['a', 'b', 'c']) self.mox.ReplayAll() self.assertRaises(exception.InstanceExists, vm_utils.lookup, self.session, self.name_label, check_rescue=True) class GenerateConfigDriveTestCase(VMUtilsTestBase): def test_no_admin_pass(self): instance = {} self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr('session').AndReturn('sr_ref') self.mox.StubOutWithMock(vm_utils, 'create_vdi') vm_utils.create_vdi('session', 'sr_ref', instance, 'config-2', 'configdrive', 64 * units.Mi).AndReturn('vdi_ref') self.mox.StubOutWithMock(vm_utils, 'vdi_attached_here') vm_utils.vdi_attached_here( 'session', 'vdi_ref', read_only=False).AndReturn( contextified('mounted_dev')) class FakeInstanceMetadata(object): def __init__(_self, instance, content=None, extra_md=None, network_info=None): self.assertEqual(network_info, "nw_info") def metadata_for_config_drive(_self): return [] self.useFixture(fixtures.MonkeyPatch( 'nova.api.metadata.base.InstanceMetadata', FakeInstanceMetadata)) self.mox.StubOutWithMock(utils, 'execute') utils.execute('genisoimage', '-o', mox.IgnoreArg(), '-ldots', '-allow-lowercase', '-allow-multidot', '-l', '-publisher', mox.IgnoreArg(), '-quiet', '-J', '-r', '-V', 'config-2', mox.IgnoreArg(), attempts=1, run_as_root=False).AndReturn(None) utils.execute('dd', mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), run_as_root=True).AndReturn(None) self.mox.StubOutWithMock(vm_utils, 'create_vbd') vm_utils.create_vbd('session', 'vm_ref', 'vdi_ref', mox.IgnoreArg(), bootable=False, read_only=True).AndReturn(None) self.mox.ReplayAll() # And the actual call we're testing vm_utils.generate_configdrive('session', instance, 'vm_ref', 'userdevice', "nw_info") @mock.patch.object(vm_utils, "destroy_vdi") @mock.patch.object(vm_utils, "vdi_attached_here") @mock.patch.object(vm_utils, "create_vdi") @mock.patch.object(vm_utils, "safe_find_sr") def test_vdi_cleaned_up(self, mock_find, mock_create_vdi, mock_attached, mock_destroy): mock_create_vdi.return_value = 'vdi_ref' mock_attached.side_effect = test.TestingException mock_destroy.side_effect = exception.StorageError(reason="") instance = {"uuid": "asdf"} self.assertRaises(test.TestingException, vm_utils.generate_configdrive, 'session', instance, 'vm_ref', 'userdevice', 'nw_info') mock_destroy.assert_called_once_with('session', 'vdi_ref') class XenAPIGetUUID(VMUtilsTestBase): def test_get_this_vm_uuid_new_kernel(self): self.mox.StubOutWithMock(vm_utils, '_get_sys_hypervisor_uuid') vm_utils._get_sys_hypervisor_uuid().AndReturn( '2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f') self.mox.ReplayAll() self.assertEqual('2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', vm_utils.get_this_vm_uuid(None)) self.mox.VerifyAll() def test_get_this_vm_uuid_old_kernel_reboot(self): self.mox.StubOutWithMock(vm_utils, '_get_sys_hypervisor_uuid') self.mox.StubOutWithMock(utils, 'execute') vm_utils._get_sys_hypervisor_uuid().AndRaise( IOError(13, 'Permission denied')) utils.execute('xenstore-read', 'domid', run_as_root=True).AndReturn( ('27', '')) utils.execute('xenstore-read', '/local/domain/27/vm', run_as_root=True).AndReturn( ('/vm/2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', '')) self.mox.ReplayAll() self.assertEqual('2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', vm_utils.get_this_vm_uuid(None)) self.mox.VerifyAll() class FakeSession(object): def call_xenapi(self, *args): pass def call_plugin(self, *args): pass def call_plugin_serialized(self, plugin, fn, *args, **kwargs): pass def call_plugin_serialized_with_retry(self, plugin, fn, num_retries, callback, *args, **kwargs): pass class FetchVhdImageTestCase(VMUtilsTestBase): def setUp(self): super(FetchVhdImageTestCase, self).setUp() self.context = context.get_admin_context() self.context.auth_token = 'auth_token' self.session = FakeSession() self.instance = {"uuid": "uuid"} self.mox.StubOutWithMock(vm_utils, '_make_uuid_stack') vm_utils._make_uuid_stack().AndReturn(["uuid_stack"]) self.mox.StubOutWithMock(vm_utils, 'get_sr_path') vm_utils.get_sr_path(self.session).AndReturn('sr_path') def _stub_glance_download_vhd(self, raise_exc=None): self.mox.StubOutWithMock( self.session, 'call_plugin_serialized_with_retry') func = self.session.call_plugin_serialized_with_retry( 'glance', 'download_vhd', 0, mox.IgnoreArg(), mox.IgnoreArg(), extra_headers={'X-Service-Catalog': '[]', 'X-Auth-Token': 'auth_token', 'X-Roles': '', 'X-Tenant-Id': None, 'X-User-Id': None, 'X-Identity-Status': 'Confirmed'}, image_id='image_id', uuid_stack=["uuid_stack"], sr_path='sr_path') if raise_exc: func.AndRaise(raise_exc) else: func.AndReturn({'root': {'uuid': 'vdi'}}) def _stub_bittorrent_download_vhd(self, raise_exc=None): self.mox.StubOutWithMock( self.session, 'call_plugin_serialized') func = self.session.call_plugin_serialized( 'bittorrent', 'download_vhd', image_id='image_id', uuid_stack=["uuid_stack"], sr_path='sr_path', torrent_download_stall_cutoff=600, torrent_listen_port_start=6881, torrent_listen_port_end=6891, torrent_max_last_accessed=86400, torrent_max_seeder_processes_per_host=1, torrent_seed_chance=1.0, torrent_seed_duration=3600, torrent_url='http://foo/image_id.torrent' ) if raise_exc: func.AndRaise(raise_exc) else: func.AndReturn({'root': {'uuid': 'vdi'}}) def test_fetch_vhd_image_works_with_glance(self): self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size( self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_fetch_vhd_image_works_with_bittorrent(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(True) self._stub_bittorrent_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_fetch_vhd_image_cleans_up_vdi_on_fail(self): self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi").AndRaise(exception.FlavorDiskTooSmall) self.mox.StubOutWithMock(self.session, 'call_xenapi') self.session.call_xenapi("VDI.get_by_uuid", "vdi").AndReturn("ref") self.mox.StubOutWithMock(vm_utils, 'destroy_vdi') vm_utils.destroy_vdi(self.session, "ref").AndRaise(exception.StorageError(reason="")) self.mox.ReplayAll() self.assertRaises(exception.FlavorDiskTooSmall, vm_utils._fetch_vhd_image, self.context, self.session, self.instance, 'image_id') self.mox.VerifyAll() def test_fallback_to_default_handler(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(True) self._stub_bittorrent_download_vhd(raise_exc=RuntimeError) vm_utils._make_uuid_stack().AndReturn(["uuid_stack"]) vm_utils.get_sr_path(self.session).AndReturn('sr_path') self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_default_handler_does_not_fallback_to_itself(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd(raise_exc=RuntimeError) self.mox.ReplayAll() self.assertRaises(RuntimeError, vm_utils._fetch_vhd_image, self.context, self.session, self.instance, 'image_id') self.mox.VerifyAll() class TestImageCompression(VMUtilsTestBase): def test_image_compression(self): # Testing for nova.conf, too low, negative, and a correct value. self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=0, group='xenserver') self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=-6, group='xenserver') self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=6, group='xenserver') self.assertEqual(vm_utils.get_compression_level(), 6) class ResizeHelpersTestCase(VMUtilsTestBase): def test_repair_filesystem(self): self.mox.StubOutWithMock(utils, 'execute') utils.execute('e2fsck', '-f', "-y", "fakepath", run_as_root=True, check_exit_code=[0, 1, 2]).AndReturn( ("size is: 42", "")) self.mox.ReplayAll() vm_utils._repair_filesystem("fakepath") def _call_tune2fs_remove_journal(self, path): utils.execute("tune2fs", "-O ^has_journal", path, run_as_root=True) def _call_tune2fs_add_journal(self, path): utils.execute("tune2fs", "-j", path, run_as_root=True) def _call_parted_mkpart(self, path, start, end): utils.execute('parted', '--script', path, 'rm', '1', run_as_root=True) utils.execute('parted', '--script', path, 'mkpart', 'primary', '%ds' % start, '%ds' % end, run_as_root=True) def _call_parted_boot_flag(sef, path): utils.execute('parted', '--script', path, 'set', '1', 'boot', 'on', run_as_root=True) def test_resize_part_and_fs_down_succeeds(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) utils.execute("resize2fs", partition_path, "10s", run_as_root=True) self._call_parted_mkpart(dev_path, 0, 9) self._call_parted_boot_flag(dev_path) self._call_tune2fs_add_journal(partition_path) self.mox.ReplayAll() vm_utils._resize_part_and_fs("fake", 0, 20, 10, "boot") def test_log_progress_if_required(self): self.mox.StubOutWithMock(vm_utils.LOG, "debug") vm_utils.LOG.debug(_("Sparse copy in progress, " "%(complete_pct).2f%% complete. " "%(left)s bytes left to copy"), {"complete_pct": 50.0, "left": 1}) current = timeutils.utcnow() timeutils.set_time_override(current) timeutils.advance_time_seconds(vm_utils.PROGRESS_INTERVAL_SECONDS + 1) self.mox.ReplayAll() vm_utils._log_progress_if_required(1, current, 2) def test_log_progress_if_not_required(self): self.mox.StubOutWithMock(vm_utils.LOG, "debug") current = timeutils.utcnow() timeutils.set_time_override(current) timeutils.advance_time_seconds(vm_utils.PROGRESS_INTERVAL_SECONDS - 1) self.mox.ReplayAll() vm_utils._log_progress_if_required(1, current, 2) def test_resize_part_and_fs_down_fails_disk_too_big(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path new_sectors = 10 vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) mobj = utils.execute("resize2fs", partition_path, "%ss" % new_sectors, run_as_root=True) mobj.AndRaise(processutils.ProcessExecutionError) self.mox.ReplayAll() self.assertRaises(exception.ResizeError, vm_utils._resize_part_and_fs, "fake", 0, 20, 10, "boot") def test_resize_part_and_fs_up_succeeds(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) self._call_parted_mkpart(dev_path, 0, 29) utils.execute("resize2fs", partition_path, run_as_root=True) self._call_tune2fs_add_journal(partition_path) self.mox.ReplayAll() vm_utils._resize_part_and_fs("fake", 0, 20, 30, "") def test_resize_disk_throws_on_zero_size(self): self.assertRaises(exception.ResizeError, vm_utils.resize_disk, "session", "instance", "vdi_ref", {"root_gb": 0}) def test_auto_config_disk_returns_early_on_zero_size(self): vm_utils.try_auto_configure_disk("bad_session", "bad_vdi_ref", 0) @mock.patch.object(utils, "execute") def test_get_partitions(self, mock_execute): parted_return = "BYT;\n...\n" parted_return += "1:2s:11s:10s:ext3::boot;\n" parted_return += "2:20s:11s:10s::bob:;\n" mock_execute.return_value = (parted_return, None) partitions = vm_utils._get_partitions("abc") self.assertEqual(2, len(partitions)) self.assertEqual((1, 2, 10, "ext3", "", "boot"), partitions[0]) self.assertEqual((2, 20, 10, "", "bob", ""), partitions[1]) class CheckVDISizeTestCase(VMUtilsTestBase): def setUp(self): super(CheckVDISizeTestCase, self).setUp() self.context = 'fakecontext' self.session = 'fakesession' self.instance = objects.Instance(uuid=str(uuid.uuid4())) self.flavor = objects.Flavor() self.vdi_uuid = 'fakeuuid' def test_not_too_large(self): self.mox.StubOutWithMock(vm_utils, '_get_vdi_chain_size') vm_utils._get_vdi_chain_size(self.session, self.vdi_uuid).AndReturn(1073741824) self.mox.ReplayAll() with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 1 get.return_value = self.flavor vm_utils._check_vdi_size(self.context, self.session, self.instance, self.vdi_uuid) def test_too_large(self): self.mox.StubOutWithMock(vm_utils, '_get_vdi_chain_size') vm_utils._get_vdi_chain_size(self.session, self.vdi_uuid).AndReturn(11811160065) # 10GB overhead allowed self.mox.ReplayAll() with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 1 get.return_value = self.flavor self.assertRaises(exception.FlavorDiskTooSmall, vm_utils._check_vdi_size, self.context, self.session, self.instance, self.vdi_uuid) def test_zero_root_gb_disables_check(self): with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 0 get.return_value = self.flavor vm_utils._check_vdi_size(self.context, self.session, self.instance, self.vdi_uuid) class GetInstanceForVdisForSrTestCase(VMUtilsTestBase): def setUp(self): super(GetInstanceForVdisForSrTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') def test_get_instance_vdis_for_sr(self): vm_ref = fake.create_vm("foo", "Running") sr_ref = fake.create_sr() vdi_1 = fake.create_vdi('vdiname1', sr_ref) vdi_2 = fake.create_vdi('vdiname2', sr_ref) for vdi_ref in [vdi_1, vdi_2]: fake.create_vbd(vm_ref, vdi_ref) stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.get_instance_vdis_for_sr( driver._session, vm_ref, sr_ref)) self.assertEqual([vdi_1, vdi_2], result) def test_get_instance_vdis_for_sr_no_vbd(self): vm_ref = fake.create_vm("foo", "Running") sr_ref = fake.create_sr() stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.get_instance_vdis_for_sr( driver._session, vm_ref, sr_ref)) self.assertEqual([], result) class VMRefOrRaiseVMFoundTestCase(VMUtilsTestBase): def test_lookup_call(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn('ignored') mock.ReplayAll() vm_utils.vm_ref_or_raise('session', 'somename') mock.VerifyAll() def test_return_value(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn('vmref') mock.ReplayAll() self.assertEqual( 'vmref', vm_utils.vm_ref_or_raise('session', 'somename')) mock.VerifyAll() class VMRefOrRaiseVMNotFoundTestCase(VMUtilsTestBase): def test_exception_raised(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn(None) mock.ReplayAll() self.assertRaises( exception.InstanceNotFound, lambda: vm_utils.vm_ref_or_raise('session', 'somename') ) mock.VerifyAll() def test_exception_msg_contains_vm_name(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn(None) mock.ReplayAll() try: vm_utils.vm_ref_or_raise('session', 'somename') except exception.InstanceNotFound as e: self.assertIn('somename', six.text_type(e)) mock.VerifyAll() @mock.patch.object(vm_utils, 'safe_find_sr', return_value='safe_find_sr') class CreateCachedImageTestCase(VMUtilsTestBase): def setUp(self): super(CreateCachedImageTestCase, self).setUp() self.session = _get_fake_session() @mock.patch.object(vm_utils, '_clone_vdi', return_value='new_vdi_ref') def test_cached(self, mock_clone_vdi, mock_safe_find_sr): self.session.call_xenapi.side_effect = ['ext', {'vdi_ref': 2}, None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) @mock.patch.object(vm_utils, '_safe_copy_vdi', return_value='new_vdi_ref') def test_no_cow(self, mock_safe_copy_vdi, mock_safe_find_sr): self.flags(use_cow_images=False) self.session.call_xenapi.side_effect = ['ext', {'vdi_ref': 2}, None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) def test_no_cow_no_ext(self, mock_safe_find_sr): self.flags(use_cow_images=False) self.session.call_xenapi.side_effect = ['non-ext', {'vdi_ref': 2}, 'vdi_ref', None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) @mock.patch.object(vm_utils, '_clone_vdi', return_value='new_vdi_ref') @mock.patch.object(vm_utils, '_fetch_image', return_value={'root': {'uuid': 'vdi_uuid', 'file': None}}) def test_noncached(self, mock_fetch_image, mock_clone_vdi, mock_safe_find_sr): self.session.call_xenapi.side_effect = ['ext', {}, 'cache_vdi_ref', None, None, None, None, None, None, 'vdi_uuid'] self.assertEqual((True, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) class BittorrentTestCase(VMUtilsTestBase): def setUp(self): super(BittorrentTestCase, self).setUp() self.context = context.get_admin_context() def test_image_uses_bittorrent(self): instance = {'system_metadata': {'image_bittorrent': True}} self.flags(torrent_images='some', group='xenserver') self.assertTrue(vm_utils._image_uses_bittorrent(self.context, instance)) def _test_create_image(self, cache_type): instance = {'system_metadata': {'image_cache_in_nova': True}} self.flags(cache_images=cache_type, group='xenserver') was = {'called': None} def fake_create_cached_image(*args): was['called'] = 'some' return (False, {}) self.stubs.Set(vm_utils, '_create_cached_image', fake_create_cached_image) def fake_fetch_image(*args): was['called'] = 'none' return {} self.stubs.Set(vm_utils, '_fetch_image', fake_fetch_image) vm_utils.create_image(self.context, None, instance, 'foo', 'bar', 'baz') self.assertEqual(was['called'], cache_type) def test_create_image_cached(self): self._test_create_image('some') def test_create_image_uncached(self): self._test_create_image('none') class ShutdownTestCase(VMUtilsTestBase): def test_hardshutdown_should_return_true_when_vm_is_shutdown(self): self.mock = mox.Mox() session = FakeSession() instance = "instance" vm_ref = "vm-ref" self.mock.StubOutWithMock(vm_utils, 'is_vm_shutdown') vm_utils.is_vm_shutdown(session, vm_ref).AndReturn(True) self.mock.StubOutWithMock(vm_utils, 'LOG') self.assertTrue(vm_utils.hard_shutdown_vm( session, instance, vm_ref)) def test_cleanshutdown_should_return_true_when_vm_is_shutdown(self): self.mock = mox.Mox() session = FakeSession() instance = "instance" vm_ref = "vm-ref" self.mock.StubOutWithMock(vm_utils, 'is_vm_shutdown') vm_utils.is_vm_shutdown(session, vm_ref).AndReturn(True) self.mock.StubOutWithMock(vm_utils, 'LOG') self.assertTrue(vm_utils.clean_shutdown_vm( session, instance, vm_ref)) class CreateVBDTestCase(VMUtilsTestBase): def setUp(self): super(CreateVBDTestCase, self).setUp() self.session = FakeSession() self.mock = mox.Mox() self.mock.StubOutWithMock(self.session, 'call_xenapi') self.vbd_rec = self._generate_vbd_rec() def _generate_vbd_rec(self): vbd_rec = {} vbd_rec['VM'] = 'vm_ref' vbd_rec['VDI'] = 'vdi_ref' vbd_rec['userdevice'] = '0' vbd_rec['bootable'] = False vbd_rec['mode'] = 'RW' vbd_rec['type'] = 'disk' vbd_rec['unpluggable'] = True vbd_rec['empty'] = False vbd_rec['other_config'] = {} vbd_rec['qos_algorithm_type'] = '' vbd_rec['qos_algorithm_params'] = {} vbd_rec['qos_supported_algorithms'] = [] return vbd_rec def test_create_vbd_default_args(self): self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", "vdi_ref", 0) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_create_vbd_osvol(self): self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.session.call_xenapi('VBD.add_to_other_config', "vbd_ref", "osvol", "True") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", "vdi_ref", 0, osvol=True) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_create_vbd_extra_args(self): self.vbd_rec['VDI'] = 'OpaqueRef:NULL' self.vbd_rec['type'] = 'a' self.vbd_rec['mode'] = 'RO' self.vbd_rec['bootable'] = True self.vbd_rec['empty'] = True self.vbd_rec['unpluggable'] = False self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", None, 0, vbd_type="a", read_only=True, bootable=True, empty=True, unpluggable=False) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_attach_cd(self): self.mock.StubOutWithMock(vm_utils, 'create_vbd') vm_utils.create_vbd(self.session, "vm_ref", None, 1, vbd_type='cd', read_only=True, bootable=True, empty=True, unpluggable=False).AndReturn("vbd_ref") self.session.call_xenapi('VBD.insert', "vbd_ref", "vdi_ref") self.mock.ReplayAll() result = vm_utils.attach_cd(self.session, "vm_ref", "vdi_ref", 1) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() class UnplugVbdTestCase(VMUtilsTestBase): @mock.patch.object(greenthread, 'sleep') def test_unplug_vbd_works(self, mock_sleep): session = _get_fake_session() vbd_ref = "vbd_ref" vm_ref = 'vm_ref' vm_utils.unplug_vbd(session, vbd_ref, vm_ref) session.call_xenapi.assert_called_once_with('VBD.unplug', vbd_ref) self.assertEqual(0, mock_sleep.call_count) def test_unplug_vbd_raises_unexpected_error(self): session = _get_fake_session() vbd_ref = "vbd_ref" vm_ref = 'vm_ref' session.call_xenapi.side_effect = test.TestingException() self.assertRaises(test.TestingException, vm_utils.unplug_vbd, session, vm_ref, vbd_ref) self.assertEqual(1, session.call_xenapi.call_count) def test_unplug_vbd_already_detached_works(self): error = "DEVICE_ALREADY_DETACHED" session = _get_fake_session(error) vbd_ref = "vbd_ref" vm_ref = 'vm_ref' vm_utils.unplug_vbd(session, vbd_ref, vm_ref) self.assertEqual(1, session.call_xenapi.call_count) def test_unplug_vbd_already_raises_unexpected_xenapi_error(self): session = _get_fake_session("") vbd_ref = "vbd_ref" vm_ref = 'vm_ref' self.assertRaises(exception.StorageError, vm_utils.unplug_vbd, session, vbd_ref, vm_ref) self.assertEqual(1, session.call_xenapi.call_count) def _test_uplug_vbd_retries(self, mock_sleep, error): session = _get_fake_session(error) vbd_ref = "vbd_ref" vm_ref = 'vm_ref' self.assertRaises(exception.StorageError, vm_utils.unplug_vbd, session, vm_ref, vbd_ref) self.assertEqual(11, session.call_xenapi.call_count) self.assertEqual(10, mock_sleep.call_count) @mock.patch.object(greenthread, 'sleep') def test_uplug_vbd_retries_on_rejected(self, mock_sleep): self._test_uplug_vbd_retries(mock_sleep, "DEVICE_DETACH_REJECTED") @mock.patch.object(greenthread, 'sleep') def test_uplug_vbd_retries_on_internal_error(self, mock_sleep): self._test_uplug_vbd_retries(mock_sleep, "INTERNAL_ERROR") class VDIOtherConfigTestCase(VMUtilsTestBase): """Tests to ensure that the code is populating VDI's `other_config` attribute with the correct metadta. """ def setUp(self): super(VDIOtherConfigTestCase, self).setUp() class _FakeSession(): def call_xenapi(self, operation, *args, **kwargs): # VDI.add_to_other_config -> VDI_add_to_other_config method = getattr(self, operation.replace('.', '_'), None) if method: return method(*args, **kwargs) self.operation = operation self.args = args self.kwargs = kwargs self.session = _FakeSession() self.context = context.get_admin_context() self.fake_instance = {'uuid': 'aaaa-bbbb-cccc-dddd', 'name': 'myinstance'} def test_create_vdi(self): # Some images are registered with XenServer explicitly by calling # `create_vdi` vm_utils.create_vdi(self.session, 'sr_ref', self.fake_instance, 'myvdi', 'root', 1024, read_only=True) expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, self.session.args[0]['other_config']) def test_create_image(self): # Other images are registered implicitly when they are dropped into # the SR by a dom0 plugin or some other process self.flags(cache_images='none', group='xenserver') def fake_fetch_image(*args): return {'root': {'uuid': 'fake-uuid'}} self.stubs.Set(vm_utils, '_fetch_image', fake_fetch_image) other_config = {} def VDI_add_to_other_config(ref, key, value): other_config[key] = value # Stubbing on the session object and not class so we don't pollute # other tests self.session.VDI_add_to_other_config = VDI_add_to_other_config self.session.VDI_get_other_config = lambda vdi: {} vm_utils.create_image(self.context, self.session, self.fake_instance, 'myvdi', 'image1', vm_utils.ImageType.DISK_VHD) expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, other_config) def test_import_migrated_vhds(self): # Migrated images should preserve the `other_config` other_config = {} def VDI_add_to_other_config(ref, key, value): other_config[key] = value def call_plugin_serialized(*args, **kwargs): return {'root': {'uuid': 'aaaa-bbbb-cccc-dddd'}} # Stubbing on the session object and not class so we don't pollute # other tests self.session.VDI_add_to_other_config = VDI_add_to_other_config self.session.VDI_get_other_config = lambda vdi: {} self.session.call_plugin_serialized = call_plugin_serialized self.stubs.Set(vm_utils, 'get_sr_path', lambda *a, **k: None) self.stubs.Set(vm_utils, 'scan_default_sr', lambda *a, **k: None) vm_utils._import_migrated_vhds(self.session, self.fake_instance, "disk_label", "root", "vdi_label") expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, other_config) class GenerateDiskTestCase(VMUtilsTestBase): def setUp(self): super(GenerateDiskTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.session.is_local_connection = False self.vm_ref = fake.create_vm("foo", "Running") def tearDown(self): super(GenerateDiskTestCase, self).tearDown() fake.destroy_vm(self.vm_ref) def _expect_parted_calls(self): self.mox.StubOutWithMock(utils, "execute") self.mox.StubOutWithMock(utils, "trycmd") self.mox.StubOutWithMock(vm_utils, "destroy_vdi") self.mox.StubOutWithMock(vm_utils.os.path, "exists") if self.session.is_local_connection: utils.execute('parted', '--script', '/dev/fakedev', 'mklabel', 'msdos', check_exit_code=False, run_as_root=True) utils.execute('parted', '--script', '/dev/fakedev', '--', 'mkpart', 'primary', '0', '-0', check_exit_code=False, run_as_root=True) vm_utils.os.path.exists('/dev/mapper/fakedev1').AndReturn(True) utils.trycmd('kpartx', '-a', '/dev/fakedev', discard_warnings=True, run_as_root=True) else: utils.execute('parted', '--script', '/dev/fakedev', 'mklabel', 'msdos', check_exit_code=True, run_as_root=True) utils.execute('parted', '--script', '/dev/fakedev', '--', 'mkpart', 'primary', '0', '-0', check_exit_code=True, run_as_root=True) def _check_vdi(self, vdi_ref, check_attached=True): vdi_rec = self.session.call_xenapi("VDI.get_record", vdi_ref) self.assertEqual(str(10 * units.Mi), vdi_rec["virtual_size"]) if check_attached: vbd_ref = vdi_rec["VBDs"][0] vbd_rec = self.session.call_xenapi("VBD.get_record", vbd_ref) self.assertEqual(self.vm_ref, vbd_rec['VM']) else: self.assertEqual(0, len(vdi_rec["VBDs"])) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_with_no_fs_given(self): self._expect_parted_calls() self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "user", 10, None) self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_swap(self): self._expect_parted_calls() utils.execute('mkswap', '/dev/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "swap", 10, "linux-swap") self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ephemeral(self): self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "ephemeral", 10, "ext4") self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ensure_cleanup_called(self): self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/fakedev1', run_as_root=True).AndRaise(test.TestingException) vm_utils.destroy_vdi(self.session, mox.IgnoreArg()).AndRaise(exception.StorageError(reason="")) self.mox.ReplayAll() self.assertRaises(test.TestingException, vm_utils._generate_disk, self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "ephemeral", 10, "ext4") @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ephemeral_local_not_attached(self): self.session.is_local_connection = True self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/mapper/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, None, "2", "name", "ephemeral", 10, "ext4") self._check_vdi(vdi_ref, check_attached=False) class GenerateEphemeralTestCase(VMUtilsTestBase): def setUp(self): super(GenerateEphemeralTestCase, self).setUp() self.session = "session" self.instance = "instance" self.vm_ref = "vm_ref" self.name_label = "name" self.ephemeral_name_label = "name ephemeral" self.userdevice = 4 self.mox.StubOutWithMock(vm_utils, "_generate_disk") self.mox.StubOutWithMock(vm_utils, "safe_destroy_vdis") def test_get_ephemeral_disk_sizes_simple(self): result = vm_utils.get_ephemeral_disk_sizes(20) expected = [20] self.assertEqual(expected, list(result)) def test_get_ephemeral_disk_sizes_three_disks_2000(self): result = vm_utils.get_ephemeral_disk_sizes(4030) expected = [2000, 2000, 30] self.assertEqual(expected, list(result)) def test_get_ephemeral_disk_sizes_two_disks_1024(self): result = vm_utils.get_ephemeral_disk_sizes(2048) expected = [1024, 1024] self.assertEqual(expected, list(result)) def _expect_generate_disk(self, size, device, name_label): vm_utils._generate_disk(self.session, self.instance, self.vm_ref, str(device), name_label, 'ephemeral', size * 1024, None).AndReturn(device) def test_generate_ephemeral_adds_one_disk(self): self._expect_generate_disk(20, self.userdevice, self.ephemeral_name_label) self.mox.ReplayAll() vm_utils.generate_ephemeral(self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 20) def test_generate_ephemeral_adds_multiple_disks(self): self._expect_generate_disk(2000, self.userdevice, self.ephemeral_name_label) self._expect_generate_disk(2000, self.userdevice + 1, self.ephemeral_name_label + " (1)") self._expect_generate_disk(30, self.userdevice + 2, self.ephemeral_name_label + " (2)") self.mox.ReplayAll() vm_utils.generate_ephemeral(self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 4030) def test_generate_ephemeral_cleans_up_on_error(self): self._expect_generate_disk(1024, self.userdevice, self.ephemeral_name_label) self._expect_generate_disk(1024, self.userdevice + 1, self.ephemeral_name_label + " (1)") vm_utils._generate_disk(self.session, self.instance, self.vm_ref, str(self.userdevice + 2), "name ephemeral (2)", 'ephemeral', units.Mi, None).AndRaise(exception.NovaException) vm_utils.safe_destroy_vdis(self.session, [4, 5]) self.mox.ReplayAll() self.assertRaises(exception.NovaException, vm_utils.generate_ephemeral, self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 4096) class FakeFile(object): def __init__(self): self._file_operations = [] def seek(self, offset): self._file_operations.append((self.seek, offset)) class StreamDiskTestCase(VMUtilsTestBase): def setUp(self): import __builtin__ super(StreamDiskTestCase, self).setUp() self.mox.StubOutWithMock(vm_utils.utils, 'make_dev_path') self.mox.StubOutWithMock(vm_utils.utils, 'temporary_chown') self.mox.StubOutWithMock(vm_utils, '_write_partition') # NOTE(matelakat): This might hide the fail reason, as test runners # are unhappy with a mocked out open. self.mox.StubOutWithMock(__builtin__, 'open') self.image_service_func = self.mox.CreateMockAnything() def test_non_ami(self): fake_file = FakeFile() vm_utils.utils.make_dev_path('dev').AndReturn('some_path') vm_utils.utils.temporary_chown( 'some_path').AndReturn(contextified(None)) open('some_path', 'wb').AndReturn(contextified(fake_file)) self.image_service_func(fake_file) self.mox.ReplayAll() vm_utils._stream_disk("session", self.image_service_func, vm_utils.ImageType.KERNEL, None, 'dev') self.assertEqual([(fake_file.seek, 0)], fake_file._file_operations) def test_ami_disk(self): fake_file = FakeFile() vm_utils._write_partition("session", 100, 'dev') vm_utils.utils.make_dev_path('dev').AndReturn('some_path') vm_utils.utils.temporary_chown( 'some_path').AndReturn(contextified(None)) open('some_path', 'wb').AndReturn(contextified(fake_file)) self.image_service_func(fake_file) self.mox.ReplayAll() vm_utils._stream_disk("session", self.image_service_func, vm_utils.ImageType.DISK, 100, 'dev') self.assertEqual( [(fake_file.seek, vm_utils.MBR_SIZE_BYTES)], fake_file._file_operations) class VMUtilsSRPath(VMUtilsTestBase): def setUp(self): super(VMUtilsSRPath, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.session.is_local_connection = False def test_defined(self): self.mox.StubOutWithMock(vm_utils, "safe_find_sr") self.mox.StubOutWithMock(self.session, "call_xenapi") vm_utils.safe_find_sr(self.session).AndReturn("sr_ref") self.session.host_ref = "host_ref" self.session.call_xenapi('PBD.get_all_records_where', 'field "host"="host_ref" and field "SR"="sr_ref"').AndReturn( {'pbd_ref': {'device_config': {'path': 'sr_path'}}}) self.mox.ReplayAll() self.assertEqual(vm_utils.get_sr_path(self.session), "sr_path") def test_default(self): self.mox.StubOutWithMock(vm_utils, "safe_find_sr") self.mox.StubOutWithMock(self.session, "call_xenapi") vm_utils.safe_find_sr(self.session).AndReturn("sr_ref") self.session.host_ref = "host_ref" self.session.call_xenapi('PBD.get_all_records_where', 'field "host"="host_ref" and field "SR"="sr_ref"').AndReturn( {'pbd_ref': {'device_config': {}}}) self.session.call_xenapi("SR.get_record", "sr_ref").AndReturn( {'uuid': 'sr_uuid', 'type': 'ext'}) self.mox.ReplayAll() self.assertEqual(vm_utils.get_sr_path(self.session), "/var/run/sr-mount/sr_uuid") class CreateKernelRamdiskTestCase(VMUtilsTestBase): def setUp(self): super(CreateKernelRamdiskTestCase, self).setUp() self.context = "context" self.session = FakeSession() self.instance = {"kernel_id": None, "ramdisk_id": None} self.name_label = "name" self.mox.StubOutWithMock(self.session, "call_plugin") self.mox.StubOutWithMock(uuid, "uuid4") self.mox.StubOutWithMock(vm_utils, "_fetch_disk_image") def test_create_kernel_and_ramdisk_no_create(self): self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual((None, None), result) def test_create_kernel_and_ramdisk_create_both_cached(self): kernel_id = "kernel" ramdisk_id = "ramdisk" self.instance["kernel_id"] = kernel_id self.instance["ramdisk_id"] = ramdisk_id args_kernel = {} args_kernel['cached-image'] = kernel_id args_kernel['new-image-uuid'] = "fake_uuid1" uuid.uuid4().AndReturn("fake_uuid1") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_kernel).AndReturn("k") args_ramdisk = {} args_ramdisk['cached-image'] = ramdisk_id args_ramdisk['new-image-uuid'] = "fake_uuid2" uuid.uuid4().AndReturn("fake_uuid2") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_ramdisk).AndReturn("r") self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual(("k", "r"), result) def test_create_kernel_and_ramdisk_create_kernel_not_cached(self): kernel_id = "kernel" self.instance["kernel_id"] = kernel_id args_kernel = {} args_kernel['cached-image'] = kernel_id args_kernel['new-image-uuid'] = "fake_uuid1" uuid.uuid4().AndReturn("fake_uuid1") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_kernel).AndReturn("") kernel = {"kernel": {"file": "k"}} vm_utils._fetch_disk_image(self.context, self.session, self.instance, self.name_label, kernel_id, 0).AndReturn(kernel) self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual(("k", None), result) class ScanSrTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, "_scan_sr") @mock.patch.object(vm_utils, "safe_find_sr") def test_scan_default_sr(self, mock_safe_find_sr, mock_scan_sr): mock_safe_find_sr.return_value = "sr_ref" self.assertEqual("sr_ref", vm_utils.scan_default_sr("fake_session")) mock_scan_sr.assert_called_once_with("fake_session", "sr_ref") def test_scan_sr_works(self): session = mock.Mock() vm_utils._scan_sr(session, "sr_ref") session.call_xenapi.assert_called_once_with('SR.scan', "sr_ref") def test_scan_sr_unknown_error_fails_once(self): session = mock.Mock() session.call_xenapi.side_effect = test.TestingException self.assertRaises(test.TestingException, vm_utils._scan_sr, session, "sr_ref") session.call_xenapi.assert_called_once_with('SR.scan', "sr_ref") @mock.patch.object(greenthread, 'sleep') def test_scan_sr_known_error_retries_then_throws(self, mock_sleep): session = mock.Mock() class FakeException(Exception): details = ['SR_BACKEND_FAILURE_40', "", "", ""] session.XenAPI.Failure = FakeException session.call_xenapi.side_effect = FakeException self.assertRaises(FakeException, vm_utils._scan_sr, session, "sr_ref") session.call_xenapi.assert_called_with('SR.scan', "sr_ref") self.assertEqual(4, session.call_xenapi.call_count) mock_sleep.assert_has_calls([mock.call(2), mock.call(4), mock.call(8)]) @mock.patch.object(greenthread, 'sleep') def test_scan_sr_known_error_retries_then_succeeds(self, mock_sleep): session = mock.Mock() class FakeException(Exception): details = ['SR_BACKEND_FAILURE_40', "", "", ""] session.XenAPI.Failure = FakeException def fake_call_xenapi(*args): fake_call_xenapi.count += 1 if fake_call_xenapi.count != 2: raise FakeException() fake_call_xenapi.count = 0 session.call_xenapi.side_effect = fake_call_xenapi vm_utils._scan_sr(session, "sr_ref") session.call_xenapi.assert_called_with('SR.scan', "sr_ref") self.assertEqual(2, session.call_xenapi.call_count) mock_sleep.assert_called_once_with(2) @mock.patch.object(flavors, 'extract_flavor', return_value={ 'memory_mb': 1024, 'vcpus': 1, 'vcpu_weight': 1.0, }) class CreateVmTestCase(VMUtilsTestBase): def test_vss_provider(self, mock_extract): self.flags(vcpu_pin_set="2,3") session = _get_fake_session() instance = objects.Instance(uuid="uuid", os_type="windows", system_metadata={}) with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) vm_utils.create_vm(session, instance, "label", "kernel", "ramdisk") vm_rec = { 'VCPUs_params': {'cap': '0', 'mask': '2,3', 'weight': '1'}, 'PV_args': '', 'memory_static_min': '0', 'ha_restart_priority': '', 'HVM_boot_policy': 'BIOS order', 'PV_bootloader': '', 'tags': [], 'VCPUs_max': '4', 'memory_static_max': '1073741824', 'actions_after_shutdown': 'destroy', 'memory_dynamic_max': '1073741824', 'user_version': '0', 'xenstore_data': {'vm-data/allowvssprovider': 'false'}, 'blocked_operations': {}, 'is_a_template': False, 'name_description': '', 'memory_dynamic_min': '1073741824', 'actions_after_crash': 'destroy', 'memory_target': '1073741824', 'PV_ramdisk': '', 'PV_bootloader_args': '', 'PCI_bus': '', 'other_config': {'nova_uuid': 'uuid'}, 'name_label': 'label', 'actions_after_reboot': 'restart', 'VCPUs_at_startup': '4', 'HVM_boot_params': {'order': 'dc'}, 'platform': {'nx': 'true', 'pae': 'true', 'apic': 'true', 'timeoffset': '0', 'viridian': 'true', 'acpi': 'true'}, 'PV_legacy_args': '', 'PV_kernel': '', 'affinity': '', 'recommendations': '', 'ha_always_run': False } session.call_xenapi.assert_called_once_with("VM.create", vm_rec) def test_invalid_cpu_mask_raises(self, mock_extract): self.flags(vcpu_pin_set="asdf") session = mock.Mock() instance = objects.Instance(uuid=str(uuid.uuid4()), system_metadata={}) with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) self.assertRaises(exception.Invalid, vm_utils.create_vm, session, instance, "label", "kernel", "ramdisk") def test_destroy_vm(self, mock_extract): session = mock.Mock() instance = objects.Instance(uuid=str(uuid.uuid4())) vm_utils.destroy_vm(session, instance, "vm_ref") session.VM.destroy.assert_called_once_with("vm_ref") def test_destroy_vm_silently_fails(self, mock_extract): session = mock.Mock() exc = test.TestingException() session.XenAPI.Failure = test.TestingException session.VM.destroy.side_effect = exc instance = objects.Instance(uuid=str(uuid.uuid4())) vm_utils.destroy_vm(session, instance, "vm_ref") session.VM.destroy.assert_called_once_with("vm_ref") class DetermineVmModeTestCase(VMUtilsTestBase): def test_determine_vm_mode_returns_xen_mode(self): instance = {"vm_mode": "xen"} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_mode(self): instance = {"vm_mode": "hvm"} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_xen_for_linux(self): instance = {"vm_mode": None, "os_type": "linux"} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_for_windows(self): instance = {"vm_mode": None, "os_type": "windows"} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_by_default(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_xen_for_VHD(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK_VHD)) def test_determine_vm_mode_returns_xen_for_DISK(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK)) class CallXenAPIHelpersTestCase(VMUtilsTestBase): def test_vm_get_vbd_refs(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vm_get_vbd_refs(session, "vm_ref")) session.call_xenapi.assert_called_once_with("VM.get_VBDs", "vm_ref") def test_vbd_get_rec(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vbd_get_rec(session, "vbd_ref")) session.call_xenapi.assert_called_once_with("VBD.get_record", "vbd_ref") def test_vdi_get_rec(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vdi_get_rec(session, "vdi_ref")) session.call_xenapi.assert_called_once_with("VDI.get_record", "vdi_ref") def test_vdi_snapshot(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vdi_snapshot(session, "vdi_ref")) session.call_xenapi.assert_called_once_with("VDI.snapshot", "vdi_ref", {}) def test_vdi_get_virtual_size(self): session = mock.Mock() session.call_xenapi.return_value = "123" self.assertEqual(123, vm_utils._vdi_get_virtual_size(session, "ref")) session.call_xenapi.assert_called_once_with("VDI.get_virtual_size", "ref") @mock.patch.object(vm_utils, '_get_resize_func_name') def test_vdi_resize(self, mock_get_resize_func_name): session = mock.Mock() mock_get_resize_func_name.return_value = "VDI.fake" vm_utils._vdi_resize(session, "ref", 123) session.call_xenapi.assert_called_once_with("VDI.fake", "ref", "123") @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_works(self, mock_get_size, mock_resize): mock_get_size.return_value = (1024 ** 3) - 1 instance = {"uuid": "a"} vm_utils.update_vdi_virtual_size("s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") mock_resize.assert_called_once_with("s", "ref", 1024 ** 3) @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_skips_resize_down(self, mock_get_size, mock_resize): mock_get_size.return_value = 1024 ** 3 instance = {"uuid": "a"} vm_utils.update_vdi_virtual_size("s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") self.assertFalse(mock_resize.called) @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_raise_if_disk_big(self, mock_get_size, mock_resize): mock_get_size.return_value = 1024 ** 3 + 1 instance = {"uuid": "a"} self.assertRaises(exception.ResizeError, vm_utils.update_vdi_virtual_size, "s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") self.assertFalse(mock_resize.called) @mock.patch.object(vm_utils, '_vdi_get_rec') @mock.patch.object(vm_utils, '_vbd_get_rec') @mock.patch.object(vm_utils, '_vm_get_vbd_refs') class GetVdiForVMTestCase(VMUtilsTestBase): def test_get_vdi_for_vm_safely(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_rec): session = "session" vm_get_vbd_refs.return_value = ["a", "b"] vbd_get_rec.return_value = {'userdevice': '0', 'VDI': 'vdi_ref'} vdi_get_rec.return_value = {} result = vm_utils.get_vdi_for_vm_safely(session, "vm_ref") self.assertEqual(('vdi_ref', {}), result) vm_get_vbd_refs.assert_called_once_with(session, "vm_ref") vbd_get_rec.assert_called_once_with(session, "a") vdi_get_rec.assert_called_once_with(session, "vdi_ref") def test_get_vdi_for_vm_safely_fails(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_rec): session = "session" vm_get_vbd_refs.return_value = ["a", "b"] vbd_get_rec.return_value = {'userdevice': '0', 'VDI': 'vdi_ref'} self.assertRaises(exception.NovaException, vm_utils.get_vdi_for_vm_safely, session, "vm_ref", userdevice='1') self.assertEqual([], vdi_get_rec.call_args_list) self.assertEqual(2, len(vbd_get_rec.call_args_list)) @mock.patch.object(vm_utils, '_vdi_get_uuid') @mock.patch.object(vm_utils, '_vbd_get_rec') @mock.patch.object(vm_utils, '_vm_get_vbd_refs') class GetAllVdiForVMTestCase(VMUtilsTestBase): def _setup_get_all_vdi_uuids_for_vm(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): def fake_vbd_get_rec(session, vbd_ref): return {'userdevice': vbd_ref, 'VDI': "vdi_ref_%s" % vbd_ref} def fake_vdi_get_uuid(session, vdi_ref): return vdi_ref vm_get_vbd_refs.return_value = ["0", "2"] vbd_get_rec.side_effect = fake_vbd_get_rec vdi_get_uuid.side_effect = fake_vdi_get_uuid def test_get_all_vdi_uuids_for_vm_works(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): self._setup_get_all_vdi_uuids_for_vm(vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid) result = vm_utils.get_all_vdi_uuids_for_vm('session', "vm_ref") expected = ['vdi_ref_0', 'vdi_ref_2'] self.assertEqual(expected, list(result)) def test_get_all_vdi_uuids_for_vm_finds_none(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): self._setup_get_all_vdi_uuids_for_vm(vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid) result = vm_utils.get_all_vdi_uuids_for_vm('session', "vm_ref", min_userdevice=1) expected = ["vdi_ref_2"] self.assertEqual(expected, list(result)) class GetAllVdisTestCase(VMUtilsTestBase): def test_get_all_vdis_in_sr(self): def fake_get_rec(record_type, ref): if ref == "2": return "vdi_rec_2" session = mock.Mock() session.call_xenapi.return_value = ["1", "2"] session.get_rec.side_effect = fake_get_rec sr_ref = "sr_ref" actual = list(vm_utils._get_all_vdis_in_sr(session, sr_ref)) self.assertEqual(actual, [('2', 'vdi_rec_2')]) session.call_xenapi.assert_called_once_with("SR.get_VDIs", sr_ref) class VDIAttachedHere(VMUtilsTestBase): @mock.patch.object(vm_utils, 'destroy_vbd') @mock.patch.object(vm_utils, '_get_this_vm_ref') @mock.patch.object(vm_utils, 'create_vbd') @mock.patch.object(vm_utils, '_remap_vbd_dev') @mock.patch.object(vm_utils, '_wait_for_device') @mock.patch.object(utils, 'execute') def test_sync_called(self, mock_execute, mock_wait_for_device, mock_remap_vbd_dev, mock_create_vbd, mock_get_this_vm_ref, mock_destroy_vbd): session = _get_fake_session() with vm_utils.vdi_attached_here(session, 'vdi_ref'): pass mock_execute.assert_called_with('sync', run_as_root=True) class SnapshotAttachedHereTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, '_snapshot_attached_here_impl') def test_snapshot_attached_here(self, mock_impl): def fake_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback): self.assertEqual("session", session) self.assertEqual("instance", instance) self.assertEqual("vm_ref", vm_ref) self.assertEqual("label", label) self.assertEqual('0', userdevice) self.assertIsNone(post_snapshot_callback) yield "fake" mock_impl.side_effect = fake_impl with vm_utils.snapshot_attached_here("session", "instance", "vm_ref", "label") as result: self.assertEqual("fake", result) mock_impl.assert_called_once_with("session", "instance", "vm_ref", "label", '0', None) @mock.patch.object(vm_utils, '_delete_snapshots_in_vdi_chain') @mock.patch.object(vm_utils, 'safe_destroy_vdis') @mock.patch.object(vm_utils, '_walk_vdi_chain') @mock.patch.object(vm_utils, '_wait_for_vhd_coalesce') @mock.patch.object(vm_utils, '_vdi_get_uuid') @mock.patch.object(vm_utils, '_vdi_snapshot') @mock.patch.object(vm_utils, 'get_vdi_for_vm_safely') def test_snapshot_attached_here_impl(self, mock_get_vdi_for_vm_safely, mock_vdi_snapshot, mock_vdi_get_uuid, mock_wait_for_vhd_coalesce, mock_walk_vdi_chain, mock_safe_destroy_vdis, mock_delete_snapshots_in_vdi_chain): session = "session" instance = {"uuid": "uuid"} mock_callback = mock.Mock() mock_get_vdi_for_vm_safely.return_value = ("vdi_ref", {"SR": "sr_ref", "uuid": "vdi_uuid"}) mock_vdi_snapshot.return_value = "snap_ref" mock_vdi_get_uuid.return_value = "snap_uuid" mock_walk_vdi_chain.return_value = [{"uuid": "a"}, {"uuid": "b"}] try: with vm_utils.snapshot_attached_here(session, instance, "vm_ref", "label", '2', mock_callback) as result: self.assertEqual(["a", "b"], result) raise test.TestingException() self.assertTrue(False) except test.TestingException: pass mock_get_vdi_for_vm_safely.assert_called_once_with(session, "vm_ref", '2') mock_vdi_snapshot.assert_called_once_with(session, "vdi_ref") mock_wait_for_vhd_coalesce.assert_called_once_with(session, instance, "sr_ref", "vdi_ref", ['a', 'b']) mock_vdi_get_uuid.assert_called_once_with(session, "snap_ref") mock_walk_vdi_chain.assert_has_calls([mock.call(session, "vdi_uuid"), mock.call(session, "snap_uuid")]) mock_callback.assert_called_once_with( task_state="image_pending_upload") mock_safe_destroy_vdis.assert_called_once_with(session, ["snap_ref"]) mock_delete_snapshots_in_vdi_chain.assert_called_once_with(session, instance, ['a', 'b'], "sr_ref") @mock.patch.object(greenthread, 'sleep') def test_wait_for_vhd_coalesce_leaf_node(self, mock_sleep): instance = {"uuid": "fake"} vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid"]) self.assertFalse(mock_sleep.called) @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(greenthread, 'sleep') def test_wait_for_vhd_coalesce_parent_snapshot(self, mock_sleep, mock_count): mock_count.return_value = 2 instance = {"uuid": "fake"} vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertFalse(mock_sleep.called) self.assertTrue(mock_count.called) @mock.patch.object(greenthread, 'sleep') @mock.patch.object(vm_utils, '_get_vhd_parent_uuid') @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(vm_utils, '_scan_sr') def test_wait_for_vhd_coalesce_raises(self, mock_scan_sr, mock_count, mock_get_vhd_parent_uuid, mock_sleep): mock_count.return_value = 1 instance = {"uuid": "fake"} self.assertRaises(exception.NovaException, vm_utils._wait_for_vhd_coalesce, "session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertTrue(mock_count.called) self.assertEqual(20, mock_sleep.call_count) self.assertEqual(20, mock_scan_sr.call_count) @mock.patch.object(greenthread, 'sleep') @mock.patch.object(vm_utils, '_get_vhd_parent_uuid') @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(vm_utils, '_scan_sr') def test_wait_for_vhd_coalesce_success(self, mock_scan_sr, mock_count, mock_get_vhd_parent_uuid, mock_sleep): mock_count.return_value = 1 instance = {"uuid": "fake"} mock_get_vhd_parent_uuid.side_effect = ["bad", "uuid2"] vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertEqual(1, mock_sleep.call_count) self.assertEqual(2, mock_scan_sr.call_count) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_count_children(self, mock_get_all_vdis_in_sr): vdis = [('child1', {'sm_config': {'vhd-parent': 'parent1'}}), ('child2', {'sm_config': {'vhd-parent': 'parent2'}}), ('child3', {'sm_config': {'vhd-parent': 'parent1'}})] mock_get_all_vdis_in_sr.return_value = vdis self.assertEqual(2, vm_utils._count_children('session', 'parent1', 'sr')) class ImportMigratedDisksTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, '_import_migrate_ephemeral_disks') @mock.patch.object(vm_utils, '_import_migrated_root_disk') def test_import_all_migrated_disks(self, mock_root, mock_ephemeral): session = "session" instance = "instance" mock_root.return_value = "root_vdi" mock_ephemeral.return_value = ["a", "b"] result = vm_utils.import_all_migrated_disks(session, instance) expected = {'root': 'root_vdi', 'ephemerals': ["a", "b"]} self.assertEqual(expected, result) mock_root.assert_called_once_with(session, instance) mock_ephemeral.assert_called_once_with(session, instance) @mock.patch.object(vm_utils, '_import_migrated_vhds') def test_import_migrated_root_disk(self, mock_migrate): mock_migrate.return_value = "foo" instance = {"uuid": "uuid", "name": "name"} result = vm_utils._import_migrated_root_disk("s", instance) self.assertEqual("foo", result) mock_migrate.assert_called_once_with("s", instance, "uuid", "root", "name") @mock.patch.object(vm_utils, '_import_migrated_vhds') def test_import_migrate_ephemeral_disks(self, mock_migrate): mock_migrate.return_value = "foo" instance = {"uuid": "uuid", "name": "name", "ephemeral_gb": 4000} result = vm_utils._import_migrate_ephemeral_disks("s", instance) self.assertEqual({'4': 'foo', '5': 'foo'}, result) expected_calls = [mock.call("s", instance, "uuid_ephemeral_1", "ephemeral", "name ephemeral (1)"), mock.call("s", instance, "uuid_ephemeral_2", "ephemeral", "name ephemeral (2)")] self.assertEqual(expected_calls, mock_migrate.call_args_list) @mock.patch.object(vm_utils, '_set_vdi_info') @mock.patch.object(vm_utils, 'scan_default_sr') @mock.patch.object(vm_utils, 'get_sr_path') def test_import_migrated_vhds(self, mock_get_sr_path, mock_scan_sr, mock_set_info): session = mock.Mock() instance = {"uuid": "uuid"} session.call_plugin_serialized.return_value = {"root": {"uuid": "a"}} session.call_xenapi.return_value = "vdi_ref" mock_get_sr_path.return_value = "sr_path" result = vm_utils._import_migrated_vhds(session, instance, 'chain_label', 'disk_type', 'vdi_label') expected = {'uuid': "a", 'ref': "vdi_ref"} self.assertEqual(expected, result) mock_get_sr_path.assert_called_once_with(session) session.call_plugin_serialized.assert_called_once_with('migration', 'move_vhds_into_sr', instance_uuid='chain_label', sr_path='sr_path', uuid_stack=mock.ANY) mock_scan_sr.assert_called_once_with(session) session.call_xenapi.assert_called_once_with('VDI.get_by_uuid', 'a') mock_set_info.assert_called_once_with(session, 'vdi_ref', 'disk_type', 'vdi_label', 'disk_type', instance) def test_get_vhd_parent_uuid_rec_provided(self): session = mock.Mock() vdi_ref = 'vdi_ref' vdi_rec = {'sm_config': {}} self.assertIsNone(vm_utils._get_vhd_parent_uuid(session, vdi_ref, vdi_rec)) self.assertFalse(session.call_xenapi.called) class MigrateVHDTestCase(VMUtilsTestBase): def _assert_transfer_called(self, session, label): session.call_plugin_serialized.assert_called_once_with( 'migration', 'transfer_vhd', instance_uuid=label, host="dest", vdi_uuid="vdi_uuid", sr_path="sr_path", seq_num=2) def test_migrate_vhd_root(self): session = mock.Mock() instance = {"uuid": "a"} vm_utils.migrate_vhd(session, instance, "vdi_uuid", "dest", "sr_path", 2) self._assert_transfer_called(session, "a") def test_migrate_vhd_ephemeral(self): session = mock.Mock() instance = {"uuid": "a"} vm_utils.migrate_vhd(session, instance, "vdi_uuid", "dest", "sr_path", 2, 2) self._assert_transfer_called(session, "a_ephemeral_2") def test_migrate_vhd_converts_exceptions(self): session = mock.Mock() session.XenAPI.Failure = test.TestingException session.call_plugin_serialized.side_effect = test.TestingException() instance = {"uuid": "a"} self.assertRaises(exception.MigrationError, vm_utils.migrate_vhd, session, instance, "vdi_uuid", "dest", "sr_path", 2) self._assert_transfer_called(session, "a") class StripBaseMirrorTestCase(VMUtilsTestBase): def test_strip_base_mirror_from_vdi_works(self): session = mock.Mock() vm_utils._try_strip_base_mirror_from_vdi(session, "vdi_ref") session.call_xenapi.assert_called_once_with( "VDI.remove_from_sm_config", "vdi_ref", "base_mirror") def test_strip_base_mirror_from_vdi_hides_error(self): session = mock.Mock() session.XenAPI.Failure = test.TestingException session.call_xenapi.side_effect = test.TestingException() vm_utils._try_strip_base_mirror_from_vdi(session, "vdi_ref") session.call_xenapi.assert_called_once_with( "VDI.remove_from_sm_config", "vdi_ref", "base_mirror") @mock.patch.object(vm_utils, '_try_strip_base_mirror_from_vdi') def test_strip_base_mirror_from_vdis(self, mock_strip): def call_xenapi(method, arg): if method == "VM.get_VBDs": return ['VBD_ref_1', 'VBD_ref_2'] if method == "VBD.get_VDI": return 'VDI' + arg[3:] return "Unexpected call_xenapi: %s.%s" % (method, arg) session = mock.Mock() session.call_xenapi.side_effect = call_xenapi vm_utils.strip_base_mirror_from_vdis(session, "vm_ref") expected = [mock.call('VM.get_VBDs', "vm_ref"), mock.call('VBD.get_VDI', "VBD_ref_1"), mock.call('VBD.get_VDI', "VBD_ref_2")] self.assertEqual(expected, session.call_xenapi.call_args_list) expected = [mock.call(session, "VDI_ref_1"), mock.call(session, "VDI_ref_2")] self.assertEqual(expected, mock_strip.call_args_list) class DeviceIdTestCase(VMUtilsTestBase): def test_device_id_is_none_if_not_specified_in_meta_data(self): image_meta = {} session = mock.Mock() session.product_version = (6, 1, 0) self.assertIsNone(vm_utils.get_vm_device_id(session, image_meta)) def test_get_device_id_if_hypervisor_version_is_greater_than_6_1(self): image_meta = {'xenapi_device_id': '0002'} session = mock.Mock() session.product_version = (6, 2, 0) self.assertEqual('0002', vm_utils.get_vm_device_id(session, image_meta)) session.product_version = (6, 3, 1) self.assertEqual('0002', vm_utils.get_vm_device_id(session, image_meta)) def test_raise_exception_if_device_id_not_supported_by_hyp_version(self): image_meta = {'xenapi_device_id': '0002'} session = mock.Mock() session.product_version = (6, 0) exc = self.assertRaises(exception.NovaException, vm_utils.get_vm_device_id, session, image_meta) self.assertEqual("Device id 0002 specified is not supported by " "hypervisor version (6, 0)", exc.message) session.product_version = ('6a') exc = self.assertRaises(exception.NovaException, vm_utils.get_vm_device_id, session, image_meta) self.assertEqual("Device id 0002 specified is not supported by " "hypervisor version 6a", exc.message) class CreateVmRecordTestCase(VMUtilsTestBase): @mock.patch.object(flavors, 'extract_flavor') def test_create_vm_record_linux(self, mock_extract_flavor): instance = objects.Instance(uuid="uuid123", os_type="linux") self._test_create_vm_record(mock_extract_flavor, instance, False) @mock.patch.object(flavors, 'extract_flavor') def test_create_vm_record_windows(self, mock_extract_flavor): instance = objects.Instance(uuid="uuid123", os_type="windows") with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) self._test_create_vm_record(mock_extract_flavor, instance, True) def _test_create_vm_record(self, mock_extract_flavor, instance, is_viridian): session = _get_fake_session() flavor = {"memory_mb": 1024, "vcpus": 1, "vcpu_weight": 2} mock_extract_flavor.return_value = flavor with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor(memory_mb=1024, vcpus=1, vcpu_weight=2) vm_utils.create_vm(session, instance, "name", "kernel", "ramdisk", device_id="0002") is_viridian_str = str(is_viridian).lower() expected_vm_rec = { 'VCPUs_params': {'cap': '0', 'weight': '2'}, 'PV_args': '', 'memory_static_min': '0', 'ha_restart_priority': '', 'HVM_boot_policy': 'BIOS order', 'PV_bootloader': '', 'tags': [], 'VCPUs_max': '1', 'memory_static_max': '1073741824', 'actions_after_shutdown': 'destroy', 'memory_dynamic_max': '1073741824', 'user_version': '0', 'xenstore_data': {'vm-data/allowvssprovider': 'false'}, 'blocked_operations': {}, 'is_a_template': False, 'name_description': '', 'memory_dynamic_min': '1073741824', 'actions_after_crash': 'destroy', 'memory_target': '1073741824', 'PV_ramdisk': '', 'PV_bootloader_args': '', 'PCI_bus': '', 'other_config': {'nova_uuid': 'uuid123'}, 'name_label': 'name', 'actions_after_reboot': 'restart', 'VCPUs_at_startup': '1', 'HVM_boot_params': {'order': 'dc'}, 'platform': {'nx': 'true', 'pae': 'true', 'apic': 'true', 'timeoffset': '0', 'viridian': is_viridian_str, 'acpi': 'true', 'device_id': '0002'}, 'PV_legacy_args': '', 'PV_kernel': '', 'affinity': '', 'recommendations': '', 'ha_always_run': False} session.call_xenapi.assert_called_with('VM.create', expected_vm_rec) def test_list_vms(self): self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') fake.create_vm("foo1", "Halted") vm_ref = fake.create_vm("foo2", "Running") stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.list_vms(driver._session)) # Will have 3 VMs - but one is Dom0 and one is not running on the host self.assertEqual(len(driver._session.call_xenapi('VM.get_all')), 3) self.assertEqual(len(result), 1) result_keys = [key for (key, value) in result] self.assertIn(vm_ref, result_keys) class ChildVHDsTestCase(test.NoDBTestCase): all_vdis = [ ("my-vdi-ref", {"uuid": "my-uuid", "sm_config": {}, "is_a_snapshot": False, "other_config": {}}), ("non-parent", {"uuid": "uuid-1", "sm_config": {}, "is_a_snapshot": False, "other_config": {}}), ("diff-parent", {"uuid": "uuid-1", "sm_config": {"vhd-parent": "other-uuid"}, "is_a_snapshot": False, "other_config": {}}), ("child", {"uuid": "uuid-child", "sm_config": {"vhd-parent": "my-uuid"}, "is_a_snapshot": False, "other_config": {}}), ("child-snap", {"uuid": "uuid-child-snap", "sm_config": {"vhd-parent": "my-uuid"}, "is_a_snapshot": True, "other_config": {}}), ] @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_defaults(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid"]) self.assertEqual(['uuid-child', 'uuid-child-snap'], result) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_only_snapshots(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid"], old_snapshots_only=True) self.assertEqual(['uuid-child-snap'], result) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_chain(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid", "other-uuid"], old_snapshots_only=True) self.assertEqual(['uuid-child-snap'], result) def test_is_vdi_a_snapshot_works(self): vdi_rec = {"is_a_snapshot": True, "other_config": {}} self.assertTrue(vm_utils._is_vdi_a_snapshot(vdi_rec)) def test_is_vdi_a_snapshot_base_images_false(self): vdi_rec = {"is_a_snapshot": True, "other_config": {"image-id": "fake"}} self.assertFalse(vm_utils._is_vdi_a_snapshot(vdi_rec)) def test_is_vdi_a_snapshot_false_for_non_snapshot(self): vdi_rec = {"is_a_snapshot": False, "other_config": {}} self.assertFalse(vm_utils._is_vdi_a_snapshot(vdi_rec)) class RemoveOldSnapshotsTestCase(test.NoDBTestCase): @mock.patch.object(vm_utils, 'get_vdi_for_vm_safely') @mock.patch.object(vm_utils, '_walk_vdi_chain') @mock.patch.object(vm_utils, '_delete_snapshots_in_vdi_chain') def test_remove_old_snapshots(self, mock_delete, mock_walk, mock_get): instance = {"uuid": "fake"} mock_get.return_value = ("ref", {"uuid": "vdi", "SR": "sr_ref"}) mock_walk.return_value = [{"uuid": "uuid1"}, {"uuid": "uuid2"}] vm_utils.remove_old_snapshots("session", instance, "vm_ref") mock_delete.assert_called_once_with("session", instance, ["uuid1", "uuid2"], "sr_ref") mock_get.assert_called_once_with("session", "vm_ref") mock_walk.assert_called_once_with("session", "vdi") @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_no_chain(self, mock_child): instance = {"uuid": "fake"} vm_utils._delete_snapshots_in_vdi_chain("session", instance, ["uuid"], "sr") self.assertFalse(mock_child.called) @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_no_snapshots(self, mock_child): instance = {"uuid": "fake"} mock_child.return_value = [] vm_utils._delete_snapshots_in_vdi_chain("session", instance, ["uuid1", "uuid2"], "sr") mock_child.assert_called_once_with("session", "sr", ["uuid2"], old_snapshots_only=True) @mock.patch.object(vm_utils, '_scan_sr') @mock.patch.object(vm_utils, 'safe_destroy_vdis') @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_calls_destroy(self, mock_child, mock_destroy, mock_scan): instance = {"uuid": "fake"} mock_child.return_value = ["suuid1", "suuid2"] session = mock.Mock() session.VDI.get_by_uuid.side_effect = ["ref1", "ref2"] vm_utils._delete_snapshots_in_vdi_chain(session, instance, ["uuid1", "uuid2"], "sr") mock_child.assert_called_once_with(session, "sr", ["uuid2"], old_snapshots_only=True) session.VDI.get_by_uuid.assert_has_calls([ mock.call("suuid1"), mock.call("suuid2")]) mock_destroy.assert_called_once_with(session, ["ref1", "ref2"]) mock_scan.assert_called_once_with(session, "sr") class ResizeFunctionTestCase(test.NoDBTestCase): def _call_get_resize_func_name(self, brand, version): session = mock.Mock() session.product_brand = brand session.product_version = version return vm_utils._get_resize_func_name(session) def _test_is_resize(self, brand, version): result = self._call_get_resize_func_name(brand, version) self.assertEqual("VDI.resize", result) def _test_is_resize_online(self, brand, version): result = self._call_get_resize_func_name(brand, version) self.assertEqual("VDI.resize_online", result) def test_xenserver_5_5(self): self._test_is_resize_online("XenServer", (5, 5, 0)) def test_xenserver_6_0(self): self._test_is_resize("XenServer", (6, 0, 0)) def test_xcp_1_1(self): self._test_is_resize_online("XCP", (1, 1, 0)) def test_xcp_1_2(self): self._test_is_resize("XCP", (1, 2, 0)) def test_xcp_2_0(self): self._test_is_resize("XCP", (2, 0, 0)) def test_random_brand(self): self._test_is_resize("asfd", (1, 1, 0)) def test_default(self): self._test_is_resize(None, None) def test_empty(self): self._test_is_resize("", "") def test_bad_version(self): self._test_is_resize("XenServer", "asdf") class VMInfoTests(VMUtilsTestBase): def setUp(self): super(VMInfoTests, self).setUp() self.session = mock.Mock() def test_get_power_state_valid(self): # Save on test setup calls by having these simple tests in one method self.session.call_xenapi.return_value = "Running" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.RUNNING) self.session.call_xenapi.return_value = "Halted" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.SHUTDOWN) self.session.call_xenapi.return_value = "Paused" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.PAUSED) self.session.call_xenapi.return_value = "Suspended" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.SUSPENDED) self.session.call_xenapi.return_value = "Crashed" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.CRASHED) def test_get_power_state_invalid(self): self.session.call_xenapi.return_value = "Invalid" self.assertRaises(KeyError, vm_utils.get_power_state, self.session, "ref") _XAPI_record = {'power_state': 'Running', 'memory_static_max': str(10 << 10), 'memory_dynamic_max': str(9 << 10), 'VCPUs_max': '5'} def test_compile_info(self): def call_xenapi(method, *args): if method.startswith('VM.get_') and args[0] == 'dummy': return self._XAPI_record[method[7:]] self.session.call_xenapi.side_effect = call_xenapi info = vm_utils.compile_info(self.session, "dummy") self.assertEqual(hardware.InstanceInfo(state=power_state.RUNNING, max_mem_kb=10L, mem_kb=9L, num_cpu='5', cpu_time_ns=0), info)
40.331
79
0.620953
import contextlib import uuid from eventlet import greenthread import fixtures import mock from mox3 import mox from oslo.config import cfg from oslo.config import fixture as config_fixture from oslo.utils import timeutils from oslo.utils import units from oslo_concurrency import lockutils from oslo_concurrency import processutils import six from nova.compute import flavors from nova.compute import power_state from nova.compute import vm_mode from nova import context from nova import exception from nova.i18n import _ from nova import objects from nova import test from nova.tests.unit.objects import test_flavor from nova.tests.unit.virt.xenapi import stubs from nova.tests.unit.virt.xenapi import test_xenapi from nova import utils from nova.virt import hardware from nova.virt.xenapi.client import session as xenapi_session from nova.virt.xenapi import driver as xenapi_conn from nova.virt.xenapi import fake from nova.virt.xenapi import vm_utils CONF = cfg.CONF XENSM_TYPE = 'xensm' ISCSI_TYPE = 'iscsi' def get_fake_connection_data(sr_type): fakes = {XENSM_TYPE: {'sr_uuid': 'falseSR', 'name_label': 'fake_storage', 'name_description': 'test purposes', 'server': 'myserver', 'serverpath': '/local/scratch/myname', 'sr_type': 'nfs', 'introduce_sr_keys': ['server', 'serverpath', 'sr_type'], 'vdi_uuid': 'falseVDI'}, ISCSI_TYPE: {'volume_id': 'fake_volume_id', 'target_lun': 1, 'target_iqn': 'fake_iqn:volume-fake_volume_id', 'target_portal': u'localhost:3260', 'target_discovered': False}, } return fakes[sr_type] def _get_fake_session(error=None): session = mock.Mock() xenapi_session.apply_session_helpers(session) if error is not None: class FakeException(Exception): details = [error, "a", "b", "c"] session.XenAPI.Failure = FakeException session.call_xenapi.side_effect = FakeException return session @contextlib.contextmanager def contextified(result): yield result def _fake_noop(*args, **kwargs): return class VMUtilsTestBase(stubs.XenAPITestBaseNoDB): pass class LookupTestCase(VMUtilsTestBase): def setUp(self): super(LookupTestCase, self).setUp() self.session = self.mox.CreateMockAnything('Fake Session') self.name_label = 'my_vm' def _do_mock(self, result): self.session.call_xenapi( "VM.get_by_name_label", self.name_label).AndReturn(result) self.mox.ReplayAll() def test_normal(self): self._do_mock(['x']) result = vm_utils.lookup(self.session, self.name_label) self.assertEqual('x', result) def test_no_result(self): self._do_mock([]) result = vm_utils.lookup(self.session, self.name_label) self.assertIsNone(result) def test_too_many(self): self._do_mock(['a', 'b']) self.assertRaises(exception.InstanceExists, vm_utils.lookup, self.session, self.name_label) def test_rescue_none(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn([]) self._do_mock(['x']) result = vm_utils.lookup(self.session, self.name_label, check_rescue=True) self.assertEqual('x', result) def test_rescue_found(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn(['y']) self.mox.ReplayAll() result = vm_utils.lookup(self.session, self.name_label, check_rescue=True) self.assertEqual('y', result) def test_rescue_too_many(self): self.session.call_xenapi( "VM.get_by_name_label", self.name_label + '-rescue').AndReturn(['a', 'b', 'c']) self.mox.ReplayAll() self.assertRaises(exception.InstanceExists, vm_utils.lookup, self.session, self.name_label, check_rescue=True) class GenerateConfigDriveTestCase(VMUtilsTestBase): def test_no_admin_pass(self): instance = {} self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr('session').AndReturn('sr_ref') self.mox.StubOutWithMock(vm_utils, 'create_vdi') vm_utils.create_vdi('session', 'sr_ref', instance, 'config-2', 'configdrive', 64 * units.Mi).AndReturn('vdi_ref') self.mox.StubOutWithMock(vm_utils, 'vdi_attached_here') vm_utils.vdi_attached_here( 'session', 'vdi_ref', read_only=False).AndReturn( contextified('mounted_dev')) class FakeInstanceMetadata(object): def __init__(_self, instance, content=None, extra_md=None, network_info=None): self.assertEqual(network_info, "nw_info") def metadata_for_config_drive(_self): return [] self.useFixture(fixtures.MonkeyPatch( 'nova.api.metadata.base.InstanceMetadata', FakeInstanceMetadata)) self.mox.StubOutWithMock(utils, 'execute') utils.execute('genisoimage', '-o', mox.IgnoreArg(), '-ldots', '-allow-lowercase', '-allow-multidot', '-l', '-publisher', mox.IgnoreArg(), '-quiet', '-J', '-r', '-V', 'config-2', mox.IgnoreArg(), attempts=1, run_as_root=False).AndReturn(None) utils.execute('dd', mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), run_as_root=True).AndReturn(None) self.mox.StubOutWithMock(vm_utils, 'create_vbd') vm_utils.create_vbd('session', 'vm_ref', 'vdi_ref', mox.IgnoreArg(), bootable=False, read_only=True).AndReturn(None) self.mox.ReplayAll() vm_utils.generate_configdrive('session', instance, 'vm_ref', 'userdevice', "nw_info") @mock.patch.object(vm_utils, "destroy_vdi") @mock.patch.object(vm_utils, "vdi_attached_here") @mock.patch.object(vm_utils, "create_vdi") @mock.patch.object(vm_utils, "safe_find_sr") def test_vdi_cleaned_up(self, mock_find, mock_create_vdi, mock_attached, mock_destroy): mock_create_vdi.return_value = 'vdi_ref' mock_attached.side_effect = test.TestingException mock_destroy.side_effect = exception.StorageError(reason="") instance = {"uuid": "asdf"} self.assertRaises(test.TestingException, vm_utils.generate_configdrive, 'session', instance, 'vm_ref', 'userdevice', 'nw_info') mock_destroy.assert_called_once_with('session', 'vdi_ref') class XenAPIGetUUID(VMUtilsTestBase): def test_get_this_vm_uuid_new_kernel(self): self.mox.StubOutWithMock(vm_utils, '_get_sys_hypervisor_uuid') vm_utils._get_sys_hypervisor_uuid().AndReturn( '2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f') self.mox.ReplayAll() self.assertEqual('2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', vm_utils.get_this_vm_uuid(None)) self.mox.VerifyAll() def test_get_this_vm_uuid_old_kernel_reboot(self): self.mox.StubOutWithMock(vm_utils, '_get_sys_hypervisor_uuid') self.mox.StubOutWithMock(utils, 'execute') vm_utils._get_sys_hypervisor_uuid().AndRaise( IOError(13, 'Permission denied')) utils.execute('xenstore-read', 'domid', run_as_root=True).AndReturn( ('27', '')) utils.execute('xenstore-read', '/local/domain/27/vm', run_as_root=True).AndReturn( ('/vm/2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', '')) self.mox.ReplayAll() self.assertEqual('2f46f0f5-f14c-ef1b-1fac-9eeca0888a3f', vm_utils.get_this_vm_uuid(None)) self.mox.VerifyAll() class FakeSession(object): def call_xenapi(self, *args): pass def call_plugin(self, *args): pass def call_plugin_serialized(self, plugin, fn, *args, **kwargs): pass def call_plugin_serialized_with_retry(self, plugin, fn, num_retries, callback, *args, **kwargs): pass class FetchVhdImageTestCase(VMUtilsTestBase): def setUp(self): super(FetchVhdImageTestCase, self).setUp() self.context = context.get_admin_context() self.context.auth_token = 'auth_token' self.session = FakeSession() self.instance = {"uuid": "uuid"} self.mox.StubOutWithMock(vm_utils, '_make_uuid_stack') vm_utils._make_uuid_stack().AndReturn(["uuid_stack"]) self.mox.StubOutWithMock(vm_utils, 'get_sr_path') vm_utils.get_sr_path(self.session).AndReturn('sr_path') def _stub_glance_download_vhd(self, raise_exc=None): self.mox.StubOutWithMock( self.session, 'call_plugin_serialized_with_retry') func = self.session.call_plugin_serialized_with_retry( 'glance', 'download_vhd', 0, mox.IgnoreArg(), mox.IgnoreArg(), extra_headers={'X-Service-Catalog': '[]', 'X-Auth-Token': 'auth_token', 'X-Roles': '', 'X-Tenant-Id': None, 'X-User-Id': None, 'X-Identity-Status': 'Confirmed'}, image_id='image_id', uuid_stack=["uuid_stack"], sr_path='sr_path') if raise_exc: func.AndRaise(raise_exc) else: func.AndReturn({'root': {'uuid': 'vdi'}}) def _stub_bittorrent_download_vhd(self, raise_exc=None): self.mox.StubOutWithMock( self.session, 'call_plugin_serialized') func = self.session.call_plugin_serialized( 'bittorrent', 'download_vhd', image_id='image_id', uuid_stack=["uuid_stack"], sr_path='sr_path', torrent_download_stall_cutoff=600, torrent_listen_port_start=6881, torrent_listen_port_end=6891, torrent_max_last_accessed=86400, torrent_max_seeder_processes_per_host=1, torrent_seed_chance=1.0, torrent_seed_duration=3600, torrent_url='http://foo/image_id.torrent' ) if raise_exc: func.AndRaise(raise_exc) else: func.AndReturn({'root': {'uuid': 'vdi'}}) def test_fetch_vhd_image_works_with_glance(self): self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size( self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_fetch_vhd_image_works_with_bittorrent(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(True) self._stub_bittorrent_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_fetch_vhd_image_cleans_up_vdi_on_fail(self): self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi").AndRaise(exception.FlavorDiskTooSmall) self.mox.StubOutWithMock(self.session, 'call_xenapi') self.session.call_xenapi("VDI.get_by_uuid", "vdi").AndReturn("ref") self.mox.StubOutWithMock(vm_utils, 'destroy_vdi') vm_utils.destroy_vdi(self.session, "ref").AndRaise(exception.StorageError(reason="")) self.mox.ReplayAll() self.assertRaises(exception.FlavorDiskTooSmall, vm_utils._fetch_vhd_image, self.context, self.session, self.instance, 'image_id') self.mox.VerifyAll() def test_fallback_to_default_handler(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(True) self._stub_bittorrent_download_vhd(raise_exc=RuntimeError) vm_utils._make_uuid_stack().AndReturn(["uuid_stack"]) vm_utils.get_sr_path(self.session).AndReturn('sr_path') self._stub_glance_download_vhd() self.mox.StubOutWithMock(vm_utils, 'safe_find_sr') vm_utils.safe_find_sr(self.session).AndReturn("sr") self.mox.StubOutWithMock(vm_utils, '_scan_sr') vm_utils._scan_sr(self.session, "sr") self.mox.StubOutWithMock(vm_utils, '_check_vdi_size') vm_utils._check_vdi_size(self.context, self.session, self.instance, "vdi") self.mox.ReplayAll() self.assertEqual("vdi", vm_utils._fetch_vhd_image(self.context, self.session, self.instance, 'image_id')['root']['uuid']) self.mox.VerifyAll() def test_default_handler_does_not_fallback_to_itself(self): cfg.CONF.import_opt('torrent_base_url', 'nova.virt.xenapi.image.bittorrent', group='xenserver') self.flags(torrent_base_url='http://foo', group='xenserver') self.mox.StubOutWithMock(vm_utils, '_image_uses_bittorrent') vm_utils._image_uses_bittorrent( self.context, self.instance).AndReturn(False) self._stub_glance_download_vhd(raise_exc=RuntimeError) self.mox.ReplayAll() self.assertRaises(RuntimeError, vm_utils._fetch_vhd_image, self.context, self.session, self.instance, 'image_id') self.mox.VerifyAll() class TestImageCompression(VMUtilsTestBase): def test_image_compression(self): # Testing for nova.conf, too low, negative, and a correct value. self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=0, group='xenserver') self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=-6, group='xenserver') self.assertIsNone(vm_utils.get_compression_level()) self.flags(image_compression_level=6, group='xenserver') self.assertEqual(vm_utils.get_compression_level(), 6) class ResizeHelpersTestCase(VMUtilsTestBase): def test_repair_filesystem(self): self.mox.StubOutWithMock(utils, 'execute') utils.execute('e2fsck', '-f', "-y", "fakepath", run_as_root=True, check_exit_code=[0, 1, 2]).AndReturn( ("size is: 42", "")) self.mox.ReplayAll() vm_utils._repair_filesystem("fakepath") def _call_tune2fs_remove_journal(self, path): utils.execute("tune2fs", "-O ^has_journal", path, run_as_root=True) def _call_tune2fs_add_journal(self, path): utils.execute("tune2fs", "-j", path, run_as_root=True) def _call_parted_mkpart(self, path, start, end): utils.execute('parted', '--script', path, 'rm', '1', run_as_root=True) utils.execute('parted', '--script', path, 'mkpart', 'primary', '%ds' % start, '%ds' % end, run_as_root=True) def _call_parted_boot_flag(sef, path): utils.execute('parted', '--script', path, 'set', '1', 'boot', 'on', run_as_root=True) def test_resize_part_and_fs_down_succeeds(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) utils.execute("resize2fs", partition_path, "10s", run_as_root=True) self._call_parted_mkpart(dev_path, 0, 9) self._call_parted_boot_flag(dev_path) self._call_tune2fs_add_journal(partition_path) self.mox.ReplayAll() vm_utils._resize_part_and_fs("fake", 0, 20, 10, "boot") def test_log_progress_if_required(self): self.mox.StubOutWithMock(vm_utils.LOG, "debug") vm_utils.LOG.debug(_("Sparse copy in progress, " "%(complete_pct).2f%% complete. " "%(left)s bytes left to copy"), {"complete_pct": 50.0, "left": 1}) current = timeutils.utcnow() timeutils.set_time_override(current) timeutils.advance_time_seconds(vm_utils.PROGRESS_INTERVAL_SECONDS + 1) self.mox.ReplayAll() vm_utils._log_progress_if_required(1, current, 2) def test_log_progress_if_not_required(self): self.mox.StubOutWithMock(vm_utils.LOG, "debug") current = timeutils.utcnow() timeutils.set_time_override(current) timeutils.advance_time_seconds(vm_utils.PROGRESS_INTERVAL_SECONDS - 1) self.mox.ReplayAll() vm_utils._log_progress_if_required(1, current, 2) def test_resize_part_and_fs_down_fails_disk_too_big(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path new_sectors = 10 vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) mobj = utils.execute("resize2fs", partition_path, "%ss" % new_sectors, run_as_root=True) mobj.AndRaise(processutils.ProcessExecutionError) self.mox.ReplayAll() self.assertRaises(exception.ResizeError, vm_utils._resize_part_and_fs, "fake", 0, 20, 10, "boot") def test_resize_part_and_fs_up_succeeds(self): self.mox.StubOutWithMock(vm_utils, "_repair_filesystem") self.mox.StubOutWithMock(utils, 'execute') dev_path = "/dev/fake" partition_path = "%s1" % dev_path vm_utils._repair_filesystem(partition_path) self._call_tune2fs_remove_journal(partition_path) self._call_parted_mkpart(dev_path, 0, 29) utils.execute("resize2fs", partition_path, run_as_root=True) self._call_tune2fs_add_journal(partition_path) self.mox.ReplayAll() vm_utils._resize_part_and_fs("fake", 0, 20, 30, "") def test_resize_disk_throws_on_zero_size(self): self.assertRaises(exception.ResizeError, vm_utils.resize_disk, "session", "instance", "vdi_ref", {"root_gb": 0}) def test_auto_config_disk_returns_early_on_zero_size(self): vm_utils.try_auto_configure_disk("bad_session", "bad_vdi_ref", 0) @mock.patch.object(utils, "execute") def test_get_partitions(self, mock_execute): parted_return = "BYT;\n...\n" parted_return += "1:2s:11s:10s:ext3::boot;\n" parted_return += "2:20s:11s:10s::bob:;\n" mock_execute.return_value = (parted_return, None) partitions = vm_utils._get_partitions("abc") self.assertEqual(2, len(partitions)) self.assertEqual((1, 2, 10, "ext3", "", "boot"), partitions[0]) self.assertEqual((2, 20, 10, "", "bob", ""), partitions[1]) class CheckVDISizeTestCase(VMUtilsTestBase): def setUp(self): super(CheckVDISizeTestCase, self).setUp() self.context = 'fakecontext' self.session = 'fakesession' self.instance = objects.Instance(uuid=str(uuid.uuid4())) self.flavor = objects.Flavor() self.vdi_uuid = 'fakeuuid' def test_not_too_large(self): self.mox.StubOutWithMock(vm_utils, '_get_vdi_chain_size') vm_utils._get_vdi_chain_size(self.session, self.vdi_uuid).AndReturn(1073741824) self.mox.ReplayAll() with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 1 get.return_value = self.flavor vm_utils._check_vdi_size(self.context, self.session, self.instance, self.vdi_uuid) def test_too_large(self): self.mox.StubOutWithMock(vm_utils, '_get_vdi_chain_size') vm_utils._get_vdi_chain_size(self.session, self.vdi_uuid).AndReturn(11811160065) # 10GB overhead allowed self.mox.ReplayAll() with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 1 get.return_value = self.flavor self.assertRaises(exception.FlavorDiskTooSmall, vm_utils._check_vdi_size, self.context, self.session, self.instance, self.vdi_uuid) def test_zero_root_gb_disables_check(self): with mock.patch.object(self.instance, 'get_flavor') as get: self.flavor.root_gb = 0 get.return_value = self.flavor vm_utils._check_vdi_size(self.context, self.session, self.instance, self.vdi_uuid) class GetInstanceForVdisForSrTestCase(VMUtilsTestBase): def setUp(self): super(GetInstanceForVdisForSrTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') def test_get_instance_vdis_for_sr(self): vm_ref = fake.create_vm("foo", "Running") sr_ref = fake.create_sr() vdi_1 = fake.create_vdi('vdiname1', sr_ref) vdi_2 = fake.create_vdi('vdiname2', sr_ref) for vdi_ref in [vdi_1, vdi_2]: fake.create_vbd(vm_ref, vdi_ref) stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.get_instance_vdis_for_sr( driver._session, vm_ref, sr_ref)) self.assertEqual([vdi_1, vdi_2], result) def test_get_instance_vdis_for_sr_no_vbd(self): vm_ref = fake.create_vm("foo", "Running") sr_ref = fake.create_sr() stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.get_instance_vdis_for_sr( driver._session, vm_ref, sr_ref)) self.assertEqual([], result) class VMRefOrRaiseVMFoundTestCase(VMUtilsTestBase): def test_lookup_call(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn('ignored') mock.ReplayAll() vm_utils.vm_ref_or_raise('session', 'somename') mock.VerifyAll() def test_return_value(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn('vmref') mock.ReplayAll() self.assertEqual( 'vmref', vm_utils.vm_ref_or_raise('session', 'somename')) mock.VerifyAll() class VMRefOrRaiseVMNotFoundTestCase(VMUtilsTestBase): def test_exception_raised(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn(None) mock.ReplayAll() self.assertRaises( exception.InstanceNotFound, lambda: vm_utils.vm_ref_or_raise('session', 'somename') ) mock.VerifyAll() def test_exception_msg_contains_vm_name(self): mock = mox.Mox() mock.StubOutWithMock(vm_utils, 'lookup') vm_utils.lookup('session', 'somename').AndReturn(None) mock.ReplayAll() try: vm_utils.vm_ref_or_raise('session', 'somename') except exception.InstanceNotFound as e: self.assertIn('somename', six.text_type(e)) mock.VerifyAll() @mock.patch.object(vm_utils, 'safe_find_sr', return_value='safe_find_sr') class CreateCachedImageTestCase(VMUtilsTestBase): def setUp(self): super(CreateCachedImageTestCase, self).setUp() self.session = _get_fake_session() @mock.patch.object(vm_utils, '_clone_vdi', return_value='new_vdi_ref') def test_cached(self, mock_clone_vdi, mock_safe_find_sr): self.session.call_xenapi.side_effect = ['ext', {'vdi_ref': 2}, None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) @mock.patch.object(vm_utils, '_safe_copy_vdi', return_value='new_vdi_ref') def test_no_cow(self, mock_safe_copy_vdi, mock_safe_find_sr): self.flags(use_cow_images=False) self.session.call_xenapi.side_effect = ['ext', {'vdi_ref': 2}, None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) def test_no_cow_no_ext(self, mock_safe_find_sr): self.flags(use_cow_images=False) self.session.call_xenapi.side_effect = ['non-ext', {'vdi_ref': 2}, 'vdi_ref', None, None, None, 'vdi_uuid'] self.assertEqual((False, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) @mock.patch.object(vm_utils, '_clone_vdi', return_value='new_vdi_ref') @mock.patch.object(vm_utils, '_fetch_image', return_value={'root': {'uuid': 'vdi_uuid', 'file': None}}) def test_noncached(self, mock_fetch_image, mock_clone_vdi, mock_safe_find_sr): self.session.call_xenapi.side_effect = ['ext', {}, 'cache_vdi_ref', None, None, None, None, None, None, 'vdi_uuid'] self.assertEqual((True, {'root': {'uuid': 'vdi_uuid', 'file': None}}), vm_utils._create_cached_image('context', self.session, 'instance', 'name', 'uuid', vm_utils.ImageType.DISK_VHD)) class BittorrentTestCase(VMUtilsTestBase): def setUp(self): super(BittorrentTestCase, self).setUp() self.context = context.get_admin_context() def test_image_uses_bittorrent(self): instance = {'system_metadata': {'image_bittorrent': True}} self.flags(torrent_images='some', group='xenserver') self.assertTrue(vm_utils._image_uses_bittorrent(self.context, instance)) def _test_create_image(self, cache_type): instance = {'system_metadata': {'image_cache_in_nova': True}} self.flags(cache_images=cache_type, group='xenserver') was = {'called': None} def fake_create_cached_image(*args): was['called'] = 'some' return (False, {}) self.stubs.Set(vm_utils, '_create_cached_image', fake_create_cached_image) def fake_fetch_image(*args): was['called'] = 'none' return {} self.stubs.Set(vm_utils, '_fetch_image', fake_fetch_image) vm_utils.create_image(self.context, None, instance, 'foo', 'bar', 'baz') self.assertEqual(was['called'], cache_type) def test_create_image_cached(self): self._test_create_image('some') def test_create_image_uncached(self): self._test_create_image('none') class ShutdownTestCase(VMUtilsTestBase): def test_hardshutdown_should_return_true_when_vm_is_shutdown(self): self.mock = mox.Mox() session = FakeSession() instance = "instance" vm_ref = "vm-ref" self.mock.StubOutWithMock(vm_utils, 'is_vm_shutdown') vm_utils.is_vm_shutdown(session, vm_ref).AndReturn(True) self.mock.StubOutWithMock(vm_utils, 'LOG') self.assertTrue(vm_utils.hard_shutdown_vm( session, instance, vm_ref)) def test_cleanshutdown_should_return_true_when_vm_is_shutdown(self): self.mock = mox.Mox() session = FakeSession() instance = "instance" vm_ref = "vm-ref" self.mock.StubOutWithMock(vm_utils, 'is_vm_shutdown') vm_utils.is_vm_shutdown(session, vm_ref).AndReturn(True) self.mock.StubOutWithMock(vm_utils, 'LOG') self.assertTrue(vm_utils.clean_shutdown_vm( session, instance, vm_ref)) class CreateVBDTestCase(VMUtilsTestBase): def setUp(self): super(CreateVBDTestCase, self).setUp() self.session = FakeSession() self.mock = mox.Mox() self.mock.StubOutWithMock(self.session, 'call_xenapi') self.vbd_rec = self._generate_vbd_rec() def _generate_vbd_rec(self): vbd_rec = {} vbd_rec['VM'] = 'vm_ref' vbd_rec['VDI'] = 'vdi_ref' vbd_rec['userdevice'] = '0' vbd_rec['bootable'] = False vbd_rec['mode'] = 'RW' vbd_rec['type'] = 'disk' vbd_rec['unpluggable'] = True vbd_rec['empty'] = False vbd_rec['other_config'] = {} vbd_rec['qos_algorithm_type'] = '' vbd_rec['qos_algorithm_params'] = {} vbd_rec['qos_supported_algorithms'] = [] return vbd_rec def test_create_vbd_default_args(self): self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", "vdi_ref", 0) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_create_vbd_osvol(self): self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.session.call_xenapi('VBD.add_to_other_config', "vbd_ref", "osvol", "True") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", "vdi_ref", 0, osvol=True) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_create_vbd_extra_args(self): self.vbd_rec['VDI'] = 'OpaqueRef:NULL' self.vbd_rec['type'] = 'a' self.vbd_rec['mode'] = 'RO' self.vbd_rec['bootable'] = True self.vbd_rec['empty'] = True self.vbd_rec['unpluggable'] = False self.session.call_xenapi('VBD.create', self.vbd_rec).AndReturn("vbd_ref") self.mock.ReplayAll() result = vm_utils.create_vbd(self.session, "vm_ref", None, 0, vbd_type="a", read_only=True, bootable=True, empty=True, unpluggable=False) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() def test_attach_cd(self): self.mock.StubOutWithMock(vm_utils, 'create_vbd') vm_utils.create_vbd(self.session, "vm_ref", None, 1, vbd_type='cd', read_only=True, bootable=True, empty=True, unpluggable=False).AndReturn("vbd_ref") self.session.call_xenapi('VBD.insert', "vbd_ref", "vdi_ref") self.mock.ReplayAll() result = vm_utils.attach_cd(self.session, "vm_ref", "vdi_ref", 1) self.assertEqual(result, "vbd_ref") self.mock.VerifyAll() class UnplugVbdTestCase(VMUtilsTestBase): @mock.patch.object(greenthread, 'sleep') def test_unplug_vbd_works(self, mock_sleep): session = _get_fake_session() vbd_ref = "vbd_ref" vm_ref = 'vm_ref' vm_utils.unplug_vbd(session, vbd_ref, vm_ref) session.call_xenapi.assert_called_once_with('VBD.unplug', vbd_ref) self.assertEqual(0, mock_sleep.call_count) def test_unplug_vbd_raises_unexpected_error(self): session = _get_fake_session() vbd_ref = "vbd_ref" vm_ref = 'vm_ref' session.call_xenapi.side_effect = test.TestingException() self.assertRaises(test.TestingException, vm_utils.unplug_vbd, session, vm_ref, vbd_ref) self.assertEqual(1, session.call_xenapi.call_count) def test_unplug_vbd_already_detached_works(self): error = "DEVICE_ALREADY_DETACHED" session = _get_fake_session(error) vbd_ref = "vbd_ref" vm_ref = 'vm_ref' vm_utils.unplug_vbd(session, vbd_ref, vm_ref) self.assertEqual(1, session.call_xenapi.call_count) def test_unplug_vbd_already_raises_unexpected_xenapi_error(self): session = _get_fake_session("") vbd_ref = "vbd_ref" vm_ref = 'vm_ref' self.assertRaises(exception.StorageError, vm_utils.unplug_vbd, session, vbd_ref, vm_ref) self.assertEqual(1, session.call_xenapi.call_count) def _test_uplug_vbd_retries(self, mock_sleep, error): session = _get_fake_session(error) vbd_ref = "vbd_ref" vm_ref = 'vm_ref' self.assertRaises(exception.StorageError, vm_utils.unplug_vbd, session, vm_ref, vbd_ref) self.assertEqual(11, session.call_xenapi.call_count) self.assertEqual(10, mock_sleep.call_count) @mock.patch.object(greenthread, 'sleep') def test_uplug_vbd_retries_on_rejected(self, mock_sleep): self._test_uplug_vbd_retries(mock_sleep, "DEVICE_DETACH_REJECTED") @mock.patch.object(greenthread, 'sleep') def test_uplug_vbd_retries_on_internal_error(self, mock_sleep): self._test_uplug_vbd_retries(mock_sleep, "INTERNAL_ERROR") class VDIOtherConfigTestCase(VMUtilsTestBase): """Tests to ensure that the code is populating VDI's `other_config` attribute with the correct metadta. """ def setUp(self): super(VDIOtherConfigTestCase, self).setUp() class _FakeSession(): def call_xenapi(self, operation, *args, **kwargs): method = getattr(self, operation.replace('.', '_'), None) if method: return method(*args, **kwargs) self.operation = operation self.args = args self.kwargs = kwargs self.session = _FakeSession() self.context = context.get_admin_context() self.fake_instance = {'uuid': 'aaaa-bbbb-cccc-dddd', 'name': 'myinstance'} def test_create_vdi(self): vm_utils.create_vdi(self.session, 'sr_ref', self.fake_instance, 'myvdi', 'root', 1024, read_only=True) expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, self.session.args[0]['other_config']) def test_create_image(self): self.flags(cache_images='none', group='xenserver') def fake_fetch_image(*args): return {'root': {'uuid': 'fake-uuid'}} self.stubs.Set(vm_utils, '_fetch_image', fake_fetch_image) other_config = {} def VDI_add_to_other_config(ref, key, value): other_config[key] = value # other tests self.session.VDI_add_to_other_config = VDI_add_to_other_config self.session.VDI_get_other_config = lambda vdi: {} vm_utils.create_image(self.context, self.session, self.fake_instance, 'myvdi', 'image1', vm_utils.ImageType.DISK_VHD) expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, other_config) def test_import_migrated_vhds(self): # Migrated images should preserve the `other_config` other_config = {} def VDI_add_to_other_config(ref, key, value): other_config[key] = value def call_plugin_serialized(*args, **kwargs): return {'root': {'uuid': 'aaaa-bbbb-cccc-dddd'}} # Stubbing on the session object and not class so we don't pollute self.session.VDI_add_to_other_config = VDI_add_to_other_config self.session.VDI_get_other_config = lambda vdi: {} self.session.call_plugin_serialized = call_plugin_serialized self.stubs.Set(vm_utils, 'get_sr_path', lambda *a, **k: None) self.stubs.Set(vm_utils, 'scan_default_sr', lambda *a, **k: None) vm_utils._import_migrated_vhds(self.session, self.fake_instance, "disk_label", "root", "vdi_label") expected = {'nova_disk_type': 'root', 'nova_instance_uuid': 'aaaa-bbbb-cccc-dddd'} self.assertEqual(expected, other_config) class GenerateDiskTestCase(VMUtilsTestBase): def setUp(self): super(GenerateDiskTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.session.is_local_connection = False self.vm_ref = fake.create_vm("foo", "Running") def tearDown(self): super(GenerateDiskTestCase, self).tearDown() fake.destroy_vm(self.vm_ref) def _expect_parted_calls(self): self.mox.StubOutWithMock(utils, "execute") self.mox.StubOutWithMock(utils, "trycmd") self.mox.StubOutWithMock(vm_utils, "destroy_vdi") self.mox.StubOutWithMock(vm_utils.os.path, "exists") if self.session.is_local_connection: utils.execute('parted', '--script', '/dev/fakedev', 'mklabel', 'msdos', check_exit_code=False, run_as_root=True) utils.execute('parted', '--script', '/dev/fakedev', '--', 'mkpart', 'primary', '0', '-0', check_exit_code=False, run_as_root=True) vm_utils.os.path.exists('/dev/mapper/fakedev1').AndReturn(True) utils.trycmd('kpartx', '-a', '/dev/fakedev', discard_warnings=True, run_as_root=True) else: utils.execute('parted', '--script', '/dev/fakedev', 'mklabel', 'msdos', check_exit_code=True, run_as_root=True) utils.execute('parted', '--script', '/dev/fakedev', '--', 'mkpart', 'primary', '0', '-0', check_exit_code=True, run_as_root=True) def _check_vdi(self, vdi_ref, check_attached=True): vdi_rec = self.session.call_xenapi("VDI.get_record", vdi_ref) self.assertEqual(str(10 * units.Mi), vdi_rec["virtual_size"]) if check_attached: vbd_ref = vdi_rec["VBDs"][0] vbd_rec = self.session.call_xenapi("VBD.get_record", vbd_ref) self.assertEqual(self.vm_ref, vbd_rec['VM']) else: self.assertEqual(0, len(vdi_rec["VBDs"])) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_with_no_fs_given(self): self._expect_parted_calls() self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "user", 10, None) self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_swap(self): self._expect_parted_calls() utils.execute('mkswap', '/dev/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "swap", 10, "linux-swap") self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ephemeral(self): self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "ephemeral", 10, "ext4") self._check_vdi(vdi_ref) @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ensure_cleanup_called(self): self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/fakedev1', run_as_root=True).AndRaise(test.TestingException) vm_utils.destroy_vdi(self.session, mox.IgnoreArg()).AndRaise(exception.StorageError(reason="")) self.mox.ReplayAll() self.assertRaises(test.TestingException, vm_utils._generate_disk, self.session, {"uuid": "fake_uuid"}, self.vm_ref, "2", "name", "ephemeral", 10, "ext4") @test_xenapi.stub_vm_utils_with_vdi_attached_here def test_generate_disk_ephemeral_local_not_attached(self): self.session.is_local_connection = True self._expect_parted_calls() utils.execute('mkfs', '-t', 'ext4', '/dev/mapper/fakedev1', run_as_root=True) self.mox.ReplayAll() vdi_ref = vm_utils._generate_disk(self.session, {"uuid": "fake_uuid"}, None, "2", "name", "ephemeral", 10, "ext4") self._check_vdi(vdi_ref, check_attached=False) class GenerateEphemeralTestCase(VMUtilsTestBase): def setUp(self): super(GenerateEphemeralTestCase, self).setUp() self.session = "session" self.instance = "instance" self.vm_ref = "vm_ref" self.name_label = "name" self.ephemeral_name_label = "name ephemeral" self.userdevice = 4 self.mox.StubOutWithMock(vm_utils, "_generate_disk") self.mox.StubOutWithMock(vm_utils, "safe_destroy_vdis") def test_get_ephemeral_disk_sizes_simple(self): result = vm_utils.get_ephemeral_disk_sizes(20) expected = [20] self.assertEqual(expected, list(result)) def test_get_ephemeral_disk_sizes_three_disks_2000(self): result = vm_utils.get_ephemeral_disk_sizes(4030) expected = [2000, 2000, 30] self.assertEqual(expected, list(result)) def test_get_ephemeral_disk_sizes_two_disks_1024(self): result = vm_utils.get_ephemeral_disk_sizes(2048) expected = [1024, 1024] self.assertEqual(expected, list(result)) def _expect_generate_disk(self, size, device, name_label): vm_utils._generate_disk(self.session, self.instance, self.vm_ref, str(device), name_label, 'ephemeral', size * 1024, None).AndReturn(device) def test_generate_ephemeral_adds_one_disk(self): self._expect_generate_disk(20, self.userdevice, self.ephemeral_name_label) self.mox.ReplayAll() vm_utils.generate_ephemeral(self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 20) def test_generate_ephemeral_adds_multiple_disks(self): self._expect_generate_disk(2000, self.userdevice, self.ephemeral_name_label) self._expect_generate_disk(2000, self.userdevice + 1, self.ephemeral_name_label + " (1)") self._expect_generate_disk(30, self.userdevice + 2, self.ephemeral_name_label + " (2)") self.mox.ReplayAll() vm_utils.generate_ephemeral(self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 4030) def test_generate_ephemeral_cleans_up_on_error(self): self._expect_generate_disk(1024, self.userdevice, self.ephemeral_name_label) self._expect_generate_disk(1024, self.userdevice + 1, self.ephemeral_name_label + " (1)") vm_utils._generate_disk(self.session, self.instance, self.vm_ref, str(self.userdevice + 2), "name ephemeral (2)", 'ephemeral', units.Mi, None).AndRaise(exception.NovaException) vm_utils.safe_destroy_vdis(self.session, [4, 5]) self.mox.ReplayAll() self.assertRaises(exception.NovaException, vm_utils.generate_ephemeral, self.session, self.instance, self.vm_ref, str(self.userdevice), self.name_label, 4096) class FakeFile(object): def __init__(self): self._file_operations = [] def seek(self, offset): self._file_operations.append((self.seek, offset)) class StreamDiskTestCase(VMUtilsTestBase): def setUp(self): import __builtin__ super(StreamDiskTestCase, self).setUp() self.mox.StubOutWithMock(vm_utils.utils, 'make_dev_path') self.mox.StubOutWithMock(vm_utils.utils, 'temporary_chown') self.mox.StubOutWithMock(vm_utils, '_write_partition') self.mox.StubOutWithMock(__builtin__, 'open') self.image_service_func = self.mox.CreateMockAnything() def test_non_ami(self): fake_file = FakeFile() vm_utils.utils.make_dev_path('dev').AndReturn('some_path') vm_utils.utils.temporary_chown( 'some_path').AndReturn(contextified(None)) open('some_path', 'wb').AndReturn(contextified(fake_file)) self.image_service_func(fake_file) self.mox.ReplayAll() vm_utils._stream_disk("session", self.image_service_func, vm_utils.ImageType.KERNEL, None, 'dev') self.assertEqual([(fake_file.seek, 0)], fake_file._file_operations) def test_ami_disk(self): fake_file = FakeFile() vm_utils._write_partition("session", 100, 'dev') vm_utils.utils.make_dev_path('dev').AndReturn('some_path') vm_utils.utils.temporary_chown( 'some_path').AndReturn(contextified(None)) open('some_path', 'wb').AndReturn(contextified(fake_file)) self.image_service_func(fake_file) self.mox.ReplayAll() vm_utils._stream_disk("session", self.image_service_func, vm_utils.ImageType.DISK, 100, 'dev') self.assertEqual( [(fake_file.seek, vm_utils.MBR_SIZE_BYTES)], fake_file._file_operations) class VMUtilsSRPath(VMUtilsTestBase): def setUp(self): super(VMUtilsSRPath, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.session.is_local_connection = False def test_defined(self): self.mox.StubOutWithMock(vm_utils, "safe_find_sr") self.mox.StubOutWithMock(self.session, "call_xenapi") vm_utils.safe_find_sr(self.session).AndReturn("sr_ref") self.session.host_ref = "host_ref" self.session.call_xenapi('PBD.get_all_records_where', 'field "host"="host_ref" and field "SR"="sr_ref"').AndReturn( {'pbd_ref': {'device_config': {'path': 'sr_path'}}}) self.mox.ReplayAll() self.assertEqual(vm_utils.get_sr_path(self.session), "sr_path") def test_default(self): self.mox.StubOutWithMock(vm_utils, "safe_find_sr") self.mox.StubOutWithMock(self.session, "call_xenapi") vm_utils.safe_find_sr(self.session).AndReturn("sr_ref") self.session.host_ref = "host_ref" self.session.call_xenapi('PBD.get_all_records_where', 'field "host"="host_ref" and field "SR"="sr_ref"').AndReturn( {'pbd_ref': {'device_config': {}}}) self.session.call_xenapi("SR.get_record", "sr_ref").AndReturn( {'uuid': 'sr_uuid', 'type': 'ext'}) self.mox.ReplayAll() self.assertEqual(vm_utils.get_sr_path(self.session), "/var/run/sr-mount/sr_uuid") class CreateKernelRamdiskTestCase(VMUtilsTestBase): def setUp(self): super(CreateKernelRamdiskTestCase, self).setUp() self.context = "context" self.session = FakeSession() self.instance = {"kernel_id": None, "ramdisk_id": None} self.name_label = "name" self.mox.StubOutWithMock(self.session, "call_plugin") self.mox.StubOutWithMock(uuid, "uuid4") self.mox.StubOutWithMock(vm_utils, "_fetch_disk_image") def test_create_kernel_and_ramdisk_no_create(self): self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual((None, None), result) def test_create_kernel_and_ramdisk_create_both_cached(self): kernel_id = "kernel" ramdisk_id = "ramdisk" self.instance["kernel_id"] = kernel_id self.instance["ramdisk_id"] = ramdisk_id args_kernel = {} args_kernel['cached-image'] = kernel_id args_kernel['new-image-uuid'] = "fake_uuid1" uuid.uuid4().AndReturn("fake_uuid1") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_kernel).AndReturn("k") args_ramdisk = {} args_ramdisk['cached-image'] = ramdisk_id args_ramdisk['new-image-uuid'] = "fake_uuid2" uuid.uuid4().AndReturn("fake_uuid2") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_ramdisk).AndReturn("r") self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual(("k", "r"), result) def test_create_kernel_and_ramdisk_create_kernel_not_cached(self): kernel_id = "kernel" self.instance["kernel_id"] = kernel_id args_kernel = {} args_kernel['cached-image'] = kernel_id args_kernel['new-image-uuid'] = "fake_uuid1" uuid.uuid4().AndReturn("fake_uuid1") self.session.call_plugin('kernel', 'create_kernel_ramdisk', args_kernel).AndReturn("") kernel = {"kernel": {"file": "k"}} vm_utils._fetch_disk_image(self.context, self.session, self.instance, self.name_label, kernel_id, 0).AndReturn(kernel) self.mox.ReplayAll() result = vm_utils.create_kernel_and_ramdisk(self.context, self.session, self.instance, self.name_label) self.assertEqual(("k", None), result) class ScanSrTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, "_scan_sr") @mock.patch.object(vm_utils, "safe_find_sr") def test_scan_default_sr(self, mock_safe_find_sr, mock_scan_sr): mock_safe_find_sr.return_value = "sr_ref" self.assertEqual("sr_ref", vm_utils.scan_default_sr("fake_session")) mock_scan_sr.assert_called_once_with("fake_session", "sr_ref") def test_scan_sr_works(self): session = mock.Mock() vm_utils._scan_sr(session, "sr_ref") session.call_xenapi.assert_called_once_with('SR.scan', "sr_ref") def test_scan_sr_unknown_error_fails_once(self): session = mock.Mock() session.call_xenapi.side_effect = test.TestingException self.assertRaises(test.TestingException, vm_utils._scan_sr, session, "sr_ref") session.call_xenapi.assert_called_once_with('SR.scan', "sr_ref") @mock.patch.object(greenthread, 'sleep') def test_scan_sr_known_error_retries_then_throws(self, mock_sleep): session = mock.Mock() class FakeException(Exception): details = ['SR_BACKEND_FAILURE_40', "", "", ""] session.XenAPI.Failure = FakeException session.call_xenapi.side_effect = FakeException self.assertRaises(FakeException, vm_utils._scan_sr, session, "sr_ref") session.call_xenapi.assert_called_with('SR.scan', "sr_ref") self.assertEqual(4, session.call_xenapi.call_count) mock_sleep.assert_has_calls([mock.call(2), mock.call(4), mock.call(8)]) @mock.patch.object(greenthread, 'sleep') def test_scan_sr_known_error_retries_then_succeeds(self, mock_sleep): session = mock.Mock() class FakeException(Exception): details = ['SR_BACKEND_FAILURE_40', "", "", ""] session.XenAPI.Failure = FakeException def fake_call_xenapi(*args): fake_call_xenapi.count += 1 if fake_call_xenapi.count != 2: raise FakeException() fake_call_xenapi.count = 0 session.call_xenapi.side_effect = fake_call_xenapi vm_utils._scan_sr(session, "sr_ref") session.call_xenapi.assert_called_with('SR.scan', "sr_ref") self.assertEqual(2, session.call_xenapi.call_count) mock_sleep.assert_called_once_with(2) @mock.patch.object(flavors, 'extract_flavor', return_value={ 'memory_mb': 1024, 'vcpus': 1, 'vcpu_weight': 1.0, }) class CreateVmTestCase(VMUtilsTestBase): def test_vss_provider(self, mock_extract): self.flags(vcpu_pin_set="2,3") session = _get_fake_session() instance = objects.Instance(uuid="uuid", os_type="windows", system_metadata={}) with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) vm_utils.create_vm(session, instance, "label", "kernel", "ramdisk") vm_rec = { 'VCPUs_params': {'cap': '0', 'mask': '2,3', 'weight': '1'}, 'PV_args': '', 'memory_static_min': '0', 'ha_restart_priority': '', 'HVM_boot_policy': 'BIOS order', 'PV_bootloader': '', 'tags': [], 'VCPUs_max': '4', 'memory_static_max': '1073741824', 'actions_after_shutdown': 'destroy', 'memory_dynamic_max': '1073741824', 'user_version': '0', 'xenstore_data': {'vm-data/allowvssprovider': 'false'}, 'blocked_operations': {}, 'is_a_template': False, 'name_description': '', 'memory_dynamic_min': '1073741824', 'actions_after_crash': 'destroy', 'memory_target': '1073741824', 'PV_ramdisk': '', 'PV_bootloader_args': '', 'PCI_bus': '', 'other_config': {'nova_uuid': 'uuid'}, 'name_label': 'label', 'actions_after_reboot': 'restart', 'VCPUs_at_startup': '4', 'HVM_boot_params': {'order': 'dc'}, 'platform': {'nx': 'true', 'pae': 'true', 'apic': 'true', 'timeoffset': '0', 'viridian': 'true', 'acpi': 'true'}, 'PV_legacy_args': '', 'PV_kernel': '', 'affinity': '', 'recommendations': '', 'ha_always_run': False } session.call_xenapi.assert_called_once_with("VM.create", vm_rec) def test_invalid_cpu_mask_raises(self, mock_extract): self.flags(vcpu_pin_set="asdf") session = mock.Mock() instance = objects.Instance(uuid=str(uuid.uuid4()), system_metadata={}) with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) self.assertRaises(exception.Invalid, vm_utils.create_vm, session, instance, "label", "kernel", "ramdisk") def test_destroy_vm(self, mock_extract): session = mock.Mock() instance = objects.Instance(uuid=str(uuid.uuid4())) vm_utils.destroy_vm(session, instance, "vm_ref") session.VM.destroy.assert_called_once_with("vm_ref") def test_destroy_vm_silently_fails(self, mock_extract): session = mock.Mock() exc = test.TestingException() session.XenAPI.Failure = test.TestingException session.VM.destroy.side_effect = exc instance = objects.Instance(uuid=str(uuid.uuid4())) vm_utils.destroy_vm(session, instance, "vm_ref") session.VM.destroy.assert_called_once_with("vm_ref") class DetermineVmModeTestCase(VMUtilsTestBase): def test_determine_vm_mode_returns_xen_mode(self): instance = {"vm_mode": "xen"} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_mode(self): instance = {"vm_mode": "hvm"} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_xen_for_linux(self): instance = {"vm_mode": None, "os_type": "linux"} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_for_windows(self): instance = {"vm_mode": None, "os_type": "windows"} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_hvm_by_default(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.HVM, vm_utils.determine_vm_mode(instance, None)) def test_determine_vm_mode_returns_xen_for_VHD(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK_VHD)) def test_determine_vm_mode_returns_xen_for_DISK(self): instance = {"vm_mode": None, "os_type": None} self.assertEqual(vm_mode.XEN, vm_utils.determine_vm_mode(instance, vm_utils.ImageType.DISK)) class CallXenAPIHelpersTestCase(VMUtilsTestBase): def test_vm_get_vbd_refs(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vm_get_vbd_refs(session, "vm_ref")) session.call_xenapi.assert_called_once_with("VM.get_VBDs", "vm_ref") def test_vbd_get_rec(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vbd_get_rec(session, "vbd_ref")) session.call_xenapi.assert_called_once_with("VBD.get_record", "vbd_ref") def test_vdi_get_rec(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vdi_get_rec(session, "vdi_ref")) session.call_xenapi.assert_called_once_with("VDI.get_record", "vdi_ref") def test_vdi_snapshot(self): session = mock.Mock() session.call_xenapi.return_value = "foo" self.assertEqual("foo", vm_utils._vdi_snapshot(session, "vdi_ref")) session.call_xenapi.assert_called_once_with("VDI.snapshot", "vdi_ref", {}) def test_vdi_get_virtual_size(self): session = mock.Mock() session.call_xenapi.return_value = "123" self.assertEqual(123, vm_utils._vdi_get_virtual_size(session, "ref")) session.call_xenapi.assert_called_once_with("VDI.get_virtual_size", "ref") @mock.patch.object(vm_utils, '_get_resize_func_name') def test_vdi_resize(self, mock_get_resize_func_name): session = mock.Mock() mock_get_resize_func_name.return_value = "VDI.fake" vm_utils._vdi_resize(session, "ref", 123) session.call_xenapi.assert_called_once_with("VDI.fake", "ref", "123") @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_works(self, mock_get_size, mock_resize): mock_get_size.return_value = (1024 ** 3) - 1 instance = {"uuid": "a"} vm_utils.update_vdi_virtual_size("s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") mock_resize.assert_called_once_with("s", "ref", 1024 ** 3) @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_skips_resize_down(self, mock_get_size, mock_resize): mock_get_size.return_value = 1024 ** 3 instance = {"uuid": "a"} vm_utils.update_vdi_virtual_size("s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") self.assertFalse(mock_resize.called) @mock.patch.object(vm_utils, '_vdi_resize') @mock.patch.object(vm_utils, '_vdi_get_virtual_size') def test_update_vdi_virtual_size_raise_if_disk_big(self, mock_get_size, mock_resize): mock_get_size.return_value = 1024 ** 3 + 1 instance = {"uuid": "a"} self.assertRaises(exception.ResizeError, vm_utils.update_vdi_virtual_size, "s", instance, "ref", 1) mock_get_size.assert_called_once_with("s", "ref") self.assertFalse(mock_resize.called) @mock.patch.object(vm_utils, '_vdi_get_rec') @mock.patch.object(vm_utils, '_vbd_get_rec') @mock.patch.object(vm_utils, '_vm_get_vbd_refs') class GetVdiForVMTestCase(VMUtilsTestBase): def test_get_vdi_for_vm_safely(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_rec): session = "session" vm_get_vbd_refs.return_value = ["a", "b"] vbd_get_rec.return_value = {'userdevice': '0', 'VDI': 'vdi_ref'} vdi_get_rec.return_value = {} result = vm_utils.get_vdi_for_vm_safely(session, "vm_ref") self.assertEqual(('vdi_ref', {}), result) vm_get_vbd_refs.assert_called_once_with(session, "vm_ref") vbd_get_rec.assert_called_once_with(session, "a") vdi_get_rec.assert_called_once_with(session, "vdi_ref") def test_get_vdi_for_vm_safely_fails(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_rec): session = "session" vm_get_vbd_refs.return_value = ["a", "b"] vbd_get_rec.return_value = {'userdevice': '0', 'VDI': 'vdi_ref'} self.assertRaises(exception.NovaException, vm_utils.get_vdi_for_vm_safely, session, "vm_ref", userdevice='1') self.assertEqual([], vdi_get_rec.call_args_list) self.assertEqual(2, len(vbd_get_rec.call_args_list)) @mock.patch.object(vm_utils, '_vdi_get_uuid') @mock.patch.object(vm_utils, '_vbd_get_rec') @mock.patch.object(vm_utils, '_vm_get_vbd_refs') class GetAllVdiForVMTestCase(VMUtilsTestBase): def _setup_get_all_vdi_uuids_for_vm(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): def fake_vbd_get_rec(session, vbd_ref): return {'userdevice': vbd_ref, 'VDI': "vdi_ref_%s" % vbd_ref} def fake_vdi_get_uuid(session, vdi_ref): return vdi_ref vm_get_vbd_refs.return_value = ["0", "2"] vbd_get_rec.side_effect = fake_vbd_get_rec vdi_get_uuid.side_effect = fake_vdi_get_uuid def test_get_all_vdi_uuids_for_vm_works(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): self._setup_get_all_vdi_uuids_for_vm(vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid) result = vm_utils.get_all_vdi_uuids_for_vm('session', "vm_ref") expected = ['vdi_ref_0', 'vdi_ref_2'] self.assertEqual(expected, list(result)) def test_get_all_vdi_uuids_for_vm_finds_none(self, vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid): self._setup_get_all_vdi_uuids_for_vm(vm_get_vbd_refs, vbd_get_rec, vdi_get_uuid) result = vm_utils.get_all_vdi_uuids_for_vm('session', "vm_ref", min_userdevice=1) expected = ["vdi_ref_2"] self.assertEqual(expected, list(result)) class GetAllVdisTestCase(VMUtilsTestBase): def test_get_all_vdis_in_sr(self): def fake_get_rec(record_type, ref): if ref == "2": return "vdi_rec_2" session = mock.Mock() session.call_xenapi.return_value = ["1", "2"] session.get_rec.side_effect = fake_get_rec sr_ref = "sr_ref" actual = list(vm_utils._get_all_vdis_in_sr(session, sr_ref)) self.assertEqual(actual, [('2', 'vdi_rec_2')]) session.call_xenapi.assert_called_once_with("SR.get_VDIs", sr_ref) class VDIAttachedHere(VMUtilsTestBase): @mock.patch.object(vm_utils, 'destroy_vbd') @mock.patch.object(vm_utils, '_get_this_vm_ref') @mock.patch.object(vm_utils, 'create_vbd') @mock.patch.object(vm_utils, '_remap_vbd_dev') @mock.patch.object(vm_utils, '_wait_for_device') @mock.patch.object(utils, 'execute') def test_sync_called(self, mock_execute, mock_wait_for_device, mock_remap_vbd_dev, mock_create_vbd, mock_get_this_vm_ref, mock_destroy_vbd): session = _get_fake_session() with vm_utils.vdi_attached_here(session, 'vdi_ref'): pass mock_execute.assert_called_with('sync', run_as_root=True) class SnapshotAttachedHereTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, '_snapshot_attached_here_impl') def test_snapshot_attached_here(self, mock_impl): def fake_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback): self.assertEqual("session", session) self.assertEqual("instance", instance) self.assertEqual("vm_ref", vm_ref) self.assertEqual("label", label) self.assertEqual('0', userdevice) self.assertIsNone(post_snapshot_callback) yield "fake" mock_impl.side_effect = fake_impl with vm_utils.snapshot_attached_here("session", "instance", "vm_ref", "label") as result: self.assertEqual("fake", result) mock_impl.assert_called_once_with("session", "instance", "vm_ref", "label", '0', None) @mock.patch.object(vm_utils, '_delete_snapshots_in_vdi_chain') @mock.patch.object(vm_utils, 'safe_destroy_vdis') @mock.patch.object(vm_utils, '_walk_vdi_chain') @mock.patch.object(vm_utils, '_wait_for_vhd_coalesce') @mock.patch.object(vm_utils, '_vdi_get_uuid') @mock.patch.object(vm_utils, '_vdi_snapshot') @mock.patch.object(vm_utils, 'get_vdi_for_vm_safely') def test_snapshot_attached_here_impl(self, mock_get_vdi_for_vm_safely, mock_vdi_snapshot, mock_vdi_get_uuid, mock_wait_for_vhd_coalesce, mock_walk_vdi_chain, mock_safe_destroy_vdis, mock_delete_snapshots_in_vdi_chain): session = "session" instance = {"uuid": "uuid"} mock_callback = mock.Mock() mock_get_vdi_for_vm_safely.return_value = ("vdi_ref", {"SR": "sr_ref", "uuid": "vdi_uuid"}) mock_vdi_snapshot.return_value = "snap_ref" mock_vdi_get_uuid.return_value = "snap_uuid" mock_walk_vdi_chain.return_value = [{"uuid": "a"}, {"uuid": "b"}] try: with vm_utils.snapshot_attached_here(session, instance, "vm_ref", "label", '2', mock_callback) as result: self.assertEqual(["a", "b"], result) raise test.TestingException() self.assertTrue(False) except test.TestingException: pass mock_get_vdi_for_vm_safely.assert_called_once_with(session, "vm_ref", '2') mock_vdi_snapshot.assert_called_once_with(session, "vdi_ref") mock_wait_for_vhd_coalesce.assert_called_once_with(session, instance, "sr_ref", "vdi_ref", ['a', 'b']) mock_vdi_get_uuid.assert_called_once_with(session, "snap_ref") mock_walk_vdi_chain.assert_has_calls([mock.call(session, "vdi_uuid"), mock.call(session, "snap_uuid")]) mock_callback.assert_called_once_with( task_state="image_pending_upload") mock_safe_destroy_vdis.assert_called_once_with(session, ["snap_ref"]) mock_delete_snapshots_in_vdi_chain.assert_called_once_with(session, instance, ['a', 'b'], "sr_ref") @mock.patch.object(greenthread, 'sleep') def test_wait_for_vhd_coalesce_leaf_node(self, mock_sleep): instance = {"uuid": "fake"} vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid"]) self.assertFalse(mock_sleep.called) @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(greenthread, 'sleep') def test_wait_for_vhd_coalesce_parent_snapshot(self, mock_sleep, mock_count): mock_count.return_value = 2 instance = {"uuid": "fake"} vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertFalse(mock_sleep.called) self.assertTrue(mock_count.called) @mock.patch.object(greenthread, 'sleep') @mock.patch.object(vm_utils, '_get_vhd_parent_uuid') @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(vm_utils, '_scan_sr') def test_wait_for_vhd_coalesce_raises(self, mock_scan_sr, mock_count, mock_get_vhd_parent_uuid, mock_sleep): mock_count.return_value = 1 instance = {"uuid": "fake"} self.assertRaises(exception.NovaException, vm_utils._wait_for_vhd_coalesce, "session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertTrue(mock_count.called) self.assertEqual(20, mock_sleep.call_count) self.assertEqual(20, mock_scan_sr.call_count) @mock.patch.object(greenthread, 'sleep') @mock.patch.object(vm_utils, '_get_vhd_parent_uuid') @mock.patch.object(vm_utils, '_count_children') @mock.patch.object(vm_utils, '_scan_sr') def test_wait_for_vhd_coalesce_success(self, mock_scan_sr, mock_count, mock_get_vhd_parent_uuid, mock_sleep): mock_count.return_value = 1 instance = {"uuid": "fake"} mock_get_vhd_parent_uuid.side_effect = ["bad", "uuid2"] vm_utils._wait_for_vhd_coalesce("session", instance, "sr_ref", "vdi_ref", ["uuid1", "uuid2"]) self.assertEqual(1, mock_sleep.call_count) self.assertEqual(2, mock_scan_sr.call_count) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_count_children(self, mock_get_all_vdis_in_sr): vdis = [('child1', {'sm_config': {'vhd-parent': 'parent1'}}), ('child2', {'sm_config': {'vhd-parent': 'parent2'}}), ('child3', {'sm_config': {'vhd-parent': 'parent1'}})] mock_get_all_vdis_in_sr.return_value = vdis self.assertEqual(2, vm_utils._count_children('session', 'parent1', 'sr')) class ImportMigratedDisksTestCase(VMUtilsTestBase): @mock.patch.object(vm_utils, '_import_migrate_ephemeral_disks') @mock.patch.object(vm_utils, '_import_migrated_root_disk') def test_import_all_migrated_disks(self, mock_root, mock_ephemeral): session = "session" instance = "instance" mock_root.return_value = "root_vdi" mock_ephemeral.return_value = ["a", "b"] result = vm_utils.import_all_migrated_disks(session, instance) expected = {'root': 'root_vdi', 'ephemerals': ["a", "b"]} self.assertEqual(expected, result) mock_root.assert_called_once_with(session, instance) mock_ephemeral.assert_called_once_with(session, instance) @mock.patch.object(vm_utils, '_import_migrated_vhds') def test_import_migrated_root_disk(self, mock_migrate): mock_migrate.return_value = "foo" instance = {"uuid": "uuid", "name": "name"} result = vm_utils._import_migrated_root_disk("s", instance) self.assertEqual("foo", result) mock_migrate.assert_called_once_with("s", instance, "uuid", "root", "name") @mock.patch.object(vm_utils, '_import_migrated_vhds') def test_import_migrate_ephemeral_disks(self, mock_migrate): mock_migrate.return_value = "foo" instance = {"uuid": "uuid", "name": "name", "ephemeral_gb": 4000} result = vm_utils._import_migrate_ephemeral_disks("s", instance) self.assertEqual({'4': 'foo', '5': 'foo'}, result) expected_calls = [mock.call("s", instance, "uuid_ephemeral_1", "ephemeral", "name ephemeral (1)"), mock.call("s", instance, "uuid_ephemeral_2", "ephemeral", "name ephemeral (2)")] self.assertEqual(expected_calls, mock_migrate.call_args_list) @mock.patch.object(vm_utils, '_set_vdi_info') @mock.patch.object(vm_utils, 'scan_default_sr') @mock.patch.object(vm_utils, 'get_sr_path') def test_import_migrated_vhds(self, mock_get_sr_path, mock_scan_sr, mock_set_info): session = mock.Mock() instance = {"uuid": "uuid"} session.call_plugin_serialized.return_value = {"root": {"uuid": "a"}} session.call_xenapi.return_value = "vdi_ref" mock_get_sr_path.return_value = "sr_path" result = vm_utils._import_migrated_vhds(session, instance, 'chain_label', 'disk_type', 'vdi_label') expected = {'uuid': "a", 'ref': "vdi_ref"} self.assertEqual(expected, result) mock_get_sr_path.assert_called_once_with(session) session.call_plugin_serialized.assert_called_once_with('migration', 'move_vhds_into_sr', instance_uuid='chain_label', sr_path='sr_path', uuid_stack=mock.ANY) mock_scan_sr.assert_called_once_with(session) session.call_xenapi.assert_called_once_with('VDI.get_by_uuid', 'a') mock_set_info.assert_called_once_with(session, 'vdi_ref', 'disk_type', 'vdi_label', 'disk_type', instance) def test_get_vhd_parent_uuid_rec_provided(self): session = mock.Mock() vdi_ref = 'vdi_ref' vdi_rec = {'sm_config': {}} self.assertIsNone(vm_utils._get_vhd_parent_uuid(session, vdi_ref, vdi_rec)) self.assertFalse(session.call_xenapi.called) class MigrateVHDTestCase(VMUtilsTestBase): def _assert_transfer_called(self, session, label): session.call_plugin_serialized.assert_called_once_with( 'migration', 'transfer_vhd', instance_uuid=label, host="dest", vdi_uuid="vdi_uuid", sr_path="sr_path", seq_num=2) def test_migrate_vhd_root(self): session = mock.Mock() instance = {"uuid": "a"} vm_utils.migrate_vhd(session, instance, "vdi_uuid", "dest", "sr_path", 2) self._assert_transfer_called(session, "a") def test_migrate_vhd_ephemeral(self): session = mock.Mock() instance = {"uuid": "a"} vm_utils.migrate_vhd(session, instance, "vdi_uuid", "dest", "sr_path", 2, 2) self._assert_transfer_called(session, "a_ephemeral_2") def test_migrate_vhd_converts_exceptions(self): session = mock.Mock() session.XenAPI.Failure = test.TestingException session.call_plugin_serialized.side_effect = test.TestingException() instance = {"uuid": "a"} self.assertRaises(exception.MigrationError, vm_utils.migrate_vhd, session, instance, "vdi_uuid", "dest", "sr_path", 2) self._assert_transfer_called(session, "a") class StripBaseMirrorTestCase(VMUtilsTestBase): def test_strip_base_mirror_from_vdi_works(self): session = mock.Mock() vm_utils._try_strip_base_mirror_from_vdi(session, "vdi_ref") session.call_xenapi.assert_called_once_with( "VDI.remove_from_sm_config", "vdi_ref", "base_mirror") def test_strip_base_mirror_from_vdi_hides_error(self): session = mock.Mock() session.XenAPI.Failure = test.TestingException session.call_xenapi.side_effect = test.TestingException() vm_utils._try_strip_base_mirror_from_vdi(session, "vdi_ref") session.call_xenapi.assert_called_once_with( "VDI.remove_from_sm_config", "vdi_ref", "base_mirror") @mock.patch.object(vm_utils, '_try_strip_base_mirror_from_vdi') def test_strip_base_mirror_from_vdis(self, mock_strip): def call_xenapi(method, arg): if method == "VM.get_VBDs": return ['VBD_ref_1', 'VBD_ref_2'] if method == "VBD.get_VDI": return 'VDI' + arg[3:] return "Unexpected call_xenapi: %s.%s" % (method, arg) session = mock.Mock() session.call_xenapi.side_effect = call_xenapi vm_utils.strip_base_mirror_from_vdis(session, "vm_ref") expected = [mock.call('VM.get_VBDs', "vm_ref"), mock.call('VBD.get_VDI', "VBD_ref_1"), mock.call('VBD.get_VDI', "VBD_ref_2")] self.assertEqual(expected, session.call_xenapi.call_args_list) expected = [mock.call(session, "VDI_ref_1"), mock.call(session, "VDI_ref_2")] self.assertEqual(expected, mock_strip.call_args_list) class DeviceIdTestCase(VMUtilsTestBase): def test_device_id_is_none_if_not_specified_in_meta_data(self): image_meta = {} session = mock.Mock() session.product_version = (6, 1, 0) self.assertIsNone(vm_utils.get_vm_device_id(session, image_meta)) def test_get_device_id_if_hypervisor_version_is_greater_than_6_1(self): image_meta = {'xenapi_device_id': '0002'} session = mock.Mock() session.product_version = (6, 2, 0) self.assertEqual('0002', vm_utils.get_vm_device_id(session, image_meta)) session.product_version = (6, 3, 1) self.assertEqual('0002', vm_utils.get_vm_device_id(session, image_meta)) def test_raise_exception_if_device_id_not_supported_by_hyp_version(self): image_meta = {'xenapi_device_id': '0002'} session = mock.Mock() session.product_version = (6, 0) exc = self.assertRaises(exception.NovaException, vm_utils.get_vm_device_id, session, image_meta) self.assertEqual("Device id 0002 specified is not supported by " "hypervisor version (6, 0)", exc.message) session.product_version = ('6a') exc = self.assertRaises(exception.NovaException, vm_utils.get_vm_device_id, session, image_meta) self.assertEqual("Device id 0002 specified is not supported by " "hypervisor version 6a", exc.message) class CreateVmRecordTestCase(VMUtilsTestBase): @mock.patch.object(flavors, 'extract_flavor') def test_create_vm_record_linux(self, mock_extract_flavor): instance = objects.Instance(uuid="uuid123", os_type="linux") self._test_create_vm_record(mock_extract_flavor, instance, False) @mock.patch.object(flavors, 'extract_flavor') def test_create_vm_record_windows(self, mock_extract_flavor): instance = objects.Instance(uuid="uuid123", os_type="windows") with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor._from_db_object( None, objects.Flavor(), test_flavor.fake_flavor) self._test_create_vm_record(mock_extract_flavor, instance, True) def _test_create_vm_record(self, mock_extract_flavor, instance, is_viridian): session = _get_fake_session() flavor = {"memory_mb": 1024, "vcpus": 1, "vcpu_weight": 2} mock_extract_flavor.return_value = flavor with mock.patch.object(instance, 'get_flavor') as get: get.return_value = objects.Flavor(memory_mb=1024, vcpus=1, vcpu_weight=2) vm_utils.create_vm(session, instance, "name", "kernel", "ramdisk", device_id="0002") is_viridian_str = str(is_viridian).lower() expected_vm_rec = { 'VCPUs_params': {'cap': '0', 'weight': '2'}, 'PV_args': '', 'memory_static_min': '0', 'ha_restart_priority': '', 'HVM_boot_policy': 'BIOS order', 'PV_bootloader': '', 'tags': [], 'VCPUs_max': '1', 'memory_static_max': '1073741824', 'actions_after_shutdown': 'destroy', 'memory_dynamic_max': '1073741824', 'user_version': '0', 'xenstore_data': {'vm-data/allowvssprovider': 'false'}, 'blocked_operations': {}, 'is_a_template': False, 'name_description': '', 'memory_dynamic_min': '1073741824', 'actions_after_crash': 'destroy', 'memory_target': '1073741824', 'PV_ramdisk': '', 'PV_bootloader_args': '', 'PCI_bus': '', 'other_config': {'nova_uuid': 'uuid123'}, 'name_label': 'name', 'actions_after_reboot': 'restart', 'VCPUs_at_startup': '1', 'HVM_boot_params': {'order': 'dc'}, 'platform': {'nx': 'true', 'pae': 'true', 'apic': 'true', 'timeoffset': '0', 'viridian': is_viridian_str, 'acpi': 'true', 'device_id': '0002'}, 'PV_legacy_args': '', 'PV_kernel': '', 'affinity': '', 'recommendations': '', 'ha_always_run': False} session.call_xenapi.assert_called_with('VM.create', expected_vm_rec) def test_list_vms(self): self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') fake.create_vm("foo1", "Halted") vm_ref = fake.create_vm("foo2", "Running") stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) result = list(vm_utils.list_vms(driver._session)) self.assertEqual(len(driver._session.call_xenapi('VM.get_all')), 3) self.assertEqual(len(result), 1) result_keys = [key for (key, value) in result] self.assertIn(vm_ref, result_keys) class ChildVHDsTestCase(test.NoDBTestCase): all_vdis = [ ("my-vdi-ref", {"uuid": "my-uuid", "sm_config": {}, "is_a_snapshot": False, "other_config": {}}), ("non-parent", {"uuid": "uuid-1", "sm_config": {}, "is_a_snapshot": False, "other_config": {}}), ("diff-parent", {"uuid": "uuid-1", "sm_config": {"vhd-parent": "other-uuid"}, "is_a_snapshot": False, "other_config": {}}), ("child", {"uuid": "uuid-child", "sm_config": {"vhd-parent": "my-uuid"}, "is_a_snapshot": False, "other_config": {}}), ("child-snap", {"uuid": "uuid-child-snap", "sm_config": {"vhd-parent": "my-uuid"}, "is_a_snapshot": True, "other_config": {}}), ] @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_defaults(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid"]) self.assertEqual(['uuid-child', 'uuid-child-snap'], result) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_only_snapshots(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid"], old_snapshots_only=True) self.assertEqual(['uuid-child-snap'], result) @mock.patch.object(vm_utils, '_get_all_vdis_in_sr') def test_child_vhds_chain(self, mock_get_all): mock_get_all.return_value = self.all_vdis result = vm_utils._child_vhds("session", "sr_ref", ["my-uuid", "other-uuid"], old_snapshots_only=True) self.assertEqual(['uuid-child-snap'], result) def test_is_vdi_a_snapshot_works(self): vdi_rec = {"is_a_snapshot": True, "other_config": {}} self.assertTrue(vm_utils._is_vdi_a_snapshot(vdi_rec)) def test_is_vdi_a_snapshot_base_images_false(self): vdi_rec = {"is_a_snapshot": True, "other_config": {"image-id": "fake"}} self.assertFalse(vm_utils._is_vdi_a_snapshot(vdi_rec)) def test_is_vdi_a_snapshot_false_for_non_snapshot(self): vdi_rec = {"is_a_snapshot": False, "other_config": {}} self.assertFalse(vm_utils._is_vdi_a_snapshot(vdi_rec)) class RemoveOldSnapshotsTestCase(test.NoDBTestCase): @mock.patch.object(vm_utils, 'get_vdi_for_vm_safely') @mock.patch.object(vm_utils, '_walk_vdi_chain') @mock.patch.object(vm_utils, '_delete_snapshots_in_vdi_chain') def test_remove_old_snapshots(self, mock_delete, mock_walk, mock_get): instance = {"uuid": "fake"} mock_get.return_value = ("ref", {"uuid": "vdi", "SR": "sr_ref"}) mock_walk.return_value = [{"uuid": "uuid1"}, {"uuid": "uuid2"}] vm_utils.remove_old_snapshots("session", instance, "vm_ref") mock_delete.assert_called_once_with("session", instance, ["uuid1", "uuid2"], "sr_ref") mock_get.assert_called_once_with("session", "vm_ref") mock_walk.assert_called_once_with("session", "vdi") @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_no_chain(self, mock_child): instance = {"uuid": "fake"} vm_utils._delete_snapshots_in_vdi_chain("session", instance, ["uuid"], "sr") self.assertFalse(mock_child.called) @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_no_snapshots(self, mock_child): instance = {"uuid": "fake"} mock_child.return_value = [] vm_utils._delete_snapshots_in_vdi_chain("session", instance, ["uuid1", "uuid2"], "sr") mock_child.assert_called_once_with("session", "sr", ["uuid2"], old_snapshots_only=True) @mock.patch.object(vm_utils, '_scan_sr') @mock.patch.object(vm_utils, 'safe_destroy_vdis') @mock.patch.object(vm_utils, '_child_vhds') def test_delete_snapshots_in_vdi_chain_calls_destroy(self, mock_child, mock_destroy, mock_scan): instance = {"uuid": "fake"} mock_child.return_value = ["suuid1", "suuid2"] session = mock.Mock() session.VDI.get_by_uuid.side_effect = ["ref1", "ref2"] vm_utils._delete_snapshots_in_vdi_chain(session, instance, ["uuid1", "uuid2"], "sr") mock_child.assert_called_once_with(session, "sr", ["uuid2"], old_snapshots_only=True) session.VDI.get_by_uuid.assert_has_calls([ mock.call("suuid1"), mock.call("suuid2")]) mock_destroy.assert_called_once_with(session, ["ref1", "ref2"]) mock_scan.assert_called_once_with(session, "sr") class ResizeFunctionTestCase(test.NoDBTestCase): def _call_get_resize_func_name(self, brand, version): session = mock.Mock() session.product_brand = brand session.product_version = version return vm_utils._get_resize_func_name(session) def _test_is_resize(self, brand, version): result = self._call_get_resize_func_name(brand, version) self.assertEqual("VDI.resize", result) def _test_is_resize_online(self, brand, version): result = self._call_get_resize_func_name(brand, version) self.assertEqual("VDI.resize_online", result) def test_xenserver_5_5(self): self._test_is_resize_online("XenServer", (5, 5, 0)) def test_xenserver_6_0(self): self._test_is_resize("XenServer", (6, 0, 0)) def test_xcp_1_1(self): self._test_is_resize_online("XCP", (1, 1, 0)) def test_xcp_1_2(self): self._test_is_resize("XCP", (1, 2, 0)) def test_xcp_2_0(self): self._test_is_resize("XCP", (2, 0, 0)) def test_random_brand(self): self._test_is_resize("asfd", (1, 1, 0)) def test_default(self): self._test_is_resize(None, None) def test_empty(self): self._test_is_resize("", "") def test_bad_version(self): self._test_is_resize("XenServer", "asdf") class VMInfoTests(VMUtilsTestBase): def setUp(self): super(VMInfoTests, self).setUp() self.session = mock.Mock() def test_get_power_state_valid(self): self.session.call_xenapi.return_value = "Running" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.RUNNING) self.session.call_xenapi.return_value = "Halted" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.SHUTDOWN) self.session.call_xenapi.return_value = "Paused" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.PAUSED) self.session.call_xenapi.return_value = "Suspended" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.SUSPENDED) self.session.call_xenapi.return_value = "Crashed" self.assertEqual(vm_utils.get_power_state(self.session, "ref"), power_state.CRASHED) def test_get_power_state_invalid(self): self.session.call_xenapi.return_value = "Invalid" self.assertRaises(KeyError, vm_utils.get_power_state, self.session, "ref") _XAPI_record = {'power_state': 'Running', 'memory_static_max': str(10 << 10), 'memory_dynamic_max': str(9 << 10), 'VCPUs_max': '5'} def test_compile_info(self): def call_xenapi(method, *args): if method.startswith('VM.get_') and args[0] == 'dummy': return self._XAPI_record[method[7:]] self.session.call_xenapi.side_effect = call_xenapi info = vm_utils.compile_info(self.session, "dummy") self.assertEqual(hardware.InstanceInfo(state=power_state.RUNNING, max_mem_kb=10L, mem_kb=9L, num_cpu='5', cpu_time_ns=0), info)
false
true
f7278d74a416cfce5eaf0b1a81d51c2651746a7a
5,101
py
Python
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
logicmonitor_sdk/models/data_source_update_reasons_pagination_response.py
JeremyTangCD/lm-sdk-python
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ LogicMonitor REST API LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account programmatically. # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from logicmonitor_sdk.models.update_reason import UpdateReason # noqa: F401,E501 class DataSourceUpdateReasonsPaginationResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'total': 'int', 'search_id': 'str', 'items': 'list[UpdateReason]' } attribute_map = { 'total': 'total', 'search_id': 'searchId', 'items': 'items' } def __init__(self, total=None, search_id=None, items=None): # noqa: E501 """DataSourceUpdateReasonsPaginationResponse - a model defined in Swagger""" # noqa: E501 self._total = None self._search_id = None self._items = None self.discriminator = None if total is not None: self.total = total if search_id is not None: self.search_id = search_id if items is not None: self.items = items @property def total(self): """Gets the total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: int """ return self._total @total.setter def total(self, total): """Sets the total of this DataSourceUpdateReasonsPaginationResponse. :param total: The total of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: int """ self._total = total @property def search_id(self): """Gets the search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: str """ return self._search_id @search_id.setter def search_id(self, search_id): """Sets the search_id of this DataSourceUpdateReasonsPaginationResponse. :param search_id: The search_id of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: str """ self._search_id = search_id @property def items(self): """Gets the items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :return: The items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :rtype: list[UpdateReason] """ return self._items @items.setter def items(self, items): """Sets the items of this DataSourceUpdateReasonsPaginationResponse. :param items: The items of this DataSourceUpdateReasonsPaginationResponse. # noqa: E501 :type: list[UpdateReason] """ self._items = items def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(DataSourceUpdateReasonsPaginationResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DataSourceUpdateReasonsPaginationResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
30.005882
304
0.612625
import pprint import re import six from logicmonitor_sdk.models.update_reason import UpdateReason class DataSourceUpdateReasonsPaginationResponse(object): swagger_types = { 'total': 'int', 'search_id': 'str', 'items': 'list[UpdateReason]' } attribute_map = { 'total': 'total', 'search_id': 'searchId', 'items': 'items' } def __init__(self, total=None, search_id=None, items=None): self._total = None self._search_id = None self._items = None self.discriminator = None if total is not None: self.total = total if search_id is not None: self.search_id = search_id if items is not None: self.items = items @property def total(self): return self._total @total.setter def total(self, total): self._total = total @property def search_id(self): return self._search_id @search_id.setter def search_id(self, search_id): self._search_id = search_id @property def items(self): return self._items @items.setter def items(self, items): self._items = items def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(DataSourceUpdateReasonsPaginationResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, DataSourceUpdateReasonsPaginationResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f7278d910a0798fa44f63254194a56095117de1f
3,950
py
Python
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
superset/embedded/api.py
7vikpeculiar/superset
800ced5e257d5d83d6dbe4ced0e7318ac40d026f
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from typing import Optional from flask import Response from flask_appbuilder.api import expose, protect, safe from flask_appbuilder.hooks import before_request from flask_appbuilder.models.sqla.interface import SQLAInterface from superset import is_feature_enabled from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod from superset.dashboards.schemas import EmbeddedDashboardResponseSchema from superset.embedded.dao import EmbeddedDAO from superset.embedded_dashboard.commands.exceptions import ( EmbeddedDashboardNotFoundError, ) from superset.extensions import event_logger from superset.models.embedded_dashboard import EmbeddedDashboard from superset.reports.logs.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi, statsd_metrics logger = logging.getLogger(__name__) class EmbeddedDashboardRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(EmbeddedDashboard) @before_request def ensure_embedded_enabled(self) -> Optional[Response]: if not is_feature_enabled("EMBEDDED_SUPERSET"): return self.response_404() return None include_route_methods = RouteMethod.GET class_permission_name = "EmbeddedDashboard" method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP resource_name = "embedded_dashboard" allow_browser_login = True openapi_spec_tag = "Embedded Dashboard" openapi_spec_methods = openapi_spec_methods_override embedded_response_schema = EmbeddedDashboardResponseSchema() @expose("/<uuid>", methods=["GET"]) @protect() @safe @statsd_metrics @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_embedded", log_to_statsd=False, ) # pylint: disable=arguments-differ, arguments-renamed) def get(self, uuid: str) -> Response: """Response Returns the dashboard's embedded configuration --- get: description: >- Returns the dashboard's embedded configuration parameters: - in: path schema: type: string name: uuid description: The embedded configuration uuid responses: 200: description: Result contains the embedded dashboard configuration content: application/json: schema: type: object properties: result: $ref: '#/components/schemas/EmbeddedDashboardResponseSchema' 401: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ try: embedded = EmbeddedDAO.find_by_id(uuid) if not embedded: raise EmbeddedDashboardNotFoundError() result = self.embedded_response_schema.dump(embedded) return self.response(200, result=result) except EmbeddedDashboardNotFoundError: return self.response_404()
37.264151
87
0.704051
import logging from typing import Optional from flask import Response from flask_appbuilder.api import expose, protect, safe from flask_appbuilder.hooks import before_request from flask_appbuilder.models.sqla.interface import SQLAInterface from superset import is_feature_enabled from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod from superset.dashboards.schemas import EmbeddedDashboardResponseSchema from superset.embedded.dao import EmbeddedDAO from superset.embedded_dashboard.commands.exceptions import ( EmbeddedDashboardNotFoundError, ) from superset.extensions import event_logger from superset.models.embedded_dashboard import EmbeddedDashboard from superset.reports.logs.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi, statsd_metrics logger = logging.getLogger(__name__) class EmbeddedDashboardRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(EmbeddedDashboard) @before_request def ensure_embedded_enabled(self) -> Optional[Response]: if not is_feature_enabled("EMBEDDED_SUPERSET"): return self.response_404() return None include_route_methods = RouteMethod.GET class_permission_name = "EmbeddedDashboard" method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP resource_name = "embedded_dashboard" allow_browser_login = True openapi_spec_tag = "Embedded Dashboard" openapi_spec_methods = openapi_spec_methods_override embedded_response_schema = EmbeddedDashboardResponseSchema() @expose("/<uuid>", methods=["GET"]) @protect() @safe @statsd_metrics @event_logger.log_this_with_context( action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get_embedded", log_to_statsd=False, ) def get(self, uuid: str) -> Response: try: embedded = EmbeddedDAO.find_by_id(uuid) if not embedded: raise EmbeddedDashboardNotFoundError() result = self.embedded_response_schema.dump(embedded) return self.response(200, result=result) except EmbeddedDashboardNotFoundError: return self.response_404()
true
true
f7278e0192857e4135b5b9ed6748496b57e99211
1,132
py
Python
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
udemy/01_walkthrough/practice_1.py
inderpal2406/python
7bd7d03a6b3cd09ff16a4447ff495a2393a87a33
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # This script will accept user input as a string. # Then display this string in left, right, center of a line in title format. string=input("Enter the string: ") # read input string string=string.title() # convert string to title format ''' # in windows cmd, mode command tells us width of a line as 122, need to check similar command in linux # in linux terminal, 'tput cols' and 'tput rows' commands lets us know the no of columns and rows in terminal, respectively # its 142 cols in linux terminal print(f"{string.ljust(142)}") # display to left print(f"{string.center(142)}") # display at center print(f"{string.rjust(142)}") # display to right ''' # this script may not display output properly if run on linux/windows terminal on other system. # So, to overcome this, we'll use os module import os width=os.get_terminal_size().columns print(f"{string.ljust(width)}") print(f"{string.center(width)}") print(f"{string.rjust(width)}") # or instead of converting the string to title format separately, # print(f"{string.ljust(width).title()}") # we can apply title operation befor ljust operation
37.733333
123
0.736749
string=input("Enter the string: ") string=string.title() import os width=os.get_terminal_size().columns print(f"{string.ljust(width)}") print(f"{string.center(width)}") print(f"{string.rjust(width)}") # or instead of converting the string to title format separately, # print(f"{string.ljust(width).title()}") # we can apply title operation befor ljust operation
true
true
f7278f1e85d824afdd21dc3d53f33b966aca7692
5,600
py
Python
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
71
2018-06-20T12:07:34.000Z
2020-01-03T21:43:01.000Z
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
75
2018-06-20T09:46:07.000Z
2019-12-23T15:04:19.000Z
copulas/multivariate/base.py
DAI-Lab/Copulas
d634437aeac02f46615398463038455260b3de25
[ "MIT" ]
25
2018-06-24T18:01:11.000Z
2020-01-02T14:30:09.000Z
"""Base Multivariate class.""" import pickle import numpy as np from copulas import NotFittedError, get_instance, validate_random_state class Multivariate(object): """Abstract class for a multi-variate copula object.""" fitted = False def __init__(self, random_state=None): self.random_state = validate_random_state(random_state) def fit(self, X): """Fit the model to table with values from multiple random variables. Arguments: X (pandas.DataFrame): Values of the random variables. """ raise NotImplementedError def probability_density(self, X): """Compute the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the probability density will be computed. Returns: numpy.ndarray: Probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def log_probability_density(self, X): """Compute the log of the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the log probability density will be computed. Returns: numpy.ndarray: Log probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ return np.log(self.probability_density(X)) def pdf(self, X): """Compute the probability density for each point in X. Arguments: X (pandas.DataFrame): Values for which the probability density will be computed. Returns: numpy.ndarray: Probability density values for points in X. Raises: NotFittedError: if the model is not fitted. """ return self.probability_density(X) def cumulative_distribution(self, X): """Compute the cumulative distribution value for each point in X. Arguments: X (pandas.DataFrame): Values for which the cumulative distribution will be computed. Returns: numpy.ndarray: Cumulative distribution values for points in X. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def cdf(self, X): """Compute the cumulative distribution value for each point in X. Arguments: X (pandas.DataFrame): Values for which the cumulative distribution will be computed. Returns: numpy.ndarray: Cumulative distribution values for points in X. Raises: NotFittedError: if the model is not fitted. """ return self.cumulative_distribution(X) def set_random_state(self, random_state): """Set the random state. Args: random_state (int, np.random.RandomState, or None): Seed or RandomState for the random generator. """ self.random_state = validate_random_state(random_state) def sample(self, num_rows=1): """Sample values from this model. Argument: num_rows (int): Number of rows to sample. Returns: numpy.ndarray: Array of shape (n_samples, *) with values randomly sampled from this model distribution. Raises: NotFittedError: if the model is not fitted. """ raise NotImplementedError def to_dict(self): """Return a `dict` with the parameters to replicate this object. Returns: dict: Parameters of this distribution. """ raise NotImplementedError @classmethod def from_dict(cls, params): """Create a new instance from a parameters dictionary. Args: params (dict): Parameters of the distribution, in the same format as the one returned by the ``to_dict`` method. Returns: Multivariate: Instance of the distribution defined on the parameters. """ multivariate_class = get_instance(params['type']) return multivariate_class.from_dict(params) @classmethod def load(cls, path): """Load a Multivariate instance from a pickle file. Args: path (str): Path to the pickle file where the distribution has been serialized. Returns: Multivariate: Loaded instance. """ with open(path, 'rb') as pickle_file: return pickle.load(pickle_file) def save(self, path): """Serialize this multivariate instance using pickle. Args: path (str): Path to where this distribution will be serialized. """ with open(path, 'wb') as pickle_file: pickle.dump(self, pickle_file) def check_fit(self): """Check whether this model has already been fit to a random variable. Raise a ``NotFittedError`` if it has not. Raises: NotFittedError: if the model is not fitted. """ if not self.fitted: raise NotFittedError('This model is not fitted.')
28
83
0.574821
import pickle import numpy as np from copulas import NotFittedError, get_instance, validate_random_state class Multivariate(object): fitted = False def __init__(self, random_state=None): self.random_state = validate_random_state(random_state) def fit(self, X): raise NotImplementedError def probability_density(self, X): raise NotImplementedError def log_probability_density(self, X): return np.log(self.probability_density(X)) def pdf(self, X): return self.probability_density(X) def cumulative_distribution(self, X): raise NotImplementedError def cdf(self, X): return self.cumulative_distribution(X) def set_random_state(self, random_state): self.random_state = validate_random_state(random_state) def sample(self, num_rows=1): raise NotImplementedError def to_dict(self): raise NotImplementedError @classmethod def from_dict(cls, params): multivariate_class = get_instance(params['type']) return multivariate_class.from_dict(params) @classmethod def load(cls, path): with open(path, 'rb') as pickle_file: return pickle.load(pickle_file) def save(self, path): with open(path, 'wb') as pickle_file: pickle.dump(self, pickle_file) def check_fit(self): if not self.fitted: raise NotFittedError('This model is not fitted.')
true
true
f7278fb2e4cecf1623625e589a46c10c6f0fc89f
2,209
py
Python
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
1
2020-03-02T05:02:33.000Z
2020-03-02T05:02:33.000Z
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
null
null
null
lowder/__init__.py
jabernardo/lowder
d7ddc7d2217ba4ab3f2a4f00314b600af9cf0e70
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import time import threading LOADERS = { 'default': { 'interval': 0.1, 'frames': ('/', '-', '|', '\\', '-') }, 'dots': { 'interval': 0.2, 'frames': ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏') }, 'dots-bar': { 'interval': 0.2, 'frames': ('. ', ' . ', ' . ',' . ', ' .', ' . ', ' . ', ' . ') }, 'bar': { 'interval': 0.2, 'frames': ('- ', ' = ', ' - ',' = ', ' -', ' = ', ' - ', ' = ') }, 'arrow': { 'interval': 0.2, 'frames': ('> ', ' > ', ' > ',' > ', ' >', ' < ', ' < ', ' < ') } } class Lowder: __run = True __loader_screen = LOADERS['default'] __result = None __loading_message = "" def __init__(self): super().__init__() def stop(self, message = None): self.__run = False cols = len(self.__loading_message) if not message is None: print(f"\x1b[${cols}D\x1b[K{message}") else: print(f"\x1b[${cols}D\x1b[K", end="\r") def __loader(self, message): while self.__run: for char in self.__loader_screen['frames']: cols = len(message) self.__loading_message = f"\x1b[${cols}D\x1b[K{char} {message}" if self.__run: print(self.__loading_message, end="\r") time.sleep(self.__loader_screen['interval']) def __call(self, callback): self.__result = callback() def start(self, message, callback, loader = LOADERS['default']): self.__loader_screen = loader self.__run = True y = threading.Thread(target=self.__call, args=(callback,)) y.start() x = threading.Thread(target=self.__loader, args=(message,)) x.start() x.join() y.join() return self.__result
28.320513
79
0.383884
import time import threading LOADERS = { 'default': { 'interval': 0.1, 'frames': ('/', '-', '|', '\\', '-') }, 'dots': { 'interval': 0.2, 'frames': ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏') }, 'dots-bar': { 'interval': 0.2, 'frames': ('. ', ' . ', ' . ',' . ', ' .', ' . ', ' . ', ' . ') }, 'bar': { 'interval': 0.2, 'frames': ('- ', ' = ', ' - ',' = ', ' -', ' = ', ' - ', ' = ') }, 'arrow': { 'interval': 0.2, 'frames': ('> ', ' > ', ' > ',' > ', ' >', ' < ', ' < ', ' < ') } } class Lowder: __run = True __loader_screen = LOADERS['default'] __result = None __loading_message = "" def __init__(self): super().__init__() def stop(self, message = None): self.__run = False cols = len(self.__loading_message) if not message is None: print(f"\x1b[${cols}D\x1b[K{message}") else: print(f"\x1b[${cols}D\x1b[K", end="\r") def __loader(self, message): while self.__run: for char in self.__loader_screen['frames']: cols = len(message) self.__loading_message = f"\x1b[${cols}D\x1b[K{char} {message}" if self.__run: print(self.__loading_message, end="\r") time.sleep(self.__loader_screen['interval']) def __call(self, callback): self.__result = callback() def start(self, message, callback, loader = LOADERS['default']): self.__loader_screen = loader self.__run = True y = threading.Thread(target=self.__call, args=(callback,)) y.start() x = threading.Thread(target=self.__loader, args=(message,)) x.start() x.join() y.join() return self.__result
true
true
f72790e1400c04034e99a0a996957a5a2bd3bdfa
14,106
py
Python
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
4
2021-10-18T05:15:59.000Z
2022-03-09T04:29:05.000Z
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
null
null
null
giung2/modeling/backbone/resnet.py
cs-giung/giung2
c8560fd1b56f20eb1f3cf57202975d8325b591f5
[ "MIT" ]
3
2022-01-12T11:47:51.000Z
2022-03-18T06:28:22.000Z
import torch import torch.nn as nn from typing import Dict, List from functools import partial from fvcore.common.config import CfgNode from giung2.layers import * __all__ = [ "build_resnet_backbone", ] class IdentityShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(IdentityShortcut, self).__init__() self.identity = MaxPool2d(kernel_size=1, stride=stride) self.pad_size = expansion * planes - in_planes def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.identity(x) out = nn.functional.pad(out, (0, 0, 0, 0, 0, self.pad_size), mode="constant", value=0) return out class ProjectionShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ProjectionShortcut, self).__init__() self.conv = conv(in_channels=in_planes, out_channels=expansion*planes, kernel_size=1, stride=stride, padding=0, **kwargs) self.norm = norm(num_features=expansion*planes) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.norm(self.conv(x, **kwargs), **kwargs) return out class FirstBlock(nn.Module): def __init__( self, in_planes: int, planes: int, conv: nn.Module, conv_ksp: List[int], norm: nn.Module, relu: nn.Module, pool: nn.Module, pool_ksp: List[int], **kwargs ) -> None: super(FirstBlock, self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=conv_ksp[0], stride=conv_ksp[1], padding=conv_ksp[2], **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.pool1 = pool(kernel_size=pool_ksp[0], stride=pool_ksp[1], padding=pool_ksp[2]) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.pool1(self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs), **kwargs) return out class BasicBlock(nn.Module): expansion = 1 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(BasicBlock,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=3, stride=1, padding=1, **kwargs) self.norm2 = norm(num_features=self.expansion*planes) self.relu2 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class Bottleneck(nn.Module): expansion = 4 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(Bottleneck,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm2 = norm(num_features=planes) self.relu2 = relu() self.conv3 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm3 = norm(num_features=self.expansion*planes) self.relu3 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs), **kwargs) out = self.relu3(self.norm3(self.conv3(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class ResNet(nn.Module): def __init__( self, channels: int, in_planes: int, first_block: nn.Module, block: nn.Module, shortcut: nn.Module, num_blocks: List[int], widen_factor: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ResNet, self).__init__() self.channels = channels self.in_planes = in_planes self._in_planes = in_planes self.first_block = first_block self.block = block self.shortcut = shortcut self.num_blocks = num_blocks self.widen_factor = widen_factor self.conv = conv self.norm = norm self.relu = relu _layers = [self.first_block(in_planes=self.channels, planes=self.in_planes, **kwargs)] _layers += self._make_layer( self.in_planes * self.widen_factor, self.num_blocks[0], stride=1, **kwargs ) for idx, num_block in enumerate(self.num_blocks[1:], start=1): _layers += self._make_layer( self.in_planes * (2 ** idx) * self.widen_factor, num_block, stride=2, **kwargs ) self.layers = nn.Sequential(*_layers) def _make_layer(self, planes: int, num_block: int, stride: int, **kwargs) -> List[nn.Module]: strides = [stride] + [1] * (num_block - 1) _layers = [] for stride in strides: _layers.append(self.block(self._in_planes, planes, stride, self.shortcut, self.conv, self.norm, self.relu, **kwargs)) self._in_planes = planes * self.block.expansion return _layers def forward(self, x: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]: outputs = dict() # intermediate feature maps for layer_idx, layer in enumerate(self.layers): x = layer(x, **kwargs) outputs[f"layer{layer_idx}"] = x # final feature vector x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) outputs["features"] = x return outputs def build_resnet_backbone(cfg: CfgNode) -> nn.Module: # Conv2d layers may be replaced by its variations _conv_layers = cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS kwargs = { "bias": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_BIAS, "same_padding": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_SAME_PADDING, } if _conv_layers == "Conv2d": conv_layers = Conv2d elif _conv_layers == "Conv2d_Bezier": conv_layers = Conv2d_Bezier elif _conv_layers in ["Conv2d_BatchEnsemble", "Conv2d_BatchEnsembleV2",]: if cfg.MODEL.BATCH_ENSEMBLE.ENABLED is False: raise AssertionError( f"Set MODEL.BATCH_ENSEMBLE.ENABLED=True to use {_conv_layers}" ) if _conv_layers == "Conv2d_BatchEnsemble": conv_layers = Conv2d_BatchEnsemble if _conv_layers == "Conv2d_BatchEnsembleV2": conv_layers = Conv2d_BatchEnsembleV2 kwargs.update({ "ensemble_size": cfg.MODEL.BATCH_ENSEMBLE.ENSEMBLE_SIZE, "use_ensemble_bias": cfg.MODEL.BATCH_ENSEMBLE.USE_ENSEMBLE_BIAS, "alpha_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.VALUES, }, "gamma_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.VALUES, }, }) elif _conv_layers == "Conv2d_Dropout": if cfg.MODEL.DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_Dropout kwargs.update({ "drop_p": cfg.MODEL.DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_SpatialDropout": if cfg.MODEL.SPATIAL_DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.SPATIAL_DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_SpatialDropout kwargs.update({ "drop_p": cfg.MODEL.SPATIAL_DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_DropBlock": if cfg.MODEL.DROP_BLOCK.ENABLED is False: raise AssertionError( f"Set MODEL.DROP_BLOCK.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_DropBlock kwargs.update({ "drop_p": cfg.MODEL.DROP_BLOCK.DROP_PROBABILITY, "block_size": cfg.MODEL.DROP_BLOCK.BLOCK_SIZE, "use_shared_masks": cfg.MODEL.DROP_BLOCK.USE_SHARED_MASKS, }) else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.CONV_LAYERS: {_conv_layers}" ) # BatchNorm2d layers may be replaced by its variations _norm_layers = cfg.MODEL.BACKBONE.RESNET.NORM_LAYERS if _norm_layers == "NONE": norm_layers = Identity elif _norm_layers == "BatchNorm2d": norm_layers = BatchNorm2d elif _norm_layers == "GroupNorm2d": norm_layers = partial(GroupNorm2d, num_groups=cfg.MODEL.BACKBONE.RESNET.IN_PLANES // 2) elif _norm_layers == "FilterResponseNorm2d": norm_layers = FilterResponseNorm2d elif _norm_layers == "FilterResponseNorm2d_Bezier": norm_layers = FilterResponseNorm2d_Bezier else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.NORM_LAYERS: {_norm_layers}" ) # ReLU layers may be replaced by its variations _activations = cfg.MODEL.BACKBONE.RESNET.ACTIVATIONS if _activations == "NONE": activations = Identity elif _activations == "ReLU": activations = ReLU elif _activations == "SiLU": activations = SiLU else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.ACTIVATIONS: {_activations}" ) # specify the first block first_block = partial( FirstBlock, conv = conv_layers, conv_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.CONV_KSP, norm = norm_layers if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_NORM_LAYER else Identity, relu = activations if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_ACTIVATION else Identity, pool = MaxPool2d if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_POOL_LAYER else Identity, pool_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.POOL_KSP, ) # specify block _block = cfg.MODEL.BACKBONE.RESNET.BLOCK if _block == "BasicBlock": block = BasicBlock elif _block == "Bottleneck": block = Bottleneck else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.BLOCK: {_block}" ) # specify shortcut _shortcut = cfg.MODEL.BACKBONE.RESNET.SHORTCUT if _shortcut == "IdentityShortcut": shortcut = IdentityShortcut elif _shortcut == "ProjectionShortcut": shortcut = ProjectionShortcut else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.SHORTCUT: {_shortcut}" ) # build backbone backbone = ResNet( channels = cfg.MODEL.BACKBONE.RESNET.CHANNELS, in_planes = cfg.MODEL.BACKBONE.RESNET.IN_PLANES, first_block = first_block, block = block, shortcut = shortcut, num_blocks = cfg.MODEL.BACKBONE.RESNET.NUM_BLOCKS, widen_factor = cfg.MODEL.BACKBONE.RESNET.WIDEN_FACTOR, conv = conv_layers, norm = norm_layers, relu = activations, **kwargs ) # initialize weights for m in backbone.modules(): if isinstance(m, Conv2d): if isinstance(m.weight, nn.ParameterList): for idx in range(len(m.weight)): nn.init.kaiming_normal_(m.weight[idx], mode="fan_out", nonlinearity="relu") else: nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") return backbone
36.638961
112
0.59223
import torch import torch.nn as nn from typing import Dict, List from functools import partial from fvcore.common.config import CfgNode from giung2.layers import * __all__ = [ "build_resnet_backbone", ] class IdentityShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(IdentityShortcut, self).__init__() self.identity = MaxPool2d(kernel_size=1, stride=stride) self.pad_size = expansion * planes - in_planes def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.identity(x) out = nn.functional.pad(out, (0, 0, 0, 0, 0, self.pad_size), mode="constant", value=0) return out class ProjectionShortcut(nn.Module): def __init__( self, in_planes: int, planes: int, stride: int, expansion: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ProjectionShortcut, self).__init__() self.conv = conv(in_channels=in_planes, out_channels=expansion*planes, kernel_size=1, stride=stride, padding=0, **kwargs) self.norm = norm(num_features=expansion*planes) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.norm(self.conv(x, **kwargs), **kwargs) return out class FirstBlock(nn.Module): def __init__( self, in_planes: int, planes: int, conv: nn.Module, conv_ksp: List[int], norm: nn.Module, relu: nn.Module, pool: nn.Module, pool_ksp: List[int], **kwargs ) -> None: super(FirstBlock, self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=conv_ksp[0], stride=conv_ksp[1], padding=conv_ksp[2], **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.pool1 = pool(kernel_size=pool_ksp[0], stride=pool_ksp[1], padding=pool_ksp[2]) def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.pool1(self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs), **kwargs) return out class BasicBlock(nn.Module): expansion = 1 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(BasicBlock,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=3, stride=1, padding=1, **kwargs) self.norm2 = norm(num_features=self.expansion*planes) self.relu2 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class Bottleneck(nn.Module): expansion = 4 def __init__( self, in_planes: int, planes: int, stride: int, shortcut: nn.Module, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(Bottleneck,self).__init__() self.conv1 = conv(in_channels=in_planes, out_channels=planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm1 = norm(num_features=planes) self.relu1 = relu() self.conv2 = conv(in_channels=planes, out_channels=planes, kernel_size=3, stride=stride, padding=1, **kwargs) self.norm2 = norm(num_features=planes) self.relu2 = relu() self.conv3 = conv(in_channels=planes, out_channels=self.expansion*planes, kernel_size=1, stride=1, padding=0, **kwargs) self.norm3 = norm(num_features=self.expansion*planes) self.relu3 = relu() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = shortcut( in_planes, planes, stride, self.expansion, conv, norm, **kwargs ) else: self.shortcut = Identity() def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor: out = self.relu1(self.norm1(self.conv1(x, **kwargs), **kwargs), **kwargs) out = self.relu2(self.norm2(self.conv2(out, **kwargs), **kwargs), **kwargs) out = self.relu3(self.norm3(self.conv3(out, **kwargs), **kwargs) + self.shortcut(x, **kwargs), **kwargs) return out class ResNet(nn.Module): def __init__( self, channels: int, in_planes: int, first_block: nn.Module, block: nn.Module, shortcut: nn.Module, num_blocks: List[int], widen_factor: int, conv: nn.Module = Conv2d, norm: nn.Module = BatchNorm2d, relu: nn.Module = ReLU, **kwargs ) -> None: super(ResNet, self).__init__() self.channels = channels self.in_planes = in_planes self._in_planes = in_planes self.first_block = first_block self.block = block self.shortcut = shortcut self.num_blocks = num_blocks self.widen_factor = widen_factor self.conv = conv self.norm = norm self.relu = relu _layers = [self.first_block(in_planes=self.channels, planes=self.in_planes, **kwargs)] _layers += self._make_layer( self.in_planes * self.widen_factor, self.num_blocks[0], stride=1, **kwargs ) for idx, num_block in enumerate(self.num_blocks[1:], start=1): _layers += self._make_layer( self.in_planes * (2 ** idx) * self.widen_factor, num_block, stride=2, **kwargs ) self.layers = nn.Sequential(*_layers) def _make_layer(self, planes: int, num_block: int, stride: int, **kwargs) -> List[nn.Module]: strides = [stride] + [1] * (num_block - 1) _layers = [] for stride in strides: _layers.append(self.block(self._in_planes, planes, stride, self.shortcut, self.conv, self.norm, self.relu, **kwargs)) self._in_planes = planes * self.block.expansion return _layers def forward(self, x: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]: outputs = dict() for layer_idx, layer in enumerate(self.layers): x = layer(x, **kwargs) outputs[f"layer{layer_idx}"] = x x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) outputs["features"] = x return outputs def build_resnet_backbone(cfg: CfgNode) -> nn.Module: _conv_layers = cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS kwargs = { "bias": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_BIAS, "same_padding": cfg.MODEL.BACKBONE.RESNET.CONV_LAYERS_SAME_PADDING, } if _conv_layers == "Conv2d": conv_layers = Conv2d elif _conv_layers == "Conv2d_Bezier": conv_layers = Conv2d_Bezier elif _conv_layers in ["Conv2d_BatchEnsemble", "Conv2d_BatchEnsembleV2",]: if cfg.MODEL.BATCH_ENSEMBLE.ENABLED is False: raise AssertionError( f"Set MODEL.BATCH_ENSEMBLE.ENABLED=True to use {_conv_layers}" ) if _conv_layers == "Conv2d_BatchEnsemble": conv_layers = Conv2d_BatchEnsemble if _conv_layers == "Conv2d_BatchEnsembleV2": conv_layers = Conv2d_BatchEnsembleV2 kwargs.update({ "ensemble_size": cfg.MODEL.BATCH_ENSEMBLE.ENSEMBLE_SIZE, "use_ensemble_bias": cfg.MODEL.BATCH_ENSEMBLE.USE_ENSEMBLE_BIAS, "alpha_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.ALPHA_INITIALIZER.VALUES, }, "gamma_initializer": { "initializer": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.NAME, "init_values": cfg.MODEL.BATCH_ENSEMBLE.GAMMA_INITIALIZER.VALUES, }, }) elif _conv_layers == "Conv2d_Dropout": if cfg.MODEL.DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_Dropout kwargs.update({ "drop_p": cfg.MODEL.DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_SpatialDropout": if cfg.MODEL.SPATIAL_DROPOUT.ENABLED is False: raise AssertionError( f"Set MODEL.SPATIAL_DROPOUT.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_SpatialDropout kwargs.update({ "drop_p": cfg.MODEL.SPATIAL_DROPOUT.DROP_PROBABILITY, }) elif _conv_layers == "Conv2d_DropBlock": if cfg.MODEL.DROP_BLOCK.ENABLED is False: raise AssertionError( f"Set MODEL.DROP_BLOCK.ENABLED=True to use {_conv_layers}" ) conv_layers = Conv2d_DropBlock kwargs.update({ "drop_p": cfg.MODEL.DROP_BLOCK.DROP_PROBABILITY, "block_size": cfg.MODEL.DROP_BLOCK.BLOCK_SIZE, "use_shared_masks": cfg.MODEL.DROP_BLOCK.USE_SHARED_MASKS, }) else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.CONV_LAYERS: {_conv_layers}" ) _norm_layers = cfg.MODEL.BACKBONE.RESNET.NORM_LAYERS if _norm_layers == "NONE": norm_layers = Identity elif _norm_layers == "BatchNorm2d": norm_layers = BatchNorm2d elif _norm_layers == "GroupNorm2d": norm_layers = partial(GroupNorm2d, num_groups=cfg.MODEL.BACKBONE.RESNET.IN_PLANES // 2) elif _norm_layers == "FilterResponseNorm2d": norm_layers = FilterResponseNorm2d elif _norm_layers == "FilterResponseNorm2d_Bezier": norm_layers = FilterResponseNorm2d_Bezier else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.NORM_LAYERS: {_norm_layers}" ) _activations = cfg.MODEL.BACKBONE.RESNET.ACTIVATIONS if _activations == "NONE": activations = Identity elif _activations == "ReLU": activations = ReLU elif _activations == "SiLU": activations = SiLU else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.ACTIVATIONS: {_activations}" ) first_block = partial( FirstBlock, conv = conv_layers, conv_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.CONV_KSP, norm = norm_layers if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_NORM_LAYER else Identity, relu = activations if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_ACTIVATION else Identity, pool = MaxPool2d if cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_POOL_LAYER else Identity, pool_ksp = cfg.MODEL.BACKBONE.RESNET.FIRST_BLOCK.POOL_KSP, ) _block = cfg.MODEL.BACKBONE.RESNET.BLOCK if _block == "BasicBlock": block = BasicBlock elif _block == "Bottleneck": block = Bottleneck else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.BLOCK: {_block}" ) _shortcut = cfg.MODEL.BACKBONE.RESNET.SHORTCUT if _shortcut == "IdentityShortcut": shortcut = IdentityShortcut elif _shortcut == "ProjectionShortcut": shortcut = ProjectionShortcut else: raise NotImplementedError( f"Unknown MODEL.BACKBONE.RESNET.SHORTCUT: {_shortcut}" ) backbone = ResNet( channels = cfg.MODEL.BACKBONE.RESNET.CHANNELS, in_planes = cfg.MODEL.BACKBONE.RESNET.IN_PLANES, first_block = first_block, block = block, shortcut = shortcut, num_blocks = cfg.MODEL.BACKBONE.RESNET.NUM_BLOCKS, widen_factor = cfg.MODEL.BACKBONE.RESNET.WIDEN_FACTOR, conv = conv_layers, norm = norm_layers, relu = activations, **kwargs ) for m in backbone.modules(): if isinstance(m, Conv2d): if isinstance(m.weight, nn.ParameterList): for idx in range(len(m.weight)): nn.init.kaiming_normal_(m.weight[idx], mode="fan_out", nonlinearity="relu") else: nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") return backbone
true
true
f727917d0f068e8d6007ff3141a9580153e749e9
4,756
py
Python
dipy/data/tests/test_fetcher.py
nasimanousheh/dipy
d737a6af80a184322e30de4760e8c205291dbed0
[ "MIT" ]
2
2018-07-25T14:04:20.000Z
2021-02-10T07:10:10.000Z
dipy/data/tests/test_fetcher.py
aarya22/dipy-reco1
9d20c911b4afe83e52ded698eff9ba0f0fafeca8
[ "MIT" ]
null
null
null
dipy/data/tests/test_fetcher.py
aarya22/dipy-reco1
9d20c911b4afe83e52ded698eff9ba0f0fafeca8
[ "MIT" ]
2
2018-07-24T21:20:54.000Z
2018-08-27T04:08:24.000Z
import tempfile import os.path as op import sys import os import numpy.testing as npt from nibabel.tmpdirs import TemporaryDirectory import dipy.data.fetcher as fetcher from dipy.data import SPHERE_FILES from threading import Thread if sys.version_info[0] < 3: from SimpleHTTPServer import SimpleHTTPRequestHandler # Python 2 from SocketServer import TCPServer as HTTPServer else: from http.server import HTTPServer, SimpleHTTPRequestHandler # Python 3 def test_check_md5(): fd, fname = tempfile.mkstemp() stored_md5 = fetcher._get_file_md5(fname) # If all is well, this shouldn't return anything: npt.assert_equal(fetcher.check_md5(fname, stored_md5), None) # If None is provided as input, it should silently not check either: npt.assert_equal(fetcher.check_md5(fname, None), None) # Otherwise, it will raise its exception class: npt.assert_raises(fetcher.FetcherError, fetcher.check_md5, fname, 'foo') def test_make_fetcher(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: stored_md5 = fetcher._get_file_md5(symmetric362) # create local HTTP Server testfile_url = op.split(symmetric362)[0] + os.sep test_server_url = "http://127.0.0.1:8000/" print(testfile_url) print(symmetric362) current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_url) server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() # test make_fetcher sphere_fetcher = fetcher._make_fetcher("sphere_fetcher", tmpdir, test_server_url, [op.split(symmetric362)[-1]], ["sphere_name"], md5_list=[stored_md5]) sphere_fetcher() assert op.isfile(op.join(tmpdir, "sphere_name")) npt.assert_equal(fetcher._get_file_md5(op.join(tmpdir, "sphere_name")), stored_md5) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) # Test that an error is raised when the md5 checksum of the download # file does not match the expected value files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_dipy_home(): test_path = 'TEST_PATH' if 'DIPY_HOME' in os.environ: old_home = os.environ['DIPY_HOME'] del os.environ['DIPY_HOME'] else: old_home = None reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, op.join(os.path.expanduser('~'), '.dipy')) os.environ['DIPY_HOME'] = test_path reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, test_path) # return to previous state if old_home: os.environ['DIPY_HOME'] = old_home
37.448819
79
0.634567
import tempfile import os.path as op import sys import os import numpy.testing as npt from nibabel.tmpdirs import TemporaryDirectory import dipy.data.fetcher as fetcher from dipy.data import SPHERE_FILES from threading import Thread if sys.version_info[0] < 3: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer as HTTPServer else: from http.server import HTTPServer, SimpleHTTPRequestHandler def test_check_md5(): fd, fname = tempfile.mkstemp() stored_md5 = fetcher._get_file_md5(fname) npt.assert_equal(fetcher.check_md5(fname, stored_md5), None) # If None is provided as input, it should silently not check either: npt.assert_equal(fetcher.check_md5(fname, None), None) # Otherwise, it will raise its exception class: npt.assert_raises(fetcher.FetcherError, fetcher.check_md5, fname, 'foo') def test_make_fetcher(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: stored_md5 = fetcher._get_file_md5(symmetric362) # create local HTTP Server testfile_url = op.split(symmetric362)[0] + os.sep test_server_url = "http://127.0.0.1:8000/" print(testfile_url) print(symmetric362) current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_url) server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() # test make_fetcher sphere_fetcher = fetcher._make_fetcher("sphere_fetcher", tmpdir, test_server_url, [op.split(symmetric362)[-1]], ["sphere_name"], md5_list=[stored_md5]) sphere_fetcher() assert op.isfile(op.join(tmpdir, "sphere_name")) npt.assert_equal(fetcher._get_file_md5(op.join(tmpdir, "sphere_name")), stored_md5) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) server.shutdown() os.chdir(current_dir) def test_dipy_home(): test_path = 'TEST_PATH' if 'DIPY_HOME' in os.environ: old_home = os.environ['DIPY_HOME'] del os.environ['DIPY_HOME'] else: old_home = None reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, op.join(os.path.expanduser('~'), '.dipy')) os.environ['DIPY_HOME'] = test_path reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, test_path) if old_home: os.environ['DIPY_HOME'] = old_home
true
true
f727925dfeb5359a5f6f7116be96d12c7354d32c
4,577
py
Python
jarviscli/plugins/bmr.py
jronzo99/Jarvis
d63b51a1a7cb5bbff36e6e7dc3c63201ae1470b2
[ "MIT" ]
1
2021-05-25T11:29:25.000Z
2021-05-25T11:29:25.000Z
jarviscli/plugins/bmr.py
nikiboura/Jarvis
eb22f7c84a345e9ae5925b4b98adbc4f2e4a93f3
[ "MIT" ]
null
null
null
jarviscli/plugins/bmr.py
nikiboura/Jarvis
eb22f7c84a345e9ae5925b4b98adbc4f2e4a93f3
[ "MIT" ]
null
null
null
from colorama import Fore from plugin import plugin @plugin("bmr") def bmr(jarvis, s): """A Jarvis plugin to calculate your Basal Metabolic Rate (BMR) and your Active Metabolic Rate(AMR)""" jarvis.say("Hello there! Ready to count your BMR? \n") jarvis.say("1. Yes, let's start! \n2. Sorry," " I don't know what BMR is :( \n ") jarvis.say("Please enter your choice: ") # validate the input for choice choice = jarvis.input() while True: if choice == "1" or choice == "2": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") choice = jarvis.input() # print definition of BMR if choice == "2": jarvis.say("\nBasal Metabolic Rate (BMR)", Fore.GREEN) jarvis.say("is the number of calories your body needs" "\nto accomplish its most basic (basal)\n" "life-sustaining functions. \n") jarvis.say("Since you know now, let's calculate it! \n") # gets inputs and makes the necessary checks jarvis.say("What's your gender? (M/F)") while True: sex = jarvis.input() # ignore lower or upper letters if sex.upper() == "M" or sex.upper() == "F": break jarvis.say("Sorry, invalid input was given!" "Please try again. (M/F)") jarvis.say("What is your height (cm) ?") while True: try: height = int(jarvis.input()) if height <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your weight (kg) ?") while True: try: weight = int(jarvis.input()) if weight <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your age ?") while True: try: age = int(jarvis.input()) if age <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") # formula changes based on sex if sex.upper() == 'F': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 116 elif sex.upper() == 'M': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 5 jarvis.say("BMR: " + str(bmr), Fore.GREEN) jarvis.say("\nNow that you know your BMR,\nwould you like to calculate " "your AMR too based on it?\n") # print definition of AMR jarvis.say("Active Metabolic Rate (AMR)", Fore.GREEN) jarvis.say("is the actual amount of calories you burn\n" "each day due to physical activities\n" "like going to the gym, aerobics\n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() # choice of calculating the amr or not while True: if amr_choice.upper() == "Y" or amr_choice.upper() == "N": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() if amr_choice.upper() == "N": jarvis.say("Okay, bye!", Fore.BLUE) else: jarvis.say("Please enter your exercise level: \n") jarvis.say("1.Low\n2.Average\n3.High\n4.Every Day\n5.Athletic") jarvis.say("Please enter your choice: ") # input for exercise level # based on the above choices exercise_level = jarvis.input() level_choices = ("1", "2", "3", "4", "5") while True: if exercise_level in level_choices: break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() # calculate the amr # depending on the exercise level if exercise_level == "1": amr = bmr * 1.2 if exercise_level == "2": amr = bmr * 1.375 if exercise_level == "3": amr = bmr * 1.55 if exercise_level == "4": amr = bmr * 1.725 if exercise_level == "5": amr = bmr * 1.9 jarvis.say("AMR: " + str(amr), Fore.GREEN)
35.757813
76
0.537688
from colorama import Fore from plugin import plugin @plugin("bmr") def bmr(jarvis, s): jarvis.say("Hello there! Ready to count your BMR? \n") jarvis.say("1. Yes, let's start! \n2. Sorry," " I don't know what BMR is :( \n ") jarvis.say("Please enter your choice: ") choice = jarvis.input() while True: if choice == "1" or choice == "2": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") choice = jarvis.input() if choice == "2": jarvis.say("\nBasal Metabolic Rate (BMR)", Fore.GREEN) jarvis.say("is the number of calories your body needs" "\nto accomplish its most basic (basal)\n" "life-sustaining functions. \n") jarvis.say("Since you know now, let's calculate it! \n") # gets inputs and makes the necessary checks jarvis.say("What's your gender? (M/F)") while True: sex = jarvis.input() if sex.upper() == "M" or sex.upper() == "F": break jarvis.say("Sorry, invalid input was given!" "Please try again. (M/F)") jarvis.say("What is your height (cm) ?") while True: try: height = int(jarvis.input()) if height <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your weight (kg) ?") while True: try: weight = int(jarvis.input()) if weight <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") jarvis.say("What is your age ?") while True: try: age = int(jarvis.input()) if age <= 0: raise ValueError break except ValueError: print("Oops! That was no valid number. Try again...") if sex.upper() == 'F': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 116 elif sex.upper() == 'M': bmr = (float(height) * 6.25) + (float(weight) * 9.99) - \ (float(age) * 4.92) - 5 jarvis.say("BMR: " + str(bmr), Fore.GREEN) jarvis.say("\nNow that you know your BMR,\nwould you like to calculate " "your AMR too based on it?\n") jarvis.say("Active Metabolic Rate (AMR)", Fore.GREEN) jarvis.say("is the actual amount of calories you burn\n" "each day due to physical activities\n" "like going to the gym, aerobics\n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() while True: if amr_choice.upper() == "Y" or amr_choice.upper() == "N": break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice(Y/N): ") amr_choice = jarvis.input() if amr_choice.upper() == "N": jarvis.say("Okay, bye!", Fore.BLUE) else: jarvis.say("Please enter your exercise level: \n") jarvis.say("1.Low\n2.Average\n3.High\n4.Every Day\n5.Athletic") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() level_choices = ("1", "2", "3", "4", "5") while True: if exercise_level in level_choices: break else: jarvis.say("Sorry, invalid input was given. Try again! \n") jarvis.say("Please enter your choice: ") exercise_level = jarvis.input() if exercise_level == "1": amr = bmr * 1.2 if exercise_level == "2": amr = bmr * 1.375 if exercise_level == "3": amr = bmr * 1.55 if exercise_level == "4": amr = bmr * 1.725 if exercise_level == "5": amr = bmr * 1.9 jarvis.say("AMR: " + str(amr), Fore.GREEN)
true
true
f7279315c269b9d8ccac798e0d91c3ab9cba61d7
3,834
py
Python
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
1
2021-05-18T04:04:31.000Z
2021-05-18T04:04:31.000Z
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
null
null
null
Project/_visualize.py
BendeguzToth/NeuralLanguageModel
f4bb60375019acd57c7396768d62ad0f3166391c
[ "MIT" ]
null
null
null
""" In this file we visualize the activations of particular neurons, at different positions of a provided sample text. """ # Standard libraries import json import tkinter as tk # Third-party libraries import numpy as np # Project files from layers import LSTM # SETUP MODEL = "saves/ShakespeareNet.json" LOOKUP_FILE = "saves/ShakespeareLookup.json" TEXT_FILE = "saves/sample.txt" def main(): with open(LOOKUP_FILE, 'r') as file: chars = json.load(file) # Here we make dictionaries that can be used to convert # between characters, integer id-s of characters, and one-hot # vectors that will be used to represent the characters. char_to_int = dict() int_to_char = dict() char_to_vec = dict() for i in range(len(chars)): char_to_int[chars[i]] = i int_to_char[i] = chars[i] vec = np.zeros((len(chars), 1)) vec[i] = 1. char_to_vec[chars[i]] = vec # The length of the vector that represents a character # is equivalent to the number of different characters # in the text. EMBEDDING_LENGTH = len(chars) # Create the LSTM layers only. We don't use the Network class, # since we are only interested in the activations of the recurrent # layers. first_layer = LSTM(size=512, input_size=EMBEDDING_LENGTH, batch_size=1, backprop_depth=1, stateful=True) second_layer = LSTM(size=512, input_size=512, batch_size=1, backprop_depth=1, stateful=True) # Load the weights. with open(MODEL, 'r') as file: weights = json.load(file) first_layer.loadParams(weights[0]) second_layer.loadParams(weights[1]) # Loading in the file. with open(TEXT_FILE, 'r', encoding='utf8') as file: text = file.read() source = list(text) for i in range(len(source)): source[i] = char_to_vec[source[i]] # Feed the text to the network. # Here we look at the activation of the neurons of the # hidden state at the 2nd LSTM layer. # We take the first element of the output as there is only one # batch. out = second_layer.forward(first_layer.forward(np.array([source])))[0] # ###############---TKINTER---############################################# class Wrap: NEURON_INDEX = 0 def showNeuron(): for j in range(out.shape[0]): # We will leave the background of the newline characters white, # regardless of its activation. The reason for that is that the color # would fill the entire remainder of the line, which is very disturbing to look at. intensity = 255 if text[j] == '\n' else 255 - int((out[j, Wrap.NEURON_INDEX, 0] + 1) * 127.5) text_box.tag_config(str(j), background="#%02x%02x%02x" % ( 255, intensity, intensity)) def inputFromEntry(evt): Wrap.NEURON_INDEX = int(entry.get()) entry.delete(0, "end") showNeuron() def nextButtonClicked(): Wrap.NEURON_INDEX += 1 entry.delete(0, "end") entry.insert(tk.INSERT, str(Wrap.NEURON_INDEX)) showNeuron() # Making the tkinter window. root = tk.Tk() text_box = tk.Text(root, height=35) text_box.insert(tk.INSERT, text) text_box.pack() current_line = 1 current_char = 0 for i in range(out.shape[0]): text_box.tag_add(str(i), f"{current_line}.{current_char}") current_char += 1 if text[i] == '\n': current_line += 1 current_char = 0 # Making the entry box. entry = tk.Entry(root, width=5) entry.pack() entry.bind("<Return>", inputFromEntry) # Buttons up = tk.Button(text="Next", command=nextButtonClicked) up.pack() # Show the first neuron by default. showNeuron() root.mainloop() if __name__ == '__main__': main()
30.188976
108
0.628326
import json import tkinter as tk import numpy as np from layers import LSTM MODEL = "saves/ShakespeareNet.json" LOOKUP_FILE = "saves/ShakespeareLookup.json" TEXT_FILE = "saves/sample.txt" def main(): with open(LOOKUP_FILE, 'r') as file: chars = json.load(file) char_to_int = dict() int_to_char = dict() char_to_vec = dict() for i in range(len(chars)): char_to_int[chars[i]] = i int_to_char[i] = chars[i] vec = np.zeros((len(chars), 1)) vec[i] = 1. char_to_vec[chars[i]] = vec EMBEDDING_LENGTH = len(chars) # since we are only interested in the activations of the recurrent # layers. first_layer = LSTM(size=512, input_size=EMBEDDING_LENGTH, batch_size=1, backprop_depth=1, stateful=True) second_layer = LSTM(size=512, input_size=512, batch_size=1, backprop_depth=1, stateful=True) # Load the weights. with open(MODEL, 'r') as file: weights = json.load(file) first_layer.loadParams(weights[0]) second_layer.loadParams(weights[1]) # Loading in the file. with open(TEXT_FILE, 'r', encoding='utf8') as file: text = file.read() source = list(text) for i in range(len(source)): source[i] = char_to_vec[source[i]] # Feed the text to the network. # Here we look at the activation of the neurons of the # hidden state at the 2nd LSTM layer. # We take the first element of the output as there is only one # batch. out = second_layer.forward(first_layer.forward(np.array([source])))[0] # ###############---TKINTER---############################################# class Wrap: NEURON_INDEX = 0 def showNeuron(): for j in range(out.shape[0]): # We will leave the background of the newline characters white, # regardless of its activation. The reason for that is that the color # would fill the entire remainder of the line, which is very disturbing to look at. intensity = 255 if text[j] == '\n' else 255 - int((out[j, Wrap.NEURON_INDEX, 0] + 1) * 127.5) text_box.tag_config(str(j), background="#%02x%02x%02x" % ( 255, intensity, intensity)) def inputFromEntry(evt): Wrap.NEURON_INDEX = int(entry.get()) entry.delete(0, "end") showNeuron() def nextButtonClicked(): Wrap.NEURON_INDEX += 1 entry.delete(0, "end") entry.insert(tk.INSERT, str(Wrap.NEURON_INDEX)) showNeuron() # Making the tkinter window. root = tk.Tk() text_box = tk.Text(root, height=35) text_box.insert(tk.INSERT, text) text_box.pack() current_line = 1 current_char = 0 for i in range(out.shape[0]): text_box.tag_add(str(i), f"{current_line}.{current_char}") current_char += 1 if text[i] == '\n': current_line += 1 current_char = 0 # Making the entry box. entry = tk.Entry(root, width=5) entry.pack() entry.bind("<Return>", inputFromEntry) # Buttons up = tk.Button(text="Next", command=nextButtonClicked) up.pack() # Show the first neuron by default. showNeuron() root.mainloop() if __name__ == '__main__': main()
true
true
f72793d54ac528bc12e6cc394f04adc65956cb34
21,296
py
Python
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
gen_data_fin.py
vjaguilera/BERT4Rec
8c460676af224c90c9cc89f1ba837b38f04e4210
[ "Apache-2.0" ]
null
null
null
# -*- coding: UTF-8 -*- import os import codecs import collections import random import sys import tensorflow as tf import six from util import * from vocab import * import pickle import multiprocessing import time random_seed = 12345 short_seq_prob = 0 # Probability of creating sequences which are shorter than the maximum length。 flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string("signature", 'default', "signature_name") flags.DEFINE_integer( "pool_size", 10, "multiprocesses pool size.") flags.DEFINE_integer( "max_seq_length", 200, "max sequence length.") flags.DEFINE_integer( "max_predictions_per_seq", 20, "max_predictions_per_seq.") flags.DEFINE_float( "masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "mask_prob", 1.0, "mask probabaility") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("prop_sliding_window", 0.1, "sliding window step size.") flags.DEFINE_string( "data_dir", './data/', "data dir.") flags.DEFINE_string( "dataset_name", 'ml-1m', "dataset name.") def printable_text(text): """Returns text encoded in a way suitable for print or `tf.logging`.""" # These functions want `str` for both Python2 and Python3, but in one case # it's a Unicode string and in the other it's a byte string. if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, info, tokens, masked_lm_positions, masked_lm_labels): self.info = info # info = [user] self.tokens = tokens self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "info: %s\n" % (" ".join([printable_text(x) for x in self.info])) s += "tokens: %s\n" % ( " ".join([printable_text(x) for x in self.tokens])) s += "masked_lm_positions: %s\n" % ( " ".join([str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % ( " ".join([printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): try: input_ids = vocab.convert_tokens_to_ids(instance.tokens) except: print(instance) input_mask = [1] * len(input_ids) assert len(input_ids) <= max_seq_length input_ids += [0] * (max_seq_length - len(input_ids)) input_mask += [0] * (max_seq_length - len(input_mask)) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = vocab.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_positions += [0] * (max_predictions_per_seq - len(masked_lm_positions)) masked_lm_ids += [0] * (max_predictions_per_seq - len(masked_lm_ids)) masked_lm_weights += [0.0] * (max_predictions_per_seq - len(masked_lm_weights)) features = collections.OrderedDict() features["info"] = create_int_feature(instance.info) features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["masked_lm_positions"] = create_int_feature( masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) tf_example = tf.train.Example( features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info("%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature( int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature( float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(all_documents_raw, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last=False): """Create `TrainingInstance`s from raw text. PARAMS: - all_documents_raw (dict): Dict containing users as keys and item-list as value """ all_documents = {} # TEST if force_last: max_num_tokens = max_seq_length for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue all_documents[user] = [item_seq[-max_num_tokens:]] # Assign list of list from the last to the max_num_tokens # TRAIN else: max_num_tokens = max_seq_length # we need two sentence sliding_step = (int)( prop_sliding_window * max_num_tokens) if prop_sliding_window != -1.0 else max_num_tokens for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue #todo: add slide if len(item_seq) <= max_num_tokens: # All to token all_documents[user] = [item_seq] else: beg_idx = list(range(len(item_seq)-max_num_tokens, 0, -sliding_step)) beg_idx.append(0) # Reverse ordered list with 0 appended all_documents[user] = [item_seq[i:i + max_num_tokens] for i in beg_idx[::-1]] instances = [] # TEST if force_last: for user in all_documents: instances.extend( create_instances_from_document_test( all_documents, user, max_seq_length)) print("num of instance:{}".format(len(instances))) # TRAIN else: start_time = time.clock() pool = multiprocessing.Pool(processes=pool_size) instances = [] print("Document quantity: {}".format(len(all_documents))) def log_result(result): print("callback function result type: {}, size: {} ".format(type(result), len(result))) # RESULT CAN BE error_callback or the result of create_instances_threading instances.extend(result) # Add Training Instances to instances list if result is correct for step in range(dupe_factor): # Run a process async as a thread pool.apply_async( create_instances_threading, args=( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, random.Random(random.randint(1,10000)), mask_prob, step, dupe_factor), callback=log_result) pool.close() pool.join() # Always masking the last item for user in all_documents: instances.extend( mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng)) print("num of instance:{}; time:{}".format(len(instances), time.clock() - start_time)) rng.shuffle(instances) return instances def create_instances_threading(all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob, step, dupe_factor): cnt = 0 start_time = time.clock() instances = [] for user in all_documents: cnt += 1 if cnt % 1000 == 0: print("step: {}/{}, name: {}, user: {}, time: {}".format(step, dupe_factor, multiprocessing.current_process().name, cnt, time.clock()-start_time)) start_time = time.clock() instances.extend(create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob)) return instances def mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances def create_instances_from_document_test(all_documents, user, max_seq_length): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length assert len(document) == 1 and len(document[0]) <= max_num_tokens tokens = document[0] assert len(tokens) >= 1 (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) info = [int(user.split("_")[1])] instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) return [instance] def create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob): """Creates `TrainingInstance`s for a single document.""" document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens # Return the tokens, the masked positions and the masked labels (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_items, rng, mask_prob) # Instantiate a TrainingInstance instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions_force_last(tokens): """Creates the predictions for the masked LM objective, BUT JUST MASKING THE LAST ITEM""" last_index = -1 for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]': continue last_index = i assert last_index > 0 output_tokens = list(tokens) output_tokens[last_index] = "[MASK]" masked_lm_positions = [last_index] masked_lm_labels = [tokens[last_index]] return (output_tokens, masked_lm_positions, masked_lm_labels) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng, mask_prob): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token not in vocab_words: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < mask_prob: masked_token = "[MASK]" else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: # masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] masked_token = rng.choice(vocab_words) output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def gen_samples(data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False): # create train instances instances = create_training_instances( data, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last) tf.logging.info("*** Writing to output files ***") tf.logging.info(" %s", output_filename) # Write training instances write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, [output_filename]) def main(): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG) max_seq_length = FLAGS.max_seq_length max_predictions_per_seq = FLAGS.max_predictions_per_seq masked_lm_prob = FLAGS.masked_lm_prob mask_prob = FLAGS.mask_prob dupe_factor = FLAGS.dupe_factor prop_sliding_window = FLAGS.prop_sliding_window pool_size = FLAGS.pool_size output_dir = FLAGS.data_dir dataset_name = FLAGS.dataset_name version_id = FLAGS.signature print(version_id) print(output_dir) print(dataset_name) if not os.path.isdir(output_dir): print(output_dir + ' is not exist') print(os.getcwd()) exit(1) dataset = data_partition(output_dir+dataset_name+'.txt') [user_train, user_valid, user_test, usernum, itemnum] = dataset cc = 0.0 max_len = 0 min_len = 100000 for u in user_train: cc += len(user_train[u]) max_len = max(len(user_train[u]), max_len) min_len = min(len(user_train[u]), min_len) print('average sequence length: %.2f' % (cc / len(user_train))) print('max:{}, min:{}'.format(max_len, min_len)) print('len_train:{}, len_valid:{}, len_test:{}, usernum:{}, itemnum:{}'. format( len(user_train), len(user_valid), len(user_test), usernum, itemnum)) for idx, u in enumerate(user_train): if idx < 10: print(user_train[u]) print(user_valid[u]) print(user_test[u]) # put validate into train for u in user_train: if u in user_valid: user_train[u].extend(user_valid[u]) # get the max index of the data user_train_data = { 'user_' + str(k): ['item_' + str(item) for item in v] for k, v in user_train.items() if len(v) > 0 } user_test_data = { 'user_' + str(u): ['item_' + str(item) for item in (user_train[u] + user_test[u])] for u in user_train if len(user_train[u]) > 0 and len(user_test[u]) > 0 } rng = random.Random(random_seed) vocab = FreqVocab(user_test_data) user_test_data_output = { k: [vocab.convert_tokens_to_ids(v)] for k, v in user_test_data.items() } print('begin to generate train') output_filename = output_dir + dataset_name + version_id + '.train.tfrecord' ## Generating training masked samples gen_samples( user_train_data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False) print('train:{}'.format(output_filename)) print('begin to generate test') output_filename = output_dir + dataset_name + version_id + '.test.tfrecord' ## Generating test masked samples ## force_last is True gen_samples( user_test_data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, -1.0, pool_size, force_last=True) print('test:{}'.format(output_filename)) print('vocab_size:{}, user_size:{}, item_size:{}, item_with_other_size:{}'. format(vocab.get_vocab_size(), vocab.get_user_count(), vocab.get_item_count(), vocab.get_item_count() + vocab.get_special_token_count())) vocab_file_name = output_dir + dataset_name + version_id + '.vocab' print('vocab pickle file: ' + vocab_file_name) with open(vocab_file_name, 'wb') as output_file: pickle.dump(vocab, output_file, protocol=2) his_file_name = output_dir + dataset_name + version_id + '.his' print('test data pickle file: ' + his_file_name) with open(his_file_name, 'wb') as output_file: pickle.dump(user_test_data_output, output_file, protocol=2) print('done.') if __name__ == "__main__": main()
32.864198
158
0.609739
import os import codecs import collections import random import sys import tensorflow as tf import six from util import * from vocab import * import pickle import multiprocessing import time random_seed = 12345 short_seq_prob = 0 flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string("signature", 'default', "signature_name") flags.DEFINE_integer( "pool_size", 10, "multiprocesses pool size.") flags.DEFINE_integer( "max_seq_length", 200, "max sequence length.") flags.DEFINE_integer( "max_predictions_per_seq", 20, "max_predictions_per_seq.") flags.DEFINE_float( "masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "mask_prob", 1.0, "mask probabaility") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("prop_sliding_window", 0.1, "sliding window step size.") flags.DEFINE_string( "data_dir", './data/', "data dir.") flags.DEFINE_string( "dataset_name", 'ml-1m', "dataset name.") def printable_text(text): if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def convert_to_unicode(text): if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") class TrainingInstance(object): def __init__(self, info, tokens, masked_lm_positions, masked_lm_labels): self.info = info self.tokens = tokens self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "info: %s\n" % (" ".join([printable_text(x) for x in self.info])) s += "tokens: %s\n" % ( " ".join([printable_text(x) for x in self.tokens])) s += "masked_lm_positions: %s\n" % ( " ".join([str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % ( " ".join([printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, output_files): writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): try: input_ids = vocab.convert_tokens_to_ids(instance.tokens) except: print(instance) input_mask = [1] * len(input_ids) assert len(input_ids) <= max_seq_length input_ids += [0] * (max_seq_length - len(input_ids)) input_mask += [0] * (max_seq_length - len(input_mask)) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = vocab.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) masked_lm_positions += [0] * (max_predictions_per_seq - len(masked_lm_positions)) masked_lm_ids += [0] * (max_predictions_per_seq - len(masked_lm_ids)) masked_lm_weights += [0.0] * (max_predictions_per_seq - len(masked_lm_weights)) features = collections.OrderedDict() features["info"] = create_int_feature(instance.info) features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["masked_lm_positions"] = create_int_feature( masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) tf_example = tf.train.Example( features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info("%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature( int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature( float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(all_documents_raw, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last=False): all_documents = {} if force_last: max_num_tokens = max_seq_length for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue all_documents[user] = [item_seq[-max_num_tokens:]] else: max_num_tokens = max_seq_length sliding_step = (int)( prop_sliding_window * max_num_tokens) if prop_sliding_window != -1.0 else max_num_tokens for user, item_seq in all_documents_raw.items(): if len(item_seq) == 0: print("got empty seq:" + user) continue if len(item_seq) <= max_num_tokens: all_documents[user] = [item_seq] else: beg_idx = list(range(len(item_seq)-max_num_tokens, 0, -sliding_step)) beg_idx.append(0) all_documents[user] = [item_seq[i:i + max_num_tokens] for i in beg_idx[::-1]] instances = [] if force_last: for user in all_documents: instances.extend( create_instances_from_document_test( all_documents, user, max_seq_length)) print("num of instance:{}".format(len(instances))) else: start_time = time.clock() pool = multiprocessing.Pool(processes=pool_size) instances = [] print("Document quantity: {}".format(len(all_documents))) def log_result(result): print("callback function result type: {}, size: {} ".format(type(result), len(result))) instances.extend(result) for step in range(dupe_factor): pool.apply_async( create_instances_threading, args=( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, random.Random(random.randint(1,10000)), mask_prob, step, dupe_factor), callback=log_result) pool.close() pool.join() for user in all_documents: instances.extend( mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng)) print("num of instance:{}; time:{}".format(len(instances), time.clock() - start_time)) rng.shuffle(instances) return instances def create_instances_threading(all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob, step, dupe_factor): cnt = 0 start_time = time.clock() instances = [] for user in all_documents: cnt += 1 if cnt % 1000 == 0: print("step: {}/{}, name: {}, user: {}, time: {}".format(step, dupe_factor, multiprocessing.current_process().name, cnt, time.clock()-start_time)) start_time = time.clock() instances.extend(create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob)) return instances def mask_last( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng): document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances def create_instances_from_document_test(all_documents, user, max_seq_length): document = all_documents[user] max_num_tokens = max_seq_length assert len(document) == 1 and len(document[0]) <= max_num_tokens tokens = document[0] assert len(tokens) >= 1 (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions_force_last(tokens) info = [int(user.split("_")[1])] instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) return [instance] def create_instances_from_document_train( all_documents, user, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab, rng, mask_prob): document = all_documents[user] max_num_tokens = max_seq_length instances = [] info = [int(user.split("_")[1])] vocab_items = vocab.get_items() for tokens in document: assert len(tokens) >= 1 and len(tokens) <= max_num_tokens (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_items, rng, mask_prob) instance = TrainingInstance( info=info, tokens=tokens, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions_force_last(tokens): last_index = -1 for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]': continue last_index = i assert last_index > 0 output_tokens = list(tokens) output_tokens[last_index] = "[MASK]" masked_lm_positions = [last_index] masked_lm_labels = [tokens[last_index]] return (output_tokens, masked_lm_positions, masked_lm_labels) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng, mask_prob): cand_indexes = [] for (i, token) in enumerate(tokens): if token not in vocab_words: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None if rng.random() < mask_prob: masked_token = "[MASK]" else: if rng.random() < 0.5: masked_token = tokens[index] else: masked_token = rng.choice(vocab_words) output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def gen_samples(data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False): instances = create_training_instances( data, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, vocab, mask_prob, prop_sliding_window, pool_size, force_last) tf.logging.info("*** Writing to output files ***") tf.logging.info(" %s", output_filename) write_instance_to_example_files(instances, max_seq_length, max_predictions_per_seq, vocab, [output_filename]) def main(): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG) max_seq_length = FLAGS.max_seq_length max_predictions_per_seq = FLAGS.max_predictions_per_seq masked_lm_prob = FLAGS.masked_lm_prob mask_prob = FLAGS.mask_prob dupe_factor = FLAGS.dupe_factor prop_sliding_window = FLAGS.prop_sliding_window pool_size = FLAGS.pool_size output_dir = FLAGS.data_dir dataset_name = FLAGS.dataset_name version_id = FLAGS.signature print(version_id) print(output_dir) print(dataset_name) if not os.path.isdir(output_dir): print(output_dir + ' is not exist') print(os.getcwd()) exit(1) dataset = data_partition(output_dir+dataset_name+'.txt') [user_train, user_valid, user_test, usernum, itemnum] = dataset cc = 0.0 max_len = 0 min_len = 100000 for u in user_train: cc += len(user_train[u]) max_len = max(len(user_train[u]), max_len) min_len = min(len(user_train[u]), min_len) print('average sequence length: %.2f' % (cc / len(user_train))) print('max:{}, min:{}'.format(max_len, min_len)) print('len_train:{}, len_valid:{}, len_test:{}, usernum:{}, itemnum:{}'. format( len(user_train), len(user_valid), len(user_test), usernum, itemnum)) for idx, u in enumerate(user_train): if idx < 10: print(user_train[u]) print(user_valid[u]) print(user_test[u]) for u in user_train: if u in user_valid: user_train[u].extend(user_valid[u]) user_train_data = { 'user_' + str(k): ['item_' + str(item) for item in v] for k, v in user_train.items() if len(v) > 0 } user_test_data = { 'user_' + str(u): ['item_' + str(item) for item in (user_train[u] + user_test[u])] for u in user_train if len(user_train[u]) > 0 and len(user_test[u]) > 0 } rng = random.Random(random_seed) vocab = FreqVocab(user_test_data) user_test_data_output = { k: [vocab.convert_tokens_to_ids(v)] for k, v in user_test_data.items() } print('begin to generate train') output_filename = output_dir + dataset_name + version_id + '.train.tfrecord' _data, output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, prop_sliding_window, pool_size, force_last=False) print('train:{}'.format(output_filename)) print('begin to generate test') output_filename = output_dir + dataset_name + version_id + '.test.tfrecord' output_filename, rng, vocab, max_seq_length, dupe_factor, short_seq_prob, mask_prob, masked_lm_prob, max_predictions_per_seq, -1.0, pool_size, force_last=True) print('test:{}'.format(output_filename)) print('vocab_size:{}, user_size:{}, item_size:{}, item_with_other_size:{}'. format(vocab.get_vocab_size(), vocab.get_user_count(), vocab.get_item_count(), vocab.get_item_count() + vocab.get_special_token_count())) vocab_file_name = output_dir + dataset_name + version_id + '.vocab' print('vocab pickle file: ' + vocab_file_name) with open(vocab_file_name, 'wb') as output_file: pickle.dump(vocab, output_file, protocol=2) his_file_name = output_dir + dataset_name + version_id + '.his' print('test data pickle file: ' + his_file_name) with open(his_file_name, 'wb') as output_file: pickle.dump(user_test_data_output, output_file, protocol=2) print('done.') if __name__ == "__main__": main()
true
true
f727954b000151483380835b1aa72d1c1ac5eccb
2,275
py
Python
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
3
2018-08-24T10:48:40.000Z
2020-05-29T06:33:23.000Z
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
null
null
null
src/scheduler/migrations/0004_scheduledemailaction.py
japesone/ontask_b
17af441f9893c521d2e14011e7790ba4077e3318
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-16 08:54 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('workflow', '0013_auto_20171209_0809'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('action', '0008_auto_20171209_1808'), ('scheduler', '0003_auto_20171216_1944'), ] operations = [ migrations.CreateModel( name='ScheduledEmailAction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=256)), ('created', models.DateTimeField(auto_now_add=True)), ('execute', models.DateTimeField(null=True)), ('status', models.IntegerField(choices=[(0, 'pending'), (1, 'running'), (2, 'done')], verbose_name='Execution Status')), ('subject', models.CharField(blank=True, default='', max_length=2048, verbose_name='Email subject')), ('send_confirmation', models.BooleanField(default=False, verbose_name='Send you a confirmation email')), ('track_read', models.BooleanField(default=False, verbose_name='Track if emails are read?')), ('add_column', models.BooleanField(default=False, verbose_name='Add a column with the number of email reads tracked')), ('action', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='action.Action')), ('email_column', models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='workflow.Column', verbose_name='Column containing the email address')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('workflow', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='workflow.Workflow')), ], options={ 'abstract': False, }, ), ]
51.704545
187
0.648352
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('workflow', '0013_auto_20171209_0809'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('action', '0008_auto_20171209_1808'), ('scheduler', '0003_auto_20171216_1944'), ] operations = [ migrations.CreateModel( name='ScheduledEmailAction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=256)), ('created', models.DateTimeField(auto_now_add=True)), ('execute', models.DateTimeField(null=True)), ('status', models.IntegerField(choices=[(0, 'pending'), (1, 'running'), (2, 'done')], verbose_name='Execution Status')), ('subject', models.CharField(blank=True, default='', max_length=2048, verbose_name='Email subject')), ('send_confirmation', models.BooleanField(default=False, verbose_name='Send you a confirmation email')), ('track_read', models.BooleanField(default=False, verbose_name='Track if emails are read?')), ('add_column', models.BooleanField(default=False, verbose_name='Add a column with the number of email reads tracked')), ('action', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='action.Action')), ('email_column', models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='workflow.Column', verbose_name='Column containing the email address')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('workflow', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scheduled_actions', to='workflow.Workflow')), ], options={ 'abstract': False, }, ), ]
true
true
f72795aa0c613268a934fa6fe9d3601b7683d86e
20,230
py
Python
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
sdk/core/azure-core/azure/core/polling/base_polling.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
1
2020-10-11T06:05:00.000Z
2020-10-11T06:05:00.000Z
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # # -------------------------------------------------------------------------- import abc import base64 import json from typing import TYPE_CHECKING, Optional, Any, Union from ..exceptions import HttpResponseError, DecodeError from . import PollingMethod from ..pipeline.policies._utils import get_retry_after if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import ( HttpResponse, AsyncHttpResponse, HttpRequest, ) ResponseType = Union[HttpResponse, AsyncHttpResponse] PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] try: ABC = abc.ABC except AttributeError: # Python 2.7, abc exists, but not ABC ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) # type: ignore _FINISHED = frozenset(["succeeded", "canceled", "failed"]) _FAILED = frozenset(["canceled", "failed"]) _SUCCEEDED = frozenset(["succeeded"]) def _finished(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FINISHED def _failed(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FAILED def _succeeded(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _SUCCEEDED class BadStatus(Exception): pass class BadResponse(Exception): pass class OperationFailed(Exception): pass def _as_json(response): # type: (ResponseType) -> dict """Assuming this is not empty, return the content as JSON. Result/exceptions is not determined if you call this method without testing _is_empty. :raises: DecodeError if response body contains invalid json data. """ try: return json.loads(response.text()) except ValueError: raise DecodeError("Error occurred in deserializing the response body.") def _raise_if_bad_http_status_and_method(response): # type: (ResponseType) -> None """Check response status code is valid. Must be 200, 201, 202, or 204. :raises: BadStatus if invalid status. """ code = response.status_code if code in {200, 201, 202, 204}: return raise BadStatus( "Invalid return status {!r} for {!r} operation".format( code, response.request.method ) ) def _is_empty(response): # type: (ResponseType) -> bool """Check if response body contains meaningful content. :rtype: bool """ return not bool(response.body()) class LongRunningOperation(ABC): """LongRunningOperation Provides default logic for interpreting operation responses and status updates. :param azure.core.pipeline.PipelineResponse response: The initial pipeline response. :param callable deserialization_callback: The deserialization callaback. :param dict lro_options: LRO options. :param kwargs: Unused for now """ @abc.abstractmethod def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ raise NotImplementedError() @abc.abstractmethod def get_polling_url(self): # type: () -> str """Return the polling URL. """ raise NotImplementedError() @abc.abstractmethod def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ raise NotImplementedError() @abc.abstractmethod def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Return the status string extracted from this response.""" raise NotImplementedError() @abc.abstractmethod def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ raise NotImplementedError() class OperationResourcePolling(LongRunningOperation): """Implements a operation resource polling, typically from Operation-Location. :param str operation_location_header: Name of the header to return operation format (default 'operation-location') """ def __init__(self, operation_location_header="operation-location"): self._operation_location_header = operation_location_header # Store the initial URLs self._async_url = None self._location_url = None self._request = None def can_poll(self, pipeline_response): """Answer if this polling method could be used. """ response = pipeline_response.http_response return self._operation_location_header in response.headers def get_polling_url(self): # type: () -> str """Return the polling URL. """ return self._async_url def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ response = pipeline_response.http_response if not _is_empty(response): body = _as_json(response) # https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#target-resource-location resource_location = body.get("resourceLocation") if resource_location: return resource_location if self._request.method in {"PUT", "PATCH"}: return self._request.url if self._request.method == "POST" and self._location_url: return self._location_url return None def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ self._request = pipeline_response.http_response.request response = pipeline_response.http_response self._set_async_url_if_present(response) if response.status_code in {200, 201, 202, 204} and self._async_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def _set_async_url_if_present(self, response): # type: (ResponseType) -> None self._async_url = response.headers[self._operation_location_header] location_url = response.headers.get("location") if location_url: self._location_url = location_url def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process the latest status update retrieved from an "Operation-Location" header. :param azure.core.pipeline.PipelineResponse response: The response to extract the status. :raises: BadResponse if response has no body, or body does not contain status. """ response = pipeline_response.http_response if _is_empty(response): raise BadResponse( "The response from long running operation does not contain a body." ) body = _as_json(response) status = body.get("status") if not status: raise BadResponse("No status found in body") return status class LocationPolling(LongRunningOperation): """Implements a Location polling. """ def __init__(self): self._location_url = None def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ response = pipeline_response.http_response return "location" in response.headers def get_polling_url(self): # type: () -> str """Return the polling URL. """ return self._location_url def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ return None def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ response = pipeline_response.http_response self._location_url = response.headers["location"] if response.status_code in {200, 201, 202, 204} and self._location_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process the latest status update retrieved from a 'location' header. :param azure.core.pipeline.PipelineResponse response: latest REST call response. :raises: BadResponse if response has no body and not status 202. """ response = pipeline_response.http_response if "location" in response.headers: self._location_url = response.headers["location"] return "InProgress" if response.status_code == 202 else "Succeeded" class StatusCheckPolling(LongRunningOperation): """Should be the fallback polling, that don't poll but exit successfully if not other polling are detected and status code is 2xx. """ def can_poll(self, pipeline_response): # type: (PipelineResponseType) -> bool """Answer if this polling method could be used. """ return True def get_polling_url(self): # type: () -> str """Return the polling URL. """ raise ValueError("This polling doesn't support polling") def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str """Process first response after initiating long running operation and set self.status attribute. :param azure.core.pipeline.PipelineResponse response: initial REST call response. """ return "Succeeded" def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] """If a final GET is needed, returns the URL. :rtype: str """ return None class LROBasePolling(PollingMethod): # pylint: disable=too-many-instance-attributes """A base LRO poller. This assumes a basic flow: - I analyze the response to decide the polling approach - I poll - I ask the final resource depending of the polling approach If your polling need are more specific, you could implement a PollingMethod directly """ def __init__( self, timeout=30, lro_algorithms=None, lro_options=None, path_format_arguments=None, **operation_config ): self._lro_algorithms = lro_algorithms or [ OperationResourcePolling(), LocationPolling(), StatusCheckPolling(), ] self._timeout = timeout self._client = None # Will hold the Pipelineclient self._operation = None # Will hold an instance of LongRunningOperation self._initial_response = None # Will hold the initial response self._pipeline_response = None # Will hold latest received response self._deserialization_callback = None # Will hold the deserialization callback self._operation_config = operation_config self._lro_options = lro_options self._path_format_arguments = path_format_arguments self._status = None def status(self): """Return the current status as a string. :rtype: str """ if not self._operation: raise ValueError( "set_initial_status was never called. Did you give this instance to a poller?" ) return self._status def finished(self): """Is this polling finished? :rtype: bool """ return _finished(self.status()) def resource(self): """Return the built resource. """ return self._parse_resource(self._pipeline_response) @property def _transport(self): return self._client._pipeline._transport # pylint: disable=protected-access def initialize(self, client, initial_response, deserialization_callback): """Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: HttpResponseError if initial status is incorrect LRO state """ self._client = client self._pipeline_response = self._initial_response = initial_response self._deserialization_callback = deserialization_callback for operation in self._lro_algorithms: if operation.can_poll(initial_response): self._operation = operation break else: raise BadResponse("Unable to find status link for polling.") try: _raise_if_bad_http_status_and_method(self._initial_response.http_response) self._status = self._operation.set_initial_status(initial_response) except BadStatus as err: self._status = "Failed" raise HttpResponseError(response=initial_response.http_response, error=err) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=initial_response.http_response, message=str(err), error=err ) except OperationFailed as err: raise HttpResponseError(response=initial_response.http_response, error=err) def get_continuation_token(self): # type() -> str import pickle return base64.b64encode(pickle.dumps(self._initial_response)).decode('ascii') @classmethod def from_continuation_token(cls, continuation_token, **kwargs): # type(str, Any) -> Tuple try: client = kwargs["client"] except KeyError: raise ValueError("Need kwarg 'client' to be recreated from continuation_token") try: deserialization_callback = kwargs["deserialization_callback"] except KeyError: raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") import pickle initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec # Restore the transport in the context initial_response.context.transport = client._pipeline._transport # pylint: disable=protected-access return client, initial_response, deserialization_callback def run(self): try: self._poll() except BadStatus as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, message=str(err), error=err, ) except OperationFailed as err: raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) def _poll(self): """Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Canceled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid. """ while not self.finished(): self._delay() self.update_status() if _failed(self.status()): raise OperationFailed("Operation failed or canceled") final_get_url = self._operation.get_final_get_url(self._pipeline_response) if final_get_url: self._pipeline_response = self.request_status(final_get_url) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) def _parse_resource(self, pipeline_response): # type: (PipelineResponseType) -> Optional[Any] """Assuming this response is a resource, use the deserialization callback to parse it. If body is empty, assuming no resource to return. """ response = pipeline_response.http_response if not _is_empty(response): return self._deserialization_callback(pipeline_response) return None def _sleep(self, delay): self._transport.sleep(delay) def _extract_delay(self): if self._pipeline_response is None: return None delay = get_retry_after(self._pipeline_response) if delay: return delay return self._timeout def _delay(self): """Check for a 'retry-after' header to set timeout, otherwise use configured timeout. """ delay = self._extract_delay() self._sleep(delay) def update_status(self): """Update the current status of the LRO. """ self._pipeline_response = self.request_status(self._operation.get_polling_url()) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) self._status = self._operation.get_status(self._pipeline_response) def _get_request_id(self): return self._pipeline_response.http_response.request.headers[ "x-ms-client-request-id" ] def request_status(self, status_link): """Do a simple GET to this status link. This method re-inject 'x-ms-client-request-id'. :rtype: azure.core.pipeline.PipelineResponse """ if self._path_format_arguments: status_link = self._client.format_url(status_link, **self._path_format_arguments) request = self._client.get(status_link) # Re-inject 'x-ms-client-request-id' while polling if "request_id" not in self._operation_config: self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run( # pylint: disable=protected-access request, stream=False, **self._operation_config ) __all__ = [ 'BadResponse', 'BadStatus', 'OperationFailed', 'LongRunningOperation', 'OperationResourcePolling', 'LocationPolling', 'StatusCheckPolling', 'LROBasePolling', ]
34.057239
118
0.659219
import abc import base64 import json from typing import TYPE_CHECKING, Optional, Any, Union from ..exceptions import HttpResponseError, DecodeError from . import PollingMethod from ..pipeline.policies._utils import get_retry_after if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import ( HttpResponse, AsyncHttpResponse, HttpRequest, ) ResponseType = Union[HttpResponse, AsyncHttpResponse] PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] try: ABC = abc.ABC except AttributeError: ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) _FINISHED = frozenset(["succeeded", "canceled", "failed"]) _FAILED = frozenset(["canceled", "failed"]) _SUCCEEDED = frozenset(["succeeded"]) def _finished(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FINISHED def _failed(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _FAILED def _succeeded(status): if hasattr(status, "value"): status = status.value return str(status).lower() in _SUCCEEDED class BadStatus(Exception): pass class BadResponse(Exception): pass class OperationFailed(Exception): pass def _as_json(response): try: return json.loads(response.text()) except ValueError: raise DecodeError("Error occurred in deserializing the response body.") def _raise_if_bad_http_status_and_method(response): code = response.status_code if code in {200, 201, 202, 204}: return raise BadStatus( "Invalid return status {!r} for {!r} operation".format( code, response.request.method ) ) def _is_empty(response): return not bool(response.body()) class LongRunningOperation(ABC): @abc.abstractmethod def can_poll(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_polling_url(self): raise NotImplementedError() @abc.abstractmethod def set_initial_status(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_status(self, pipeline_response): raise NotImplementedError() @abc.abstractmethod def get_final_get_url(self, pipeline_response): raise NotImplementedError() class OperationResourcePolling(LongRunningOperation): def __init__(self, operation_location_header="operation-location"): self._operation_location_header = operation_location_header self._async_url = None self._location_url = None self._request = None def can_poll(self, pipeline_response): response = pipeline_response.http_response return self._operation_location_header in response.headers def get_polling_url(self): return self._async_url def get_final_get_url(self, pipeline_response): response = pipeline_response.http_response if not _is_empty(response): body = _as_json(response) ation = body.get("resourceLocation") if resource_location: return resource_location if self._request.method in {"PUT", "PATCH"}: return self._request.url if self._request.method == "POST" and self._location_url: return self._location_url return None def set_initial_status(self, pipeline_response): self._request = pipeline_response.http_response.request response = pipeline_response.http_response self._set_async_url_if_present(response) if response.status_code in {200, 201, 202, 204} and self._async_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def _set_async_url_if_present(self, response): self._async_url = response.headers[self._operation_location_header] location_url = response.headers.get("location") if location_url: self._location_url = location_url def get_status(self, pipeline_response): response = pipeline_response.http_response if _is_empty(response): raise BadResponse( "The response from long running operation does not contain a body." ) body = _as_json(response) status = body.get("status") if not status: raise BadResponse("No status found in body") return status class LocationPolling(LongRunningOperation): def __init__(self): self._location_url = None def can_poll(self, pipeline_response): response = pipeline_response.http_response return "location" in response.headers def get_polling_url(self): return self._location_url def get_final_get_url(self, pipeline_response): return None def set_initial_status(self, pipeline_response): response = pipeline_response.http_response self._location_url = response.headers["location"] if response.status_code in {200, 201, 202, 204} and self._location_url: return "InProgress" raise OperationFailed("Operation failed or canceled") def get_status(self, pipeline_response): response = pipeline_response.http_response if "location" in response.headers: self._location_url = response.headers["location"] return "InProgress" if response.status_code == 202 else "Succeeded" class StatusCheckPolling(LongRunningOperation): def can_poll(self, pipeline_response): return True def get_polling_url(self): raise ValueError("This polling doesn't support polling") def set_initial_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_status(self, pipeline_response): # type: (PipelineResponseType) -> str return "Succeeded" def get_final_get_url(self, pipeline_response): # type: (PipelineResponseType) -> Optional[str] return None class LROBasePolling(PollingMethod): # pylint: disable=too-many-instance-attributes def __init__( self, timeout=30, lro_algorithms=None, lro_options=None, path_format_arguments=None, **operation_config ): self._lro_algorithms = lro_algorithms or [ OperationResourcePolling(), LocationPolling(), StatusCheckPolling(), ] self._timeout = timeout self._client = None # Will hold the Pipelineclient self._operation = None # Will hold an instance of LongRunningOperation self._initial_response = None # Will hold the initial response self._pipeline_response = None # Will hold latest received response self._deserialization_callback = None # Will hold the deserialization callback self._operation_config = operation_config self._lro_options = lro_options self._path_format_arguments = path_format_arguments self._status = None def status(self): if not self._operation: raise ValueError( "set_initial_status was never called. Did you give this instance to a poller?" ) return self._status def finished(self): return _finished(self.status()) def resource(self): return self._parse_resource(self._pipeline_response) @property def _transport(self): return self._client._pipeline._transport # pylint: disable=protected-access def initialize(self, client, initial_response, deserialization_callback): self._client = client self._pipeline_response = self._initial_response = initial_response self._deserialization_callback = deserialization_callback for operation in self._lro_algorithms: if operation.can_poll(initial_response): self._operation = operation break else: raise BadResponse("Unable to find status link for polling.") try: _raise_if_bad_http_status_and_method(self._initial_response.http_response) self._status = self._operation.set_initial_status(initial_response) except BadStatus as err: self._status = "Failed" raise HttpResponseError(response=initial_response.http_response, error=err) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=initial_response.http_response, message=str(err), error=err ) except OperationFailed as err: raise HttpResponseError(response=initial_response.http_response, error=err) def get_continuation_token(self): # type() -> str import pickle return base64.b64encode(pickle.dumps(self._initial_response)).decode('ascii') @classmethod def from_continuation_token(cls, continuation_token, **kwargs): # type(str, Any) -> Tuple try: client = kwargs["client"] except KeyError: raise ValueError("Need kwarg 'client' to be recreated from continuation_token") try: deserialization_callback = kwargs["deserialization_callback"] except KeyError: raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") import pickle initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec # Restore the transport in the context initial_response.context.transport = client._pipeline._transport # pylint: disable=protected-access return client, initial_response, deserialization_callback def run(self): try: self._poll() except BadStatus as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) except BadResponse as err: self._status = "Failed" raise HttpResponseError( response=self._pipeline_response.http_response, message=str(err), error=err, ) except OperationFailed as err: raise HttpResponseError( response=self._pipeline_response.http_response, error=err ) def _poll(self): while not self.finished(): self._delay() self.update_status() if _failed(self.status()): raise OperationFailed("Operation failed or canceled") final_get_url = self._operation.get_final_get_url(self._pipeline_response) if final_get_url: self._pipeline_response = self.request_status(final_get_url) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) def _parse_resource(self, pipeline_response): # type: (PipelineResponseType) -> Optional[Any] response = pipeline_response.http_response if not _is_empty(response): return self._deserialization_callback(pipeline_response) return None def _sleep(self, delay): self._transport.sleep(delay) def _extract_delay(self): if self._pipeline_response is None: return None delay = get_retry_after(self._pipeline_response) if delay: return delay return self._timeout def _delay(self): delay = self._extract_delay() self._sleep(delay) def update_status(self): self._pipeline_response = self.request_status(self._operation.get_polling_url()) _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) self._status = self._operation.get_status(self._pipeline_response) def _get_request_id(self): return self._pipeline_response.http_response.request.headers[ "x-ms-client-request-id" ] def request_status(self, status_link): if self._path_format_arguments: status_link = self._client.format_url(status_link, **self._path_format_arguments) request = self._client.get(status_link) # Re-inject 'x-ms-client-request-id' while polling if "request_id" not in self._operation_config: self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run( # pylint: disable=protected-access request, stream=False, **self._operation_config ) __all__ = [ 'BadResponse', 'BadStatus', 'OperationFailed', 'LongRunningOperation', 'OperationResourcePolling', 'LocationPolling', 'StatusCheckPolling', 'LROBasePolling', ]
true
true
f72796cfdb731f2805f402a224271fe7a843f908
3,858
py
Python
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
397
2015-05-30T11:02:28.000Z
2022-03-09T01:39:31.000Z
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
32
2015-04-27T21:26:29.000Z
2021-08-19T10:20:45.000Z
tests/test_similarity.py
dhimmel/sematch
7e92b171c27a8b25e844a467554fe4bb2adfb883
[ "Apache-2.0" ]
110
2015-11-06T17:01:48.000Z
2022-02-17T05:09:02.000Z
# -*- coding: utf-8 -*- def test_word_similarity(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() dog = wns.word2synset('dog') cat = wns.word2synset('cat') # Measuring semantic similarity between concepts using Path method assert wns.similarity(dog[0], cat[0], 'path') is not None # 0.2 # Computing English word similarity using Li method assert wns.word_similarity('dog', 'cat', 'li') is not None# 0.449327301063 # Computing Spanish word similarity using Lin method assert wns.monol_word_similarity('perro', 'gato', 'spa', 'lin') is not None#0.876800984373 # Computing Chinese word similarity using Wu & Palmer method assert wns.monol_word_similarity('狗', '猫', 'cmn', 'wup') is not None# 0.857142857143 # Computing Spanish and English word similarity using Resnik method assert wns.crossl_word_similarity('perro', 'cat', 'spa', 'eng', 'res') is not None#7.91166650904 # Computing Spanish and Chinese word similarity using Jiang & Conrad method assert wns.crossl_word_similarity('perro', '猫', 'spa', 'cmn', 'jcn') is not None#0.31023804699 # Computing Chinese and English word similarity using WPath method assert wns.crossl_word_similarity('狗', 'cat', 'cmn', 'eng', 'wpath') is not None#0.593666388463 def test_yago_concept_similarity(): from sematch.semantic.similarity import YagoTypeSimilarity yagosim = YagoTypeSimilarity() dancer = yagosim.word2yago('dancer') actor = yagosim.word2yago('actor') singer = yagosim.word2yago('singer') assert yagosim.yago2synset(actor[0]) is not None assert yagosim.yago_similarity(dancer[0], actor[0], 'wpath') is not None assert yagosim.yago_similarity(singer[0], actor[0], 'wpath') is not None assert yagosim.word2yago('university') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/EducationalInstitution108276342') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Institution108053576') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None #using corpus-based IC from brown corpus assert yagosim.word_similarity('dancer', 'actor', 'wpath') is not None #using graph-based IC from DBpedia assert yagosim.word_similarity('dancer', 'actor', 'wpath_graph') is not None def test_dbpedia_concept_similarity(): from sematch.semantic.graph import DBpediaDataTransform, Taxonomy from sematch.semantic.similarity import ConceptSimilarity concept_sim = ConceptSimilarity(Taxonomy(DBpediaDataTransform()), 'models/dbpedia_type_ic.txt') assert concept_sim.similarity('http://dbpedia.org/ontology/Actor', 'http://dbpedia.org/ontology/Film', 'path') is not None def test_synset_expand(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() cat = wns.word2synset('cat')[0] assert wns.synset_expand(cat) is not None def test_entity_similarity(): from sematch.semantic.similarity import EntitySimilarity entity_sim = EntitySimilarity() assert entity_sim.similarity('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None assert entity_sim.relatedness('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None def test_language(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() #check the supported languages assert wns.languages() is not None #find the language code assert wns.languages('English') is not None assert wns.languages('chinese_simplified') is not None assert wns.languages('spanish') is not None
52.849315
126
0.736133
def test_word_similarity(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() dog = wns.word2synset('dog') cat = wns.word2synset('cat') assert wns.similarity(dog[0], cat[0], 'path') is not None assert wns.word_similarity('dog', 'cat', 'li') is not None assert wns.monol_word_similarity('perro', 'gato', 'spa', 'lin') is not None assert wns.monol_word_similarity('狗', '猫', 'cmn', 'wup') is not None assert wns.crossl_word_similarity('perro', 'cat', 'spa', 'eng', 'res') is not None assert wns.crossl_word_similarity('perro', '猫', 'spa', 'cmn', 'jcn') is not None assert wns.crossl_word_similarity('狗', 'cat', 'cmn', 'eng', 'wpath') is not None def test_yago_concept_similarity(): from sematch.semantic.similarity import YagoTypeSimilarity yagosim = YagoTypeSimilarity() dancer = yagosim.word2yago('dancer') actor = yagosim.word2yago('actor') singer = yagosim.word2yago('singer') assert yagosim.yago2synset(actor[0]) is not None assert yagosim.yago_similarity(dancer[0], actor[0], 'wpath') is not None assert yagosim.yago_similarity(singer[0], actor[0], 'wpath') is not None assert yagosim.word2yago('university') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/EducationalInstitution108276342') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Institution108053576') is not None assert yagosim.yago2synset('http://dbpedia.org/class/yago/Organization108008335') is not None assert yagosim.word_similarity('dancer', 'actor', 'wpath') is not None assert yagosim.word_similarity('dancer', 'actor', 'wpath_graph') is not None def test_dbpedia_concept_similarity(): from sematch.semantic.graph import DBpediaDataTransform, Taxonomy from sematch.semantic.similarity import ConceptSimilarity concept_sim = ConceptSimilarity(Taxonomy(DBpediaDataTransform()), 'models/dbpedia_type_ic.txt') assert concept_sim.similarity('http://dbpedia.org/ontology/Actor', 'http://dbpedia.org/ontology/Film', 'path') is not None def test_synset_expand(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() cat = wns.word2synset('cat')[0] assert wns.synset_expand(cat) is not None def test_entity_similarity(): from sematch.semantic.similarity import EntitySimilarity entity_sim = EntitySimilarity() assert entity_sim.similarity('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None assert entity_sim.relatedness('http://dbpedia.org/resource/Madrid', 'http://dbpedia.org/resource/Barcelona') is not None def test_language(): from sematch.semantic.similarity import WordNetSimilarity wns = WordNetSimilarity() assert wns.languages() is not None assert wns.languages('English') is not None assert wns.languages('chinese_simplified') is not None assert wns.languages('spanish') is not None
true
true
f72797852f54a7b4a109a290c7e4ff3ec4e2193c
3,676
py
Python
src/chaospizza/orders/migrations/0001_initial.py
chaosdorf/chaospizza
6f0895f28095260d04b41a8b86edf07a87bcccb8
[ "MIT" ]
9
2017-05-19T23:32:19.000Z
2020-06-28T20:40:13.000Z
src/chaospizza/orders/migrations/0001_initial.py
step21/chaospizza
8011ebb5fd021bf74897099cedd1869bcfbd031f
[ "MIT" ]
31
2017-05-19T21:27:30.000Z
2022-01-25T21:38:13.000Z
src/chaospizza/orders/migrations/0001_initial.py
step21/chaospizza
8011ebb5fd021bf74897099cedd1869bcfbd031f
[ "MIT" ]
4
2017-05-19T23:32:05.000Z
2019-02-26T03:41:51.000Z
# Generated by Django 1.11.3 on 2017-07-07 19:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): # noqa initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('coordinator', models.CharField(max_length=100)), ('restaurant_name', models.CharField(max_length=250)), ('restaurant_url', models.URLField(blank=True)), ('state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], default='preparing', max_length=16)), ('created_at', models.DateTimeField(auto_now_add=True)), ('preparation_expires_after', models.DurationField(blank=True, help_text='How long the order is allowed to be prepared.', null=True)), ], options={ 'ordering': ('history__created_at',), }, ), migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('participant', models.CharField(max_length=100)), ('description', models.CharField(max_length=250)), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ('amount', models.PositiveIntegerField(default=1)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.Order')), ], ), migrations.CreateModel( name='OrderStateChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('old_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('new_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('reason', models.CharField(max_length=1000, null=True)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='orders.Order')), ], ), migrations.AlterUniqueTogether( name='order', unique_together=set([('coordinator', 'restaurant_name')]), ), migrations.AlterUniqueTogether( name='orderitem', unique_together=set([('order', 'participant', 'description')]), ), ]
59.290323
392
0.612078
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('coordinator', models.CharField(max_length=100)), ('restaurant_name', models.CharField(max_length=250)), ('restaurant_url', models.URLField(blank=True)), ('state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], default='preparing', max_length=16)), ('created_at', models.DateTimeField(auto_now_add=True)), ('preparation_expires_after', models.DurationField(blank=True, help_text='How long the order is allowed to be prepared.', null=True)), ], options={ 'ordering': ('history__created_at',), }, ), migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('participant', models.CharField(max_length=100)), ('description', models.CharField(max_length=250)), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ('amount', models.PositiveIntegerField(default=1)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.Order')), ], ), migrations.CreateModel( name='OrderStateChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('old_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('new_state', models.CharField(choices=[('preparing', 'Order is prepared, order items can be modified.'), ('ordering', 'Order is locked and sent to delivery service by coordinator.'), ('ordered', 'Order has been sent to delivery service.'), ('delivered', 'Delivery has arrived.'), ('canceled', 'Order has been canceled due to some reason.')], max_length=16)), ('reason', models.CharField(max_length=1000, null=True)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='orders.Order')), ], ), migrations.AlterUniqueTogether( name='order', unique_together=set([('coordinator', 'restaurant_name')]), ), migrations.AlterUniqueTogether( name='orderitem', unique_together=set([('order', 'participant', 'description')]), ), ]
true
true
f7279801d19e14d38461c4393e790d31ce9d5df4
479
py
Python
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
2
2019-02-15T16:04:19.000Z
2019-02-19T15:42:27.000Z
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
null
null
null
accounting/root.py
michellab/BioSimSpaceCloud
456b146a2131565e354352872d3e75a08c3652d1
[ "Apache-2.0" ]
null
null
null
from Acquire.Service import create_return_value from Acquire.Service import get_service_info, get_service_private_key def run(args): """This function return the status and service info""" status = 0 message = None service = None service = get_service_info() status = 0 message = "Success" return_value = create_return_value(status, message) if service: return_value["service_info"] = service.to_data() return return_value
19.958333
69
0.707724
from Acquire.Service import create_return_value from Acquire.Service import get_service_info, get_service_private_key def run(args): status = 0 message = None service = None service = get_service_info() status = 0 message = "Success" return_value = create_return_value(status, message) if service: return_value["service_info"] = service.to_data() return return_value
true
true
f72798a96967ad3fd309ebf1baee8b1a120bae4d
13,803
py
Python
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
2
2020-06-09T01:48:13.000Z
2021-07-06T11:53:51.000Z
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
7
2020-09-26T01:11:45.000Z
2022-03-12T00:34:09.000Z
layers.py
richardsfc/neural_rerendering_plus
f5b2bd2ebe7e9657e3584612818eb0d137714276
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #     https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools from options import FLAGS as opts import numpy as np import tensorflow as tf from plyfile import PlyData, PlyElement class LayerDescriptor(object): def __init__(self, name, m): with tf.variable_scope(name): plydata = PlyData.read(opts.descriptor_folder + '/fused.ply') shape = [(plydata.elements[0].count // opts.descriptor_div) + 1, m] self.dim = m with tf.device('/device:GPU:1'): self.descriptors = tf.get_variable('descriptors', shape=shape) # 0 index is the null descriptor def __call__(self, x): """Apply layer to tensor x.""" with tf.device('/device:GPU:1'): shape = x.get_shape().as_list() indices = tf.reshape(x[:, :, :, -1], shape=[-1, 1]) indices = tf.compat.v1.cast(tf.math.ceil(tf.compat.v1.divide(indices, opts.descriptor_div)), tf.int64) D = tf.gather_nd(self.descriptors, indices) D = tf.reshape(D, shape=[-1, shape[1], shape[2], self.dim]) return tf.compat.v1.concat([tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, opts.deep_buffer_nc]), D], axis=-1) class LayerInstanceNorm(object): def __init__(self, scope_suffix='instance_norm'): curr_scope = tf.compat.v1.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.compat.v1.AUTO_REUSE): return tf.contrib.layers.instance_norm( x, epsilon=1e-05, center=True, scale=True) def layer_norm(x, scope='layer_norm'): return tf.contrib.layers.layer_norm(x, center=True, scale=True) def pixel_norm(x): """Pixel normalization. Args: x: 4D image tensor in B01C format. Returns: 4D tensor with pixel normalized channels. """ return x * tf.compat.v1.rsqrt(tf.compat.v1.reduce_mean(tf.compat.v1.square(x), [-1], keepdims=True) + 1e-8) def global_avg_pooling(x): return tf.compat.v1.reduce_mean(x, axis=[1, 2], keepdims=True) class FullyConnected(object): def __init__(self, n_out_units, scope_suffix='FC'): weight_init = tf.compat.v1.random_normal_initializer(mean=0., stddev=0.02) weight_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0001) curr_scope = tf.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix self.fc_layer = functools.partial( tf.layers.dense, units=n_out_units, kernel_initializer=weight_init, kernel_regularizer=weight_regularizer, use_bias=True) def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.AUTO_REUSE): return self.fc_layer(x) def init_he_scale(shape, slope=1.0): """He neural network random normal scaling for initialization. Args: shape: list of the dimensions of the tensor. slope: float, slope of the ReLu following the layer. Returns: a float, He's standard deviation. """ fan_in = np.prod(shape[:-1]) return np.sqrt(2. / ((1. + slope**2) * fan_in)) class LayerConv(object): """Convolution layer with support for equalized learning.""" def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple of ints, input and output channel depths. stride: int or 2-tuple, stride for the convolution kernel. padding: string, the padding method. {SAME, VALID, REFLECT}. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding' self._padding = padding with tf.compat.v1.variable_scope(name): if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.w = w shape = [w[0], w[1], n[0], n[1]] init_scale, pre_scale = init_he_scale(shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._stride = stride self._pre_scale = pre_scale self._weight = tf.compat.v1.get_variable( 'weight', shape=shape, initializer=tf.compat.v1.random_normal_initializer(stddev=init_scale)) self._bias = tf.compat.v1.get_variable( 'bias', shape=[n[1]], initializer=tf.compat.v1.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" if self._padding != 'REFLECT': padding = self._padding else: padding = 'VALID' pad_top = self.w[0] // 2 pad_left = self.w[1] // 2 if (self.w[0] - self._stride[1]) % 2 == 0: pad_bottom = pad_top else: pad_bottom = self.w[0] - self._stride[1] - pad_top if (self.w[1] - self._stride[2]) % 2 == 0: pad_right = pad_left else: pad_right = self.w[1] - self._stride[2] - pad_left x = tf.compat.v1.pad(x, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], mode='REFLECT') y = tf.compat.v1.nn.conv2d(x, self._weight, strides=self._stride, padding=padding) return self._pre_scale * y + self._bias class LayerTransposedConv(object): """Convolution layer with support for equalized learning.""" def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. w: int or 2-tuple, width of the convolution kernel. n: 2-tuple int, [n_in_channels, n_out_channels] stride: int or 2-tuple, stride for the convolution kernel. padding: string, the padding method {SAME, VALID, REFLECT}. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ assert padding in ['SAME'], 'Error: unsupported padding for transposed conv' if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.padding = padding self.nc_in, self.nc_out = n self.stride = stride with tf.variable_scope(name): kernel_shape = [w[0], w[1], self.nc_out, self.nc_in] init_scale, pre_scale = init_he_scale(kernel_shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=kernel_shape, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[self.nc_out], initializer=tf.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" x_shape = x.get_shape().as_list() batch_size = tf.shape(x)[0] stride_x, stride_y = self.stride[1], self.stride[2] output_shape = tf.stack([ batch_size, x_shape[1] * stride_x, x_shape[2] * stride_y, self.nc_out]) y = tf.nn.conv2d_transpose( x, filter=self._weight, output_shape=output_shape, strides=self.stride, padding=self.padding) return self._pre_scale * y + self._bias class ResBlock(object): def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.): """Layer constructor.""" self.name = name conv2d = functools.partial( LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) self.blocks = [] with tf.variable_scope(self.name): with tf.variable_scope('res0'): self.blocks.append( LayerPipe([ conv2d('res0_conv'), norm_layer_constructor('res0_norm'), activation ]) ) with tf.variable_scope('res1'): self.blocks.append( LayerPipe([ conv2d('res1_conv'), norm_layer_constructor('res1_norm') ]) ) def __call__(self, x_init): """Apply layer to tensor x.""" x = x_init for f in self.blocks: x = f(x) return x + x_init class BasicBlock(object): def __init__(self, name, n, activation=functools.partial(tf.compat.v1.nn.leaky_relu, alpha=0.2), padding='SAME', use_scaling=True, relu_slope=1.): """Layer constructor.""" self.name = name conv2d = functools.partial( LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) nc_in, nc_out = n # n is a 2-tuple with tf.compat.v1.variable_scope(self.name): self.path1_blocks = [] with tf.compat.v1.variable_scope('bb_path1'): self.path1_blocks.append( LayerPipe([ activation, conv2d('bb_conv0', w=3, n=[nc_in, nc_out]), activation, conv2d('bb_conv1', w=3, n=[nc_out, nc_out]), downscale ]) ) self.path2_blocks = [] with tf.compat.v1.variable_scope('bb_path2'): self.path2_blocks.append( LayerPipe([ downscale, conv2d('path2_conv', w=1, n=[nc_in, nc_out]) ]) ) def __call__(self, x_init): """Apply layer to tensor x.""" x1 = x_init x2 = x_init for f in self.path1_blocks: x1 = f(x1) for f in self.path2_blocks: x2 = f(x2) return x1 + x2 class LayerDense(object): """Dense layer with a non-linearity.""" def __init__(self, name, n, use_scaling=False, relu_slope=1.): """Layer constructor. Args: name: string, layer name. n: 2-tuple of ints, input and output widths. use_scaling: bool, whether to use weight norm and scaling. relu_slope: float, the slope of the ReLu following the layer. """ with tf.variable_scope(name): init_scale, pre_scale = init_he_scale(n, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=n, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[n[1]], initializer=tf.zeros_initializer) def __call__(self, x): """Apply layer to tensor x.""" return self._pre_scale * tf.matmul(x, self._weight) + self._bias class LayerPipe(object): """Pipe a sequence of functions.""" def __init__(self, functions): """Layer constructor. Args: functions: list, functions to pipe. """ self._functions = tuple(functions) def __call__(self, x, **kwargs): """Apply pipe to tensor x and return result.""" del kwargs for f in self._functions: x = f(x) return x def downscale(x, n=2): """Box downscaling. Args: x: 4D image tensor. n: integer scale (must be a power of 2). Returns: 4D tensor of images down scaled by a factor n. """ if n == 1: return x return tf.compat.v1.nn.avg_pool(x, [1, n, n, 1], [1, n, n, 1], 'VALID') def upscale(x, n): """Box upscaling (also called nearest neighbors). Args: x: 4D image tensor in B01C format. n: integer scale (must be a power of 2). Returns: 4D tensor of images up scaled by a factor n. """ if n == 1: return x x_shape = tf.compat.v1.shape(x) height, width = x_shape[1], x_shape[2] return tf.compat.v1.image.resize_nearest_neighbor(x, [n * height, n * width]) def tile_and_concatenate(x, z, n_z): z = tf.compat.v1.reshape(z, shape=[-1, 1, 1, n_z]) z = tf.compat.v1.tile(z, [1, tf.compat.v1.shape(x)[1], tf.compat.v1.shape(x)[2], 1]) x = tf.compat.v1.concat([x, z], axis=-1) return x def minibatch_mean_variance(x): """Computes the variance average. This is used by the discriminator as a form of batch discrimination. Args: x: nD tensor for which to compute variance average. Returns: a scalar, the mean variance of variable x. """ mean = tf.compat.v1.reduce_mean(x, 0, keepdims=True) vals = tf.compat.v1.sqrt(tf.compat.v1.reduce_mean(tf.compat.v1.squared_difference(x, mean), 0) + 1e-8) vals = tf.compat.v1.reduce_mean(vals) return vals def scalar_concat(x, scalar): """Concatenate a scalar to a 4D tensor as an extra channel. Args: x: 4D image tensor in B01C format. scalar: a scalar to concatenate to the tensor. Returns: a 4D tensor with one extra channel containing the value scalar at every position. """ s = tf.compat.v1.shape(x) return tf.compat.v1.concat([x, tf.compat.v1.ones([s[0], s[1], s[2], 1]) * scalar], axis=3)
31.658257
110
0.626096
import functools from options import FLAGS as opts import numpy as np import tensorflow as tf from plyfile import PlyData, PlyElement class LayerDescriptor(object): def __init__(self, name, m): with tf.variable_scope(name): plydata = PlyData.read(opts.descriptor_folder + '/fused.ply') shape = [(plydata.elements[0].count // opts.descriptor_div) + 1, m] self.dim = m with tf.device('/device:GPU:1'): self.descriptors = tf.get_variable('descriptors', shape=shape) def __call__(self, x): with tf.device('/device:GPU:1'): shape = x.get_shape().as_list() indices = tf.reshape(x[:, :, :, -1], shape=[-1, 1]) indices = tf.compat.v1.cast(tf.math.ceil(tf.compat.v1.divide(indices, opts.descriptor_div)), tf.int64) D = tf.gather_nd(self.descriptors, indices) D = tf.reshape(D, shape=[-1, shape[1], shape[2], self.dim]) return tf.compat.v1.concat([tf.slice(x, [0, 0, 0, 0], [-1, -1, -1, opts.deep_buffer_nc]), D], axis=-1) class LayerInstanceNorm(object): def __init__(self, scope_suffix='instance_norm'): curr_scope = tf.compat.v1.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.compat.v1.AUTO_REUSE): return tf.contrib.layers.instance_norm( x, epsilon=1e-05, center=True, scale=True) def layer_norm(x, scope='layer_norm'): return tf.contrib.layers.layer_norm(x, center=True, scale=True) def pixel_norm(x): return x * tf.compat.v1.rsqrt(tf.compat.v1.reduce_mean(tf.compat.v1.square(x), [-1], keepdims=True) + 1e-8) def global_avg_pooling(x): return tf.compat.v1.reduce_mean(x, axis=[1, 2], keepdims=True) class FullyConnected(object): def __init__(self, n_out_units, scope_suffix='FC'): weight_init = tf.compat.v1.random_normal_initializer(mean=0., stddev=0.02) weight_regularizer = tf.contrib.layers.l2_regularizer(scale=0.0001) curr_scope = tf.get_variable_scope().name self._scope = curr_scope + '/' + scope_suffix self.fc_layer = functools.partial( tf.layers.dense, units=n_out_units, kernel_initializer=weight_init, kernel_regularizer=weight_regularizer, use_bias=True) def __call__(self, x): with tf.compat.v1.variable_scope(self._scope, reuse=tf.AUTO_REUSE): return self.fc_layer(x) def init_he_scale(shape, slope=1.0): fan_in = np.prod(shape[:-1]) return np.sqrt(2. / ((1. + slope**2) * fan_in)) class LayerConv(object): def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): assert padding in ['SAME', 'VALID', 'REFLECT'], 'Error: unsupported padding' self._padding = padding with tf.compat.v1.variable_scope(name): if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.w = w shape = [w[0], w[1], n[0], n[1]] init_scale, pre_scale = init_he_scale(shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._stride = stride self._pre_scale = pre_scale self._weight = tf.compat.v1.get_variable( 'weight', shape=shape, initializer=tf.compat.v1.random_normal_initializer(stddev=init_scale)) self._bias = tf.compat.v1.get_variable( 'bias', shape=[n[1]], initializer=tf.compat.v1.zeros_initializer) def __call__(self, x): if self._padding != 'REFLECT': padding = self._padding else: padding = 'VALID' pad_top = self.w[0] // 2 pad_left = self.w[1] // 2 if (self.w[0] - self._stride[1]) % 2 == 0: pad_bottom = pad_top else: pad_bottom = self.w[0] - self._stride[1] - pad_top if (self.w[1] - self._stride[2]) % 2 == 0: pad_right = pad_left else: pad_right = self.w[1] - self._stride[2] - pad_left x = tf.compat.v1.pad(x, [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], mode='REFLECT') y = tf.compat.v1.nn.conv2d(x, self._weight, strides=self._stride, padding=padding) return self._pre_scale * y + self._bias class LayerTransposedConv(object): def __init__(self, name, w, n, stride, padding='SAME', use_scaling=False, relu_slope=1.): assert padding in ['SAME'], 'Error: unsupported padding for transposed conv' if isinstance(stride, int): stride = [1, stride, stride, 1] else: assert len(stride) == 2, "stride is either an int or a 2-tuple" stride = [1, stride[0], stride[1], 1] if isinstance(w, int): w = [w, w] self.padding = padding self.nc_in, self.nc_out = n self.stride = stride with tf.variable_scope(name): kernel_shape = [w[0], w[1], self.nc_out, self.nc_in] init_scale, pre_scale = init_he_scale(kernel_shape, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=kernel_shape, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[self.nc_out], initializer=tf.zeros_initializer) def __call__(self, x): x_shape = x.get_shape().as_list() batch_size = tf.shape(x)[0] stride_x, stride_y = self.stride[1], self.stride[2] output_shape = tf.stack([ batch_size, x_shape[1] * stride_x, x_shape[2] * stride_y, self.nc_out]) y = tf.nn.conv2d_transpose( x, filter=self._weight, output_shape=output_shape, strides=self.stride, padding=self.padding) return self._pre_scale * y + self._bias class ResBlock(object): def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.): self.name = name conv2d = functools.partial( LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) self.blocks = [] with tf.variable_scope(self.name): with tf.variable_scope('res0'): self.blocks.append( LayerPipe([ conv2d('res0_conv'), norm_layer_constructor('res0_norm'), activation ]) ) with tf.variable_scope('res1'): self.blocks.append( LayerPipe([ conv2d('res1_conv'), norm_layer_constructor('res1_norm') ]) ) def __call__(self, x_init): x = x_init for f in self.blocks: x = f(x) return x + x_init class BasicBlock(object): def __init__(self, name, n, activation=functools.partial(tf.compat.v1.nn.leaky_relu, alpha=0.2), padding='SAME', use_scaling=True, relu_slope=1.): self.name = name conv2d = functools.partial( LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) nc_in, nc_out = n with tf.compat.v1.variable_scope(self.name): self.path1_blocks = [] with tf.compat.v1.variable_scope('bb_path1'): self.path1_blocks.append( LayerPipe([ activation, conv2d('bb_conv0', w=3, n=[nc_in, nc_out]), activation, conv2d('bb_conv1', w=3, n=[nc_out, nc_out]), downscale ]) ) self.path2_blocks = [] with tf.compat.v1.variable_scope('bb_path2'): self.path2_blocks.append( LayerPipe([ downscale, conv2d('path2_conv', w=1, n=[nc_in, nc_out]) ]) ) def __call__(self, x_init): x1 = x_init x2 = x_init for f in self.path1_blocks: x1 = f(x1) for f in self.path2_blocks: x2 = f(x2) return x1 + x2 class LayerDense(object): def __init__(self, name, n, use_scaling=False, relu_slope=1.): with tf.variable_scope(name): init_scale, pre_scale = init_he_scale(n, relu_slope), 1. if use_scaling: init_scale, pre_scale = pre_scale, init_scale self._pre_scale = pre_scale self._weight = tf.get_variable( 'weight', shape=n, initializer=tf.random_normal_initializer(stddev=init_scale)) self._bias = tf.get_variable( 'bias', shape=[n[1]], initializer=tf.zeros_initializer) def __call__(self, x): return self._pre_scale * tf.matmul(x, self._weight) + self._bias class LayerPipe(object): def __init__(self, functions): self._functions = tuple(functions) def __call__(self, x, **kwargs): del kwargs for f in self._functions: x = f(x) return x def downscale(x, n=2): if n == 1: return x return tf.compat.v1.nn.avg_pool(x, [1, n, n, 1], [1, n, n, 1], 'VALID') def upscale(x, n): if n == 1: return x x_shape = tf.compat.v1.shape(x) height, width = x_shape[1], x_shape[2] return tf.compat.v1.image.resize_nearest_neighbor(x, [n * height, n * width]) def tile_and_concatenate(x, z, n_z): z = tf.compat.v1.reshape(z, shape=[-1, 1, 1, n_z]) z = tf.compat.v1.tile(z, [1, tf.compat.v1.shape(x)[1], tf.compat.v1.shape(x)[2], 1]) x = tf.compat.v1.concat([x, z], axis=-1) return x def minibatch_mean_variance(x): mean = tf.compat.v1.reduce_mean(x, 0, keepdims=True) vals = tf.compat.v1.sqrt(tf.compat.v1.reduce_mean(tf.compat.v1.squared_difference(x, mean), 0) + 1e-8) vals = tf.compat.v1.reduce_mean(vals) return vals def scalar_concat(x, scalar): s = tf.compat.v1.shape(x) return tf.compat.v1.concat([x, tf.compat.v1.ones([s[0], s[1], s[2], 1]) * scalar], axis=3)
true
true
f7279945818ccb74868b87f76d1ec78f62a9ecf6
536
py
Python
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
12
2021-03-12T12:12:02.000Z
2021-10-04T18:30:19.000Z
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
28
2021-03-14T05:52:36.000Z
2022-03-17T04:16:28.000Z
pysql/__init__.py
fossabot/PySQL
3cd46130ce12bcd7636d4715176d6610b1dcf279
[ "MIT" ]
8
2021-03-31T14:31:49.000Z
2022-03-13T09:43:31.000Z
""" module for PySQL wrapper functions, for using as a library """ __author__ = "Devansh Singh" __email__ = "devanshamity@gmail.com" __license__ = "MIT" from pysql import * """ classes for functions for initializing object instances, use (username, password) of local MySQL server """ from pysql.packages.auth import Database from pysql.packages.ddl_commands import DDL, Alter from pysql.packages.dml_commands import DML from pysql.data.export import Export from pysql.data.imports import Import """ PySQL Devansh Singh, 2021 """
17.290323
50
0.772388
__author__ = "Devansh Singh" __email__ = "devanshamity@gmail.com" __license__ = "MIT" from pysql import * from pysql.packages.auth import Database from pysql.packages.ddl_commands import DDL, Alter from pysql.packages.dml_commands import DML from pysql.data.export import Export from pysql.data.imports import Import
true
true
f72799e9e1cbfc52c99b8a8ba84b5bcb51232a74
982
py
Python
setup.py
AndreJambersi/Project_hours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
1
2019-10-23T17:38:07.000Z
2019-10-23T17:38:07.000Z
setup.py
AndreJambersi/TimeBetweenBusinessHours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
null
null
null
setup.py
AndreJambersi/TimeBetweenBusinessHours
3f99566e0b1e54aa4e2f848ad34dbe9988f75591
[ "MIT" ]
null
null
null
from distutils.core import setup setup( name = 'TimeBetweenBusinessHours', packages = ['TimeBetweenBusinessHours'], version = '0.1', license='MIT', description = 'Get the Time Between Business Hours', author = 'AndreJambersi', author_email = 'andrejambersi@gmail.com', url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours', download_url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours/archive/v_01.tar.gz', keywords = ['JOB', 'TIME', 'DATE'], install_requires=[ 'TimeBetweenBusinessHours', 'datetime', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
35.071429
98
0.645621
from distutils.core import setup setup( name = 'TimeBetweenBusinessHours', packages = ['TimeBetweenBusinessHours'], version = '0.1', license='MIT', description = 'Get the Time Between Business Hours', author = 'AndreJambersi', author_email = 'andrejambersi@gmail.com', url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours', download_url = 'https://github.com/AndreJambersi/TimeBetweenBusinessHours/archive/v_01.tar.gz', keywords = ['JOB', 'TIME', 'DATE'], install_requires=[ 'TimeBetweenBusinessHours', 'datetime', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
true
true
f72799ee803e4457c079e7493a5b02931855af6b
4,817
py
Python
docs/_static/pyparsing_examples/simpleSQL.py
emacsway/sqlbuilder
72f32bbbfc1116550343c471dc43ef6284492a5a
[ "BSD-3-Clause" ]
33
2017-07-26T02:33:48.000Z
2022-03-18T06:38:12.000Z
docs/_static/pyparsing_examples/simpleSQL.py
emacsway/sqlbuilder
72f32bbbfc1116550343c471dc43ef6284492a5a
[ "BSD-3-Clause" ]
1
2019-03-03T15:09:46.000Z
2019-03-03T15:09:46.000Z
docs/_static/pyparsing_examples/simpleSQL.py
emacsway/sqlbuilder
72f32bbbfc1116550343c471dc43ef6284492a5a
[ "BSD-3-Clause" ]
3
2017-09-25T03:00:11.000Z
2020-10-21T09:59:09.000Z
# Source: http://pyparsing.wikispaces.com/file/view/simpleSQL.py # simpleSQL.py # # simple demo of using the parsing library to do simple-minded SQL parsing # could be extended to include where clauses etc. # # Copyright (c) 2003, Paul McGuire # from pyparsing import Literal, CaselessLiteral, Word, Upcase, delimitedList, Optional, \ Combine, Group, alphas, nums, alphanums, ParseException, Forward, oneOf, quotedString, \ ZeroOrMore, restOfLine, Keyword def test( str ): print str,"->" try: tokens = simpleSQL.parseString( str ) print "tokens = ", tokens print "tokens.columns =", tokens.columns print "tokens.tables =", tokens.tables print "tokens.where =", tokens.where except ParseException, err: print " "*err.loc + "^\n" + err.msg print err print # define SQL tokens selectStmt = Forward() selectToken = Keyword("select", caseless=True) fromToken = Keyword("from", caseless=True) ident = Word( alphas, alphanums + "_$" ).setName("identifier") columnName = Upcase( delimitedList( ident, ".", combine=True ) ) columnNameList = Group( delimitedList( columnName ) ) tableName = Upcase( delimitedList( ident, ".", combine=True ) ) tableNameList = Group( delimitedList( tableName ) ) whereExpression = Forward() and_ = Keyword("and", caseless=True) or_ = Keyword("or", caseless=True) in_ = Keyword("in", caseless=True) E = CaselessLiteral("E") binop = oneOf("= != < > >= <= eq ne lt le gt ge", caseless=True) arithSign = Word("+-",exact=1) realNum = Combine( Optional(arithSign) + ( Word( nums ) + "." + Optional( Word(nums) ) | ( "." + Word(nums) ) ) + Optional( E + Optional(arithSign) + Word(nums) ) ) intNum = Combine( Optional(arithSign) + Word( nums ) + Optional( E + Optional("+") + Word(nums) ) ) columnRval = realNum | intNum | quotedString | columnName # need to add support for alg expressions whereCondition = Group( ( columnName + binop + columnRval ) | ( columnName + in_ + "(" + delimitedList( columnRval ) + ")" ) | ( columnName + in_ + "(" + selectStmt + ")" ) | ( "(" + whereExpression + ")" ) ) whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression ) # define the grammar selectStmt << ( selectToken + ( '*' | columnNameList ).setResultsName( "columns" ) + fromToken + tableNameList.setResultsName( "tables" ) + Optional( Group( CaselessLiteral("where") + whereExpression ), "" ).setResultsName("where") ) simpleSQL = selectStmt # define Oracle comment format, and ignore them oracleSqlComment = "--" + restOfLine simpleSQL.ignore( oracleSqlComment ) test( "SELECT * from XYZZY, ABC" ) test( "select * from SYS.XYZZY" ) test( "Select A from Sys.dual" ) test( "Select A,B,C from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Select A, B, C from Sys.dual, Table2 " ) test( "Xelect A, B, C from Sys.dual" ) test( "Select A, B, C frox Sys.dual" ) test( "Select" ) test( "Select &&& frox Sys.dual" ) test( "Select A from Sys.dual where a in ('RED','GREEN','BLUE')" ) test( "Select A from Sys.dual where a in ('RED','GREEN','BLUE') and b in (10,20,30)" ) test( "Select A,b from table1,table2 where table1.id eq table2.id -- test out comparison operators" ) """ Test output: >pythonw -u simpleSQL.py SELECT * from XYZZY, ABC -> tokens = ['select', '*', 'from', ['XYZZY', 'ABC']] tokens.columns = * tokens.tables = ['XYZZY', 'ABC'] select * from SYS.XYZZY -> tokens = ['select', '*', 'from', ['SYS.XYZZY']] tokens.columns = * tokens.tables = ['SYS.XYZZY'] Select A from Sys.dual -> tokens = ['select', ['A'], 'from', ['SYS.DUAL']] tokens.columns = ['A'] tokens.tables = ['SYS.DUAL'] Select A,B,C from Sys.dual -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL'] Select A, B, C from Sys.dual -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL'] Select A, B, C from Sys.dual, Table2 -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL', 'TABLE2']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL', 'TABLE2'] Xelect A, B, C from Sys.dual -> ^ Expected 'select' Expected 'select' (0), (1,1) Select A, B, C frox Sys.dual -> ^ Expected 'from' Expected 'from' (15), (1,16) Select -> ^ Expected '*' Expected '*' (6), (1,7) Select &&& frox Sys.dual -> ^ Expected '*' Expected '*' (7), (1,8) >Exit code: 0 """
33.451389
113
0.588333
from pyparsing import Literal, CaselessLiteral, Word, Upcase, delimitedList, Optional, \ Combine, Group, alphas, nums, alphanums, ParseException, Forward, oneOf, quotedString, \ ZeroOrMore, restOfLine, Keyword def test( str ): print str,"->" try: tokens = simpleSQL.parseString( str ) print "tokens = ", tokens print "tokens.columns =", tokens.columns print "tokens.tables =", tokens.tables print "tokens.where =", tokens.where except ParseException, err: print " "*err.loc + "^\n" + err.msg print err print selectStmt = Forward() selectToken = Keyword("select", caseless=True) fromToken = Keyword("from", caseless=True) ident = Word( alphas, alphanums + "_$" ).setName("identifier") columnName = Upcase( delimitedList( ident, ".", combine=True ) ) columnNameList = Group( delimitedList( columnName ) ) tableName = Upcase( delimitedList( ident, ".", combine=True ) ) tableNameList = Group( delimitedList( tableName ) ) whereExpression = Forward() and_ = Keyword("and", caseless=True) or_ = Keyword("or", caseless=True) in_ = Keyword("in", caseless=True) E = CaselessLiteral("E") binop = oneOf("= != < > >= <= eq ne lt le gt ge", caseless=True) arithSign = Word("+-",exact=1) realNum = Combine( Optional(arithSign) + ( Word( nums ) + "." + Optional( Word(nums) ) | ( "." + Word(nums) ) ) + Optional( E + Optional(arithSign) + Word(nums) ) ) intNum = Combine( Optional(arithSign) + Word( nums ) + Optional( E + Optional("+") + Word(nums) ) ) columnRval = realNum | intNum | quotedString | columnName whereCondition = Group( ( columnName + binop + columnRval ) | ( columnName + in_ + "(" + delimitedList( columnRval ) + ")" ) | ( columnName + in_ + "(" + selectStmt + ")" ) | ( "(" + whereExpression + ")" ) ) whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression ) selectStmt << ( selectToken + ( '*' | columnNameList ).setResultsName( "columns" ) + fromToken + tableNameList.setResultsName( "tables" ) + Optional( Group( CaselessLiteral("where") + whereExpression ), "" ).setResultsName("where") ) simpleSQL = selectStmt oracleSqlComment = "--" + restOfLine simpleSQL.ignore( oracleSqlComment ) test( "SELECT * from XYZZY, ABC" ) test( "select * from SYS.XYZZY" ) test( "Select A from Sys.dual" ) test( "Select A,B,C from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Select A, B, C from Sys.dual, Table2 " ) test( "Xelect A, B, C from Sys.dual" ) test( "Select A, B, C frox Sys.dual" ) test( "Select" ) test( "Select &&& frox Sys.dual" ) test( "Select A from Sys.dual where a in ('RED','GREEN','BLUE')" ) test( "Select A from Sys.dual where a in ('RED','GREEN','BLUE') and b in (10,20,30)" ) test( "Select A,b from table1,table2 where table1.id eq table2.id -- test out comparison operators" ) """ Test output: >pythonw -u simpleSQL.py SELECT * from XYZZY, ABC -> tokens = ['select', '*', 'from', ['XYZZY', 'ABC']] tokens.columns = * tokens.tables = ['XYZZY', 'ABC'] select * from SYS.XYZZY -> tokens = ['select', '*', 'from', ['SYS.XYZZY']] tokens.columns = * tokens.tables = ['SYS.XYZZY'] Select A from Sys.dual -> tokens = ['select', ['A'], 'from', ['SYS.DUAL']] tokens.columns = ['A'] tokens.tables = ['SYS.DUAL'] Select A,B,C from Sys.dual -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL'] Select A, B, C from Sys.dual -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL'] Select A, B, C from Sys.dual, Table2 -> tokens = ['select', ['A', 'B', 'C'], 'from', ['SYS.DUAL', 'TABLE2']] tokens.columns = ['A', 'B', 'C'] tokens.tables = ['SYS.DUAL', 'TABLE2'] Xelect A, B, C from Sys.dual -> ^ Expected 'select' Expected 'select' (0), (1,1) Select A, B, C frox Sys.dual -> ^ Expected 'from' Expected 'from' (15), (1,16) Select -> ^ Expected '*' Expected '*' (6), (1,7) Select &&& frox Sys.dual -> ^ Expected '*' Expected '*' (7), (1,8) >Exit code: 0 """
false
true
f7279c891026d6d9c304e4c395e6d04dfac0fd5f
44,050
py
Python
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
190
2016-09-26T08:38:31.000Z
2022-02-10T23:18:00.000Z
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
127
2016-05-20T07:31:06.000Z
2022-02-16T14:48:09.000Z
TexSoup/data.py
pablo-angulo/TexSoup
bfd09bcfc8e020f26939a7166d9316bac51515f0
[ "BSD-2-Clause" ]
44
2017-07-23T19:58:00.000Z
2021-12-03T12:57:48.000Z
"""TexSoup transforms a LaTeX document into a complex tree of various Python objects, but all objects fall into one of the following three categories: ``TexNode``, ``TexExpr`` (environments and commands), and ``TexGroup`` s. """ import itertools import re from TexSoup.utils import CharToLineOffset, Token, TC, to_list __all__ = ['TexNode', 'TexCmd', 'TexEnv', 'TexGroup', 'BracketGroup', 'BraceGroup', 'TexArgs', 'TexText', 'TexMathEnv', 'TexDisplayMathEnv', 'TexNamedEnv', 'TexMathModeEnv', 'TexDisplayMathModeEnv'] ############# # Interface # ############# class TexNode(object): r"""A tree node representing an expression in the LaTeX document. Every node in the parse tree is a ``TexNode``, equipped with navigation, search, and modification utilities. To navigate the parse tree, use abstractions such as ``children`` and ``descendant``. To access content in the parse tree, use abstractions such as ``contents``, ``text``, ``string`` , and ``args``. Note that the LaTeX parse tree is largely shallow: only environments such as ``itemize`` or ``enumerate`` have children and thus descendants. Typical LaTeX expressions such as ``\section`` have *arguments* but not children. """ def __init__(self, expr, src=None): """Creates TexNode object. :param TexExpr expr: a LaTeX expression, either a singleton command or an environment containing other commands :param str src: LaTeX source string """ assert isinstance(expr, TexExpr), \ 'Expression given to node must be a valid TexExpr' super().__init__() self.expr = expr self.parent = None if src is not None: self.char_to_line = CharToLineOffset(src) else: self.char_to_line = None ################# # MAGIC METHODS # ################# def __contains__(self, other): """Use custom containment checker where applicable (TexText, for ex)""" if hasattr(self.expr, '__contains__'): return other in self.expr return other in iter(self) def __getattr__(self, attr, default=None): """Convert all invalid attributes into basic find operation.""" return self.find(attr) or default def __getitem__(self, item): return list(self.contents)[item] def __iter__(self): """ >>> node = TexNode(TexNamedEnv('lstlisting', ('hai', 'there'))) >>> list(node) ['hai', 'there'] """ return iter(self.contents) def __match__(self, name=None, attrs=()): r"""Check if given attributes match current object >>> from TexSoup import TexSoup >>> soup = TexSoup(r'\ref{hello}\ref{hello}\ref{hello}\ref{nono}') >>> soup.count(r'\ref{hello}') 3 """ return self.expr.__match__(name, attrs) def __repr__(self): """Interpreter representation.""" return str(self) def __str__(self): """Stringified command.""" return str(self.expr) ############## # PROPERTIES # ############## @property @to_list def all(self): r"""Returns all content in this node, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \newcommand{reverseconcat}[3]{#3#2#1} ... ''') >>> alls = soup.all >>> alls[0] <BLANKLINE> <BLANKLINE> >>> alls[1] \newcommand{reverseconcat}[3]{#3#2#1} """ for child in self.expr.all: assert isinstance(child, TexExpr) node = TexNode(child) node.parent = self yield node @property def args(self): r"""Arguments for this node. Note that this argument is settable. :rtype: TexArgs >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\newcommand{reverseconcat}[3]{#3#2#1}''') >>> soup.newcommand.args [BraceGroup('reverseconcat'), BracketGroup('3'), BraceGroup('#3#2#1')] >>> soup.newcommand.args = soup.newcommand.args[:2] >>> soup.newcommand \newcommand{reverseconcat}[3] """ return self.expr.args @args.setter def args(self, args): assert isinstance(args, TexArgs), "`args` must be of type `TexArgs`" self.expr.args = args @property @to_list def children(self): r"""Immediate children of this TeX element that are valid TeX objects. This is equivalent to contents, excluding text elements and keeping only Tex expressions. :return: generator of all children :rtype: Iterator[TexExpr] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... Random text! ... \item Hello ... \end{itemize}''') >>> soup.itemize.children[0] \item Hello <BLANKLINE> """ for child in self.expr.children: node = TexNode(child) node.parent = self yield node @property @to_list def contents(self): r"""Any non-whitespace contents inside of this TeX element. :return: generator of all nodes, tokens, and strings :rtype: Iterator[Union[TexNode,str]] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... Random text! ... \item Hello ... \end{itemize}''') >>> contents = soup.itemize.contents >>> contents[0] '\n Random text!\n ' >>> contents[1] \item Hello <BLANKLINE> """ for child in self.expr.contents: if isinstance(child, TexExpr): node = TexNode(child) node.parent = self yield node else: yield child @contents.setter def contents(self, contents): self.expr.contents = contents @property def descendants(self): r"""Returns all descendants for this TeX element. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \begin{itemize} ... \item Nested ... \end{itemize} ... \end{itemize}''') >>> descendants = list(soup.itemize.descendants) >>> descendants[1] \item Nested <BLANKLINE> """ return self.__descendants() @property def name(self): r"""Name of the expression. Used for search functions. :rtype: str >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textbf{Hello}''') >>> soup.textbf.name 'textbf' >>> soup.textbf.name = 'textit' >>> soup.textit \textit{Hello} """ return self.expr.name @name.setter def name(self, name): self.expr.name = name @property def string(self): r"""This is valid if and only if 1. the expression is a :class:`.TexCmd` AND has only one argument OR 2. the expression is a :class:`.TexEnv` AND has only one TexText child :rtype: Union[None,str] >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textbf{Hello}''') >>> soup.textbf.string 'Hello' >>> soup.textbf.string = 'Hello World' >>> soup.textbf.string 'Hello World' >>> soup.textbf \textbf{Hello World} >>> soup = TexSoup(r'''\begin{equation}1+1\end{equation}''') >>> soup.equation.string '1+1' >>> soup.equation.string = '2+2' >>> soup.equation.string '2+2' """ if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' return self.expr.args[0].string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' return contents[0] @string.setter def string(self, string): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' self.expr.args[0].string = string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' self.contents = [string] @property def position(self): r"""Position of first character in expression, in original source. Note this position is NOT updated as the parsed tree is modified. """ return self.expr.position @property @to_list def text(self): r"""All text in descendant nodes. This is equivalent to contents, keeping text elements and excluding Tex expressions. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \begin{itemize} ... \item Nested ... \end{itemize} ... \end{itemize}''') >>> soup.text[0] ' Nested\n ' """ for descendant in self.contents: if isinstance(descendant, (TexText, Token)): yield descendant elif hasattr(descendant, 'text'): yield from descendant.text ################## # PUBLIC METHODS # ################## def append(self, *nodes): r"""Add node(s) to this node's list of children. :param TexNode nodes: List of nodes to add >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \end{itemize} ... \section{Hey} ... \textit{Willy}''') >>> soup.section \section{Hey} >>> soup.section.append(soup.textit) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: ... >>> soup.section \section{Hey} >>> soup.itemize.append(' ', soup.item) >>> soup.itemize \begin{itemize} \item Hello \item Hello \end{itemize} """ self.expr.append(*nodes) def insert(self, i, *nodes): r"""Add node(s) to this node's list of children, at position i. :param int i: Position to add nodes to :param TexNode nodes: List of nodes to add >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> item = soup.item.copy() >>> soup.item.delete() >>> soup.itemize.insert(1, item) >>> soup.itemize \begin{itemize} \item Hello \item Bye \end{itemize} >>> item.parent.name == soup.itemize.name True """ assert isinstance(i, int), ( 'Provided index "{}" is not an integer! Did you switch your ' 'arguments? The first argument to `insert` is the ' 'index.'.format(i)) for node in nodes: if not isinstance(node, TexNode): continue assert not node.parent, ( 'Inserted node should not already have parent. Call `.copy()` ' 'on node to fix.' ) node.parent = self self.expr.insert(i, *nodes) def char_pos_to_line(self, char_pos): r"""Map position in the original string to parsed LaTeX position. :param int char_pos: Character position in the original string :return: (line number, index of character in line) :rtype: Tuple[int, int] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textbf{Silly} ... \textit{Willy}''') >>> soup.char_pos_to_line(10) (1, 9) >>> soup.char_pos_to_line(20) (2, 5) """ assert self.char_to_line is not None, ( 'CharToLineOffset is not initialized. Pass src to TexNode ' 'constructor') return self.char_to_line(char_pos) def copy(self): r"""Create another copy of the current node. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textit{Silly} ... \textit{Willy}''') >>> s = soup.section.copy() >>> s.parent is None True """ return TexNode(self.expr) def count(self, name=None, **attrs): r"""Number of descendants matching criteria. :param Union[None,str] name: name of LaTeX expression :param attrs: LaTeX expression attributes, such as item text. :return: number of matching expressions :rtype: int >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Hey} ... \textit{Silly} ... \textit{Willy}''') >>> soup.count('section') 1 >>> soup.count('textit') 2 """ return len(list(self.find_all(name, **attrs))) def delete(self): r"""Delete this node from the parse tree. Where applicable, this will remove all descendants of this node from the parse tree. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \textit{\color{blue}{Silly}}\textit{keep me!}''') >>> soup.textit.color.delete() >>> soup <BLANKLINE> \textit{}\textit{keep me!} >>> soup.textit.delete() >>> soup <BLANKLINE> \textit{keep me!} """ # TODO: needs better abstraction for supports contents parent = self.parent if parent.expr._supports_contents(): parent.remove(self) return # TODO: needs abstraction for removing from arg for arg in parent.args: if self.expr in arg.contents: arg._contents.remove(self.expr) def find(self, name=None, **attrs): r"""First descendant node matching criteria. Returns None if no descendant node found. :return: descendant node matching criteria :rtype: Union[None,TexExpr] >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Ooo} ... \textit{eee} ... \textit{ooo}''') >>> soup.find('textit') \textit{eee} >>> soup.find('textbf') """ try: return self.find_all(name, **attrs)[0] except IndexError: return None @to_list def find_all(self, name=None, **attrs): r"""Return all descendant nodes matching criteria. :param Union[None,str,list] name: name of LaTeX expression :param attrs: LaTeX expression attributes, such as item text. :return: All descendant nodes matching criteria :rtype: Iterator[TexNode] If `name` is a list of `str`'s, any matching section will be matched. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \section{Ooo} ... \textit{eee} ... \textit{ooo}''') >>> gen = soup.find_all('textit') >>> gen[0] \textit{eee} >>> gen[1] \textit{ooo} >>> soup.find_all('textbf')[0] Traceback (most recent call last): ... IndexError: list index out of range """ for descendant in self.__descendants(): if hasattr(descendant, '__match__') and \ descendant.__match__(name, attrs): yield descendant def remove(self, node): r"""Remove a node from this node's list of contents. :param TexExpr node: Node to remove >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> soup.itemize.remove(soup.item) >>> soup.itemize \begin{itemize} \item Bye \end{itemize} """ self.expr.remove(node.expr) def replace_with(self, *nodes): r"""Replace this node in the parse tree with the provided node(s). :param TexNode nodes: List of nodes to subtitute in >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> items = list(soup.find_all('item')) >>> bye = items[1] >>> soup.item.replace_with(bye) >>> soup.itemize \begin{itemize} \item Bye \item Bye \end{itemize} """ self.parent.replace(self, *nodes) def replace(self, child, *nodes): r"""Replace provided node with node(s). :param TexNode child: Child node to replace :param TexNode nodes: List of nodes to subtitute in >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... \end{itemize}''') >>> items = list(soup.find_all('item')) >>> bye = items[1] >>> soup.itemize.replace(soup.item, bye) >>> soup.itemize \begin{itemize} \item Bye \item Bye \end{itemize} """ self.expr.insert( self.expr.remove(child.expr), *nodes) def search_regex(self, pattern): for node in self.text: for match in re.finditer(pattern, node): body = match.group() # group() returns the full match start = match.start() yield Token(body, node.position + start) def __descendants(self): """Implementation for descendants, hacky workaround for __getattr__ issues.""" return itertools.chain(self.contents, *[c.descendants for c in self.children]) ############### # Expressions # ############### class TexExpr(object): """General abstraction for a TeX expression. An expression may be a command or an environment and is identified by a name, arguments, and place in the parse tree. This is an abstract and is not directly instantiated. """ def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialize a tex expression. :param str name: name of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ self.name = name.strip() # TODO: should not ever have space self.args = TexArgs(args) self.parent = None self._contents = list(contents) or [] self.preserve_whitespace = preserve_whitespace self.position = position for content in contents: if isinstance(content, (TexEnv, TexCmd)): content.parent = self ################# # MAGIC METHODS # ################# def __eq__(self, other): """Check if two expressions are equal. This is useful when defining data structures over TexExprs. >>> exprs = [ ... TexExpr('cake', ['flour', 'taro']), ... TexExpr('corgi', ['derp', 'collar', 'drool', 'sass']) ... ] >>> exprs[0] in exprs True >>> TexExpr('cake', ['flour', 'taro']) in exprs True """ return str(other) == str(self) def __match__(self, name=None, attrs=()): """Check if given attributes match current object.""" # TODO: this should re-parse the name, instead of hardcoding here if '{' in name or '[' in name: return str(self) == name if isinstance(name, list): node_name = getattr(self, 'name') if node_name not in name: return False else: attrs['name'] = name for k, v in attrs.items(): if getattr(self, k) != v: return False return True def __repr__(self): if not self.args: return "TexExpr('%s', %s)" % (self.name, repr(self._contents)) return "TexExpr('%s', %s, %s)" % ( self.name, repr(self._contents), repr(self.args)) ############## # PROPERTIES # ############## @property @to_list def all(self): r"""Returns all content in this expression, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. >>> expr1 = TexExpr('textbf', ('\n', 'hi')) >>> expr2 = TexExpr('textbf', ('\n', 'hi'), preserve_whitespace=True) >>> list(expr1.all) == list(expr2.all) True """ for arg in self.args: for expr in arg.contents: yield expr for content in self._contents: yield content @property @to_list def children(self): return filter(lambda x: isinstance(x, (TexEnv, TexCmd)), self.contents) @property @to_list def contents(self): r"""Returns all contents in this expression. Optionally includes whitespace if set when node was created. >>> expr1 = TexExpr('textbf', ('\n', 'hi')) >>> list(expr1.contents) ['hi'] >>> expr2 = TexExpr('textbf', ('\n', 'hi'), preserve_whitespace=True) >>> list(expr2.contents) ['\n', 'hi'] >>> expr = TexExpr('textbf', ('\n', 'hi')) >>> expr.contents = ('hehe', '👻') >>> list(expr.contents) ['hehe', '👻'] >>> expr.contents = 35 #doctest:+ELLIPSIS Traceback (most recent call last): ... TypeError: ... """ for content in self.all: if isinstance(content, TexText): content = content._text is_whitespace = isinstance(content, str) and content.isspace() if not is_whitespace or self.preserve_whitespace: yield content @contents.setter def contents(self, contents): if not isinstance(contents, (list, tuple)) or not all( isinstance(content, (str, TexExpr)) for content in contents): raise TypeError( '.contents value "%s" must be a list or tuple of strings or ' 'TexExprs' % contents) _contents = [TexText(c) if isinstance(c, str) else c for c in contents] self._contents = _contents @property def string(self): """All contents stringified. A convenience property >>> expr = TexExpr('hello', ['naw']) >>> expr.string 'naw' >>> expr.string = 'huehue' >>> expr.string 'huehue' >>> type(expr.string) <class 'TexSoup.data.TexText'> >>> str(expr) "TexExpr('hello', ['huehue'])" >>> expr.string = 35 #doctest:+ELLIPSIS Traceback (most recent call last): ... TypeError: ... """ return TexText(''.join(map(str, self._contents))) @string.setter def string(self, s): if not isinstance(s, str): raise TypeError( '.string value "%s" must be a string or TexText. To set ' 'non-string content, use .contents' % s) self.contents = [TexText(s)] ################## # PUBLIC METHODS # ################## def append(self, *exprs): """Add contents to the expression. :param Union[TexExpr,str] exprs: List of contents to add >>> expr = TexExpr('textbf', ('hello',)) >>> expr TexExpr('textbf', ['hello']) >>> expr.append('world') >>> expr TexExpr('textbf', ['hello', 'world']) """ self._assert_supports_contents() self._contents.extend(exprs) def insert(self, i, *exprs): """Insert content at specified position into expression. :param int i: Position to add content to :param Union[TexExpr,str] exprs: List of contents to add >>> expr = TexExpr('textbf', ('hello',)) >>> expr TexExpr('textbf', ['hello']) >>> expr.insert(0, 'world') >>> expr TexExpr('textbf', ['world', 'hello']) >>> expr.insert(0, TexText('asdf')) >>> expr TexExpr('textbf', ['asdf', 'world', 'hello']) """ self._assert_supports_contents() for j, expr in enumerate(exprs): if isinstance(expr, TexExpr): expr.parent = self self._contents.insert(i + j, expr) def remove(self, expr): """Remove a provided expression from its list of contents. :param Union[TexExpr,str] expr: Content to add :return: index of the expression removed :rtype: int >>> expr = TexExpr('textbf', ('hello',)) >>> expr.remove('hello') 0 >>> expr TexExpr('textbf', []) """ self._assert_supports_contents() index = self._contents.index(expr) self._contents.remove(expr) return index def _supports_contents(self): return True def _assert_supports_contents(self): pass class TexEnv(TexExpr): r"""Abstraction for a LaTeX command, with starting and ending markers. Contains three attributes: 1. a human-readable environment name, 2. the environment delimiters 3. the environment's contents. >>> t = TexEnv('displaymath', r'\[', r'\]', ... ['\\mathcal{M} \\circ \\mathcal{A}']) >>> t TexEnv('displaymath', ['\\mathcal{M} \\circ \\mathcal{A}'], []) >>> print(t) \[\mathcal{M} \circ \mathcal{A}\] >>> len(list(t.children)) 0 """ _begin = None _end = None def __init__(self, name, begin, end, contents=(), args=(), preserve_whitespace=False, position=-1): r"""Initialization for Tex environment. :param str name: name of environment :param str begin: string denoting start of environment :param str end: string denoting end of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source >>> env = TexEnv('math', '$', '$', [r'\$']) >>> str(env) '$\\$$' >>> env.begin = '^^' >>> env.end = '**' >>> str(env) '^^\\$**' """ super().__init__(name, contents, args, preserve_whitespace, position) self._begin = begin self._end = end @property def begin(self): return self._begin @begin.setter def begin(self, begin): self._begin = begin @property def end(self): return self._end @end.setter def end(self, end): self._end = end def __match__(self, name=None, attrs=()): """Check if given attributes match environment.""" if name in (self.name, self.begin + str(self.args), self.begin, self.end): return True return super().__match__(name, attrs) def __str__(self): contents = ''.join(map(str, self._contents)) if self.name == '[tex]': return contents else: return '%s%s%s' % ( self.begin + str(self.args), contents, self.end) def __repr__(self): if self.name == '[tex]': return str(self._contents) if not self.args and not self._contents: return "%s('%s')" % (self.__class__.__name__, self.name) return "%s('%s', %s, %s)" % ( self.__class__.__name__, self.name, repr(self._contents), repr(self.args)) class TexNamedEnv(TexEnv): r"""Abstraction for a LaTeX command, denoted by ``\begin{env}`` and ``\end{env}``. Contains three attributes: 1. the environment name itself, 2. the environment arguments, whether optional or required, and 3. the environment's contents. **Warning**: Note that *setting* TexNamedEnv.begin or TexNamedEnv.end has no effect. The begin and end tokens are always constructed from TexNamedEnv.name. >>> t = TexNamedEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'], ... [BraceGroup('c | c c')]) >>> t TexNamedEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'], [BraceGroup('c | c c')]) >>> print(t) \begin{tabular}{c | c c} 0 & 0 & * \\ 1 & 1 & * \\ \end{tabular} >>> len(list(t.children)) 0 >>> t = TexNamedEnv('equation', [r'5\sum_{i=0}^n i^2']) >>> str(t) '\\begin{equation}5\\sum_{i=0}^n i^2\\end{equation}' >>> t.name = 'eqn' >>> str(t) '\\begin{eqn}5\\sum_{i=0}^n i^2\\end{eqn}' """ def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialization for Tex environment. :param str name: name of environment :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ super().__init__(name, r"\begin{%s}" % name, r"\end{%s}" % name, contents, args, preserve_whitespace, position=position) @property def begin(self): return r"\begin{%s}" % self.name @property def end(self): return r"\end{%s}" % self.name class TexUnNamedEnv(TexEnv): name = None begin = None end = None def __init__(self, contents=(), args=(), preserve_whitespace=False, position=-1): """Initialization for Tex environment. :param iterable contents: list of contents :param iterable args: list of Tex Arguments :param bool preserve_whitespace: If false, elements containing only whitespace will be removed from contents. :param int position: position of first character in original source """ assert self.name, 'Name must be non-falsey' assert self.begin and self.end, 'Delimiters must be non-falsey' super().__init__(self.name, self.begin, self.end, contents, args, preserve_whitespace, position=position) class TexDisplayMathModeEnv(TexUnNamedEnv): name = '$$' begin = '$$' end = '$$' token_begin = TC.DisplayMathSwitch token_end = TC.DisplayMathSwitch class TexMathModeEnv(TexUnNamedEnv): name = '$' begin = '$' end = '$' token_begin = TC.MathSwitch token_end = TC.MathSwitch class TexDisplayMathEnv(TexUnNamedEnv): name = 'displaymath' begin = r'\[' end = r'\]' token_begin = TC.DisplayMathGroupBegin token_end = TC.DisplayMathGroupEnd class TexMathEnv(TexUnNamedEnv): name = 'math' begin = r'\(' end = r'\)' token_begin = TC.MathGroupBegin token_end = TC.MathGroupEnd class TexCmd(TexExpr): r"""Abstraction for a LaTeX command. Contains two attributes: 1. the command name itself and 2. the command arguments, whether optional or required. >>> textit = TexCmd('textit', args=[BraceGroup('slant')]) >>> t = TexCmd('textbf', args=[BraceGroup('big ', textit, '.')]) >>> t TexCmd('textbf', [BraceGroup('big ', TexCmd('textit', [BraceGroup('slant')]), '.')]) >>> print(t) \textbf{big \textit{slant}.} >>> children = list(map(str, t.children)) >>> len(children) 1 >>> print(children[0]) \textit{slant} """ def __str__(self): if self._contents: return '\\%s%s%s' % (self.name, self.args, ''.join( [str(e) for e in self._contents])) return '\\%s%s' % (self.name, self.args) def __repr__(self): if not self.args: return "TexCmd('%s')" % self.name return "TexCmd('%s', %s)" % (self.name, repr(self.args)) def _supports_contents(self): return self.name == 'item' def _assert_supports_contents(self): if not self._supports_contents(): raise TypeError( 'Command "{}" has no children. `add_contents` is only valid' 'for: 1. environments like `itemize` and 2. `\\item`. ' 'Alternatively, you can add, edit, or delete arguments by ' 'modifying `.args`, which behaves like a list.' .format(self.name)) class TexText(TexExpr, str): r"""Abstraction for LaTeX text. Representing regular text objects in the parsed tree allows users to search and modify text objects as any other expression allows. >>> obj = TexNode(TexText('asdf gg')) >>> 'asdf' in obj True >>> 'err' in obj False >>> TexText('df ').strip() 'df' """ _has_custom_contain = True def __init__(self, text, position=-1): """Initialize text as tex expresssion. :param str text: Text content :param int position: position of first character in original source """ super().__init__('text', [text], position=position) self._text = text def __contains__(self, other): """ >>> obj = TexText(Token('asdf')) >>> 'a' in obj True >>> 'b' in obj False """ return other in self._text def __eq__(self, other): """ >>> TexText('asdf') == 'asdf' True >>> TexText('asdf') == TexText('asdf') True >>> TexText('asfd') == 'sdddsss' False """ if isinstance(other, TexText): return self._text == other._text if isinstance(other, str): return self._text == other return False def __str__(self): """ >>> TexText('asdf') 'asdf' """ return str(self._text) def __repr__(self): """ >>> TexText('asdf') 'asdf' """ return repr(self._text) ############# # Arguments # ############# class TexGroup(TexUnNamedEnv): """Abstraction for a LaTeX environment with single-character delimiters. Used primarily to identify and associate arguments with commands. """ def __init__(self, *contents, preserve_whitespace=False, position=-1): """Initialize argument using list of expressions. :param Union[str,TexCmd,TexEnv] exprs: Tex expressions contained in the argument. Can be other commands or environments, or even strings. :param int position: position of first character in original source """ super().__init__(contents, preserve_whitespace=preserve_whitespace, position=position) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(map(repr, self._contents))) @classmethod def parse(cls, s): """Parse a string or list and return an Argument object. Naive implementation, does not parse expressions in provided string. :param Union[str,iterable] s: Either a string or a list, where the first and last elements are valid argument delimiters. >>> TexGroup.parse('[arg0]') BracketGroup('arg0') """ assert isinstance(s, str) for arg in arg_type: if s.startswith(arg.begin) and s.endswith(arg.end): return arg(s[len(arg.begin):-len(arg.end)]) raise TypeError('Malformed argument: %s. Must be an TexGroup or a string in' ' either brackets or curly braces.' % s) class BracketGroup(TexGroup): """Optional argument, denoted as ``[arg]``""" begin = '[' end = ']' name = 'BracketGroup' token_begin = TC.BracketBegin token_end = TC.BracketEnd class BraceGroup(TexGroup): """Required argument, denoted as ``{arg}``.""" begin = '{' end = '}' name = 'BraceGroup' token_begin = TC.GroupBegin token_end = TC.GroupEnd arg_type = (BracketGroup, BraceGroup) class TexArgs(list): r"""List of arguments for a TeX expression. Supports all standard list ops. Additional support for conversion from and to unparsed argument strings. >>> arguments = TexArgs(['\n', BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments [BraceGroup('arg0'), BracketGroup('arg1'), BraceGroup('arg2')] >>> arguments.all ['\n', BraceGroup('arg0'), BracketGroup('arg1'), BraceGroup('arg2')] >>> arguments[2] BraceGroup('arg2') >>> len(arguments) 3 >>> arguments[:2] [BraceGroup('arg0'), BracketGroup('arg1')] >>> isinstance(arguments[:2], TexArgs) True """ def __init__(self, args=[]): """List of arguments for a command. :param list args: List of parsed or unparsed arguments """ super().__init__() self.all = [] self.extend(args) def __coerce(self, arg): if isinstance(arg, str) and not arg.isspace(): arg = TexGroup.parse(arg) return arg def append(self, arg): """Append whitespace, an unparsed argument string, or an argument object. :param TexGroup arg: argument to add to the end of the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments.append('[arg3]') >>> arguments[3] BracketGroup('arg3') >>> arguments.append(BraceGroup('arg4')) >>> arguments[4] BraceGroup('arg4') >>> len(arguments) 5 >>> arguments.append('\\n') >>> len(arguments) 5 >>> len(arguments.all) 6 """ self.insert(len(self), arg) def extend(self, args): """Extend mixture of unparsed argument strings, arguments objects, and whitespace. :param List[TexGroup] args: Arguments to add to end of the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments.extend(['[arg3]', BraceGroup('arg4'), '\\t']) >>> len(arguments) 5 >>> arguments[4] BraceGroup('arg4') """ for arg in args: self.append(arg) def insert(self, i, arg): r"""Insert whitespace, an unparsed argument string, or an argument object. :param int i: Index to insert argument into :param TexGroup arg: Argument to insert >>> arguments = TexArgs(['\n', BraceGroup('arg0'), '[arg2]']) >>> arguments.insert(1, '[arg1]') >>> len(arguments) 3 >>> arguments [BraceGroup('arg0'), BracketGroup('arg1'), BracketGroup('arg2')] >>> arguments.all ['\n', BraceGroup('arg0'), BracketGroup('arg1'), BracketGroup('arg2')] >>> arguments.insert(10, '[arg3]') >>> arguments[3] BracketGroup('arg3') """ arg = self.__coerce(arg) if isinstance(arg, TexGroup): super().insert(i, arg) if len(self) <= 1: self.all.append(arg) else: if i > len(self): i = len(self) - 1 before = self[i - 1] index_before = self.all.index(before) self.all.insert(index_before + 1, arg) def remove(self, item): """Remove either an unparsed argument string or an argument object. :param Union[str,TexGroup] item: Item to remove >>> arguments = TexArgs([BraceGroup('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments) 2 >>> arguments[0] BracketGroup('arg2') >>> arguments.remove(arguments[0]) >>> arguments[0] BraceGroup('arg3') >>> arguments.remove(BraceGroup('arg3')) >>> len(arguments) 0 >>> arguments = TexArgs([ ... BraceGroup(TexCmd('color')), ... BraceGroup(TexCmd('color', [BraceGroup('blue')])) ... ]) >>> arguments.remove(arguments[0]) >>> len(arguments) 1 >>> arguments.remove(arguments[0]) >>> len(arguments) 0 """ item = self.__coerce(item) self.all.remove(item) super().remove(item) def pop(self, i): """Pop argument object at provided index. :param int i: Index to pop from the list >>> arguments = TexArgs([BraceGroup('arg0'), '[arg2]', '{arg3}']) >>> arguments.pop(1) BracketGroup('arg2') >>> len(arguments) 2 >>> arguments[0] BraceGroup('arg0') """ item = super().pop(i) j = self.all.index(item) return self.all.pop(j) def reverse(self): r"""Reverse both the list and the proxy `.all`. >>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')]) >>> args.reverse() >>> args.all [BracketGroup('arg2'), BraceGroup('arg1'), '\n'] >>> args [BracketGroup('arg2'), BraceGroup('arg1')] """ super().reverse() self.all.reverse() def clear(self): r"""Clear both the list and the proxy `.all`. >>> args = TexArgs(['\n', BraceGroup('arg1'), BracketGroup('arg2')]) >>> args.clear() >>> len(args) == len(args.all) == 0 True """ super().clear() self.all.clear() def __getitem__(self, key): """Standard list slicing. Returns TexArgs object for subset of list and returns an TexGroup object for single items. >>> arguments = TexArgs([BraceGroup('arg0'), '[arg1]', '{arg2}']) >>> arguments[2] BraceGroup('arg2') >>> arguments[:2] [BraceGroup('arg0'), BracketGroup('arg1')] """ value = super().__getitem__(key) if isinstance(value, list): return TexArgs(value) return value def __contains__(self, item): """Checks for membership. Allows string comparisons to args. >>> arguments = TexArgs(['{arg0}', '[arg1]']) >>> 'arg0' in arguments True >>> BracketGroup('arg0') in arguments False >>> BraceGroup('arg0') in arguments True >>> 'arg3' in arguments False """ if isinstance(item, str): return any([item == arg.string for arg in self]) return super().__contains__(item) def __str__(self): """Stringifies a list of arguments. >>> str(TexArgs(['{a}', '[b]', '{c}'])) '{a}[b]{c}' """ return ''.join(map(str, self)) def __repr__(self): """Makes list of arguments command-line friendly. >>> TexArgs(['{a}', '[b]', '{c}']) [BraceGroup('a'), BracketGroup('b'), BraceGroup('c')] """ return '[%s]' % ', '.join(map(repr, self))
30.274914
91
0.545358
import itertools import re from TexSoup.utils import CharToLineOffset, Token, TC, to_list __all__ = ['TexNode', 'TexCmd', 'TexEnv', 'TexGroup', 'BracketGroup', 'BraceGroup', 'TexArgs', 'TexText', 'TexMathEnv', 'TexDisplayMathEnv', 'TexNamedEnv', 'TexMathModeEnv', 'TexDisplayMathModeEnv'] e a valid TexExpr' super().__init__() self.expr = expr self.parent = None if src is not None: self.char_to_line = CharToLineOffset(src) else: self.char_to_line = None em__(self, item): return list(self.contents)[item] def __iter__(self): return iter(self.contents) def __match__(self, name=None, attrs=()): return self.expr.__match__(name, attrs) def __repr__(self): return str(self) def __str__(self): return str(self.expr) node.parent = self yield node @property def args(self): return self.expr.args @args.setter def args(self, args): assert isinstance(args, TexArgs), "`args` must be of type `TexArgs`" self.expr.args = args @property @to_list def children(self): for child in self.expr.children: node = TexNode(child) node.parent = self yield node @property @to_list def contents(self): for child in self.expr.contents: if isinstance(child, TexExpr): node = TexNode(child) node.parent = self yield node else: yield child @contents.setter def contents(self, contents): self.expr.contents = contents @property def descendants(self): return self.__descendants() @property def name(self): return self.expr.name @name.setter def name(self, name): self.expr.name = name @property def string(self): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' return self.expr.args[0].string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' return contents[0] @string.setter def string(self, string): if isinstance(self.expr, TexCmd): assert len(self.expr.args) == 1, \ '.string is only valid for commands with one argument' self.expr.args[0].string = string contents = list(self.contents) if isinstance(self.expr, TexEnv): assert len(contents) == 1 and \ isinstance(contents[0], (TexText, str)), \ '.string is only valid for environments with only text content' self.contents = [string] @property def position(self): return self.expr.position @property @to_list def text(self): for descendant in self.contents: if isinstance(descendant, (TexText, Token)): yield descendant elif hasattr(descendant, 'text'): yield from descendant.text rmat(i)) for node in nodes: if not isinstance(node, TexNode): continue assert not node.parent, ( 'Inserted node should not already have parent. Call `.copy()` ' 'on node to fix.' ) node.parent = self self.expr.insert(i, *nodes) def char_pos_to_line(self, char_pos): assert self.char_to_line is not None, ( 'CharToLineOffset is not initialized. Pass src to TexNode ' 'constructor') return self.char_to_line(char_pos) def copy(self): return TexNode(self.expr) def count(self, name=None, **attrs): return len(list(self.find_all(name, **attrs))) def delete(self): parent = self.parent if parent.expr._supports_contents(): parent.remove(self) return for arg in parent.args: if self.expr in arg.contents: arg._contents.remove(self.expr) def find(self, name=None, **attrs): try: return self.find_all(name, **attrs)[0] except IndexError: return None @to_list def find_all(self, name=None, **attrs): for descendant in self.__descendants(): if hasattr(descendant, '__match__') and \ descendant.__match__(name, attrs): yield descendant def remove(self, node): self.expr.remove(node.expr) def replace_with(self, *nodes): self.parent.replace(self, *nodes) def replace(self, child, *nodes): self.expr.insert( self.expr.remove(child.expr), *nodes) def search_regex(self, pattern): for node in self.text: for match in re.finditer(pattern, node): body = match.group() start = match.start() yield Token(body, node.position + start) def __descendants(self): return itertools.chain(self.contents, *[c.descendants for c in self.children]) self.parent = None self._contents = list(contents) or [] self.preserve_whitespace = preserve_whitespace self.position = position for content in contents: if isinstance(content, (TexEnv, TexCmd)): content.parent = self tattr(self, 'name') if node_name not in name: return False else: attrs['name'] = name for k, v in attrs.items(): if getattr(self, k) != v: return False return True def __repr__(self): if not self.args: return "TexExpr('%s', %s)" % (self.name, repr(self._contents)) return "TexExpr('%s', %s, %s)" % ( self.name, repr(self._contents), repr(self.args)) ontents: yield content @property @to_list def children(self): return filter(lambda x: isinstance(x, (TexEnv, TexCmd)), self.contents) @property @to_list def contents(self): for content in self.all: if isinstance(content, TexText): content = content._text is_whitespace = isinstance(content, str) and content.isspace() if not is_whitespace or self.preserve_whitespace: yield content @contents.setter def contents(self, contents): if not isinstance(contents, (list, tuple)) or not all( isinstance(content, (str, TexExpr)) for content in contents): raise TypeError( '.contents value "%s" must be a list or tuple of strings or ' 'TexExprs' % contents) _contents = [TexText(c) if isinstance(c, str) else c for c in contents] self._contents = _contents @property def string(self): return TexText(''.join(map(str, self._contents))) @string.setter def string(self, s): if not isinstance(s, str): raise TypeError( '.string value "%s" must be a string or TexText. To set ' 'non-string content, use .contents' % s) self.contents = [TexText(s)] self self._contents.insert(i + j, expr) def remove(self, expr): self._assert_supports_contents() index = self._contents.index(expr) self._contents.remove(expr) return index def _supports_contents(self): return True def _assert_supports_contents(self): pass class TexEnv(TexExpr): _begin = None _end = None def __init__(self, name, begin, end, contents=(), args=(), preserve_whitespace=False, position=-1): super().__init__(name, contents, args, preserve_whitespace, position) self._begin = begin self._end = end @property def begin(self): return self._begin @begin.setter def begin(self, begin): self._begin = begin @property def end(self): return self._end @end.setter def end(self, end): self._end = end def __match__(self, name=None, attrs=()): if name in (self.name, self.begin + str(self.args), self.begin, self.end): return True return super().__match__(name, attrs) def __str__(self): contents = ''.join(map(str, self._contents)) if self.name == '[tex]': return contents else: return '%s%s%s' % ( self.begin + str(self.args), contents, self.end) def __repr__(self): if self.name == '[tex]': return str(self._contents) if not self.args and not self._contents: return "%s('%s')" % (self.__class__.__name__, self.name) return "%s('%s', %s, %s)" % ( self.__class__.__name__, self.name, repr(self._contents), repr(self.args)) class TexNamedEnv(TexEnv): def __init__(self, name, contents=(), args=(), preserve_whitespace=False, position=-1): super().__init__(name, r"\begin{%s}" % name, r"\end{%s}" % name, contents, args, preserve_whitespace, position=position) @property def begin(self): return r"\begin{%s}" % self.name @property def end(self): return r"\end{%s}" % self.name class TexUnNamedEnv(TexEnv): name = None begin = None end = None def __init__(self, contents=(), args=(), preserve_whitespace=False, position=-1): assert self.name, 'Name must be non-falsey' assert self.begin and self.end, 'Delimiters must be non-falsey' super().__init__(self.name, self.begin, self.end, contents, args, preserve_whitespace, position=position) class TexDisplayMathModeEnv(TexUnNamedEnv): name = '$$' begin = '$$' end = '$$' token_begin = TC.DisplayMathSwitch token_end = TC.DisplayMathSwitch class TexMathModeEnv(TexUnNamedEnv): name = '$' begin = '$' end = '$' token_begin = TC.MathSwitch token_end = TC.MathSwitch class TexDisplayMathEnv(TexUnNamedEnv): name = 'displaymath' begin = r'\[' end = r'\]' token_begin = TC.DisplayMathGroupBegin token_end = TC.DisplayMathGroupEnd class TexMathEnv(TexUnNamedEnv): name = 'math' begin = r'\(' end = r'\)' token_begin = TC.MathGroupBegin token_end = TC.MathGroupEnd class TexCmd(TexExpr): def __str__(self): if self._contents: return '\\%s%s%s' % (self.name, self.args, ''.join( [str(e) for e in self._contents])) return '\\%s%s' % (self.name, self.args) def __repr__(self): if not self.args: return "TexCmd('%s')" % self.name return "TexCmd('%s', %s)" % (self.name, repr(self.args)) def _supports_contents(self): return self.name == 'item' def _assert_supports_contents(self): if not self._supports_contents(): raise TypeError( 'Command "{}" has no children. `add_contents` is only valid' 'for: 1. environments like `itemize` and 2. `\\item`. ' 'Alternatively, you can add, edit, or delete arguments by ' 'modifying `.args`, which behaves like a list.' .format(self.name)) class TexText(TexExpr, str): _has_custom_contain = True def __init__(self, text, position=-1): super().__init__('text', [text], position=position) self._text = text def __contains__(self, other): return other in self._text def __eq__(self, other): if isinstance(other, TexText): return self._text == other._text if isinstance(other, str): return self._text == other return False def __str__(self): return str(self._text) def __repr__(self): return repr(self._text) hitespace=preserve_whitespace, position=position) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(map(repr, self._contents))) @classmethod def parse(cls, s): assert isinstance(s, str) for arg in arg_type: if s.startswith(arg.begin) and s.endswith(arg.end): return arg(s[len(arg.begin):-len(arg.end)]) raise TypeError('Malformed argument: %s. Must be an TexGroup or a string in' ' either brackets or curly braces.' % s) class BracketGroup(TexGroup): begin = '[' end = ']' name = 'BracketGroup' token_begin = TC.BracketBegin token_end = TC.BracketEnd class BraceGroup(TexGroup): begin = '{' end = '}' name = 'BraceGroup' token_begin = TC.GroupBegin token_end = TC.GroupEnd arg_type = (BracketGroup, BraceGroup) class TexArgs(list): def __init__(self, args=[]): super().__init__() self.all = [] self.extend(args) def __coerce(self, arg): if isinstance(arg, str) and not arg.isspace(): arg = TexGroup.parse(arg) return arg def append(self, arg): self.insert(len(self), arg) def extend(self, args): for arg in args: self.append(arg) def insert(self, i, arg): arg = self.__coerce(arg) if isinstance(arg, TexGroup): super().insert(i, arg) if len(self) <= 1: self.all.append(arg) else: if i > len(self): i = len(self) - 1 before = self[i - 1] index_before = self.all.index(before) self.all.insert(index_before + 1, arg) def remove(self, item): item = self.__coerce(item) self.all.remove(item) super().remove(item) def pop(self, i): item = super().pop(i) j = self.all.index(item) return self.all.pop(j) def reverse(self): super().reverse() self.all.reverse() def clear(self): super().clear() self.all.clear() def __getitem__(self, key): value = super().__getitem__(key) if isinstance(value, list): return TexArgs(value) return value def __contains__(self, item): if isinstance(item, str): return any([item == arg.string for arg in self]) return super().__contains__(item) def __str__(self): return ''.join(map(str, self)) def __repr__(self): return '[%s]' % ', '.join(map(repr, self))
true
true
f7279d2a0928d92d1790424e41fa2a880cbb1be9
138
py
Python
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
multiples_list.py
GYosifov88/Python-Fundamentals
b46ba2822bd2dac6ff46830c6a520e559b448442
[ "MIT" ]
null
null
null
factor = int(input()) count = int(input()) new_list = [] for num in range (1, count+1): new_list.append(factor * num) print(new_list)
19.714286
33
0.65942
factor = int(input()) count = int(input()) new_list = [] for num in range (1, count+1): new_list.append(factor * num) print(new_list)
true
true
f7279d86e14fb0fc3c957ab9728d907bc9972e34
712
py
Python
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
1
2022-02-06T23:05:37.000Z
2022-02-06T23:05:37.000Z
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
3
2022-02-07T06:13:31.000Z
2022-03-11T12:43:39.000Z
sdk/test/test_user_location.py
aqualinkorg/aqualink-sdk
dad972d1dd5b74e8216bdc30521a8b76f7844733
[ "MIT" ]
null
null
null
""" Aqualink API documentation The Aqualink public API documentation # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import sys import unittest import aqualink_sdk from aqualink_sdk.model.user_location import UserLocation class TestUserLocation(unittest.TestCase): """UserLocation unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUserLocation(self): """Test UserLocation""" # FIXME: construct object with mandatory attributes with example values # model = UserLocation() # noqa: E501 pass if __name__ == '__main__': unittest.main()
19.777778
79
0.676966
import sys import unittest import aqualink_sdk from aqualink_sdk.model.user_location import UserLocation class TestUserLocation(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testUserLocation(self): s if __name__ == '__main__': unittest.main()
true
true
f7279df45c4b42335c35e8630786466cee4cd860
698
py
Python
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
models/final_model.py
Abxhor/Coldairarrow
3735beec8a6fa7ad9356375081229c68f0e83f3d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Stacking of some good solutions. IMPORTANT: To run this model you need run before the differents models. """ import pandas as pd import numpy as np df1 = pd.read_csv('submission40.csv') # 0.309812 (public leaderboard) df2 = pd.read_csv('submission41.csv') # 0.305985 (public leaderboard) df3 = pd.read_csv('submission42.csv') # 0.313587 (public leaderboard) df4 = pd.read_csv('submission45.csv') # 0.309749 (public leaderboard) df5 = pd.read_csv('submission47.csv') # 0.306439 (public leaderboard) df = pd.DataFrame() df['y'] = 0.2*df1['y'] + 0.23*df2['y'] + 0.2*df3['y'] + 0.15*df4['y'] + 0.22*df5['y'] df.to_csv('submission53.csv') # 0.301697 (public leaderboard)
33.238095
85
0.690544
import pandas as pd import numpy as np df1 = pd.read_csv('submission40.csv') df2 = pd.read_csv('submission41.csv') df3 = pd.read_csv('submission42.csv') df4 = pd.read_csv('submission45.csv') df5 = pd.read_csv('submission47.csv') df = pd.DataFrame() df['y'] = 0.2*df1['y'] + 0.23*df2['y'] + 0.2*df3['y'] + 0.15*df4['y'] + 0.22*df5['y'] df.to_csv('submission53.csv')
true
true
f7279e1c3124420e19cf7b1c5a2e96104f93c057
19,081
py
Python
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
777_all_in_one_v1.py
vlbthambawita/singan-polyp-aug-exp
b4ec5155f5c36a931fad022aec04dda6b3180b55
[ "MIT" ]
null
null
null
#========================================================= # Developer: Vajira Thambawita # Reference: https://github.com/meetshah1995/pytorch-semseg #========================================================= import argparse from datetime import datetime import os import copy from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np #Pytorch import torch import torch.optim as optim from torch.optim import lr_scheduler import torch.nn as nn from torch.utils.data import DataLoader from torchvision import models, transforms,datasets, utils from torchvision.utils import save_image from torch.utils.tensorboard import SummaryWriter from torch.autograd import Variable from torchsummary import summary import segmentation_models_pytorch as smp from data.dataset import Dataset from data.prepare_data import prepare_data, prepare_test_data #from data import PolypsDatasetWithGridEncoding #from data import PolypsDatasetWithGridEncoding_TestData import pyra_pytorch as pyra from utils import dice_coeff, iou_pytorch, visualize import segmentation_models_pytorch as smp #====================================== # Get and set all input parameters #====================================== parser = argparse.ArgumentParser() # Hardware #parser.add_argument("--device", default="gpu", help="Device to run the code") parser.add_argument("--device_id", type=int, default=0, help="") # Optional parameters to identify the experiments parser.add_argument("--exp_name", type=str, help="A name to identify the experiment", required=True) #parser.add_argument("--py_file",default=os.path.abspath(__file__)) # store current python file # Directory and file handling parser.add_argument("--train_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--val_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--test_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--out_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/checkpoints", help="Main output dierectory") parser.add_argument("--tensorboard_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/tensorboard", help="Folder to save output of tensorboard") parser.add_argument("--test_out_dir", default= "/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/test_samples", help="Output folder for testing data" ) parser.add_argument("--best_checkpoint_name", type=str, default="best_checkpoint.pth", help="A name to save bet checkpoint") parser.add_argument("--img_size", type=int, default=128, help="Image height and width to resize") # Action handling parser.add_argument("--num_epochs", type=int, default=1, help="Numbe of epochs to train") parser.add_argument("--start_epoch", type=int, default=0, help="start epoch of training") parser.add_argument("--num_test_samples", type=int, default=5, help="Number of samples to test.") # smp parameters parser.add_argument("--model", help="The model to perform segmentation", required=True) parser.add_argument("--encoder", type=str, default='se_resnext50_32x4d', help="smp encoders") parser.add_argument("--encoder_weights", type=str, default='imagenet', help="encoder weights") parser.add_argument("--classes", default=[0,255], help="classes per pixel") parser.add_argument("--activation", type=str, default='softmax2d', help="last activation layers activation") #PYRA parser.add_argument("--pyra", type=bool, default=False, help="To enable PYRA grid encoding.") parser.add_argument("--grid_sizes_train", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_val", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_test", type=list, default=[256], help="Grid sizes to use in testing") parser.add_argument("--in_channels", type=int, default=3, help="Number of input channgels") # Parameters parser.add_argument("--bs", type=int, default=8, help="Mini batch size") parser.add_argument("--val_bs", type=int, default=1, help="Batch size") parser.add_argument("--lr", type=float, default=0.0001, help="Learning rate for training") parser.add_argument("--lr_change_point", type=int, default=50, help="After this point LR will be changed.") parser.add_argument("--num_workers", type=int, default=12, help="Number of workers in dataloader") parser.add_argument("--weight_decay", type=float, default=1e-5, help="weight decay of the optimizer") parser.add_argument("--lr_sch_factor", type=float, default=0.1, help="Factor to reduce lr in the scheduler") parser.add_argument("--lr_sch_patience", type=int, default=25, help="Num of epochs to be patience for updating lr") parser.add_argument("--num_samples", type=int, default=5, help="Number of samples to print from validation set") parser.add_argument("action", type=str, help="Select an action to run", choices=["train", "retrain", "test", "check", "check_val"]) parser.add_argument("--checkpoint_interval", type=int, default=25, help="Interval to save checkpoint models") #parser.add_argument("--fold", type=str, default="fold_1", help="Select the validation fold", choices=["fold_1", "fold_2", "fold_3"]) #parser.add_argument("--num_test", default= 200, type=int, help="Number of samples to test set from 1k dataset") #parser.add_argument("--model_path", default="", help="Model path to load weights") #parser.add_argument("--num_of_samples", default=30, type=int, help="Number of samples to validate (Montecalo sampling)") parser.add_argument("--record_name", type=str, default="VAL", help="Some name to identify records in tensorboard output") opt = parser.parse_args() #========================================== # Device handling #========================================== torch.cuda.set_device(opt.device_id) DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") opt.device = DEVICE #=========================================== # Folder handling #=========================================== #make output folder if not exist os.makedirs(opt.out_dir, exist_ok=True) # make subfolder in the output folder #py_file_name = opt.py_file.split("/")[-1] # Get python file name (soruce code name) CHECKPOINT_DIR = os.path.join(opt.out_dir, opt.exp_name + "/checkpoints") os.makedirs(CHECKPOINT_DIR, exist_ok=True) # make tensorboard subdirectory for the experiment tensorboard_exp_dir = os.path.join(opt.tensorboard_dir, opt.exp_name) os.makedirs( tensorboard_exp_dir, exist_ok=True) #========================================== # Tensorboard #========================================== # Initialize summary writer writer = SummaryWriter(tensorboard_exp_dir) #========================================== # Prepare Data #========================================== #================================================ # Train the model #================================================ def train_model(train_loader, valid_loader, model, loss, metrics, optimizer, opt): # create epoch runners # it is a simple loop of iterating over dataloader`s samples train_epoch = smp.utils.train.TrainEpoch( model, loss=loss, metrics=metrics, optimizer=optimizer, device=DEVICE, verbose=True, ) valid_epoch = smp.utils.train.ValidEpoch( model, loss=loss, metrics=metrics, device=DEVICE, verbose=True, ) max_score = 0 best_chk_path = os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name) for i in range(opt.start_epoch + 1, opt.start_epoch + opt.num_epochs +1 ): print('\nEpoch: {}'.format(i)) train_logs = train_epoch.run(train_loader) valid_logs = valid_epoch.run(valid_loader) # do something (save model, change lr, etc.) if max_score < valid_logs['iou_score']: max_score = valid_logs['iou_score'] torch.save({"model":model, "epoch": i}, best_chk_path) print('Best Model saved!') print("Testing....") do_test(opt) print("Tested") if i == opt.lr_change_point: optimizer.param_groups[0]['lr'] = 1e-5 print('Decrease decoder learning rate to 1e-5!') # writing to logs to tensorboard for key, value in train_logs.items(): writer.add_scalar(f"Train/{key}", value, i) for key, value in valid_logs.items(): writer.add_scalar(f"Valid/{key}", value, i) # update here #============================================== # Heatmap generator from tensor #============================================== def generate_heatmapts(img_tensor): print(img_tensor.shape) fig_list = [] for n in range(img_tensor.shape[0]): img = img_tensor[n] img = img.squeeze(dim=0) img_np = img.detach().cpu().numpy() #img_np = np.transforms(img_np, (1,2,0)) plt.imshow(img_np, cmap="hot") fig = plt.gcf() fig_list.append(fig) # plt.clf() plt.close() return fig_list #=============================================== # Prepare models #=============================================== def prepare_model(opt): # model = UNet(n_channels=4, n_classes=1) # 4 = 3 channels + 1 grid encode # create segmentation model with pretrained encoder model = getattr(smp, opt.model)( encoder_name=opt.encoder, in_channels=opt.in_channels, encoder_weights=opt.encoder_weights, classes=len(opt.classes), activation=opt.activation, ) return model #==================================== # Run training process #==================================== def run_train(opt): model = prepare_model(opt) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn=None) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) #==================================== # Re-train process #==================================== def run_retrain(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) opt.start_epoch = checkpoint_dict["epoch"] model = checkpoint_dict["model"] print("Model epoch:", checkpoint_dict["epoch"]) print("Model retrain started from epoch:", opt.start_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) #===================================== # Check model #==================================== def check_model_graph(): raise NotImplementedError #=================================== # Inference from pre-trained models #=================================== def do_test(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None) for i in range(opt.num_test_samples): image, mask = test_dataset[i] image_vis, _ = test_dataset_vis[i] #print(image) mask_tensor = torch.from_numpy(mask).to(opt.device).unsqueeze(0) image_tensor = torch.from_numpy(image).to(opt.device).unsqueeze(0) pr_mask = best_model.predict(image_tensor) pr_mask = pr_mask.squeeze().cpu().numpy().round() fig = visualize( input_image_new=np.transpose(image_vis, (1,2,0)).astype(int), GT_mask_0=mask[0, :,:], Pred_mask_0 = pr_mask[0,:,:], GT_mask_1= mask[1,:,:], Pred_mask_1 = pr_mask[1, :,:] ) fig.savefig(f"./test_202_{i}.png") writer.add_figure(f"Test_sample/sample-{i}", fig, global_step=test_epoch) def check_test_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=48) loss = smp.utils.losses.DiceLoss() # Testing with two class layers metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score", str(logs), global_step=test_best_epoch) # Testing with only class layer 1 (polyps) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-0", str(logs), global_step=test_best_epoch) # Testing with only class layer 0 (BG) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-1", str(logs), global_step=test_best_epoch) def check_val_full_score(opt): # changing test data files into val data #opt.test_CSVs = opt.val_CSVs #opt.record_name = "VAL" checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=12) loss = smp.utils.losses.DiceLoss() # Testing with two class layers metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=None), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=None), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=None), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-scores-->{opt.record_name}", str(logs), global_step=test_best_epoch) # Testing with only class layer 1 (polyps) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-0-->{opt.record_name}", str(logs), global_step=test_best_epoch) # Testing with only class layer 0 (BG) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ #smp.utils.metrics.IoU(threshold=0.5), smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-1-->{opt.record_name}", str(logs), global_step=test_best_epoch) if __name__ == "__main__": #data_loaders = prepare_data() print(vars(opt)) print("Test OK") # Train or retrain or inference if opt.action == "train": print("Training process is strted..!") run_train(opt) pass elif opt.action == "retrain": print("Retrainning process is strted..!") run_retrain(opt) pass elif opt.action == "test": print("Inference process is strted..!") do_test(opt) print("Done") elif opt.action == "check": check_test_score(opt) print("Check pass") elif opt.action == "check_val": check_val_full_score(opt) # Finish tensorboard writer writer.close()
32.728988
133
0.639432
import argparse from datetime import datetime import os import copy from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np import torch import torch.optim as optim from torch.optim import lr_scheduler import torch.nn as nn from torch.utils.data import DataLoader from torchvision import models, transforms,datasets, utils from torchvision.utils import save_image from torch.utils.tensorboard import SummaryWriter from torch.autograd import Variable from torchsummary import summary import segmentation_models_pytorch as smp from data.dataset import Dataset from data.prepare_data import prepare_data, prepare_test_data import pyra_pytorch as pyra from utils import dice_coeff, iou_pytorch, visualize import segmentation_models_pytorch as smp parser = argparse.ArgumentParser() parser.add_argument("--device_id", type=int, default=0, help="") parser.add_argument("--exp_name", type=str, help="A name to identify the experiment", required=True) train_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--val_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--test_CSVs", nargs="+", default=None, help="CSV file list with image and mask paths") parser.add_argument("--out_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/checkpoints", help="Main output dierectory") parser.add_argument("--tensorboard_dir", default="/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/tensorboard", help="Folder to save output of tensorboard") parser.add_argument("--test_out_dir", default= "/work/vajira/DATA/sinGAN_polyps/sinGAN_exp_out/test_samples", help="Output folder for testing data" ) parser.add_argument("--best_checkpoint_name", type=str, default="best_checkpoint.pth", help="A name to save bet checkpoint") parser.add_argument("--img_size", type=int, default=128, help="Image height and width to resize") parser.add_argument("--num_epochs", type=int, default=1, help="Numbe of epochs to train") parser.add_argument("--start_epoch", type=int, default=0, help="start epoch of training") parser.add_argument("--num_test_samples", type=int, default=5, help="Number of samples to test.") parser.add_argument("--model", help="The model to perform segmentation", required=True) parser.add_argument("--encoder", type=str, default='se_resnext50_32x4d', help="smp encoders") parser.add_argument("--encoder_weights", type=str, default='imagenet', help="encoder weights") parser.add_argument("--classes", default=[0,255], help="classes per pixel") parser.add_argument("--activation", type=str, default='softmax2d', help="last activation layers activation") parser.add_argument("--pyra", type=bool, default=False, help="To enable PYRA grid encoding.") parser.add_argument("--grid_sizes_train", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_val", type=list, default=[256], help="Grid sizes to use in training") parser.add_argument("--grid_sizes_test", type=list, default=[256], help="Grid sizes to use in testing") parser.add_argument("--in_channels", type=int, default=3, help="Number of input channgels") parser.add_argument("--bs", type=int, default=8, help="Mini batch size") parser.add_argument("--val_bs", type=int, default=1, help="Batch size") parser.add_argument("--lr", type=float, default=0.0001, help="Learning rate for training") parser.add_argument("--lr_change_point", type=int, default=50, help="After this point LR will be changed.") parser.add_argument("--num_workers", type=int, default=12, help="Number of workers in dataloader") parser.add_argument("--weight_decay", type=float, default=1e-5, help="weight decay of the optimizer") parser.add_argument("--lr_sch_factor", type=float, default=0.1, help="Factor to reduce lr in the scheduler") parser.add_argument("--lr_sch_patience", type=int, default=25, help="Num of epochs to be patience for updating lr") parser.add_argument("--num_samples", type=int, default=5, help="Number of samples to print from validation set") parser.add_argument("action", type=str, help="Select an action to run", choices=["train", "retrain", "test", "check", "check_val"]) parser.add_argument("--checkpoint_interval", type=int, default=25, help="Interval to save checkpoint models") parser.add_argument("--record_name", type=str, default="VAL", help="Some name to identify records in tensorboard output") opt = parser.parse_args() torch.cuda.set_device(opt.device_id) DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") opt.device = DEVICE os.makedirs(opt.out_dir, exist_ok=True) r, opt.exp_name + "/checkpoints") os.makedirs(CHECKPOINT_DIR, exist_ok=True) tensorboard_exp_dir = os.path.join(opt.tensorboard_dir, opt.exp_name) os.makedirs( tensorboard_exp_dir, exist_ok=True) writer = SummaryWriter(tensorboard_exp_dir) def train_model(train_loader, valid_loader, model, loss, metrics, optimizer, opt): train_epoch = smp.utils.train.TrainEpoch( model, loss=loss, metrics=metrics, optimizer=optimizer, device=DEVICE, verbose=True, ) valid_epoch = smp.utils.train.ValidEpoch( model, loss=loss, metrics=metrics, device=DEVICE, verbose=True, ) max_score = 0 best_chk_path = os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name) for i in range(opt.start_epoch + 1, opt.start_epoch + opt.num_epochs +1 ): print('\nEpoch: {}'.format(i)) train_logs = train_epoch.run(train_loader) valid_logs = valid_epoch.run(valid_loader) if max_score < valid_logs['iou_score']: max_score = valid_logs['iou_score'] torch.save({"model":model, "epoch": i}, best_chk_path) print('Best Model saved!') print("Testing....") do_test(opt) print("Tested") if i == opt.lr_change_point: optimizer.param_groups[0]['lr'] = 1e-5 print('Decrease decoder learning rate to 1e-5!') for key, value in train_logs.items(): writer.add_scalar(f"Train/{key}", value, i) for key, value in valid_logs.items(): writer.add_scalar(f"Valid/{key}", value, i) def generate_heatmapts(img_tensor): print(img_tensor.shape) fig_list = [] for n in range(img_tensor.shape[0]): img = img_tensor[n] img = img.squeeze(dim=0) img_np = img.detach().cpu().numpy() plt.imshow(img_np, cmap="hot") fig = plt.gcf() fig_list.append(fig) plt.close() return fig_list def prepare_model(opt): opt.model)( encoder_name=opt.encoder, in_channels=opt.in_channels, encoder_weights=opt.encoder_weights, classes=len(opt.classes), activation=opt.activation, ) return model def run_train(opt): model = prepare_model(opt) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn=None) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) def run_retrain(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) opt.start_epoch = checkpoint_dict["epoch"] model = checkpoint_dict["model"] print("Model epoch:", checkpoint_dict["epoch"]) print("Model retrain started from epoch:", opt.start_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) train_loader, val_loader = prepare_data(opt, preprocessing_fn) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5), ] optimizer = torch.optim.Adam([ dict(params=model.parameters(), lr=opt.lr), ]) train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt) def check_model_graph(): raise NotImplementedError def do_test(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None) for i in range(opt.num_test_samples): image, mask = test_dataset[i] image_vis, _ = test_dataset_vis[i] mask_tensor = torch.from_numpy(mask).to(opt.device).unsqueeze(0) image_tensor = torch.from_numpy(image).to(opt.device).unsqueeze(0) pr_mask = best_model.predict(image_tensor) pr_mask = pr_mask.squeeze().cpu().numpy().round() fig = visualize( input_image_new=np.transpose(image_vis, (1,2,0)).astype(int), GT_mask_0=mask[0, :,:], Pred_mask_0 = pr_mask[0,:,:], GT_mask_1= mask[1,:,:], Pred_mask_1 = pr_mask[1, :,:] ) fig.savefig(f"./test_202_{i}.png") writer.add_figure(f"Test_sample/sample-{i}", fig, global_step=test_epoch) def check_test_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=48) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-0", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-test-score-ignore-channel-1", str(logs), global_step=test_best_epoch) def check_val_full_score(opt): checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)) test_best_epoch = checkpoint_dict["epoch"] best_model = checkpoint_dict["model"] print("Model best epoch:", test_best_epoch) preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights) test_dataset = prepare_test_data(opt, preprocessing_fn=None) test_dataloader = DataLoader(test_dataset, num_workers=12) loss = smp.utils.losses.DiceLoss() metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=None), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=None), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=None), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=None), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-scores-->{opt.record_name}", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[0]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[0]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[0]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-0-->{opt.record_name}", str(logs), global_step=test_best_epoch) loss = smp.utils.losses.DiceLoss(ignore_channels=[1]) metrics = [ smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Fscore(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Accuracy(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Recall(threshold=0.5, ignore_channels=[1]), smp.utils.metrics.Precision(threshold=0.5, ignore_channels=[1]), ] test_epoch = smp.utils.train.ValidEpoch( model=best_model, loss=loss, metrics=metrics, device=DEVICE, ) logs = test_epoch.run(test_dataloader) print("logs=", str(logs)) writer.add_text(f"{opt.exp_name}-val-scores-ignore-channel-1-->{opt.record_name}", str(logs), global_step=test_best_epoch) if __name__ == "__main__": print(vars(opt)) print("Test OK") if opt.action == "train": print("Training process is strted..!") run_train(opt) pass elif opt.action == "retrain": print("Retrainning process is strted..!") run_retrain(opt) pass elif opt.action == "test": print("Inference process is strted..!") do_test(opt) print("Done") elif opt.action == "check": check_test_score(opt) print("Check pass") elif opt.action == "check_val": check_val_full_score(opt) writer.close()
true
true
f7279ecc02853cb1115ebc5b8d75e8798d77b6ea
5,301
py
Python
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
null
null
null
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
1
2021-10-19T13:34:15.000Z
2021-10-19T13:34:15.000Z
tests/app/models/test_webauthn_credential.py
TechforgoodCAST/notifications-admin
0a9e06aafd79d0fbe50c26a85bf757aaeaa59340
[ "MIT" ]
1
2021-03-05T13:18:44.000Z
2021-03-05T13:18:44.000Z
import base64 import pytest from fido2 import cbor from fido2.cose import ES256 from app.models.webauthn_credential import RegistrationError, WebAuthnCredential # noqa adapted from https://github.com/duo-labs/py_webauthn/blob/90e3d97e0182899a35a70fc510280b4082cce19b/tests/test_webauthn.py#L14-L24 SESSION_STATE = {'challenge': 'bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94', 'user_verification': 'discouraged'} CLIENT_DATA_JSON = b'{"type": "webauthn.create", "clientExtensions": {}, "challenge": "bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94", "origin": "https://webauthn.io"}' # noqa # had to use the cbor2 library to re-encode the attestationObject due to implementation differences ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyYhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') # noqa # manually adapted by working out which character in the encoded CBOR corresponds to the public key algorithm ID UNSUPPORTED_ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyUhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') # noqa def test_from_registration_verifies_response(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert credential.name == 'Unnamed key' assert credential.registration_response == base64.b64encode(cbor.encode(registration_response)).decode('utf-8') credential_data = credential.to_credential_data() assert type(credential_data.credential_id) is bytes assert type(credential_data.aaguid) is bytes assert credential_data.public_key[3] == ES256.ALGORITHM def test_from_registration_encodes_as_unicode(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) serialized_credential = credential.serialize() assert type(serialized_credential['credential_data']) == str assert type(serialized_credential['registration_response']) == str def test_from_registration_handles_library_errors(notify_admin): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Invalid origin' in str(exc_info.value) def test_from_registration_handles_unsupported_keys(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': UNSUPPORTED_ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Encryption algorithm not supported' in str(exc_info.value)
73.625
1,274
0.873986
import base64 import pytest from fido2 import cbor from fido2.cose import ES256 from app.models.webauthn_credential import RegistrationError, WebAuthnCredential _STATE = {'challenge': 'bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94', 'user_verification': 'discouraged'} CLIENT_DATA_JSON = b'{"type": "webauthn.create", "clientExtensions": {}, "challenge": "bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94", "origin": "https://webauthn.io"}' ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyYhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') UNSUPPORTED_ATTESTATION_OBJECT = base64.b64decode(b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos/t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB/lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv/FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ/ukcONgxkRZ8K04QtP/CB5x6olTlxsj+SXArQDCRzEYUgbws6kZKfuRt2a1P+EzUiqDWLjRILSr+3/o7yR7ZP/GpiFKwdm+czb94POoGD+TS1IYdfXj94mAr5cKWx4EKjh210uovu/pLdLjc8xkQciUrXzZpPR9rT2k/q9HkZhHU+NaCJzky+PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS+5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD/KNU+iBqJdAwTLPPDRoLLvPTl29weCAIh+HUpmBQd0UltcPOrA/LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3/lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r/oOaP8RS44dlQjrH+ALfYtpAECAyUhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M+hPcV+fHehEOeW+KCyd0H+WGY8s6') def test_from_registration_verifies_response(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert credential.name == 'Unnamed key' assert credential.registration_response == base64.b64encode(cbor.encode(registration_response)).decode('utf-8') credential_data = credential.to_credential_data() assert type(credential_data.credential_id) is bytes assert type(credential_data.aaguid) is bytes assert credential_data.public_key[3] == ES256.ALGORITHM def test_from_registration_encodes_as_unicode(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } credential = WebAuthnCredential.from_registration(SESSION_STATE, registration_response) serialized_credential = credential.serialize() assert type(serialized_credential['credential_data']) == str assert type(serialized_credential['registration_response']) == str def test_from_registration_handles_library_errors(notify_admin): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Invalid origin' in str(exc_info.value) def test_from_registration_handles_unsupported_keys(webauthn_dev_server): registration_response = { 'clientDataJSON': CLIENT_DATA_JSON, 'attestationObject': UNSUPPORTED_ATTESTATION_OBJECT, } with pytest.raises(RegistrationError) as exc_info: WebAuthnCredential.from_registration(SESSION_STATE, registration_response) assert 'Encryption algorithm not supported' in str(exc_info.value)
true
true
f727a030df092bb2e0060f668a84075527b879dd
913
py
Python
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
6
2021-08-01T17:48:57.000Z
2022-03-07T15:41:26.000Z
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
33
2021-08-08T16:09:21.000Z
2022-03-15T15:17:37.000Z
src/dicom_parser/utils/bids/utils.py
open-dicom/dicom_parser
acc82f6f989a335fd3cf30e716334081ab9ac43b
[ "MIT" ]
6
2021-10-19T09:19:22.000Z
2022-03-13T19:26:10.000Z
""" Utilities for the :mod:`dicom_parser.utils.bids` module. """ from typing import Dict, List # A summary of the unique parts (key/value) pairs that make up the appropriate # BIDS-compatible file name by data type. ANATOMICAL_NAME_PARTS: List[str] = ["acq", "ce", "rec", "inv", "run", "part"] DWI_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] FIELDMAP_NAME_PARTS: List[str] = ["acq", "ce", "dir", "run"] FUNCTIONAL_NAME_PARTS: List[str] = [ "task", "acq", "ce", "rec", "dir", "run", "echo", "part", ] SBREF_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] NAME_PARTS_BY_DATA_TYPE: Dict[str, List[str]] = { "anat": ANATOMICAL_NAME_PARTS, "func": FUNCTIONAL_NAME_PARTS, "dwi": DWI_NAME_PARTS, "sbref": SBREF_NAME_PARTS, "fmap": FIELDMAP_NAME_PARTS, } BIDS_PATH_TEMPLATE: str = ( "{subject}/{session}/{data_type}/{subject}_{session}{labels}" )
27.666667
78
0.637459
from typing import Dict, List ANATOMICAL_NAME_PARTS: List[str] = ["acq", "ce", "rec", "inv", "run", "part"] DWI_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] FIELDMAP_NAME_PARTS: List[str] = ["acq", "ce", "dir", "run"] FUNCTIONAL_NAME_PARTS: List[str] = [ "task", "acq", "ce", "rec", "dir", "run", "echo", "part", ] SBREF_NAME_PARTS: List[str] = ["acq", "dir", "run", "part"] NAME_PARTS_BY_DATA_TYPE: Dict[str, List[str]] = { "anat": ANATOMICAL_NAME_PARTS, "func": FUNCTIONAL_NAME_PARTS, "dwi": DWI_NAME_PARTS, "sbref": SBREF_NAME_PARTS, "fmap": FIELDMAP_NAME_PARTS, } BIDS_PATH_TEMPLATE: str = ( "{subject}/{session}/{data_type}/{subject}_{session}{labels}" )
true
true
f727a06b1b074152cadb873d888a24a742788ecb
761
py
Python
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
cride/users/admin.py
valot3/Cride-API
a9e201942e6eecd479f575733e93ff73e6df573d
[ "MIT" ]
null
null
null
"""User models admin""" #Django from django.contrib import admin from django.contrib.auth.admin import UserAdmin #Project from cride.users.models import User, Profile class CustomUserAdmin(UserAdmin): """User model admin.""" list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff', 'is_client') list_filter = ('is_client', 'is_staff', 'created_at', 'modified_at') class ProfileAdmin(admin.ModelAdmin): """Profile model admin.""" list_display = ('user', 'reputation', 'rides_taken', 'rides_offered') search_fields = ('user__username', 'user__email', 'user__first_name', 'user__last_name') list_filter = ('reputation',) admin.site.register(User, CustomUserAdmin) admin.site.register(Profile, ProfileAdmin)
27.178571
92
0.720105
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from cride.users.models import User, Profile class CustomUserAdmin(UserAdmin): list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff', 'is_client') list_filter = ('is_client', 'is_staff', 'created_at', 'modified_at') class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'reputation', 'rides_taken', 'rides_offered') search_fields = ('user__username', 'user__email', 'user__first_name', 'user__last_name') list_filter = ('reputation',) admin.site.register(User, CustomUserAdmin) admin.site.register(Profile, ProfileAdmin)
true
true
f727a107c1b6bc630f2298f8758fa301408ca175
105
py
Python
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
wrapcord/__init__.py
nsde/wrapcord
d9a6225085a658a630a9527edb4fa7b991657856
[ "MIT" ]
null
null
null
from .channel import Channel from .guild import Guild from .message import Message from .user import User
26.25
28
0.819048
from .channel import Channel from .guild import Guild from .message import Message from .user import User
true
true
f727a133e51c2b5e804c815e0c981bdfa6b73676
3,793
py
Python
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
95
2019-01-23T04:19:45.000Z
2022-03-17T18:22:10.000Z
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
366
2019-02-20T07:15:08.000Z
2022-03-31T13:37:23.000Z
pyleecan/GUI/Dialog/DMachineSetup/SWSlot/PWSlot15/Gen_PWSlot15.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
74
2019-01-24T01:47:31.000Z
2022-02-25T05:44:42.000Z
# -*- coding: utf-8 -*- """File generated according to PWSlot15/gen_list.json WARNING! All changes made in this file will be lost! """ from pyleecan.GUI.Dialog.DMachineSetup.SWSlot.PWSlot15.Ui_PWSlot15 import Ui_PWSlot15 class Gen_PWSlot15(Ui_PWSlot15): def setupUi(self, PWSlot15): """Abstract class to update the widget according to the csv doc""" Ui_PWSlot15.setupUi(self, PWSlot15) # Setup of in_W0 txt = self.tr(u"""Slot isthmus width.""") self.in_W0.setWhatsThis(txt) self.in_W0.setToolTip(txt) # Setup of lf_W0 self.lf_W0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus width.""") self.lf_W0.setWhatsThis(txt) self.lf_W0.setToolTip(txt) # Setup of unit_W0 txt = self.tr(u"""Slot isthmus width.""") self.unit_W0.setWhatsThis(txt) self.unit_W0.setToolTip(txt) # Setup of in_W3 txt = self.tr(u"""Tooth width""") self.in_W3.setWhatsThis(txt) self.in_W3.setToolTip(txt) # Setup of lf_W3 self.lf_W3.validator().setBottom(0) txt = self.tr(u"""Tooth width""") self.lf_W3.setWhatsThis(txt) self.lf_W3.setToolTip(txt) # Setup of unit_W3 txt = self.tr(u"""Tooth width""") self.unit_W3.setWhatsThis(txt) self.unit_W3.setToolTip(txt) # Setup of in_H0 txt = self.tr(u"""Slot isthmus height.""") self.in_H0.setWhatsThis(txt) self.in_H0.setToolTip(txt) # Setup of lf_H0 self.lf_H0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus height.""") self.lf_H0.setWhatsThis(txt) self.lf_H0.setToolTip(txt) # Setup of unit_H0 txt = self.tr(u"""Slot isthmus height.""") self.unit_H0.setWhatsThis(txt) self.unit_H0.setToolTip(txt) # Setup of in_H1 txt = self.tr(u"""Slot intermediate height.""") self.in_H1.setWhatsThis(txt) self.in_H1.setToolTip(txt) # Setup of lf_H1 self.lf_H1.validator().setBottom(0) txt = self.tr(u"""Slot intermediate height.""") self.lf_H1.setWhatsThis(txt) self.lf_H1.setToolTip(txt) # Setup of unit_H1 txt = self.tr(u"""Slot intermediate height.""") self.unit_H1.setWhatsThis(txt) self.unit_H1.setToolTip(txt) # Setup of in_H2 txt = self.tr(u"""Slot height""") self.in_H2.setWhatsThis(txt) self.in_H2.setToolTip(txt) # Setup of lf_H2 self.lf_H2.validator().setBottom(0) txt = self.tr(u"""Slot height""") self.lf_H2.setWhatsThis(txt) self.lf_H2.setToolTip(txt) # Setup of unit_H2 txt = self.tr(u"""Slot height""") self.unit_H2.setWhatsThis(txt) self.unit_H2.setToolTip(txt) # Setup of in_R1 txt = self.tr(u"""Top radius""") self.in_R1.setWhatsThis(txt) self.in_R1.setToolTip(txt) # Setup of lf_R1 self.lf_R1.validator().setBottom(0) txt = self.tr(u"""Top radius""") self.lf_R1.setWhatsThis(txt) self.lf_R1.setToolTip(txt) # Setup of unit_R1 txt = self.tr(u"""Top radius""") self.unit_R1.setWhatsThis(txt) self.unit_R1.setToolTip(txt) # Setup of in_R2 txt = self.tr(u"""Bottom radius""") self.in_R2.setWhatsThis(txt) self.in_R2.setToolTip(txt) # Setup of lf_R2 self.lf_R2.validator().setBottom(0) txt = self.tr(u"""Bottom radius""") self.lf_R2.setWhatsThis(txt) self.lf_R2.setToolTip(txt) # Setup of unit_R2 txt = self.tr(u"""Bottom radius""") self.unit_R2.setWhatsThis(txt) self.unit_R2.setToolTip(txt)
30.837398
85
0.594516
from pyleecan.GUI.Dialog.DMachineSetup.SWSlot.PWSlot15.Ui_PWSlot15 import Ui_PWSlot15 class Gen_PWSlot15(Ui_PWSlot15): def setupUi(self, PWSlot15): Ui_PWSlot15.setupUi(self, PWSlot15) txt = self.tr(u"""Slot isthmus width.""") self.in_W0.setWhatsThis(txt) self.in_W0.setToolTip(txt) self.lf_W0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus width.""") self.lf_W0.setWhatsThis(txt) self.lf_W0.setToolTip(txt) txt = self.tr(u"""Slot isthmus width.""") self.unit_W0.setWhatsThis(txt) self.unit_W0.setToolTip(txt) txt = self.tr(u"""Tooth width""") self.in_W3.setWhatsThis(txt) self.in_W3.setToolTip(txt) self.lf_W3.validator().setBottom(0) txt = self.tr(u"""Tooth width""") self.lf_W3.setWhatsThis(txt) self.lf_W3.setToolTip(txt) txt = self.tr(u"""Tooth width""") self.unit_W3.setWhatsThis(txt) self.unit_W3.setToolTip(txt) txt = self.tr(u"""Slot isthmus height.""") self.in_H0.setWhatsThis(txt) self.in_H0.setToolTip(txt) self.lf_H0.validator().setBottom(0) txt = self.tr(u"""Slot isthmus height.""") self.lf_H0.setWhatsThis(txt) self.lf_H0.setToolTip(txt) txt = self.tr(u"""Slot isthmus height.""") self.unit_H0.setWhatsThis(txt) self.unit_H0.setToolTip(txt) txt = self.tr(u"""Slot intermediate height.""") self.in_H1.setWhatsThis(txt) self.in_H1.setToolTip(txt) self.lf_H1.validator().setBottom(0) txt = self.tr(u"""Slot intermediate height.""") self.lf_H1.setWhatsThis(txt) self.lf_H1.setToolTip(txt) txt = self.tr(u"""Slot intermediate height.""") self.unit_H1.setWhatsThis(txt) self.unit_H1.setToolTip(txt) txt = self.tr(u"""Slot height""") self.in_H2.setWhatsThis(txt) self.in_H2.setToolTip(txt) self.lf_H2.validator().setBottom(0) txt = self.tr(u"""Slot height""") self.lf_H2.setWhatsThis(txt) self.lf_H2.setToolTip(txt) txt = self.tr(u"""Slot height""") self.unit_H2.setWhatsThis(txt) self.unit_H2.setToolTip(txt) txt = self.tr(u"""Top radius""") self.in_R1.setWhatsThis(txt) self.in_R1.setToolTip(txt) self.lf_R1.validator().setBottom(0) txt = self.tr(u"""Top radius""") self.lf_R1.setWhatsThis(txt) self.lf_R1.setToolTip(txt) txt = self.tr(u"""Top radius""") self.unit_R1.setWhatsThis(txt) self.unit_R1.setToolTip(txt) txt = self.tr(u"""Bottom radius""") self.in_R2.setWhatsThis(txt) self.in_R2.setToolTip(txt) self.lf_R2.validator().setBottom(0) txt = self.tr(u"""Bottom radius""") self.lf_R2.setWhatsThis(txt) self.lf_R2.setToolTip(txt) txt = self.tr(u"""Bottom radius""") self.unit_R2.setWhatsThis(txt) self.unit_R2.setToolTip(txt)
true
true
f727a15310a842d4dcb36ff94d72138869d2a3dc
40,610
py
Python
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
1
2021-08-05T01:45:26.000Z
2021-08-05T01:45:26.000Z
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
null
null
null
pytorch_lightning/trainer/training_loop.py
MasaYan24/pytorch-lightning
046ac714f6955ed14b831657ea1b7b16bc28ac93
[ "Apache-2.0" ]
1
2021-02-16T00:47:46.000Z
2021-02-16T00:47:46.000Z
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from contextlib import contextmanager, suppress from copy import copy, deepcopy import numpy as np import torch from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.core.memory import ModelSummary from pytorch_lightning.core.optimizer import LightningOptimizer from pytorch_lightning.core.step_result import Result from pytorch_lightning.plugins import ParallelPlugin from pytorch_lightning.trainer.states import RunningStage, TrainerState from pytorch_lightning.trainer.supporters import Accumulator, TensorRunningAccum from pytorch_lightning.utilities import _TPU_AVAILABLE, AMPType, DeviceType, parsing from pytorch_lightning.utilities.distributed import rank_zero_info, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.memory import recursive_detach from pytorch_lightning.utilities.model_helpers import is_overridden from pytorch_lightning.utilities.parsing import AttributeDict from pytorch_lightning.utilities.warnings import WarningCache class TrainLoop: def __init__(self, trainer, multiple_trainloader_mode): self.trainer = trainer self.early_stopping_accumulator = None self.checkpoint_accumulator = None self.accumulated_loss = None self.warning_cache = WarningCache() self._teardown_already_run = False self.running_loss = TensorRunningAccum(window_length=20) self.automatic_optimization = True self._curr_step_result = None self._cur_grad_norm_dict = None self._multiple_trainloader_mode = multiple_trainloader_mode self._skip_backward = False self.trainer._multiple_trainloader_mode = multiple_trainloader_mode def on_trainer_init( self, max_epochs, min_epochs, max_steps, min_steps, num_sanity_val_steps, automatic_optimization, weights_summary, ): self.trainer.global_step = 0 self.trainer.current_epoch = 0 self.trainer.interrupted = False self.trainer.should_stop = False self.trainer._state = TrainerState.INITIALIZING self.trainer.total_batch_idx = 0 self.trainer.batch_idx = 0 self.trainer.num_training_batches = 0 self.trainer.train_dataloader = None self.automatic_optimization = automatic_optimization # If neither max_epochs or max_steps is set, then use existing default of max_epochs = 1000 self.trainer.max_epochs = 1000 if (max_epochs is None and max_steps is None) else max_epochs # If neither min_epochs or min_steps is set, then use existing default of min_epochs = 1 self.trainer.min_epochs = 1 if (min_epochs is None and min_steps is None) else min_epochs self.trainer.max_steps = max_steps self.trainer.min_steps = min_steps if num_sanity_val_steps == -1: self.trainer.num_sanity_val_steps = float("inf") else: self.trainer.num_sanity_val_steps = num_sanity_val_steps self.trainer.weights_summary = weights_summary if weights_summary is not None and weights_summary not in ModelSummary.MODES: raise MisconfigurationException( f"`weights_summary` can be None, {', '.join(ModelSummary.MODES)}, got {weights_summary}" ) @property def num_optimizers(self): num_optimizers = len(self.get_optimizers_iterable()) return num_optimizers def should_skip_training(self): should_by_max_steps = self.trainer.max_steps is not None and self.trainer.global_step >= self.trainer.max_steps should_by_epoch = self.trainer.max_epochs is not None and self.trainer.current_epoch >= self.trainer.max_epochs return should_by_max_steps or should_by_epoch or self.trainer.num_training_batches == 0 def on_train_start(self): # hook self.trainer.call_hook("on_train_start") # provide rank to profiler self.trainer.profile_connector.on_train_start(self.trainer) def setup_fit(self, model, train_dataloader, val_dataloaders, datamodule): # clean hparams if hasattr(model, "hparams"): parsing.clean_namespace(model.hparams) # links data to the trainer self.trainer.data_connector.attach_data(model, train_dataloader, val_dataloaders, datamodule) # check that model is configured correctly self.trainer.config_validator.verify_loop_configurations(model) # attach model log function to callback self.trainer.callback_connector.attach_model_logging_functions(model) def on_train_end(self): if self._teardown_already_run: return self._teardown_already_run = True # trigger checkpoint check. need to temporarily decrease the global step to avoid saving duplicates # when a checkpoint was saved at the last step self.trainer.global_step -= 1 self.check_checkpoint_callback(should_update=True, is_last=True) self.trainer.global_step += 1 # hook self.trainer.call_hook("on_train_end") # todo: TPU 8 cores hangs in flush with TensorBoard. Might do for all loggers. # It might be related to xla tensors blocked when moving the cpu # kill loggers if self.trainer.logger is not None and self.trainer.training_type_plugin.should_finalize: self.trainer.logger.finalize("success") # summarize profile results if self.trainer.global_rank == 0: self.trainer.profiler.describe() # give accelerators a chance to finish self.trainer.accelerator_backend.on_train_end() # clear mem if self.trainer._device_type == DeviceType.GPU: model = self.trainer.get_model() model.cpu() torch.cuda.empty_cache() def check_checkpoint_callback(self, should_update, is_last=False): # TODO bake this logic into the ModelCheckpoint callback if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = self.trainer.checkpoint_callbacks if is_last and any(cb.save_last for cb in callbacks): rank_zero_info("Saving latest checkpoint...") model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def check_early_stopping_callback(self, should_update): # TODO bake this logic into the EarlyStopping callback if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = [c for c in self.trainer.callbacks if isinstance(c, EarlyStopping)] model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def on_train_epoch_start(self, epoch): # update training progress in trainer self.trainer.current_epoch = epoch model = self.trainer.get_model() # reset train dataloader if epoch != 0 and self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) # todo: specify the possible exception with suppress(Exception): # set seed for distributed sampler (enables shuffling for each epoch) self.trainer.train_dataloader.sampler.set_epoch(epoch) # changing gradient according accumulation_scheduler self.trainer.accumulation_scheduler.on_epoch_start(self.trainer, self.trainer.get_model()) # stores accumulated grad fractions per batch self.accumulated_loss = TensorRunningAccum(window_length=self.trainer.accumulate_grad_batches) # structured result accumulators for callbacks self.early_stopping_accumulator = Accumulator() self.checkpoint_accumulator = Accumulator() # hook self.trainer.call_hook("on_epoch_start") self.trainer.call_hook("on_train_epoch_start") def on_train_batch_end(self, epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx): # hook self.trainer.call_hook('on_train_batch_end', batch_end_outputs, batch, batch_idx, dataloader_idx) self.trainer.call_hook('on_batch_end') # figure out what to track for epoch end self.track_epoch_end_reduce_metrics(epoch_output, batch_end_outputs) # reset batch logger internals self.trainer.logger_connector.on_train_batch_end() def reset_train_val_dataloaders(self, model): if self.trainer.train_dataloader is None or not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) if self.trainer.val_dataloaders is None and not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_val_dataloader(model) def track_epoch_end_reduce_metrics(self, epoch_output, batch_end_outputs): # track the outputs to reduce at the end of the epoch for opt_idx, opt_outputs in enumerate(batch_end_outputs): sample_output = opt_outputs[-1] # decide if we need to reduce at the end of the epoch automatically auto_reduce_tng_result = isinstance(sample_output, Result) and sample_output.should_reduce_on_epoch_end hook_overridden = ( is_overridden("training_epoch_end", model=self.trainer.get_model()) or is_overridden("on_train_epoch_end", model=self.trainer.get_model()) ) # only track when a) it needs to be autoreduced OR b) the user wants to manually reduce on epoch end if not (hook_overridden or auto_reduce_tng_result): continue # with 1 step (no tbptt) don't use a sequence at epoch end if isinstance(opt_outputs, list) and len(opt_outputs) == 1 and not isinstance(opt_outputs[0], Result): opt_outputs = opt_outputs[0] epoch_output[opt_idx].append(opt_outputs) def get_optimizers_iterable(self): """ Generates an iterable with (idx, optimizer) for each optimizer. """ if not self.trainer.optimizer_frequencies: # call training_step once per optimizer return list(enumerate(self.trainer.optimizers)) optimizer_freq_cumsum = np.cumsum(self.trainer.optimizer_frequencies) optimizers_loop_length = optimizer_freq_cumsum[-1] current_place_in_loop = self.trainer.total_batch_idx % optimizers_loop_length # find optimzier index by looking for the first {item > current_place} in the cumsum list opt_idx = np.argmax(optimizer_freq_cumsum > current_place_in_loop) return [[opt_idx, self.trainer.optimizers[opt_idx]]] def on_after_backward(self, training_step_output, batch_idx, untouched_loss): is_result_obj = isinstance(training_step_output, Result) if is_result_obj: training_step_output.detach() else: training_step_output.batch_loss = training_step_output.batch_loss.detach() # insert after step hook self.trainer.call_hook("on_after_backward") # when in dev debugging track the losses self.trainer.dev_debugger.track_train_loss_history(batch_idx, untouched_loss.detach()) def _check_training_step_output(self, training_step_output): if isinstance(training_step_output, torch.Tensor) and not self.automatic_optimization: if training_step_output.grad_fn is None: # TODO: Find why - RuntimeError: Expected to mark a variable ready only once ... raise MisconfigurationException("In manual optimization, `training_step` should not return a Tensor") def training_step(self, split_batch, batch_idx, opt_idx, hiddens): # give the PL module a result for logging model_ref = self.trainer.get_model() with self.trainer.profiler.profile("model_forward"): args = self.build_train_args(split_batch, batch_idx, opt_idx, hiddens) # manually capture logged metrics model_ref._current_fx_name = 'training_step' model_ref._results = Result() with self.trainer.profiler.profile("training_step"): training_step_output = self.trainer.accelerator_backend.training_step(args) self.trainer.accelerator_backend.post_training_step() self.trainer.logger_connector.cache_logged_metrics() self._check_training_step_output(training_step_output) training_step_output = self.trainer.call_hook("training_step_end", training_step_output) training_step_output_for_epoch_end, training_step_output = self._process_training_step_output( training_step_output, split_batch ) is_result_obj = isinstance(training_step_output, Result) if training_step_output_for_epoch_end is None: return None # enable empty loss when using manual opt closure_loss = None untouched_loss = None if self.trainer.train_loop.automatic_optimization: # accumulate loss # (if accumulate_grad_batches = 1 no effect) if is_result_obj: closure_loss = training_step_output.minimize else: closure_loss = training_step_output.batch_loss closure_loss = closure_loss / self.trainer.accumulate_grad_batches # the loss will get scaled for amp. avoid any modifications to it untouched_loss = closure_loss.detach().clone() # result result = AttributeDict( closure_loss=closure_loss, loss=untouched_loss, training_step_output=training_step_output, training_step_output_for_epoch_end=training_step_output_for_epoch_end, hiddens=training_step_output.hiddens, ) return result def _process_training_step_output(self, training_step_output, split_batch): training_step_output_for_epoch_end = training_step_output # enable validation_step return None if training_step_output_for_epoch_end is None: return None, None # ----------------------------------------- # process result return (DEPRECATE in 1.0) # ----------------------------------------- if isinstance(training_step_output, Result): training_step_output_for_epoch_end = self._process_result(training_step_output, split_batch) return training_step_output_for_epoch_end, training_step_output # ----------------------------------------- # process hybrid (1.0) # ----------------------------------------- # no need for these checks in 1.0.0 # TODO: remove checks in 1.0.0 is_tensor = isinstance(training_step_output_for_epoch_end, torch.Tensor) is_1_0_output = is_tensor or ("log" not in training_step_output and "progress_bar" not in training_step_output) if is_1_0_output: return self._process_training_step_output_1_0(training_step_output, split_batch) # ----------------------------------------- # process old dict (deprecate 1.0) # ----------------------------------------- training_step_output = self.trainer.process_dict_result(training_step_output, train=True) training_step_output = AttributeDict( batch_loss=training_step_output[0], pbar_on_batch_end=training_step_output[1], log_metrics=training_step_output[2], callback_metrics=training_step_output[3], hiddens=training_step_output[4], ) # if the user decides to finally reduce things in epoch_end, save raw output without graphs if isinstance(training_step_output_for_epoch_end, torch.Tensor): training_step_output_for_epoch_end = training_step_output_for_epoch_end.detach() else: training_step_output_for_epoch_end = recursive_detach(training_step_output_for_epoch_end) return training_step_output_for_epoch_end, training_step_output def _process_training_step_output_1_0(self, training_step_output, split_batch): result = self.trainer.get_model()._results loss = None hiddens = None # handle dict return if isinstance(training_step_output, dict): loss = training_step_output.pop("loss", None) hiddens = training_step_output.pop("hiddens", None) result["extra"] = training_step_output # handle scalar return elif isinstance(training_step_output, torch.Tensor): loss = training_step_output result["extra"] = {} # map to results under the hood result.minimize = loss result.hiddens = hiddens # track batch for manual reduction with result result.track_batch_size(len(split_batch)) # track metrics without grads for epoch reduction training_step_output_for_epoch_end = copy(result) training_step_output_for_epoch_end.detach() if self.trainer.move_metrics_to_cpu: training_step_output_for_epoch_end.cpu() # what flows back into the system training_step_output = result return training_step_output_for_epoch_end, training_step_output def _process_result(self, training_step_output, split_batch): training_step_output.track_batch_size(len(split_batch)) m = """ TrainResult and EvalResult were deprecated in 0.9.1 and support will drop in 1.0.0. Use self.log and .write from the LightningModule to log metrics and write predictions. training_step can now only return a scalar (for the loss) or a dictionary with anything you want. Option 1: return loss Option 2: return {'loss': loss, 'anything_else': ...} Option 3: return {'loss': loss, 'hiddens': hiddens, 'anything_else': ...} """ rank_zero_warn(m) training_step_output_for_epoch_end = copy(training_step_output) training_step_output_for_epoch_end.detach() return training_step_output_for_epoch_end def optimizer_step(self, optimizer, opt_idx, batch_idx, train_step_and_backward_closure): model_ref = self.trainer.get_model() is_lbfgs = isinstance(optimizer, torch.optim.LBFGS) using_native_amp = self.trainer.amp_backend == AMPType.NATIVE # native amp + lbfgs is a no go right now if using_native_amp and is_lbfgs: raise MisconfigurationException( 'native PyTorch amp and lbfgs are not compatible.' ' To request, please file a Github issue in PyTorch and tag @mcarilli' ) # wraps into LightningOptimizer only for running step optimizer = LightningOptimizer._to_lightning_optimizer(optimizer, self.trainer, opt_idx) # model hook model_ref.optimizer_step( self.trainer.current_epoch, batch_idx, optimizer, opt_idx, train_step_and_backward_closure, on_tpu=self.trainer._device_type == DeviceType.TPU and _TPU_AVAILABLE, using_native_amp=using_native_amp, using_lbfgs=is_lbfgs, ) def on_before_zero_grad(self, optimizer): self.trainer.call_hook('on_before_zero_grad', optimizer) def optimizer_zero_grad(self, batch_idx, optimizer, opt_idx): self.trainer.accelerator_backend.optimizer_zero_grad(self.trainer.current_epoch, batch_idx, optimizer, opt_idx) def track_and_norm_grad(self, optimizer): # track gradient norms grad_norm_dic = self._track_gradient_norm() # clip gradients self.trainer.accelerator_backend.clip_gradients(optimizer, self.trainer.gradient_clip_val) self._cur_grad_norm_dict = grad_norm_dic def _track_gradient_norm(self): grad_norm_dict = {} if (self.trainer.global_step + 1) % self.trainer.log_every_n_steps == 0: if float(self.trainer.track_grad_norm) > 0: model = self.trainer.get_model() grad_norm_dict = model.grad_norm(self.trainer.track_grad_norm) return grad_norm_dict def process_hiddens(self, opt_closure_result): hiddens = opt_closure_result.hiddens if isinstance(opt_closure_result.training_step_output, Result): opt_closure_result.training_step_output_for_epoch_end.drop_hiddens() return hiddens def tbptt_split_batch(self, batch): splits = [batch] if self.trainer.truncated_bptt_steps is not None: model_ref = self.trainer.get_model() with self.trainer.profiler.profile("tbptt_split_batch"): splits = model_ref.tbptt_split_batch(batch, self.trainer.truncated_bptt_steps) return splits def run_training_epoch(self): # modify dataloader if needed (ddp, etc...) train_dataloader = self.trainer.accelerator_backend.process_dataloader(self.trainer.train_dataloader) # track epoch output epoch_output = [[] for _ in range(self.num_optimizers)] train_dataloader = self.trainer.data_connector.get_profiled_train_dataloader(train_dataloader) dataloader_idx = 0 should_check_val = False for batch_idx, (batch, is_last_batch) in train_dataloader: self.trainer.batch_idx = batch_idx # ------------------------------------ # TRAINING_STEP + TRAINING_STEP_END # ------------------------------------ with self.trainer.profiler.profile("run_training_batch"): batch_output = self.run_training_batch(batch, batch_idx, dataloader_idx) # when returning -1 from train_step, we end epoch early if batch_output.signal == -1: break batch_end_outputs = self.process_train_step_outputs( batch_output.training_step_output_for_epoch_end, self.early_stopping_accumulator, self.checkpoint_accumulator, ) # hook # TODO: add outputs to batches self.on_train_batch_end(epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx) # ----------------------------------------- # SAVE METRICS TO LOGGERS # ----------------------------------------- self.trainer.logger_connector.log_train_step_metrics(batch_output) # ----------------------------------------- # VALIDATE IF NEEDED + CHECKPOINT CALLBACK # ----------------------------------------- should_check_val = self.should_check_val_fx(batch_idx, is_last_batch) if should_check_val: self.trainer.run_evaluation() # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) # ----------------------------------------- # SAVE LOGGERS (ie: Tensorboard, etc...) # ----------------------------------------- self.save_loggers_on_train_batch_end() # update LR schedulers monitor_metrics = deepcopy(self.trainer.logger_connector.callback_metrics) self.update_train_loop_lr_schedulers(monitor_metrics=monitor_metrics) self.trainer.checkpoint_connector.has_trained = True # max steps reached, end training if ( self.trainer.max_steps is not None and self.trainer.max_steps == self.trainer.global_step + 1 and self._accumulated_batches_reached() ): break # end epoch early # stop when the flag is changed or we've gone past the amount # requested in the batches if self.trainer.should_stop: break self.trainer.total_batch_idx += 1 # stop epoch if we limited the number of training batches if self._num_training_batches_reached(is_last_batch): break # progress global step according to grads progress self.increment_accumulated_grad_global_step() # epoch end hook self.run_on_epoch_end_hook(epoch_output) # log epoch metrics self.trainer.logger_connector.log_train_epoch_end_metrics( epoch_output, self.checkpoint_accumulator, self.early_stopping_accumulator, self.num_optimizers ) should_check_val = self.should_check_val_fx(batch_idx, is_last_batch, on_epoch=True) if should_check_val: self.trainer.run_evaluation(on_epoch=True) # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) should_skip_eval = self.trainer.evaluation_loop.should_skip_evaluation(self.trainer.num_val_batches) should_train_only = self.trainer.disable_validation or should_skip_eval if should_train_only: # update epoch level lr_schedulers self.trainer.optimizer_connector.update_learning_rates(interval='epoch') self.check_checkpoint_callback(True) self.check_early_stopping_callback(True) # increment the global step once # progress global step according to grads progress self.increment_accumulated_grad_global_step() def run_training_batch(self, batch, batch_idx, dataloader_idx): # track grad norms grad_norm_dic = {} # bookkeeping self.trainer.hiddens = None # track all outputs across time and num of optimizers batch_outputs = [[] for _ in range(len(self.get_optimizers_iterable()))] if batch is None: return AttributeDict(signal=0, grad_norm_dic=grad_norm_dic) # hook response = self.trainer.call_hook("on_batch_start") if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) # hook response = self.trainer.call_hook("on_train_batch_start", batch, batch_idx, dataloader_idx) if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) # lightning module hook splits = self.tbptt_split_batch(batch) for split_idx, split_batch in enumerate(splits): # create an iterable for optimizers and loop over them for opt_idx, optimizer in self.prepare_optimizers(): # toggle model params + set info to logger_connector self.run_train_split_start(split_idx, split_batch, opt_idx, optimizer) if self.should_accumulate(): # For gradient accumulation # ------------------- # calculate loss (train step + train step end) # ------------------- # automatic_optimization=True: perform dpp sync only when performing optimizer_step # automatic_optimization=False: don't block synchronization here with self.block_ddp_sync_behaviour(): self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # ------------------------------ # BACKWARD PASS # ------------------------------ # gradient update with accumulated gradients else: if self.automatic_optimization: def train_step_and_backward_closure(): result = self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) return None if result is None else result.loss # optimizer step self.optimizer_step(optimizer, opt_idx, batch_idx, train_step_and_backward_closure) else: self._curr_step_result = self.training_step( split_batch, batch_idx, opt_idx, self.trainer.hiddens ) if self._curr_step_result is None: # user decided to skip optimization # make sure to zero grad. continue batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # todo: Properly aggregate grad_norm accros opt_idx and split_idx grad_norm_dic = self._cur_grad_norm_dict self._cur_grad_norm_dict = None # update running loss + reset accumulated loss self.update_running_loss() result = AttributeDict( signal=0, grad_norm_dic=grad_norm_dic, training_step_output_for_epoch_end=batch_outputs, ) return result @contextmanager def block_ddp_sync_behaviour(self, should_block_sync: bool = False): """ automatic_optimization = True Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead automatic_optimization = False do not block ddp gradient sync when using manual optimization as gradients are needed within the training step Returns: context manager with sync behaviour off """ if ( isinstance(self.trainer.training_type_plugin, ParallelPlugin) and (self.automatic_optimization or should_block_sync) ): with self.trainer.training_type_plugin.block_backward_sync(): yield None else: yield None def _process_closure_result(self, batch_outputs: list, opt_idx: int) -> list: opt_closure_result = self._curr_step_result if opt_closure_result is not None: # cache metrics self.trainer.logger_connector.cache_training_step_metrics(opt_closure_result) # track hiddens self.trainer.hiddens = self.process_hiddens(opt_closure_result) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(opt_closure_result.loss) # track all the outputs across all steps batch_opt_idx = opt_idx if len(batch_outputs) > 1 else 0 batch_outputs[batch_opt_idx].append(opt_closure_result.training_step_output_for_epoch_end) if self.automatic_optimization: # track total loss for logging (avoid mem leaks) self.accumulated_loss.append(opt_closure_result.loss) self._curr_step_result = None return batch_outputs def training_step_and_backward(self, split_batch, batch_idx, opt_idx, optimizer, hiddens): """ wrap the forward step in a closure so second order methods work """ with self.trainer.profiler.profile("training_step_and_backward"): # lightning module hook result = self.training_step(split_batch, batch_idx, opt_idx, hiddens) self._curr_step_result = result if result is None: if self.automatic_optimization: self.warning_cache.warn("training_step returned None if it was on purpose, ignore this warning...") return None if not self._skip_backward and self.trainer.train_loop.automatic_optimization: # backward pass with self.trainer.profiler.profile("model_backward"): self.backward(result, optimizer, opt_idx) # hook - call this hook only # when gradients have finished to accumulate if not self.should_accumulate(): self.on_after_backward(result.training_step_output, batch_idx, result.loss) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(result.loss) if len(self.trainer.optimizers) > 1: # revert back to previous state self.trainer.get_model().untoggle_optimizer(opt_idx) return result def backward(self, result, optimizer, opt_idx, *args, **kwargs): self.trainer.dev_debugger.track_event("backward_call") should_accumulate = self.should_accumulate() # backward can be called manually in the training loop if isinstance(result, torch.Tensor): self.trainer.accelerator_backend.backward(result, optimizer, opt_idx, should_accumulate, *args, **kwargs) else: result.closure_loss = self.trainer.accelerator_backend.backward( result.closure_loss, optimizer, opt_idx, should_accumulate, *args, **kwargs ) if not self.should_accumulate(): # track gradients self.track_and_norm_grad(optimizer=optimizer) def update_train_loop_lr_schedulers(self, monitor_metrics=None): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() if num_accumulated_batches_reached or num_training_batches_reached: # update lr self.trainer.optimizer_connector.update_learning_rates(interval="step", monitor_metrics=monitor_metrics) def run_on_epoch_end_hook(self, epoch_output): # inform logger the batch loop has finished self.trainer.logger_connector.on_train_epoch_end() self.trainer.call_hook('on_train_epoch_end', epoch_output) self.trainer.call_hook('on_epoch_end') def increment_accumulated_grad_global_step(self): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() # progress global step according to grads progress if num_accumulated_batches_reached or num_training_batches_reached: self.trainer.global_step += 1 def _accumulated_batches_reached(self): return (self.trainer.batch_idx + 1) % self.trainer.accumulate_grad_batches == 0 def _num_training_batches_reached(self, is_last_batch=False): return (self.trainer.batch_idx + 1) == self.trainer.num_training_batches or is_last_batch def should_accumulate(self): # checks if backward or backward + optimizer step (via closure) accumulation_done = self._accumulated_batches_reached() is_final_batch = self._num_training_batches_reached() return not (accumulation_done or is_final_batch) def should_check_val_fx(self, batch_idx, is_last_batch, on_epoch=False): # decide if we should run validation is_val_check_batch = (batch_idx + 1) % self.trainer.val_check_batch == 0 is_val_check_epoch = (self.trainer.current_epoch + 1) % self.trainer.check_val_every_n_epoch == 0 can_check_val = self.trainer.enable_validation and is_val_check_epoch is_last_batch_for_infinite_dataset = is_last_batch and self.trainer.val_check_batch == float("inf") epoch_end_val_check = self.trainer.val_check_batch == self.trainer.num_training_batches should_check_val = ((is_val_check_batch and epoch_end_val_check) or self.trainer.should_stop or is_last_batch_for_infinite_dataset ) if on_epoch else (is_val_check_batch and not epoch_end_val_check) return should_check_val and can_check_val def build_train_args(self, batch, batch_idx, opt_idx, hiddens): # enable not needing to add opt_idx to training_step args = [batch, batch_idx] if len(self.trainer.optimizers) > 1: if self.trainer.has_arg("training_step", "optimizer_idx"): args.append(opt_idx) else: num_opts = len(self.trainer.optimizers) raise ValueError( f"Your LightningModule defines {num_opts} optimizers but " f'training_step is missing the "optimizer_idx" argument.' ) # pass hiddens if using tbptt if self.trainer.truncated_bptt_steps is not None: args.append(hiddens) return args def save_loggers_on_train_batch_end(self): # when loggers should save to disk should_flush_logs = self.trainer.logger_connector.should_flush_logs if should_flush_logs and self.trainer.is_global_zero and self.trainer.logger is not None: self.trainer.logger.save() def process_train_step_outputs(self, all_train_step_outputs, early_stopping_accumulator, checkpoint_accumulator): """ Figure out what needs to be tracked/logged at the end of the epoch """ # the training step outputs a list per optimizer. The list contains the outputs at each time step # when no TBPTT is used, then the list has 1 item per batch # when TBPTT IS used, then the list has n items (1 per time step) batch_end_outputs = [] for optimizer_idx_outputs in all_train_step_outputs: # extract one representative sample from each time step (1 if no tbptt) and 0th optimizer if len(optimizer_idx_outputs) == 0: continue sample_output = optimizer_idx_outputs[-1] # pull out callback info if available (ie: Results object) if isinstance(sample_output, dict) and "early_stop_on" in sample_output: early_stopping_accumulator.accumulate(sample_output["early_stop_on"]) if isinstance(sample_output, dict) and "checkpoint_on" in sample_output: checkpoint_accumulator.accumulate(sample_output["checkpoint_on"]) batch_end_outputs.append(optimizer_idx_outputs) return batch_end_outputs def prepare_optimizers(self): # in manual optimization we loop over all optimizers at once optimizers = self.get_optimizers_iterable() if not self.automatic_optimization: optimizers = [optimizers[0]] return optimizers def run_train_split_start(self, split_idx, split_batch, opt_idx, optimizer): # set split_idx to trainer for tracking self.trainer.split_idx = split_idx # make sure only the gradients of the current optimizer's parameters are calculated # in the training step to prevent dangling gradients in multiple-optimizer setup. if self.automatic_optimization and len(self.trainer.optimizers) > 1: model = self.trainer.get_model() model.toggle_optimizer(optimizer, opt_idx) # use to track metrics internally self.trainer.logger_connector.on_train_split_start(split_idx, opt_idx, split_batch) def update_running_loss(self): accumulated_loss = self.accumulated_loss.mean() if accumulated_loss is not None: # calculate running loss for display self.running_loss.append(self.accumulated_loss.mean() * self.trainer.accumulate_grad_batches) # reset for next set of accumulated grads self.accumulated_loss.reset()
42.747368
119
0.661241
from contextlib import contextmanager, suppress from copy import copy, deepcopy import numpy as np import torch from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.core.memory import ModelSummary from pytorch_lightning.core.optimizer import LightningOptimizer from pytorch_lightning.core.step_result import Result from pytorch_lightning.plugins import ParallelPlugin from pytorch_lightning.trainer.states import RunningStage, TrainerState from pytorch_lightning.trainer.supporters import Accumulator, TensorRunningAccum from pytorch_lightning.utilities import _TPU_AVAILABLE, AMPType, DeviceType, parsing from pytorch_lightning.utilities.distributed import rank_zero_info, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.memory import recursive_detach from pytorch_lightning.utilities.model_helpers import is_overridden from pytorch_lightning.utilities.parsing import AttributeDict from pytorch_lightning.utilities.warnings import WarningCache class TrainLoop: def __init__(self, trainer, multiple_trainloader_mode): self.trainer = trainer self.early_stopping_accumulator = None self.checkpoint_accumulator = None self.accumulated_loss = None self.warning_cache = WarningCache() self._teardown_already_run = False self.running_loss = TensorRunningAccum(window_length=20) self.automatic_optimization = True self._curr_step_result = None self._cur_grad_norm_dict = None self._multiple_trainloader_mode = multiple_trainloader_mode self._skip_backward = False self.trainer._multiple_trainloader_mode = multiple_trainloader_mode def on_trainer_init( self, max_epochs, min_epochs, max_steps, min_steps, num_sanity_val_steps, automatic_optimization, weights_summary, ): self.trainer.global_step = 0 self.trainer.current_epoch = 0 self.trainer.interrupted = False self.trainer.should_stop = False self.trainer._state = TrainerState.INITIALIZING self.trainer.total_batch_idx = 0 self.trainer.batch_idx = 0 self.trainer.num_training_batches = 0 self.trainer.train_dataloader = None self.automatic_optimization = automatic_optimization self.trainer.max_epochs = 1000 if (max_epochs is None and max_steps is None) else max_epochs self.trainer.min_epochs = 1 if (min_epochs is None and min_steps is None) else min_epochs self.trainer.max_steps = max_steps self.trainer.min_steps = min_steps if num_sanity_val_steps == -1: self.trainer.num_sanity_val_steps = float("inf") else: self.trainer.num_sanity_val_steps = num_sanity_val_steps self.trainer.weights_summary = weights_summary if weights_summary is not None and weights_summary not in ModelSummary.MODES: raise MisconfigurationException( f"`weights_summary` can be None, {', '.join(ModelSummary.MODES)}, got {weights_summary}" ) @property def num_optimizers(self): num_optimizers = len(self.get_optimizers_iterable()) return num_optimizers def should_skip_training(self): should_by_max_steps = self.trainer.max_steps is not None and self.trainer.global_step >= self.trainer.max_steps should_by_epoch = self.trainer.max_epochs is not None and self.trainer.current_epoch >= self.trainer.max_epochs return should_by_max_steps or should_by_epoch or self.trainer.num_training_batches == 0 def on_train_start(self): self.trainer.call_hook("on_train_start") self.trainer.profile_connector.on_train_start(self.trainer) def setup_fit(self, model, train_dataloader, val_dataloaders, datamodule): if hasattr(model, "hparams"): parsing.clean_namespace(model.hparams) self.trainer.data_connector.attach_data(model, train_dataloader, val_dataloaders, datamodule) self.trainer.config_validator.verify_loop_configurations(model) self.trainer.callback_connector.attach_model_logging_functions(model) def on_train_end(self): if self._teardown_already_run: return self._teardown_already_run = True self.trainer.global_step -= 1 self.check_checkpoint_callback(should_update=True, is_last=True) self.trainer.global_step += 1 self.trainer.call_hook("on_train_end") if self.trainer.logger is not None and self.trainer.training_type_plugin.should_finalize: self.trainer.logger.finalize("success") if self.trainer.global_rank == 0: self.trainer.profiler.describe() self.trainer.accelerator_backend.on_train_end() if self.trainer._device_type == DeviceType.GPU: model = self.trainer.get_model() model.cpu() torch.cuda.empty_cache() def check_checkpoint_callback(self, should_update, is_last=False): if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = self.trainer.checkpoint_callbacks if is_last and any(cb.save_last for cb in callbacks): rank_zero_info("Saving latest checkpoint...") model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def check_early_stopping_callback(self, should_update): if should_update and self.trainer.checkpoint_connector.has_trained: callbacks = [c for c in self.trainer.callbacks if isinstance(c, EarlyStopping)] model = self.trainer.get_model() for cb in callbacks: cb.on_validation_end(self.trainer, model) def on_train_epoch_start(self, epoch): self.trainer.current_epoch = epoch model = self.trainer.get_model() if epoch != 0 and self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) with suppress(Exception): self.trainer.train_dataloader.sampler.set_epoch(epoch) self.trainer.accumulation_scheduler.on_epoch_start(self.trainer, self.trainer.get_model()) self.accumulated_loss = TensorRunningAccum(window_length=self.trainer.accumulate_grad_batches) self.early_stopping_accumulator = Accumulator() self.checkpoint_accumulator = Accumulator() self.trainer.call_hook("on_epoch_start") self.trainer.call_hook("on_train_epoch_start") def on_train_batch_end(self, epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx): self.trainer.call_hook('on_train_batch_end', batch_end_outputs, batch, batch_idx, dataloader_idx) self.trainer.call_hook('on_batch_end') self.track_epoch_end_reduce_metrics(epoch_output, batch_end_outputs) self.trainer.logger_connector.on_train_batch_end() def reset_train_val_dataloaders(self, model): if self.trainer.train_dataloader is None or not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_train_dataloader(model) if self.trainer.val_dataloaders is None and not self.trainer.reload_dataloaders_every_epoch: self.trainer.reset_val_dataloader(model) def track_epoch_end_reduce_metrics(self, epoch_output, batch_end_outputs): for opt_idx, opt_outputs in enumerate(batch_end_outputs): sample_output = opt_outputs[-1] auto_reduce_tng_result = isinstance(sample_output, Result) and sample_output.should_reduce_on_epoch_end hook_overridden = ( is_overridden("training_epoch_end", model=self.trainer.get_model()) or is_overridden("on_train_epoch_end", model=self.trainer.get_model()) ) if not (hook_overridden or auto_reduce_tng_result): continue if isinstance(opt_outputs, list) and len(opt_outputs) == 1 and not isinstance(opt_outputs[0], Result): opt_outputs = opt_outputs[0] epoch_output[opt_idx].append(opt_outputs) def get_optimizers_iterable(self): if not self.trainer.optimizer_frequencies: # call training_step once per optimizer return list(enumerate(self.trainer.optimizers)) optimizer_freq_cumsum = np.cumsum(self.trainer.optimizer_frequencies) optimizers_loop_length = optimizer_freq_cumsum[-1] current_place_in_loop = self.trainer.total_batch_idx % optimizers_loop_length # find optimzier index by looking for the first {item > current_place} in the cumsum list opt_idx = np.argmax(optimizer_freq_cumsum > current_place_in_loop) return [[opt_idx, self.trainer.optimizers[opt_idx]]] def on_after_backward(self, training_step_output, batch_idx, untouched_loss): is_result_obj = isinstance(training_step_output, Result) if is_result_obj: training_step_output.detach() else: training_step_output.batch_loss = training_step_output.batch_loss.detach() # insert after step hook self.trainer.call_hook("on_after_backward") # when in dev debugging track the losses self.trainer.dev_debugger.track_train_loss_history(batch_idx, untouched_loss.detach()) def _check_training_step_output(self, training_step_output): if isinstance(training_step_output, torch.Tensor) and not self.automatic_optimization: if training_step_output.grad_fn is None: # TODO: Find why - RuntimeError: Expected to mark a variable ready only once ... raise MisconfigurationException("In manual optimization, `training_step` should not return a Tensor") def training_step(self, split_batch, batch_idx, opt_idx, hiddens): # give the PL module a result for logging model_ref = self.trainer.get_model() with self.trainer.profiler.profile("model_forward"): args = self.build_train_args(split_batch, batch_idx, opt_idx, hiddens) # manually capture logged metrics model_ref._current_fx_name = 'training_step' model_ref._results = Result() with self.trainer.profiler.profile("training_step"): training_step_output = self.trainer.accelerator_backend.training_step(args) self.trainer.accelerator_backend.post_training_step() self.trainer.logger_connector.cache_logged_metrics() self._check_training_step_output(training_step_output) training_step_output = self.trainer.call_hook("training_step_end", training_step_output) training_step_output_for_epoch_end, training_step_output = self._process_training_step_output( training_step_output, split_batch ) is_result_obj = isinstance(training_step_output, Result) if training_step_output_for_epoch_end is None: return None # enable empty loss when using manual opt closure_loss = None untouched_loss = None if self.trainer.train_loop.automatic_optimization: # accumulate loss # (if accumulate_grad_batches = 1 no effect) if is_result_obj: closure_loss = training_step_output.minimize else: closure_loss = training_step_output.batch_loss closure_loss = closure_loss / self.trainer.accumulate_grad_batches # the loss will get scaled for amp. avoid any modifications to it untouched_loss = closure_loss.detach().clone() # result result = AttributeDict( closure_loss=closure_loss, loss=untouched_loss, training_step_output=training_step_output, training_step_output_for_epoch_end=training_step_output_for_epoch_end, hiddens=training_step_output.hiddens, ) return result def _process_training_step_output(self, training_step_output, split_batch): training_step_output_for_epoch_end = training_step_output # enable validation_step return None if training_step_output_for_epoch_end is None: return None, None # ----------------------------------------- # process result return (DEPRECATE in 1.0) # ----------------------------------------- if isinstance(training_step_output, Result): training_step_output_for_epoch_end = self._process_result(training_step_output, split_batch) return training_step_output_for_epoch_end, training_step_output # ----------------------------------------- # process hybrid (1.0) # ----------------------------------------- # no need for these checks in 1.0.0 # TODO: remove checks in 1.0.0 is_tensor = isinstance(training_step_output_for_epoch_end, torch.Tensor) is_1_0_output = is_tensor or ("log" not in training_step_output and "progress_bar" not in training_step_output) if is_1_0_output: return self._process_training_step_output_1_0(training_step_output, split_batch) # ----------------------------------------- # process old dict (deprecate 1.0) # ----------------------------------------- training_step_output = self.trainer.process_dict_result(training_step_output, train=True) training_step_output = AttributeDict( batch_loss=training_step_output[0], pbar_on_batch_end=training_step_output[1], log_metrics=training_step_output[2], callback_metrics=training_step_output[3], hiddens=training_step_output[4], ) # if the user decides to finally reduce things in epoch_end, save raw output without graphs if isinstance(training_step_output_for_epoch_end, torch.Tensor): training_step_output_for_epoch_end = training_step_output_for_epoch_end.detach() else: training_step_output_for_epoch_end = recursive_detach(training_step_output_for_epoch_end) return training_step_output_for_epoch_end, training_step_output def _process_training_step_output_1_0(self, training_step_output, split_batch): result = self.trainer.get_model()._results loss = None hiddens = None # handle dict return if isinstance(training_step_output, dict): loss = training_step_output.pop("loss", None) hiddens = training_step_output.pop("hiddens", None) result["extra"] = training_step_output # handle scalar return elif isinstance(training_step_output, torch.Tensor): loss = training_step_output result["extra"] = {} # map to results under the hood result.minimize = loss result.hiddens = hiddens # track batch for manual reduction with result result.track_batch_size(len(split_batch)) # track metrics without grads for epoch reduction training_step_output_for_epoch_end = copy(result) training_step_output_for_epoch_end.detach() if self.trainer.move_metrics_to_cpu: training_step_output_for_epoch_end.cpu() # what flows back into the system training_step_output = result return training_step_output_for_epoch_end, training_step_output def _process_result(self, training_step_output, split_batch): training_step_output.track_batch_size(len(split_batch)) m = """ TrainResult and EvalResult were deprecated in 0.9.1 and support will drop in 1.0.0. Use self.log and .write from the LightningModule to log metrics and write predictions. training_step can now only return a scalar (for the loss) or a dictionary with anything you want. Option 1: return loss Option 2: return {'loss': loss, 'anything_else': ...} Option 3: return {'loss': loss, 'hiddens': hiddens, 'anything_else': ...} """ rank_zero_warn(m) training_step_output_for_epoch_end = copy(training_step_output) training_step_output_for_epoch_end.detach() return training_step_output_for_epoch_end def optimizer_step(self, optimizer, opt_idx, batch_idx, train_step_and_backward_closure): model_ref = self.trainer.get_model() is_lbfgs = isinstance(optimizer, torch.optim.LBFGS) using_native_amp = self.trainer.amp_backend == AMPType.NATIVE # native amp + lbfgs is a no go right now if using_native_amp and is_lbfgs: raise MisconfigurationException( 'native PyTorch amp and lbfgs are not compatible.' ' To request, please file a Github issue in PyTorch and tag @mcarilli' ) # wraps into LightningOptimizer only for running step optimizer = LightningOptimizer._to_lightning_optimizer(optimizer, self.trainer, opt_idx) # model hook model_ref.optimizer_step( self.trainer.current_epoch, batch_idx, optimizer, opt_idx, train_step_and_backward_closure, on_tpu=self.trainer._device_type == DeviceType.TPU and _TPU_AVAILABLE, using_native_amp=using_native_amp, using_lbfgs=is_lbfgs, ) def on_before_zero_grad(self, optimizer): self.trainer.call_hook('on_before_zero_grad', optimizer) def optimizer_zero_grad(self, batch_idx, optimizer, opt_idx): self.trainer.accelerator_backend.optimizer_zero_grad(self.trainer.current_epoch, batch_idx, optimizer, opt_idx) def track_and_norm_grad(self, optimizer): # track gradient norms grad_norm_dic = self._track_gradient_norm() # clip gradients self.trainer.accelerator_backend.clip_gradients(optimizer, self.trainer.gradient_clip_val) self._cur_grad_norm_dict = grad_norm_dic def _track_gradient_norm(self): grad_norm_dict = {} if (self.trainer.global_step + 1) % self.trainer.log_every_n_steps == 0: if float(self.trainer.track_grad_norm) > 0: model = self.trainer.get_model() grad_norm_dict = model.grad_norm(self.trainer.track_grad_norm) return grad_norm_dict def process_hiddens(self, opt_closure_result): hiddens = opt_closure_result.hiddens if isinstance(opt_closure_result.training_step_output, Result): opt_closure_result.training_step_output_for_epoch_end.drop_hiddens() return hiddens def tbptt_split_batch(self, batch): splits = [batch] if self.trainer.truncated_bptt_steps is not None: model_ref = self.trainer.get_model() with self.trainer.profiler.profile("tbptt_split_batch"): splits = model_ref.tbptt_split_batch(batch, self.trainer.truncated_bptt_steps) return splits def run_training_epoch(self): # modify dataloader if needed (ddp, etc...) train_dataloader = self.trainer.accelerator_backend.process_dataloader(self.trainer.train_dataloader) # track epoch output epoch_output = [[] for _ in range(self.num_optimizers)] train_dataloader = self.trainer.data_connector.get_profiled_train_dataloader(train_dataloader) dataloader_idx = 0 should_check_val = False for batch_idx, (batch, is_last_batch) in train_dataloader: self.trainer.batch_idx = batch_idx # ------------------------------------ # TRAINING_STEP + TRAINING_STEP_END # ------------------------------------ with self.trainer.profiler.profile("run_training_batch"): batch_output = self.run_training_batch(batch, batch_idx, dataloader_idx) # when returning -1 from train_step, we end epoch early if batch_output.signal == -1: break batch_end_outputs = self.process_train_step_outputs( batch_output.training_step_output_for_epoch_end, self.early_stopping_accumulator, self.checkpoint_accumulator, ) # hook # TODO: add outputs to batches self.on_train_batch_end(epoch_output, batch_end_outputs, batch, batch_idx, dataloader_idx) # ----------------------------------------- # SAVE METRICS TO LOGGERS # ----------------------------------------- self.trainer.logger_connector.log_train_step_metrics(batch_output) # ----------------------------------------- # VALIDATE IF NEEDED + CHECKPOINT CALLBACK # ----------------------------------------- should_check_val = self.should_check_val_fx(batch_idx, is_last_batch) if should_check_val: self.trainer.run_evaluation() # reset stage to train self.trainer._set_wide_running_stage(RunningStage.TRAINING) # ----------------------------------------- # SAVE LOGGERS (ie: Tensorboard, etc...) # ----------------------------------------- self.save_loggers_on_train_batch_end() # update LR schedulers monitor_metrics = deepcopy(self.trainer.logger_connector.callback_metrics) self.update_train_loop_lr_schedulers(monitor_metrics=monitor_metrics) self.trainer.checkpoint_connector.has_trained = True # max steps reached, end training if ( self.trainer.max_steps is not None and self.trainer.max_steps == self.trainer.global_step + 1 and self._accumulated_batches_reached() ): break # end epoch early # stop when the flag is changed or we've gone past the amount if self.trainer.should_stop: break self.trainer.total_batch_idx += 1 if self._num_training_batches_reached(is_last_batch): break self.increment_accumulated_grad_global_step() self.run_on_epoch_end_hook(epoch_output) self.trainer.logger_connector.log_train_epoch_end_metrics( epoch_output, self.checkpoint_accumulator, self.early_stopping_accumulator, self.num_optimizers ) should_check_val = self.should_check_val_fx(batch_idx, is_last_batch, on_epoch=True) if should_check_val: self.trainer.run_evaluation(on_epoch=True) self.trainer._set_wide_running_stage(RunningStage.TRAINING) should_skip_eval = self.trainer.evaluation_loop.should_skip_evaluation(self.trainer.num_val_batches) should_train_only = self.trainer.disable_validation or should_skip_eval if should_train_only: self.trainer.optimizer_connector.update_learning_rates(interval='epoch') self.check_checkpoint_callback(True) self.check_early_stopping_callback(True) self.increment_accumulated_grad_global_step() def run_training_batch(self, batch, batch_idx, dataloader_idx): grad_norm_dic = {} self.trainer.hiddens = None batch_outputs = [[] for _ in range(len(self.get_optimizers_iterable()))] if batch is None: return AttributeDict(signal=0, grad_norm_dic=grad_norm_dic) response = self.trainer.call_hook("on_batch_start") if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) response = self.trainer.call_hook("on_train_batch_start", batch, batch_idx, dataloader_idx) if response == -1: return AttributeDict(signal=-1, grad_norm_dic=grad_norm_dic) splits = self.tbptt_split_batch(batch) for split_idx, split_batch in enumerate(splits): for opt_idx, optimizer in self.prepare_optimizers(): self.run_train_split_start(split_idx, split_batch, opt_idx, optimizer) if self.should_accumulate(): with self.block_ddp_sync_behaviour(): self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # ------------------------------ # BACKWARD PASS # ------------------------------ # gradient update with accumulated gradients else: if self.automatic_optimization: def train_step_and_backward_closure(): result = self.training_step_and_backward( split_batch, batch_idx, opt_idx, optimizer, self.trainer.hiddens ) return None if result is None else result.loss # optimizer step self.optimizer_step(optimizer, opt_idx, batch_idx, train_step_and_backward_closure) else: self._curr_step_result = self.training_step( split_batch, batch_idx, opt_idx, self.trainer.hiddens ) if self._curr_step_result is None: # user decided to skip optimization # make sure to zero grad. continue batch_outputs = self._process_closure_result( batch_outputs=batch_outputs, opt_idx=opt_idx, ) # todo: Properly aggregate grad_norm accros opt_idx and split_idx grad_norm_dic = self._cur_grad_norm_dict self._cur_grad_norm_dict = None # update running loss + reset accumulated loss self.update_running_loss() result = AttributeDict( signal=0, grad_norm_dic=grad_norm_dic, training_step_output_for_epoch_end=batch_outputs, ) return result @contextmanager def block_ddp_sync_behaviour(self, should_block_sync: bool = False): if ( isinstance(self.trainer.training_type_plugin, ParallelPlugin) and (self.automatic_optimization or should_block_sync) ): with self.trainer.training_type_plugin.block_backward_sync(): yield None else: yield None def _process_closure_result(self, batch_outputs: list, opt_idx: int) -> list: opt_closure_result = self._curr_step_result if opt_closure_result is not None: # cache metrics self.trainer.logger_connector.cache_training_step_metrics(opt_closure_result) # track hiddens self.trainer.hiddens = self.process_hiddens(opt_closure_result) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(opt_closure_result.loss) # track all the outputs across all steps batch_opt_idx = opt_idx if len(batch_outputs) > 1 else 0 batch_outputs[batch_opt_idx].append(opt_closure_result.training_step_output_for_epoch_end) if self.automatic_optimization: # track total loss for logging (avoid mem leaks) self.accumulated_loss.append(opt_closure_result.loss) self._curr_step_result = None return batch_outputs def training_step_and_backward(self, split_batch, batch_idx, opt_idx, optimizer, hiddens): with self.trainer.profiler.profile("training_step_and_backward"): # lightning module hook result = self.training_step(split_batch, batch_idx, opt_idx, hiddens) self._curr_step_result = result if result is None: if self.automatic_optimization: self.warning_cache.warn("training_step returned None if it was on purpose, ignore this warning...") return None if not self._skip_backward and self.trainer.train_loop.automatic_optimization: # backward pass with self.trainer.profiler.profile("model_backward"): self.backward(result, optimizer, opt_idx) # hook - call this hook only # when gradients have finished to accumulate if not self.should_accumulate(): self.on_after_backward(result.training_step_output, batch_idx, result.loss) # check if loss or model weights are nan if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(result.loss) if len(self.trainer.optimizers) > 1: # revert back to previous state self.trainer.get_model().untoggle_optimizer(opt_idx) return result def backward(self, result, optimizer, opt_idx, *args, **kwargs): self.trainer.dev_debugger.track_event("backward_call") should_accumulate = self.should_accumulate() # backward can be called manually in the training loop if isinstance(result, torch.Tensor): self.trainer.accelerator_backend.backward(result, optimizer, opt_idx, should_accumulate, *args, **kwargs) else: result.closure_loss = self.trainer.accelerator_backend.backward( result.closure_loss, optimizer, opt_idx, should_accumulate, *args, **kwargs ) if not self.should_accumulate(): # track gradients self.track_and_norm_grad(optimizer=optimizer) def update_train_loop_lr_schedulers(self, monitor_metrics=None): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() if num_accumulated_batches_reached or num_training_batches_reached: # update lr self.trainer.optimizer_connector.update_learning_rates(interval="step", monitor_metrics=monitor_metrics) def run_on_epoch_end_hook(self, epoch_output): # inform logger the batch loop has finished self.trainer.logger_connector.on_train_epoch_end() self.trainer.call_hook('on_train_epoch_end', epoch_output) self.trainer.call_hook('on_epoch_end') def increment_accumulated_grad_global_step(self): num_accumulated_batches_reached = self._accumulated_batches_reached() num_training_batches_reached = self._num_training_batches_reached() # progress global step according to grads progress if num_accumulated_batches_reached or num_training_batches_reached: self.trainer.global_step += 1 def _accumulated_batches_reached(self): return (self.trainer.batch_idx + 1) % self.trainer.accumulate_grad_batches == 0 def _num_training_batches_reached(self, is_last_batch=False): return (self.trainer.batch_idx + 1) == self.trainer.num_training_batches or is_last_batch def should_accumulate(self): # checks if backward or backward + optimizer step (via closure) accumulation_done = self._accumulated_batches_reached() is_final_batch = self._num_training_batches_reached() return not (accumulation_done or is_final_batch) def should_check_val_fx(self, batch_idx, is_last_batch, on_epoch=False): # decide if we should run validation is_val_check_batch = (batch_idx + 1) % self.trainer.val_check_batch == 0 is_val_check_epoch = (self.trainer.current_epoch + 1) % self.trainer.check_val_every_n_epoch == 0 can_check_val = self.trainer.enable_validation and is_val_check_epoch is_last_batch_for_infinite_dataset = is_last_batch and self.trainer.val_check_batch == float("inf") epoch_end_val_check = self.trainer.val_check_batch == self.trainer.num_training_batches should_check_val = ((is_val_check_batch and epoch_end_val_check) or self.trainer.should_stop or is_last_batch_for_infinite_dataset ) if on_epoch else (is_val_check_batch and not epoch_end_val_check) return should_check_val and can_check_val def build_train_args(self, batch, batch_idx, opt_idx, hiddens): # enable not needing to add opt_idx to training_step args = [batch, batch_idx] if len(self.trainer.optimizers) > 1: if self.trainer.has_arg("training_step", "optimizer_idx"): args.append(opt_idx) else: num_opts = len(self.trainer.optimizers) raise ValueError( f"Your LightningModule defines {num_opts} optimizers but " f'training_step is missing the "optimizer_idx" argument.' ) # pass hiddens if using tbptt if self.trainer.truncated_bptt_steps is not None: args.append(hiddens) return args def save_loggers_on_train_batch_end(self): # when loggers should save to disk should_flush_logs = self.trainer.logger_connector.should_flush_logs if should_flush_logs and self.trainer.is_global_zero and self.trainer.logger is not None: self.trainer.logger.save() def process_train_step_outputs(self, all_train_step_outputs, early_stopping_accumulator, checkpoint_accumulator): # the training step outputs a list per optimizer. The list contains the outputs at each time step # when no TBPTT is used, then the list has 1 item per batch # when TBPTT IS used, then the list has n items (1 per time step) batch_end_outputs = [] for optimizer_idx_outputs in all_train_step_outputs: # extract one representative sample from each time step (1 if no tbptt) and 0th optimizer if len(optimizer_idx_outputs) == 0: continue sample_output = optimizer_idx_outputs[-1] # pull out callback info if available (ie: Results object) if isinstance(sample_output, dict) and "early_stop_on" in sample_output: early_stopping_accumulator.accumulate(sample_output["early_stop_on"]) if isinstance(sample_output, dict) and "checkpoint_on" in sample_output: checkpoint_accumulator.accumulate(sample_output["checkpoint_on"]) batch_end_outputs.append(optimizer_idx_outputs) return batch_end_outputs def prepare_optimizers(self): # in manual optimization we loop over all optimizers at once optimizers = self.get_optimizers_iterable() if not self.automatic_optimization: optimizers = [optimizers[0]] return optimizers def run_train_split_start(self, split_idx, split_batch, opt_idx, optimizer): # set split_idx to trainer for tracking self.trainer.split_idx = split_idx # make sure only the gradients of the current optimizer's parameters are calculated if self.automatic_optimization and len(self.trainer.optimizers) > 1: model = self.trainer.get_model() model.toggle_optimizer(optimizer, opt_idx) self.trainer.logger_connector.on_train_split_start(split_idx, opt_idx, split_batch) def update_running_loss(self): accumulated_loss = self.accumulated_loss.mean() if accumulated_loss is not None: self.running_loss.append(self.accumulated_loss.mean() * self.trainer.accumulate_grad_batches) self.accumulated_loss.reset()
true
true
f727a25388ee496e5f885a90c81f3d667b3f2d2c
478
py
Python
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/options.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
from . import ffi from .common import _encode_string from ctypes import c_char_p def set_option(name, option): """ Set the given LLVM "command-line" option. For example set_option("test", "-debug-pass=Structure") would display all optimization passes when generating code. """ ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option)) ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p]
26.555556
73
0.692469
from . import ffi from .common import _encode_string from ctypes import c_char_p def set_option(name, option): ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option)) ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p]
true
true
f727a288f380466a672dfe1936fa261ebf099560
2,761
py
Python
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
utils.py
gurbaaz27/fb-ai3
8c294845594ea3e3dce3922385de34b77d8e3dad
[ "MIT" ]
null
null
null
import pyaudio import wave from wit import Wit class Speech2Intent: def __init__(self, access_token): self.client = Wit(access_token) self.headers = {'authorization': 'Bearer '+ access_token, 'Content-Type': 'audio/wav'} def recognize_speech(self, AUDIO_FILENAME, num_seconds = 4): self.record_audio(num_seconds, AUDIO_FILENAME) # record audio of specified length in specified audio file audio = self.read_audio(AUDIO_FILENAME) # reading audio text = self.client.speech(audio, self.headers)['text'] return self.client.message(text)['intents'][0]['name'] def record_audio(self,RECORD_SECONDS, WAVE_OUTPUT_FILENAME): #--------- SETTING PARAMS FOR OUR AUDIO FILE ------------# FORMAT = pyaudio.paInt16 # format of wave CHANNELS = 2 # no. of audio channels RATE = 44100 # frame rate CHUNK = 1024 # frames per audio sample #--------------------------------------------------------# # creating PyAudio object audio = pyaudio.PyAudio() # open a new stream for microphone # It creates a PortAudio Stream Wrapper class object stream = audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) #----------------- start of recording -------------------# print("Listening...") # list to save all audio frames frames = [] for i in range(int(RATE / CHUNK * RECORD_SECONDS)): # read audio stream from microphone data = stream.read(CHUNK) # append audio data to frames list frames.append(data) #------------------ end of recording --------------------# print("Finished listening.") stream.stop_stream() # stop the stream object stream.close() # close the stream object audio.terminate() # terminate PortAudio #------------------ saving audio ------------------------# # create wave file object waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') # settings for wave file object waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(audio.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(b''.join(frames)) # closing the wave file object waveFile.close() def read_audio(self, WAVE_FILENAME): with open(WAVE_FILENAME, 'rb') as f: audio = f.read() return audio
33.26506
114
0.532054
import pyaudio import wave from wit import Wit class Speech2Intent: def __init__(self, access_token): self.client = Wit(access_token) self.headers = {'authorization': 'Bearer '+ access_token, 'Content-Type': 'audio/wav'} def recognize_speech(self, AUDIO_FILENAME, num_seconds = 4): self.record_audio(num_seconds, AUDIO_FILENAME) audio = self.read_audio(AUDIO_FILENAME) text = self.client.speech(audio, self.headers)['text'] return self.client.message(text)['intents'][0]['name'] def record_audio(self,RECORD_SECONDS, WAVE_OUTPUT_FILENAME): FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 CHUNK = 1024 audio = pyaudio.PyAudio() stream = audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("Listening...") frames = [] for i in range(int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("Finished listening.") stream.stop_stream() stream.close() audio.terminate() waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(audio.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(b''.join(frames)) waveFile.close() def read_audio(self, WAVE_FILENAME): with open(WAVE_FILENAME, 'rb') as f: audio = f.read() return audio
true
true
f727a2fc3479a82a78afc6c257c0409a5c9b4b20
330
py
Python
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
5
2021-09-06T04:27:56.000Z
2021-12-14T14:50:27.000Z
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
null
null
null
Hello_Python/class_electricalcar.py
JaydenYL/Projects
b51c0476f7be80f0b0d6aa84592966ecb4343d76
[ "MIT" ]
null
null
null
from class_car import car class electrical_car(car): def __init__(self, make, model,year): super().__init__(make, model, year) self.battery_volume = 70 # KWh def describe_battery(self): description = 'This car has a '+str(self.battery_volume)+' KWh battery . ' return description.title()
33
82
0.663636
from class_car import car class electrical_car(car): def __init__(self, make, model,year): super().__init__(make, model, year) self.battery_volume = 70 def describe_battery(self): description = 'This car has a '+str(self.battery_volume)+' KWh battery . ' return description.title()
true
true
f727a38e124401ba01468b18ed046aa832af9abd
1,461
py
Python
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
21
2021-03-01T00:31:23.000Z
2022-03-12T06:11:46.000Z
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
28
2021-04-07T19:02:37.000Z
2022-03-27T19:11:21.000Z
backend/berkeleytime/config/semesters/fall2017.py
Boomaa23/berkeleytime
f4c3f41025576056953fb944f5e978df43fa9cdc
[ "MIT" ]
4
2021-04-19T00:42:00.000Z
2021-11-30T06:29:59.000Z
"""Configurations for Fall 2016.""" from berkeleytime.config.finals.semesters.fall2017 import * import datetime CURRENT_SEMESTER = 'fall' CURRENT_YEAR = '2017' CURRENT_SEMESTER_DISPLAY = 'Fall 2017' # SIS API Keys SIS_TERM_ID = 2178 TELEBEARS = { 'phase1_start': datetime.datetime(2017, 4, 18), 'phase2_start': datetime.datetime(2017, 7, 18), 'phase1_end': datetime.datetime(2017, 7, 15), 'phase2_end': datetime.datetime(2017, 8, 14), 'adj_start': datetime.datetime(2017, 8, 15), } # Please don't edit anything below this line unless you know what you are doing TELEBEARS_JSON = { 'phase1_start_date': TELEBEARS['phase1_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_end_date': TELEBEARS['phase1_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_start_day': 1, 'phase1_end_date': (TELEBEARS['phase1_end'] - TELEBEARS['phase1_start']).days + 1, 'phase2_start_date': TELEBEARS['phase2_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_end_date': TELEBEARS['phase2_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_start_day': (TELEBEARS['phase2_start'] - TELEBEARS['phase1_start']).days + 1, 'phase2_end_date': (TELEBEARS['phase2_end'] - TELEBEARS['phase1_start']).days + 1, 'adj_start_date': TELEBEARS['adj_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'adj_start_day': (TELEBEARS['adj_start'] - TELEBEARS['phase1_start']).days + 1, } TELEBEARS_ALREADY_STARTED = datetime.datetime.now() >= TELEBEARS['phase1_start']
40.583333
89
0.687885
from berkeleytime.config.finals.semesters.fall2017 import * import datetime CURRENT_SEMESTER = 'fall' CURRENT_YEAR = '2017' CURRENT_SEMESTER_DISPLAY = 'Fall 2017' SIS_TERM_ID = 2178 TELEBEARS = { 'phase1_start': datetime.datetime(2017, 4, 18), 'phase2_start': datetime.datetime(2017, 7, 18), 'phase1_end': datetime.datetime(2017, 7, 15), 'phase2_end': datetime.datetime(2017, 8, 14), 'adj_start': datetime.datetime(2017, 8, 15), } TELEBEARS_JSON = { 'phase1_start_date': TELEBEARS['phase1_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_end_date': TELEBEARS['phase1_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase1_start_day': 1, 'phase1_end_date': (TELEBEARS['phase1_end'] - TELEBEARS['phase1_start']).days + 1, 'phase2_start_date': TELEBEARS['phase2_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_end_date': TELEBEARS['phase2_end'].strftime('%m/%d/%Y-%H:%M:%S'), 'phase2_start_day': (TELEBEARS['phase2_start'] - TELEBEARS['phase1_start']).days + 1, 'phase2_end_date': (TELEBEARS['phase2_end'] - TELEBEARS['phase1_start']).days + 1, 'adj_start_date': TELEBEARS['adj_start'].strftime('%m/%d/%Y-%H:%M:%S'), 'adj_start_day': (TELEBEARS['adj_start'] - TELEBEARS['phase1_start']).days + 1, } TELEBEARS_ALREADY_STARTED = datetime.datetime.now() >= TELEBEARS['phase1_start']
true
true
f727a3cd29e902d31223aa1b5f1bbe02c67a9180
4,804
py
Python
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
features/command_handler.py
DAgostinateur/Woh-Bot-2.0
4e99d97218a59156bacb1669cc1cb6c8807dd5b1
[ "MIT" ]
null
null
null
import re import discord from commands import set_presence, avatar, erp from commands.admin import list_user_admin, add_user_admin, rm_user_admin from commands.birthday import (set_channel_bd, show_channel_bd, set_user_bd, set_notif_time, list_user_bd, manual_bd_check, show_message_bd, set_message_bd) from commands.cant_be_disabled import disable, enable, help from commands.music import play, leave, repeat, now_playing, resume, pause, volume, next, previous, queue, search class CommandHandler(object): do_not_disable = ["enable", "disable", "help"] dict_cmd_name = "cmd_name" dict_enabled = "enabled" def __init__(self, client): self.parent_client = client self.commands = self.get_commands() self.set_every_command_state() def set_every_command_state(self): if self.parent_client.settings.user_command_states is None: return for cmd in self.commands: if self.command_state_exists(cmd.cmd_name): cmd.enabled = self.get_command_enabled(cmd.cmd_name) def get_command_enabled(self, cmd_name): if self.parent_client.settings.user_command_states is None: return None for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: if cmd_state[self.dict_enabled] == "True": return True else: return False return None def command_state_exists(self, cmd_name): if self.parent_client.settings.user_command_states is None: return False for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: return True return False def get_cmd(self, command_name): """Returns a Command with a command name :param command_name: :return: Command """ for command in self.commands: if command.cmd_name == command_name: return command return None def get_commands(self): return [set_presence.SetPresence(self), disable.Disable(self), enable.Enable(self), manual_bd_check.ManualBDCheck(self), set_notif_time.SetNotifTime(self), add_user_admin.AddUserAdmin(self), rm_user_admin.RmUserAdmin(self), set_message_bd.SetMessageBD(self), show_message_bd.ShowMessageBD(self), set_channel_bd.SetChannelBD(self), show_channel_bd.ShowChannelBD(self), list_user_admin.ListUserAdmin(self), list_user_bd.ListUserBD(self), set_user_bd.SetUserBD(self), avatar.Avatar(self), play.Play(self), leave.Leave(self), resume.Resume(self), pause.Pause(self), now_playing.NowPlaying(self), repeat.Repeat(self), volume.Volume(self), previous.Previous(self), next.Next(self), queue.Queue(self), search.Search(self), erp.Erp(self), help.Help(self)] async def check_message(self, message: discord.Message): for cmd in self.commands: argument = re.compile("^" + self.parent_client.prefix + "[a-z]*").search(message.content.lower()) if argument is not None: if argument.group() == self.parent_client.prefix + cmd.cmd_name: await cmd.command(message) def get_cmd_inlines(self): return [cmd.get_help_inline() for cmd in self.commands] def enable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to enable an unchangeable command." cmd.enabled = True if self.command_state_exists(cmd.cmd_name): self.parent_client.settings.delete_command_state( {self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Enabled '{}'!".format(command_name) except AttributeError: return "Failed to enable command, '{}' doesn't exist.".format(command_name) def disable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to disable an unchangeable command." cmd.enabled = False if not self.command_state_exists(cmd.cmd_name): self.parent_client.settings.save_user_defaults( command_state={self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Disabled '{}'!".format(command_name) except AttributeError: return "Failed to disable command, '{}' doesn't exist.".format(command_name)
42.513274
113
0.648626
import re import discord from commands import set_presence, avatar, erp from commands.admin import list_user_admin, add_user_admin, rm_user_admin from commands.birthday import (set_channel_bd, show_channel_bd, set_user_bd, set_notif_time, list_user_bd, manual_bd_check, show_message_bd, set_message_bd) from commands.cant_be_disabled import disable, enable, help from commands.music import play, leave, repeat, now_playing, resume, pause, volume, next, previous, queue, search class CommandHandler(object): do_not_disable = ["enable", "disable", "help"] dict_cmd_name = "cmd_name" dict_enabled = "enabled" def __init__(self, client): self.parent_client = client self.commands = self.get_commands() self.set_every_command_state() def set_every_command_state(self): if self.parent_client.settings.user_command_states is None: return for cmd in self.commands: if self.command_state_exists(cmd.cmd_name): cmd.enabled = self.get_command_enabled(cmd.cmd_name) def get_command_enabled(self, cmd_name): if self.parent_client.settings.user_command_states is None: return None for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: if cmd_state[self.dict_enabled] == "True": return True else: return False return None def command_state_exists(self, cmd_name): if self.parent_client.settings.user_command_states is None: return False for cmd_state in self.parent_client.settings.user_command_states: if cmd_state[self.dict_cmd_name] == cmd_name: return True return False def get_cmd(self, command_name): for command in self.commands: if command.cmd_name == command_name: return command return None def get_commands(self): return [set_presence.SetPresence(self), disable.Disable(self), enable.Enable(self), manual_bd_check.ManualBDCheck(self), set_notif_time.SetNotifTime(self), add_user_admin.AddUserAdmin(self), rm_user_admin.RmUserAdmin(self), set_message_bd.SetMessageBD(self), show_message_bd.ShowMessageBD(self), set_channel_bd.SetChannelBD(self), show_channel_bd.ShowChannelBD(self), list_user_admin.ListUserAdmin(self), list_user_bd.ListUserBD(self), set_user_bd.SetUserBD(self), avatar.Avatar(self), play.Play(self), leave.Leave(self), resume.Resume(self), pause.Pause(self), now_playing.NowPlaying(self), repeat.Repeat(self), volume.Volume(self), previous.Previous(self), next.Next(self), queue.Queue(self), search.Search(self), erp.Erp(self), help.Help(self)] async def check_message(self, message: discord.Message): for cmd in self.commands: argument = re.compile("^" + self.parent_client.prefix + "[a-z]*").search(message.content.lower()) if argument is not None: if argument.group() == self.parent_client.prefix + cmd.cmd_name: await cmd.command(message) def get_cmd_inlines(self): return [cmd.get_help_inline() for cmd in self.commands] def enable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to enable an unchangeable command." cmd.enabled = True if self.command_state_exists(cmd.cmd_name): self.parent_client.settings.delete_command_state( {self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Enabled '{}'!".format(command_name) except AttributeError: return "Failed to enable command, '{}' doesn't exist.".format(command_name) def disable_command(self, command_name): try: cmd = self.get_cmd(command_name) if cmd in self.do_not_disable: return "Attempted to disable an unchangeable command." cmd.enabled = False if not self.command_state_exists(cmd.cmd_name): self.parent_client.settings.save_user_defaults( command_state={self.dict_cmd_name: cmd.cmd_name, self.dict_enabled: "False"}) return "Disabled '{}'!".format(command_name) except AttributeError: return "Failed to disable command, '{}' doesn't exist.".format(command_name)
true
true
f727a444defc0c229318bcae59c50a66a901568f
737
py
Python
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
handcoding/fire.py
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
1
2017-04-01T21:34:23.000Z
2017-04-01T21:34:23.000Z
import itertools as it def fire(manager_list, salary_list, productivity_list): acc_list = [val[0] - val[1] for val in it.chain([(0,0)], zip(productivity_list, salary_list))][-1::-1] for i, e in it.takewhile(lambda v: v[0] != 0, zip(range(len(acc_list)-1, -1, -1), acc_list)): acc_list[-1 - manager_list[i]] += e if 0 < e else 0 return acc_list[-1] if __name__ == "__main__": manager_list = [int(val) for val in it.chain([0], input().split())] productivity_list = [int(val) for val in input().split()] salary_list = [int(val) for val in input().split()] print(fire(manager_list, salary_list, productivity_list)) #print(fire([0,0,0,0,1,1,2,2], [1,3,2,2,3,3,0], [2,2,1,1,4,1,4]))
40.944444
97
0.617368
import itertools as it def fire(manager_list, salary_list, productivity_list): acc_list = [val[0] - val[1] for val in it.chain([(0,0)], zip(productivity_list, salary_list))][-1::-1] for i, e in it.takewhile(lambda v: v[0] != 0, zip(range(len(acc_list)-1, -1, -1), acc_list)): acc_list[-1 - manager_list[i]] += e if 0 < e else 0 return acc_list[-1] if __name__ == "__main__": manager_list = [int(val) for val in it.chain([0], input().split())] productivity_list = [int(val) for val in input().split()] salary_list = [int(val) for val in input().split()] print(fire(manager_list, salary_list, productivity_list))
true
true
f727a4a852b255e576e4ed8f9b5db24f9d41a4fc
27,397
py
Python
openstack_dashboard/test/api_tests/neutron_tests.py
HaManhDong/Custom-Horizon
17513ebbe03b8ae58e0925f826801343e1e3e3e0
[ "Apache-2.0" ]
null
null
null
openstack_dashboard/test/api_tests/neutron_tests.py
HaManhDong/Custom-Horizon
17513ebbe03b8ae58e0925f826801343e1e3e3e0
[ "Apache-2.0" ]
null
null
null
openstack_dashboard/test/api_tests/neutron_tests.py
HaManhDong/Custom-Horizon
17513ebbe03b8ae58e0925f826801343e1e3e3e0
[ "Apache-2.0" ]
null
null
null
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import uuid from mox3.mox import IsA # noqa from django import http from django.test.utils import override_settings from neutronclient.common import exceptions as neutron_exc from openstack_dashboard import api from openstack_dashboard import policy from openstack_dashboard.test import helpers as test class NeutronApiTests(test.APITestCase): def test_network_list(self): networks = {'networks': self.api_networks.list()} subnets = {'subnets': self.api_subnets.list()} neutronclient = self.stub_neutronclient() neutronclient.list_networks().AndReturn(networks) neutronclient.list_subnets().AndReturn(subnets) self.mox.ReplayAll() ret_val = api.neutron.network_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Network) @test.create_stubs({api.neutron: ('network_list', 'subnet_list')}) def _test_network_list_for_tenant(self, include_external): all_networks = self.networks.list() tenant_id = '1' api.neutron.network_list( IsA(http.HttpRequest), tenant_id=tenant_id, shared=False).AndReturn([ network for network in all_networks if network['tenant_id'] == tenant_id ]) api.neutron.network_list( IsA(http.HttpRequest), shared=True).AndReturn([ network for network in all_networks if network.get('shared') ]) if include_external: api.neutron.network_list( IsA(http.HttpRequest), **{'router:external': True}).AndReturn([ network for network in all_networks if network.get('router:external') ]) self.mox.ReplayAll() ret_val = api.neutron.network_list_for_tenant( self.request, tenant_id, include_external=include_external) expected = [n for n in all_networks if (n['tenant_id'] == tenant_id or n['shared'] or (include_external and n['router:external']))] self.assertEqual(set(n.id for n in expected), set(n.id for n in ret_val)) def test_network_list_for_tenant(self): self._test_network_list_for_tenant(include_external=False) def test_network_list_for_tenant_with_external(self): self._test_network_list_for_tenant(include_external=True) def test_network_get(self): network = {'network': self.api_networks.first()} subnet = {'subnet': self.api_subnets.first()} network_id = self.api_networks.first()['id'] subnet_id = self.api_networks.first()['subnets'][0] neutronclient = self.stub_neutronclient() neutronclient.show_network(network_id).AndReturn(network) neutronclient.show_subnet(subnet_id).AndReturn(subnet) self.mox.ReplayAll() ret_val = api.neutron.network_get(self.request, network_id) self.assertIsInstance(ret_val, api.neutron.Network) def _test_network_create(self, with_n1kv=False): network = {'network': self.api_networks.first()} form_data = {'network': {'name': 'net1', 'tenant_id': self.request.user.project_id}} neutronclient = self.stub_neutronclient() if with_n1kv: n1kv_profile = 'n1kv:profile' test_net_profile = 'test_net_profile' network['network'][n1kv_profile] = test_net_profile form_data['network'][n1kv_profile] = test_net_profile neutronclient.create_network(body=form_data).AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_create( self.request, name='net1', net_profile_id=test_net_profile) # assert that when 'net_profile_id' is passed as a param to # network_create function, 'n1kv:profile' is appended as a key to # the returned network dictionary with value TEST_NET_PROFILE self.assertEqual(test_net_profile, ret_val[n1kv_profile]) # also assert that 'net_profile_id' isn't there in the returned # network dictionary self.assertNotIn('net_profile_id', [k for k, _ in ret_val.items()]) else: neutronclient.create_network(body=form_data).AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_create(self.request, name='net1') self.assertIsInstance(ret_val, api.neutron.Network) def test_network_create(self): self._test_network_create() def test_network_create_with_net_profile(self): self._test_network_create(with_n1kv=True) def test_network_update(self): network = {'network': self.api_networks.first()} network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() form_data = {'network': {'name': 'net1'}} neutronclient.update_network(network_id, body=form_data)\ .AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_update(self.request, network_id, name='net1') self.assertIsInstance(ret_val, api.neutron.Network) def test_network_delete(self): network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_network(network_id) self.mox.ReplayAll() api.neutron.network_delete(self.request, network_id) def test_get_network_ip_availability(self): network = {'network': self.api_networks.first()} mock_ip_availability = self.ip_availability.get() neutronclient = self.stub_neutronclient() neutronclient.show_network_ip_availability(network).\ AndReturn(mock_ip_availability) self.mox.ReplayAll() ret_val = api.neutron.show_network_ip_availability(self.request, network) self.assertIsInstance(ret_val, dict) def test_subnet_network_ip_availability(self): network = {'network': self.api_networks.first()} mock_ip_availability = self.ip_availability.get() neutronclient = self.stub_neutronclient() neutronclient.show_network_ip_availability(network).\ AndReturn(mock_ip_availability) self.mox.ReplayAll() ip_availability = api.neutron. \ show_network_ip_availability(self.request, network) availabilities = ip_availability.get("network_ip_availability", {}) ret_val = availabilities.get("subnet_ip_availability", []) self.assertIsInstance(ret_val, list) def test_subnet_list(self): subnets = {'subnets': self.api_subnets.list()} neutronclient = self.stub_neutronclient() neutronclient.list_subnets().AndReturn(subnets) self.mox.ReplayAll() ret_val = api.neutron.subnet_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Subnet) def test_subnet_get(self): subnet = {'subnet': self.api_subnets.first()} subnet_id = self.api_subnets.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_subnet(subnet_id).AndReturn(subnet) self.mox.ReplayAll() ret_val = api.neutron.subnet_get(self.request, subnet_id) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_create(self): subnet_data = self.api_subnets.first() params = {'network_id': subnet_data['network_id'], 'tenant_id': subnet_data['tenant_id'], 'name': subnet_data['name'], 'cidr': subnet_data['cidr'], 'ip_version': subnet_data['ip_version'], 'gateway_ip': subnet_data['gateway_ip']} neutronclient = self.stub_neutronclient() neutronclient.create_subnet(body={'subnet': params})\ .AndReturn({'subnet': subnet_data}) self.mox.ReplayAll() ret_val = api.neutron.subnet_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_update(self): subnet_data = self.api_subnets.first() subnet_id = subnet_data['id'] params = {'name': subnet_data['name'], 'gateway_ip': subnet_data['gateway_ip']} neutronclient = self.stub_neutronclient() neutronclient.update_subnet(subnet_id, body={'subnet': params})\ .AndReturn({'subnet': subnet_data}) self.mox.ReplayAll() ret_val = api.neutron.subnet_update(self.request, subnet_id, **params) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_delete(self): subnet_id = self.api_subnets.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_subnet(subnet_id) self.mox.ReplayAll() api.neutron.subnet_delete(self.request, subnet_id) def test_subnetpool_list(self): subnetpools = {'subnetpools': self.api_subnetpools.list()} neutronclient = self.stub_neutronclient() neutronclient.list_subnetpools().AndReturn(subnetpools) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.SubnetPool) def test_subnetpool_get(self): subnetpool = {'subnetpool': self.api_subnetpools.first()} subnetpool_id = self.api_subnetpools.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_subnetpool(subnetpool_id).AndReturn(subnetpool) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_get(self.request, subnetpool_id) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_create(self): subnetpool_data = self.api_subnetpools.first() params = {'name': subnetpool_data['name'], 'prefixes': subnetpool_data['prefixes'], 'tenant_id': subnetpool_data['tenant_id']} neutronclient = self.stub_neutronclient() neutronclient.create_subnetpool(body={'subnetpool': params})\ .AndReturn({'subnetpool': subnetpool_data}) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_update(self): subnetpool_data = self.api_subnetpools.first() subnetpool_id = subnetpool_data['id'] params = {'name': subnetpool_data['name'], 'prefixes': subnetpool_data['prefixes']} neutronclient = self.stub_neutronclient() neutronclient.update_subnetpool(subnetpool_id, body={'subnetpool': params})\ .AndReturn({'subnetpool': subnetpool_data}) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_update(self.request, subnetpool_id, **params) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_delete(self): subnetpool_id = self.api_subnetpools.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_subnetpool(subnetpool_id) self.mox.ReplayAll() api.neutron.subnetpool_delete(self.request, subnetpool_id) def test_port_list(self): ports = {'ports': self.api_ports.list()} neutronclient = self.stub_neutronclient() neutronclient.list_ports().AndReturn(ports) self.mox.ReplayAll() ret_val = api.neutron.port_list(self.request) for p in ret_val: self.assertIsInstance(p, api.neutron.Port) def test_port_get(self): port = {'port': self.api_ports.first()} port_id = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_port(port_id).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_get(self.request, port_id) self.assertIsInstance(ret_val, api.neutron.Port) def _test_port_create(self, with_n1kv=False): port = {'port': self.api_ports.first()} params = {'network_id': port['port']['network_id'], 'tenant_id': port['port']['tenant_id'], 'name': port['port']['name'], 'device_id': port['port']['device_id']} neutronclient = self.stub_neutronclient() if with_n1kv: n1kv_profile = 'n1kv:profile' test_policy_profile = 'test_policy_profile' port['port'][n1kv_profile] = test_policy_profile body = {k: v for (k, v) in params.items()} body[n1kv_profile] = port['port'][n1kv_profile] neutronclient.create_port(body={'port': body}).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_create( self.request, policy_profile_id=test_policy_profile, **params) # assert that when 'policy_profile_id' is passed as a param to # port_create function, 'n1kv:profile' is appended as a key to the # returned port dictionary with value TEST_POLICY_PROFILE self.assertEqual(test_policy_profile, ret_val[n1kv_profile]) # also assert that 'policy_profile_id' isn't there in the returned # port dictionary self.assertNotIn('policy_profile_id', [k for k, _ in ret_val.items()]) else: neutronclient.create_port(body={'port': params}).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.Port) self.assertEqual(api.neutron.Port(port['port']).id, ret_val.id) def test_port_create(self): self._test_port_create() def test_port_create_with_policy_profile(self): self._test_port_create(with_n1kv=True) def test_port_update(self): port_data = self.api_ports.first() port_id = port_data['id'] params = {'name': port_data['name'], 'device_id': port_data['device_id']} neutronclient = self.stub_neutronclient() neutronclient.update_port(port_id, body={'port': params})\ .AndReturn({'port': port_data}) self.mox.ReplayAll() ret_val = api.neutron.port_update(self.request, port_id, **params) self.assertIsInstance(ret_val, api.neutron.Port) self.assertEqual(api.neutron.Port(port_data).id, ret_val.id) def test_port_delete(self): port_id = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_port(port_id) self.mox.ReplayAll() api.neutron.port_delete(self.request, port_id) def test_router_list(self): routers = {'routers': self.api_routers.list()} neutronclient = self.stub_neutronclient() neutronclient.list_routers().AndReturn(routers) self.mox.ReplayAll() ret_val = api.neutron.router_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Router) def test_router_get(self): router = {'router': self.api_routers.first()} router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_get(self.request, router_id) self.assertIsInstance(ret_val, api.neutron.Router) def test_router_create(self): router = {'router': self.api_routers.first()} neutronclient = self.stub_neutronclient() form_data = {'router': {'name': 'router1', 'tenant_id': self.request.user.project_id}} neutronclient.create_router(body=form_data).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_create(self.request, name='router1') self.assertIsInstance(ret_val, api.neutron.Router) def test_router_delete(self): router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_router(router_id) self.mox.ReplayAll() api.neutron.router_delete(self.request, router_id) def test_router_add_interface(self): subnet_id = self.api_subnets.first()['id'] router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() form_data = {'subnet_id': subnet_id} neutronclient.add_interface_router( router_id, form_data).AndReturn(None) self.mox.ReplayAll() api.neutron.router_add_interface( self.request, router_id, subnet_id=subnet_id) def test_router_remove_interface(self): router_id = self.api_routers.first()['id'] fake_port = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.remove_interface_router( router_id, {'port_id': fake_port}) self.mox.ReplayAll() api.neutron.router_remove_interface( self.request, router_id, port_id=fake_port) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def test_is_extension_supported(self): api.neutron.is_extension_supported(self.request, "quotas")\ .AndReturn(True) api.neutron.is_extension_supported(self.request, "doesntexist") \ .AndReturn(False) self.mox.ReplayAll() self.assertTrue( api.neutron.is_extension_supported(self.request, 'quotas')) self.assertFalse( api.neutron.is_extension_supported(self.request, 'doesntexist')) def test_router_static_route_list(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_static_route_list(self.request, router_id) self.assertIsInstance(ret_val[0], api.neutron.RouterStaticRoute) def test_router_static_route_remove(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] post_router = copy.deepcopy(router) route = api.neutron.RouterStaticRoute(post_router['router'] ['routes'].pop()) neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) body = {'router': {'routes': post_router['router']['routes']}} neutronclient.update_router(router_id, body=body)\ .AndReturn(post_router) self.mox.ReplayAll() api.neutron.router_static_route_remove(self.request, router_id, route.id) def test_router_static_route_add(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] post_router = copy.deepcopy(router) route = {'nexthop': '10.0.0.5', 'destination': '40.0.1.0/24'} post_router['router']['routes'].insert(0, route) body = {'router': {'routes': post_router['router']['routes']}} neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) neutronclient.update_router(router_id, body=body)\ .AndReturn(post_router) self.mox.ReplayAll() api.neutron.router_static_route_add(self.request, router_id, route) # NOTE(amotoki): "dvr" permission tests check most of # get_feature_permission features. # These tests are not specific to "dvr" extension. # Please be careful if you drop "dvr" extension in future. @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=None) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def _test_get_dvr_permission_dvr_supported(self, dvr_enabled): api.neutron.is_extension_supported(self.request, 'dvr').\ AndReturn(dvr_enabled) self.mox.ReplayAll() self.assertEqual(dvr_enabled, api.neutron.get_feature_permission(self.request, 'dvr', 'get')) def test_get_dvr_permission_dvr_supported(self): self._test_get_dvr_permission_dvr_supported(dvr_enabled=True) def test_get_dvr_permission_dvr_not_supported(self): self._test_get_dvr_permission_dvr_supported(dvr_enabled=False) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=policy.check) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def _test_get_dvr_permission_with_policy_check(self, policy_check_allowed, operation): self.mox.StubOutWithMock(policy, 'check') if operation == "create": role = (("network", "create_router:distributed"),) elif operation == "get": role = (("network", "get_router:distributed"),) policy.check(role, self.request).AndReturn(policy_check_allowed) if policy_check_allowed: api.neutron.is_extension_supported(self.request, 'dvr').\ AndReturn(policy_check_allowed) self.mox.ReplayAll() self.assertEqual(policy_check_allowed, api.neutron.get_feature_permission(self.request, 'dvr', operation)) def test_get_dvr_permission_with_policy_check_allowed(self): self._test_get_dvr_permission_with_policy_check(True, "get") def test_get_dvr_permission_with_policy_check_disallowed(self): self._test_get_dvr_permission_with_policy_check(False, "get") def test_get_dvr_permission_create_with_policy_check_allowed(self): self._test_get_dvr_permission_with_policy_check(True, "create") def test_get_dvr_permission_create_with_policy_check_disallowed(self): self._test_get_dvr_permission_with_policy_check(False, "create") @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': False}) def test_get_dvr_permission_dvr_disabled_by_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'dvr', 'get')) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=policy.check) def test_get_dvr_permission_dvr_unsupported_operation(self): self.assertRaises(ValueError, api.neutron.get_feature_permission, self.request, 'dvr', 'unSupported') @override_settings(OPENSTACK_NEUTRON_NETWORK={}) def test_get_dvr_permission_dvr_default_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'dvr', 'get')) @override_settings(OPENSTACK_NEUTRON_NETWORK={}) def test_get_dvr_permission_router_ha_default_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'l3-ha', 'get')) # NOTE(amotoki): Most of get_feature_permission are checked by "dvr" check # above. l3-ha check only checks l3-ha specific code. @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_ha_router': True}, POLICY_CHECK_FUNCTION=policy.check) @test.create_stubs({api.neutron: ('is_extension_supported', )}) def _test_get_router_ha_permission_with_policy_check(self, ha_enabled): self.mox.StubOutWithMock(policy, 'check') role = (("network", "create_router:ha"),) policy.check(role, self.request).AndReturn(True) api.neutron.is_extension_supported(self.request, 'l3-ha')\ .AndReturn(ha_enabled) self.mox.ReplayAll() self.assertEqual(ha_enabled, api.neutron.get_feature_permission(self.request, 'l3-ha', 'create')) def test_get_router_ha_permission_with_l3_ha_extension(self): self._test_get_router_ha_permission_with_policy_check(True) def test_get_router_ha_permission_without_l3_ha_extension(self): self._test_get_router_ha_permission_with_policy_check(False) def test_list_resources_with_long_filters(self): # In this tests, port_list is called with id=[10 port ID] # filter. It generates about 40*10 char length URI. # Each port ID is converted to "id=<UUID>&" in URI and # it means 40 chars (len(UUID)=36). # If excess length is 220, it means 400-220=180 chars # can be sent in the first request. # As a result three API calls with 4, 4, 2 port ID # are expected. ports = [{'id': str(uuid.uuid4()), 'name': 'port%s' % i, 'admin_state_up': True} for i in range(10)] port_ids = [port['id'] for port in ports] neutronclient = self.stub_neutronclient() uri_len_exc = neutron_exc.RequestURITooLong(excess=220) neutronclient.list_ports(id=port_ids).AndRaise(uri_len_exc) for i in range(0, 10, 4): neutronclient.list_ports(id=port_ids[i:i + 4]) \ .AndReturn({'ports': ports[i:i + 4]}) self.mox.ReplayAll() ret_val = api.neutron.list_resources_with_long_filters( api.neutron.port_list, 'id', port_ids, request=self.request) self.assertEqual(10, len(ret_val)) self.assertEqual(port_ids, [p.id for p in ret_val])
42.019939
84
0.638756
import copy import uuid from mox3.mox import IsA from django import http from django.test.utils import override_settings from neutronclient.common import exceptions as neutron_exc from openstack_dashboard import api from openstack_dashboard import policy from openstack_dashboard.test import helpers as test class NeutronApiTests(test.APITestCase): def test_network_list(self): networks = {'networks': self.api_networks.list()} subnets = {'subnets': self.api_subnets.list()} neutronclient = self.stub_neutronclient() neutronclient.list_networks().AndReturn(networks) neutronclient.list_subnets().AndReturn(subnets) self.mox.ReplayAll() ret_val = api.neutron.network_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Network) @test.create_stubs({api.neutron: ('network_list', 'subnet_list')}) def _test_network_list_for_tenant(self, include_external): all_networks = self.networks.list() tenant_id = '1' api.neutron.network_list( IsA(http.HttpRequest), tenant_id=tenant_id, shared=False).AndReturn([ network for network in all_networks if network['tenant_id'] == tenant_id ]) api.neutron.network_list( IsA(http.HttpRequest), shared=True).AndReturn([ network for network in all_networks if network.get('shared') ]) if include_external: api.neutron.network_list( IsA(http.HttpRequest), **{'router:external': True}).AndReturn([ network for network in all_networks if network.get('router:external') ]) self.mox.ReplayAll() ret_val = api.neutron.network_list_for_tenant( self.request, tenant_id, include_external=include_external) expected = [n for n in all_networks if (n['tenant_id'] == tenant_id or n['shared'] or (include_external and n['router:external']))] self.assertEqual(set(n.id for n in expected), set(n.id for n in ret_val)) def test_network_list_for_tenant(self): self._test_network_list_for_tenant(include_external=False) def test_network_list_for_tenant_with_external(self): self._test_network_list_for_tenant(include_external=True) def test_network_get(self): network = {'network': self.api_networks.first()} subnet = {'subnet': self.api_subnets.first()} network_id = self.api_networks.first()['id'] subnet_id = self.api_networks.first()['subnets'][0] neutronclient = self.stub_neutronclient() neutronclient.show_network(network_id).AndReturn(network) neutronclient.show_subnet(subnet_id).AndReturn(subnet) self.mox.ReplayAll() ret_val = api.neutron.network_get(self.request, network_id) self.assertIsInstance(ret_val, api.neutron.Network) def _test_network_create(self, with_n1kv=False): network = {'network': self.api_networks.first()} form_data = {'network': {'name': 'net1', 'tenant_id': self.request.user.project_id}} neutronclient = self.stub_neutronclient() if with_n1kv: n1kv_profile = 'n1kv:profile' test_net_profile = 'test_net_profile' network['network'][n1kv_profile] = test_net_profile form_data['network'][n1kv_profile] = test_net_profile neutronclient.create_network(body=form_data).AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_create( self.request, name='net1', net_profile_id=test_net_profile) self.assertEqual(test_net_profile, ret_val[n1kv_profile]) # network dictionary self.assertNotIn('net_profile_id', [k for k, _ in ret_val.items()]) else: neutronclient.create_network(body=form_data).AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_create(self.request, name='net1') self.assertIsInstance(ret_val, api.neutron.Network) def test_network_create(self): self._test_network_create() def test_network_create_with_net_profile(self): self._test_network_create(with_n1kv=True) def test_network_update(self): network = {'network': self.api_networks.first()} network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() form_data = {'network': {'name': 'net1'}} neutronclient.update_network(network_id, body=form_data)\ .AndReturn(network) self.mox.ReplayAll() ret_val = api.neutron.network_update(self.request, network_id, name='net1') self.assertIsInstance(ret_val, api.neutron.Network) def test_network_delete(self): network_id = self.api_networks.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_network(network_id) self.mox.ReplayAll() api.neutron.network_delete(self.request, network_id) def test_get_network_ip_availability(self): network = {'network': self.api_networks.first()} mock_ip_availability = self.ip_availability.get() neutronclient = self.stub_neutronclient() neutronclient.show_network_ip_availability(network).\ AndReturn(mock_ip_availability) self.mox.ReplayAll() ret_val = api.neutron.show_network_ip_availability(self.request, network) self.assertIsInstance(ret_val, dict) def test_subnet_network_ip_availability(self): network = {'network': self.api_networks.first()} mock_ip_availability = self.ip_availability.get() neutronclient = self.stub_neutronclient() neutronclient.show_network_ip_availability(network).\ AndReturn(mock_ip_availability) self.mox.ReplayAll() ip_availability = api.neutron. \ show_network_ip_availability(self.request, network) availabilities = ip_availability.get("network_ip_availability", {}) ret_val = availabilities.get("subnet_ip_availability", []) self.assertIsInstance(ret_val, list) def test_subnet_list(self): subnets = {'subnets': self.api_subnets.list()} neutronclient = self.stub_neutronclient() neutronclient.list_subnets().AndReturn(subnets) self.mox.ReplayAll() ret_val = api.neutron.subnet_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Subnet) def test_subnet_get(self): subnet = {'subnet': self.api_subnets.first()} subnet_id = self.api_subnets.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_subnet(subnet_id).AndReturn(subnet) self.mox.ReplayAll() ret_val = api.neutron.subnet_get(self.request, subnet_id) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_create(self): subnet_data = self.api_subnets.first() params = {'network_id': subnet_data['network_id'], 'tenant_id': subnet_data['tenant_id'], 'name': subnet_data['name'], 'cidr': subnet_data['cidr'], 'ip_version': subnet_data['ip_version'], 'gateway_ip': subnet_data['gateway_ip']} neutronclient = self.stub_neutronclient() neutronclient.create_subnet(body={'subnet': params})\ .AndReturn({'subnet': subnet_data}) self.mox.ReplayAll() ret_val = api.neutron.subnet_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_update(self): subnet_data = self.api_subnets.first() subnet_id = subnet_data['id'] params = {'name': subnet_data['name'], 'gateway_ip': subnet_data['gateway_ip']} neutronclient = self.stub_neutronclient() neutronclient.update_subnet(subnet_id, body={'subnet': params})\ .AndReturn({'subnet': subnet_data}) self.mox.ReplayAll() ret_val = api.neutron.subnet_update(self.request, subnet_id, **params) self.assertIsInstance(ret_val, api.neutron.Subnet) def test_subnet_delete(self): subnet_id = self.api_subnets.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_subnet(subnet_id) self.mox.ReplayAll() api.neutron.subnet_delete(self.request, subnet_id) def test_subnetpool_list(self): subnetpools = {'subnetpools': self.api_subnetpools.list()} neutronclient = self.stub_neutronclient() neutronclient.list_subnetpools().AndReturn(subnetpools) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.SubnetPool) def test_subnetpool_get(self): subnetpool = {'subnetpool': self.api_subnetpools.first()} subnetpool_id = self.api_subnetpools.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_subnetpool(subnetpool_id).AndReturn(subnetpool) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_get(self.request, subnetpool_id) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_create(self): subnetpool_data = self.api_subnetpools.first() params = {'name': subnetpool_data['name'], 'prefixes': subnetpool_data['prefixes'], 'tenant_id': subnetpool_data['tenant_id']} neutronclient = self.stub_neutronclient() neutronclient.create_subnetpool(body={'subnetpool': params})\ .AndReturn({'subnetpool': subnetpool_data}) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_update(self): subnetpool_data = self.api_subnetpools.first() subnetpool_id = subnetpool_data['id'] params = {'name': subnetpool_data['name'], 'prefixes': subnetpool_data['prefixes']} neutronclient = self.stub_neutronclient() neutronclient.update_subnetpool(subnetpool_id, body={'subnetpool': params})\ .AndReturn({'subnetpool': subnetpool_data}) self.mox.ReplayAll() ret_val = api.neutron.subnetpool_update(self.request, subnetpool_id, **params) self.assertIsInstance(ret_val, api.neutron.SubnetPool) def test_subnetpool_delete(self): subnetpool_id = self.api_subnetpools.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_subnetpool(subnetpool_id) self.mox.ReplayAll() api.neutron.subnetpool_delete(self.request, subnetpool_id) def test_port_list(self): ports = {'ports': self.api_ports.list()} neutronclient = self.stub_neutronclient() neutronclient.list_ports().AndReturn(ports) self.mox.ReplayAll() ret_val = api.neutron.port_list(self.request) for p in ret_val: self.assertIsInstance(p, api.neutron.Port) def test_port_get(self): port = {'port': self.api_ports.first()} port_id = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_port(port_id).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_get(self.request, port_id) self.assertIsInstance(ret_val, api.neutron.Port) def _test_port_create(self, with_n1kv=False): port = {'port': self.api_ports.first()} params = {'network_id': port['port']['network_id'], 'tenant_id': port['port']['tenant_id'], 'name': port['port']['name'], 'device_id': port['port']['device_id']} neutronclient = self.stub_neutronclient() if with_n1kv: n1kv_profile = 'n1kv:profile' test_policy_profile = 'test_policy_profile' port['port'][n1kv_profile] = test_policy_profile body = {k: v for (k, v) in params.items()} body[n1kv_profile] = port['port'][n1kv_profile] neutronclient.create_port(body={'port': body}).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_create( self.request, policy_profile_id=test_policy_profile, **params) # assert that when 'policy_profile_id' is passed as a param to # port_create function, 'n1kv:profile' is appended as a key to the # returned port dictionary with value TEST_POLICY_PROFILE self.assertEqual(test_policy_profile, ret_val[n1kv_profile]) # also assert that 'policy_profile_id' isn't there in the returned self.assertNotIn('policy_profile_id', [k for k, _ in ret_val.items()]) else: neutronclient.create_port(body={'port': params}).AndReturn(port) self.mox.ReplayAll() ret_val = api.neutron.port_create(self.request, **params) self.assertIsInstance(ret_val, api.neutron.Port) self.assertEqual(api.neutron.Port(port['port']).id, ret_val.id) def test_port_create(self): self._test_port_create() def test_port_create_with_policy_profile(self): self._test_port_create(with_n1kv=True) def test_port_update(self): port_data = self.api_ports.first() port_id = port_data['id'] params = {'name': port_data['name'], 'device_id': port_data['device_id']} neutronclient = self.stub_neutronclient() neutronclient.update_port(port_id, body={'port': params})\ .AndReturn({'port': port_data}) self.mox.ReplayAll() ret_val = api.neutron.port_update(self.request, port_id, **params) self.assertIsInstance(ret_val, api.neutron.Port) self.assertEqual(api.neutron.Port(port_data).id, ret_val.id) def test_port_delete(self): port_id = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_port(port_id) self.mox.ReplayAll() api.neutron.port_delete(self.request, port_id) def test_router_list(self): routers = {'routers': self.api_routers.list()} neutronclient = self.stub_neutronclient() neutronclient.list_routers().AndReturn(routers) self.mox.ReplayAll() ret_val = api.neutron.router_list(self.request) for n in ret_val: self.assertIsInstance(n, api.neutron.Router) def test_router_get(self): router = {'router': self.api_routers.first()} router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_get(self.request, router_id) self.assertIsInstance(ret_val, api.neutron.Router) def test_router_create(self): router = {'router': self.api_routers.first()} neutronclient = self.stub_neutronclient() form_data = {'router': {'name': 'router1', 'tenant_id': self.request.user.project_id}} neutronclient.create_router(body=form_data).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_create(self.request, name='router1') self.assertIsInstance(ret_val, api.neutron.Router) def test_router_delete(self): router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.delete_router(router_id) self.mox.ReplayAll() api.neutron.router_delete(self.request, router_id) def test_router_add_interface(self): subnet_id = self.api_subnets.first()['id'] router_id = self.api_routers.first()['id'] neutronclient = self.stub_neutronclient() form_data = {'subnet_id': subnet_id} neutronclient.add_interface_router( router_id, form_data).AndReturn(None) self.mox.ReplayAll() api.neutron.router_add_interface( self.request, router_id, subnet_id=subnet_id) def test_router_remove_interface(self): router_id = self.api_routers.first()['id'] fake_port = self.api_ports.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.remove_interface_router( router_id, {'port_id': fake_port}) self.mox.ReplayAll() api.neutron.router_remove_interface( self.request, router_id, port_id=fake_port) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def test_is_extension_supported(self): api.neutron.is_extension_supported(self.request, "quotas")\ .AndReturn(True) api.neutron.is_extension_supported(self.request, "doesntexist") \ .AndReturn(False) self.mox.ReplayAll() self.assertTrue( api.neutron.is_extension_supported(self.request, 'quotas')) self.assertFalse( api.neutron.is_extension_supported(self.request, 'doesntexist')) def test_router_static_route_list(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) self.mox.ReplayAll() ret_val = api.neutron.router_static_route_list(self.request, router_id) self.assertIsInstance(ret_val[0], api.neutron.RouterStaticRoute) def test_router_static_route_remove(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] post_router = copy.deepcopy(router) route = api.neutron.RouterStaticRoute(post_router['router'] ['routes'].pop()) neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) body = {'router': {'routes': post_router['router']['routes']}} neutronclient.update_router(router_id, body=body)\ .AndReturn(post_router) self.mox.ReplayAll() api.neutron.router_static_route_remove(self.request, router_id, route.id) def test_router_static_route_add(self): router = {'router': self.api_routers_with_routes.first()} router_id = self.api_routers_with_routes.first()['id'] post_router = copy.deepcopy(router) route = {'nexthop': '10.0.0.5', 'destination': '40.0.1.0/24'} post_router['router']['routes'].insert(0, route) body = {'router': {'routes': post_router['router']['routes']}} neutronclient = self.stub_neutronclient() neutronclient.show_router(router_id).AndReturn(router) neutronclient.update_router(router_id, body=body)\ .AndReturn(post_router) self.mox.ReplayAll() api.neutron.router_static_route_add(self.request, router_id, route) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=None) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def _test_get_dvr_permission_dvr_supported(self, dvr_enabled): api.neutron.is_extension_supported(self.request, 'dvr').\ AndReturn(dvr_enabled) self.mox.ReplayAll() self.assertEqual(dvr_enabled, api.neutron.get_feature_permission(self.request, 'dvr', 'get')) def test_get_dvr_permission_dvr_supported(self): self._test_get_dvr_permission_dvr_supported(dvr_enabled=True) def test_get_dvr_permission_dvr_not_supported(self): self._test_get_dvr_permission_dvr_supported(dvr_enabled=False) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=policy.check) @test.create_stubs({api.neutron: ('is_extension_supported',)}) def _test_get_dvr_permission_with_policy_check(self, policy_check_allowed, operation): self.mox.StubOutWithMock(policy, 'check') if operation == "create": role = (("network", "create_router:distributed"),) elif operation == "get": role = (("network", "get_router:distributed"),) policy.check(role, self.request).AndReturn(policy_check_allowed) if policy_check_allowed: api.neutron.is_extension_supported(self.request, 'dvr').\ AndReturn(policy_check_allowed) self.mox.ReplayAll() self.assertEqual(policy_check_allowed, api.neutron.get_feature_permission(self.request, 'dvr', operation)) def test_get_dvr_permission_with_policy_check_allowed(self): self._test_get_dvr_permission_with_policy_check(True, "get") def test_get_dvr_permission_with_policy_check_disallowed(self): self._test_get_dvr_permission_with_policy_check(False, "get") def test_get_dvr_permission_create_with_policy_check_allowed(self): self._test_get_dvr_permission_with_policy_check(True, "create") def test_get_dvr_permission_create_with_policy_check_disallowed(self): self._test_get_dvr_permission_with_policy_check(False, "create") @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': False}) def test_get_dvr_permission_dvr_disabled_by_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'dvr', 'get')) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router': True}, POLICY_CHECK_FUNCTION=policy.check) def test_get_dvr_permission_dvr_unsupported_operation(self): self.assertRaises(ValueError, api.neutron.get_feature_permission, self.request, 'dvr', 'unSupported') @override_settings(OPENSTACK_NEUTRON_NETWORK={}) def test_get_dvr_permission_dvr_default_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'dvr', 'get')) @override_settings(OPENSTACK_NEUTRON_NETWORK={}) def test_get_dvr_permission_router_ha_default_config(self): self.assertFalse(api.neutron.get_feature_permission(self.request, 'l3-ha', 'get')) @override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_ha_router': True}, POLICY_CHECK_FUNCTION=policy.check) @test.create_stubs({api.neutron: ('is_extension_supported', )}) def _test_get_router_ha_permission_with_policy_check(self, ha_enabled): self.mox.StubOutWithMock(policy, 'check') role = (("network", "create_router:ha"),) policy.check(role, self.request).AndReturn(True) api.neutron.is_extension_supported(self.request, 'l3-ha')\ .AndReturn(ha_enabled) self.mox.ReplayAll() self.assertEqual(ha_enabled, api.neutron.get_feature_permission(self.request, 'l3-ha', 'create')) def test_get_router_ha_permission_with_l3_ha_extension(self): self._test_get_router_ha_permission_with_policy_check(True) def test_get_router_ha_permission_without_l3_ha_extension(self): self._test_get_router_ha_permission_with_policy_check(False) def test_list_resources_with_long_filters(self): ports = [{'id': str(uuid.uuid4()), 'name': 'port%s' % i, 'admin_state_up': True} for i in range(10)] port_ids = [port['id'] for port in ports] neutronclient = self.stub_neutronclient() uri_len_exc = neutron_exc.RequestURITooLong(excess=220) neutronclient.list_ports(id=port_ids).AndRaise(uri_len_exc) for i in range(0, 10, 4): neutronclient.list_ports(id=port_ids[i:i + 4]) \ .AndReturn({'ports': ports[i:i + 4]}) self.mox.ReplayAll() ret_val = api.neutron.list_resources_with_long_filters( api.neutron.port_list, 'id', port_ids, request=self.request) self.assertEqual(10, len(ret_val)) self.assertEqual(port_ids, [p.id for p in ret_val])
true
true
f727a6fbe910664403fa49773ddc8bc6ca0f017c
3,896
py
Python
cfgs_fatdet/voc/fatnat/ttfnet_fatnet_ttfheadfull_96_10x_aug_no_pretrain.py
Leotju/ttfnet
94eea28ea22215310140caee492d5de2b01b3d04
[ "Apache-2.0" ]
null
null
null
cfgs_fatdet/voc/fatnat/ttfnet_fatnet_ttfheadfull_96_10x_aug_no_pretrain.py
Leotju/ttfnet
94eea28ea22215310140caee492d5de2b01b3d04
[ "Apache-2.0" ]
null
null
null
cfgs_fatdet/voc/fatnat/ttfnet_fatnet_ttfheadfull_96_10x_aug_no_pretrain.py
Leotju/ttfnet
94eea28ea22215310140caee492d5de2b01b3d04
[ "Apache-2.0" ]
null
null
null
# model settings model = dict( type='TTFNet', # pretrained='modelzoo://resnet18', pretrained=None, backbone=dict( type='FatNetSimple', norm_cfg = dict(type='BN', requires_grad=True), ), neck=None, bbox_head=dict( type='TTFHeadFull', inplanes=16, planes=64, head_conv=64, down_ratio=1, wh_conv=64, hm_head_conv_num=2, wh_head_conv_num=1, num_classes=21, wh_agnostic=True, wh_gaussian=True, norm_cfg=dict(type='BN'), alpha=0.54, hm_weight=1., wh_weight=5.)) cudnn_benchmark = True # training and testing settings train_cfg = dict( vis_every_n_iters=100, debug=False) test_cfg = dict( score_thr=0.01, max_per_img=100) # dataset settings dataset_type = 'VOCDataset' data_root = '../data/VOCdevkit/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) data = dict( imgs_per_gpu=16, workers_per_gpu=2, train=dict( type='RepeatDataset', # to avoid reloading datasets frequently times=30, dataset=dict( type=dataset_type, ann_file=[ data_root + 'VOC2007/ImageSets/Main/trainval.txt', data_root + 'VOC2012/ImageSets/Main/trainval.txt' ], img_prefix=[data_root + 'VOC2007/', data_root + 'VOC2012/'], img_scale=(96, 96), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0.5, with_mask=False, with_crowd=False, with_label=True, extra_aug=dict( photo_metric_distortion=dict( brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), expand=dict( mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), random_crop=dict( min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3)), resize_keep_ratio=False)), val=dict( type=dataset_type, ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt', img_prefix=data_root + 'VOC2007/', img_scale=(512, 512), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False, with_label=True, resize_keep_ratio=False), test=dict( type=dataset_type, ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt', img_prefix=data_root + 'VOC2007/', img_scale=(96, 96), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False, with_label=False, test_mode=True, resize_keep_ratio=False)) # optimizer optimizer = dict(type='SGD', lr=0.016, momentum=0.9, weight_decay=0.0004, paramwise_options=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 5, step=[3]) checkpoint_config = dict(interval=1) bbox_head_hist_config = dict( model_type=['ConvModule', 'DeformConvPack'], sub_modules=['bbox_head'], save_every_n_steps=500) log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), ]) # yapf:enable # runtime settings total_epochs = 4 device_ids = range(8) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = '../work_dirs/pascal/baseline/ttfnet_fatnet_ttfhead_full_96_10x_aug_no_pretrain' load_from = None resume_from = None workflow = [('train', 1)] # 26.6
29.969231
91
0.592402
model = dict( type='TTFNet', pretrained=None, backbone=dict( type='FatNetSimple', norm_cfg = dict(type='BN', requires_grad=True), ), neck=None, bbox_head=dict( type='TTFHeadFull', inplanes=16, planes=64, head_conv=64, down_ratio=1, wh_conv=64, hm_head_conv_num=2, wh_head_conv_num=1, num_classes=21, wh_agnostic=True, wh_gaussian=True, norm_cfg=dict(type='BN'), alpha=0.54, hm_weight=1., wh_weight=5.)) cudnn_benchmark = True train_cfg = dict( vis_every_n_iters=100, debug=False) test_cfg = dict( score_thr=0.01, max_per_img=100) dataset_type = 'VOCDataset' data_root = '../data/VOCdevkit/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) data = dict( imgs_per_gpu=16, workers_per_gpu=2, train=dict( type='RepeatDataset', times=30, dataset=dict( type=dataset_type, ann_file=[ data_root + 'VOC2007/ImageSets/Main/trainval.txt', data_root + 'VOC2012/ImageSets/Main/trainval.txt' ], img_prefix=[data_root + 'VOC2007/', data_root + 'VOC2012/'], img_scale=(96, 96), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0.5, with_mask=False, with_crowd=False, with_label=True, extra_aug=dict( photo_metric_distortion=dict( brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), expand=dict( mean=img_norm_cfg['mean'], to_rgb=img_norm_cfg['to_rgb'], ratio_range=(1, 4)), random_crop=dict( min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3)), resize_keep_ratio=False)), val=dict( type=dataset_type, ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt', img_prefix=data_root + 'VOC2007/', img_scale=(512, 512), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False, with_label=True, resize_keep_ratio=False), test=dict( type=dataset_type, ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt', img_prefix=data_root + 'VOC2007/', img_scale=(96, 96), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False, with_label=False, test_mode=True, resize_keep_ratio=False)) optimizer = dict(type='SGD', lr=0.016, momentum=0.9, weight_decay=0.0004, paramwise_options=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 5, step=[3]) checkpoint_config = dict(interval=1) bbox_head_hist_config = dict( model_type=['ConvModule', 'DeformConvPack'], sub_modules=['bbox_head'], save_every_n_steps=500) log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), ]) total_epochs = 4 device_ids = range(8) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = '../work_dirs/pascal/baseline/ttfnet_fatnet_ttfhead_full_96_10x_aug_no_pretrain' load_from = None resume_from = None workflow = [('train', 1)]
true
true
f727a95057ac0c7fae2ad50f1000ff55d2fd438e
35,520
py
Python
tests/test_project.py
Anton-Latukha/wakatime
3035a28a3f996a11d928802dcb05844bb0a52655
[ "BSD-3-Clause" ]
1,198
2015-01-02T12:08:49.000Z
2021-10-07T02:46:59.000Z
tests/test_project.py
Anton-Latukha/wakatime
3035a28a3f996a11d928802dcb05844bb0a52655
[ "BSD-3-Clause" ]
249
2015-01-22T13:31:12.000Z
2021-05-01T08:01:22.000Z
tests/test_project.py
Anton-Latukha/wakatime
3035a28a3f996a11d928802dcb05844bb0a52655
[ "BSD-3-Clause" ]
118
2015-01-16T19:13:15.000Z
2021-07-21T15:09:15.000Z
# -*- coding: utf-8 -*- from wakatime.main import execute from wakatime.packages import requests from wakatime.packages.requests.models import Response import logging import os import shutil import tempfile import time from testfixtures import log_capture from wakatime.compat import u, open from wakatime.constants import API_ERROR, SUCCESS from wakatime.exceptions import NotYetImplemented from wakatime.project import generate_project_name from wakatime.projects.base import BaseProject from wakatime.projects.git import Git from .utils import ANY, DynamicIterable, TestCase, TemporaryDirectory, CustomResponse, mock, json class ProjectTestCase(TestCase): patch_these = [ 'wakatime.packages.requests.adapters.HTTPAdapter.send', 'wakatime.offlinequeue.Queue.push', ['wakatime.offlinequeue.Queue.pop', None], ['wakatime.offlinequeue.Queue.connect', None], 'wakatime.session_cache.SessionCache.save', 'wakatime.session_cache.SessionCache.delete', ['wakatime.session_cache.SessionCache.get', requests.session], ['wakatime.session_cache.SessionCache.connect', None], ] def shared(self, expected_project='', expected_branch=ANY, entity='', config='good_config.cfg', extra_args=[]): self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() config = os.path.join('tests/samples/configs', config) if not os.path.exists(entity): entity = os.path.realpath(os.path.join('tests/samples', entity)) now = u(int(time.time())) args = ['--file', entity, '--config', config, '--time', now] + extra_args retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() heartbeat = { 'language': ANY, 'lines': ANY, 'entity': os.path.realpath(entity), 'project': expected_project, 'branch': expected_branch, 'dependencies': ANY, 'time': float(now), 'type': 'file', 'is_write': False, 'user_agent': ANY, } self.assertHeartbeatSent(heartbeat) self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsSynced() self.assertSessionCacheSaved() def test_project_base(self): path = 'tests/samples/codefiles/see.h' project = BaseProject(path) with self.assertRaises(NotYetImplemented): project.process() with self.assertRaises(NotYetImplemented): project.name() with self.assertRaises(NotYetImplemented): project.branch() def test_project_argument_overrides_detected_project(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--project', 'forced-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('forced-project', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_does_not_override_detected_project(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' project = os.path.basename(os.path.abspath('.')) args = ['--alternate-project', 'alt-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals(project, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_does_not_override_project_argument(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--project', 'forced-project', '--alternate-project', 'alt-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('forced-project', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_used_when_project_not_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() entity = 'tests/samples/projects/git/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) now = u(int(time.time())) entity = os.path.join(tempdir, 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) args = ['--file', entity, '--config', config, '--time', now, '--alternate-project', 'alt-project'] execute(args) calls = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args_list body = calls[0][0][0].body data = json.loads(body)[0] self.assertEquals(None, data.get('project')) body = calls[1][0][0].body data = json.loads(body)[0] self.assertEquals('alt-project', data['project']) def test_wakatime_project_file(self): self.shared( expected_project='waka-project-file', entity='projects/wakatime_project_file/emptyfile.txt', ) def test_wakatime_project_file_used_even_when_project_names_hidden(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/wakatime_project_file', os.path.join(tempdir, 'wakatime_project_file')) self.shared( expected_project='waka-project-file', entity=os.path.join(tempdir, 'wakatime_project_file', 'emptyfile.txt'), extra_args=['--hide-project-names'], ) def test_git_project_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch='master', entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), ) def test_git_project_not_used_when_project_names_hidden(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--hide-project-names', '--file', entity, '--config', config, '--time', now] execute(args) self.assertHeartbeatSavedOffline() self.assertNotEquals('git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals(None, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) proj = open(os.path.join(tempdir, 'git', '.wakatime-project')).read() self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) execute(args) self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_git_branch_not_used_when_branch_names_hidden(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch=None, entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), extra_args=['--hide-branch-names'], ) def test_branch_used_when_project_names_hidden_but_branch_names_visible(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/show_branch_names.cfg' args = ['--hide-project-names', '--file', entity, '--config', config, '--time', now] execute(args) self.assertHeartbeatSavedOffline() self.assertNotEquals('git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNotEquals(None, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) proj = open(os.path.join(tempdir, 'git', '.wakatime-project')).read() self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) execute(args) self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) @log_capture() def test_ioerror_when_reading_git_branch(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = IOError('') self.shared( expected_project='git', expected_branch='master', entity=entity, ) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) def test_git_detached_head_not_used_as_branch(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-detached-head', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') self.shared( expected_project='git', expected_branch=None, entity=entity, ) def test_svn_project_detected(self): with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.Subversion._has_xcode_tools') as mock_has_xcode: mock_has_xcode.return_value = True with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' mock_popen.return_value = DynamicIterable((stdout, stderr), max_calls=1) self.shared( expected_project='svn', entity='projects/svn/afolder/emptyfile.txt', ) @log_capture() def test_svn_exception_handled(self, logs): logging.disable(logging.NOTSET) with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.Subversion._has_xcode_tools') as mock_has_xcode: mock_has_xcode.return_value = True with mock.patch('wakatime.projects.subversion.Popen') as mock_popen: mock_popen.side_effect = OSError('') with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_communicate: mock_communicate.side_effect = OSError('') self.shared( expected_project=None, entity='projects/svn/afolder/emptyfile.txt', ) self.assertNothingPrinted() self.assertNothingLogged(logs) def test_svn_on_mac_without_xcode_tools_installed(self): with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.platform.system') as mock_system: mock_system.return_value = 'Darwin' with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' mock_popen.return_value = DynamicIterable((stdout, stderr), raise_on_calls=[OSError('')]) self.shared( expected_project=None, entity='projects/svn/afolder/emptyfile.txt', ) def test_svn_on_mac_with_xcode_tools_installed(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/svn/afolder/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.platform.system') as mock_system: mock_system.return_value = 'Darwin' with mock.patch('wakatime.projects.subversion.Popen') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' class Dynamic(object): def __init__(self): self.called = 0 def communicate(self): self.called += 1 if self.called == 2: return (stdout, stderr) def wait(self): if self.called == 1: return 0 mock_popen.return_value = Dynamic() execute(args) self.assertEquals('svn', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_mercurial_project_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('hg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('test-hg-branch', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) def test_mercurial_project_branch_with_slash_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg-branch-with-slash/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('hg-branch-with-slash', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('branch/with/slash', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) @log_capture() def test_ioerror_when_reading_mercurial_branch(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with mock.patch('wakatime.projects.mercurial.open') as mock_open: mock_open.side_effect = IOError('') execute(args) self.assertEquals('hg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('default', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) def test_git_submodule_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, ) def test_git_submodule_without_option(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-without-option.cfg', ) def test_git_submodule_detected_and_enabled_globally(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-enabled.cfg', ) def test_git_submodule_detected_but_disabled_globally(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-disabled.cfg', ) def test_git_submodule_detected_and_disabled_using_regex(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-disabled-using-regex.cfg', ) def test_git_submodule_detected_and_enabled_using_regex(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-enabled-using-regex.cfg', ) @log_capture() def test_git_submodule_detected_with_invalid_regex(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-invalid-regex.cfg', ) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for disable git submodules pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = 'WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for disable git submodules pattern: \\(invalid regex)' self.assertEquals(expected, actual) def test_git_worktree_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-worktree', os.path.join(tempdir, 'git-wt')) shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git-wt', 'dot_git'), os.path.join(tempdir, 'git-wt', '.git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git-wt', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='worktree-detection-branch', entity=entity, ) def test_git_worktree_not_detected_when_commondir_missing(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-worktree', os.path.join(tempdir, 'git-wt')) shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git-wt', 'dot_git'), os.path.join(tempdir, 'git-wt', '.git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) os.remove(os.path.join(tempdir, 'git', '.git', 'worktrees', 'git-worktree', 'commondir')) entity = os.path.join(tempdir, 'git-wt', 'emptyfile.txt') self.shared( expected_project=None, expected_branch='worktree-detection-branch', entity=entity, ) @log_capture() def test_git_path_from_gitdir_link_file(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) path = os.path.join(tempdir, 'git', 'asubmodule') git = Git(None) result = git._path_from_gitdir_link_file(path) expected = os.path.realpath(os.path.join(tempdir, 'git', '.git', 'modules', 'asubmodule')) self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_git_path_from_gitdir_link_file_handles_exceptions(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) self.orig_open = open self.count = 0 with mock.patch('wakatime.projects.git.open') as mock_open: def side_effect_function(*args, **kwargs): self.count += 1 if self.count <= 1: raise IOError('') return self.orig_open(*args, **kwargs) mock_open.side_effect = side_effect_function git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) expected = os.path.realpath(os.path.join(tempdir, 'git', '.git', 'modules', 'asubmodule')) self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = UnicodeDecodeError('utf8', ''.encode('utf8'), 0, 0, '') git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) self.assertIsNone(result) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'UnicodeDecodeError' self.assertIn(expected, actual) with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = IOError('') git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) self.assertIsNone(result) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) @log_capture() def test_git_path_from_gitdir_link_file_handles_invalid_link(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) path = os.path.join(tempdir, 'git', 'asubmodule') git = Git(None) result = git._path_from_gitdir_link_file(path) expected = None self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) def test_git_branch_with_slash(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-branch-with-slash', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch='branch/with/slash', entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), ) @log_capture() def test_project_map(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_group_usage(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map42', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_with_invalid_regex(self, logs): logging.disable(logging.NOTSET) self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map_invalid.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (unexpected end of regular expression) for projectmap pattern: invalid[({regex') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unterminated character set at position 7) for projectmap pattern: invalid[({regex') self.assertEquals(expected, actual) @log_capture() def test_project_map_with_replacement_group_index_error(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map_malformed.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (tuple index out of range) for projectmap pattern: proj-map{3}') self.assertEquals(expected, actual) @log_capture() def test_project_map_allows_duplicate_keys(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map_with_duplicate_keys.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map-duplicate-5', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_allows_colon_in_key(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map_with_colon_in_key.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map-match', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_exclude_unknown_project_when_project_detected(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt')) config = 'tests/samples/configs/exclude_unknown_project.cfg' args = ['--file', entity, '--project', 'proj-arg', '--config', config, '--log-file', '~/.wakatime.log'] execute(args) self.assertNothingPrinted() self.assertNothingLogged(logs) self.assertEquals('proj-arg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_generate_project_name(self): self.assertGreater(len(generate_project_name()), 1) self.assertNotEqual(generate_project_name(), generate_project_name())
41.788235
147
0.633136
from wakatime.main import execute from wakatime.packages import requests from wakatime.packages.requests.models import Response import logging import os import shutil import tempfile import time from testfixtures import log_capture from wakatime.compat import u, open from wakatime.constants import API_ERROR, SUCCESS from wakatime.exceptions import NotYetImplemented from wakatime.project import generate_project_name from wakatime.projects.base import BaseProject from wakatime.projects.git import Git from .utils import ANY, DynamicIterable, TestCase, TemporaryDirectory, CustomResponse, mock, json class ProjectTestCase(TestCase): patch_these = [ 'wakatime.packages.requests.adapters.HTTPAdapter.send', 'wakatime.offlinequeue.Queue.push', ['wakatime.offlinequeue.Queue.pop', None], ['wakatime.offlinequeue.Queue.connect', None], 'wakatime.session_cache.SessionCache.save', 'wakatime.session_cache.SessionCache.delete', ['wakatime.session_cache.SessionCache.get', requests.session], ['wakatime.session_cache.SessionCache.connect', None], ] def shared(self, expected_project='', expected_branch=ANY, entity='', config='good_config.cfg', extra_args=[]): self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() config = os.path.join('tests/samples/configs', config) if not os.path.exists(entity): entity = os.path.realpath(os.path.join('tests/samples', entity)) now = u(int(time.time())) args = ['--file', entity, '--config', config, '--time', now] + extra_args retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() heartbeat = { 'language': ANY, 'lines': ANY, 'entity': os.path.realpath(entity), 'project': expected_project, 'branch': expected_branch, 'dependencies': ANY, 'time': float(now), 'type': 'file', 'is_write': False, 'user_agent': ANY, } self.assertHeartbeatSent(heartbeat) self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsSynced() self.assertSessionCacheSaved() def test_project_base(self): path = 'tests/samples/codefiles/see.h' project = BaseProject(path) with self.assertRaises(NotYetImplemented): project.process() with self.assertRaises(NotYetImplemented): project.name() with self.assertRaises(NotYetImplemented): project.branch() def test_project_argument_overrides_detected_project(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--project', 'forced-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('forced-project', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_does_not_override_detected_project(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' project = os.path.basename(os.path.abspath('.')) args = ['--alternate-project', 'alt-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals(project, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_does_not_override_project_argument(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--project', 'forced-project', '--alternate-project', 'alt-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('forced-project', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_alternate_project_argument_used_when_project_not_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() entity = 'tests/samples/projects/git/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) now = u(int(time.time())) entity = os.path.join(tempdir, 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) args = ['--file', entity, '--config', config, '--time', now, '--alternate-project', 'alt-project'] execute(args) calls = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args_list body = calls[0][0][0].body data = json.loads(body)[0] self.assertEquals(None, data.get('project')) body = calls[1][0][0].body data = json.loads(body)[0] self.assertEquals('alt-project', data['project']) def test_wakatime_project_file(self): self.shared( expected_project='waka-project-file', entity='projects/wakatime_project_file/emptyfile.txt', ) def test_wakatime_project_file_used_even_when_project_names_hidden(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/wakatime_project_file', os.path.join(tempdir, 'wakatime_project_file')) self.shared( expected_project='waka-project-file', entity=os.path.join(tempdir, 'wakatime_project_file', 'emptyfile.txt'), extra_args=['--hide-project-names'], ) def test_git_project_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch='master', entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), ) def test_git_project_not_used_when_project_names_hidden(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--hide-project-names', '--file', entity, '--config', config, '--time', now] execute(args) self.assertHeartbeatSavedOffline() self.assertNotEquals('git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals(None, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) proj = open(os.path.join(tempdir, 'git', '.wakatime-project')).read() self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) execute(args) self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_git_branch_not_used_when_branch_names_hidden(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch=None, entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), extra_args=['--hide-branch-names'], ) def test_branch_used_when_project_names_hidden_but_branch_names_visible(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/show_branch_names.cfg' args = ['--hide-project-names', '--file', entity, '--config', config, '--time', now] execute(args) self.assertHeartbeatSavedOffline() self.assertNotEquals('git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNotEquals(None, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) proj = open(os.path.join(tempdir, 'git', '.wakatime-project')).read() self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) execute(args) self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) @log_capture() def test_ioerror_when_reading_git_branch(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = IOError('') self.shared( expected_project='git', expected_branch='master', entity=entity, ) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) def test_git_detached_head_not_used_as_branch(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-detached-head', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') self.shared( expected_project='git', expected_branch=None, entity=entity, ) def test_svn_project_detected(self): with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.Subversion._has_xcode_tools') as mock_has_xcode: mock_has_xcode.return_value = True with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' mock_popen.return_value = DynamicIterable((stdout, stderr), max_calls=1) self.shared( expected_project='svn', entity='projects/svn/afolder/emptyfile.txt', ) @log_capture() def test_svn_exception_handled(self, logs): logging.disable(logging.NOTSET) with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.Subversion._has_xcode_tools') as mock_has_xcode: mock_has_xcode.return_value = True with mock.patch('wakatime.projects.subversion.Popen') as mock_popen: mock_popen.side_effect = OSError('') with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_communicate: mock_communicate.side_effect = OSError('') self.shared( expected_project=None, entity='projects/svn/afolder/emptyfile.txt', ) self.assertNothingPrinted() self.assertNothingLogged(logs) def test_svn_on_mac_without_xcode_tools_installed(self): with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.platform.system') as mock_system: mock_system.return_value = 'Darwin' with mock.patch('wakatime.projects.subversion.Popen.communicate') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' mock_popen.return_value = DynamicIterable((stdout, stderr), raise_on_calls=[OSError('')]) self.shared( expected_project=None, entity='projects/svn/afolder/emptyfile.txt', ) def test_svn_on_mac_with_xcode_tools_installed(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/svn/afolder/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False with mock.patch('wakatime.projects.subversion.platform.system') as mock_system: mock_system.return_value = 'Darwin' with mock.patch('wakatime.projects.subversion.Popen') as mock_popen: stdout = open('tests/samples/output/svn').read() stderr = '' class Dynamic(object): def __init__(self): self.called = 0 def communicate(self): self.called += 1 if self.called == 2: return (stdout, stderr) def wait(self): if self.called == 1: return 0 mock_popen.return_value = Dynamic() execute(args) self.assertEquals('svn', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_mercurial_project_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('hg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('test-hg-branch', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) def test_mercurial_project_branch_with_slash_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg-branch-with-slash/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('hg-branch-with-slash', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('branch/with/slash', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) @log_capture() def test_ioerror_when_reading_mercurial_branch(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with mock.patch('wakatime.projects.mercurial.open') as mock_open: mock_open.side_effect = IOError('') execute(args) self.assertEquals('hg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('default', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) def test_git_submodule_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, ) def test_git_submodule_without_option(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-without-option.cfg', ) def test_git_submodule_detected_and_enabled_globally(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-enabled.cfg', ) def test_git_submodule_detected_but_disabled_globally(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-disabled.cfg', ) def test_git_submodule_detected_and_disabled_using_regex(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-disabled-using-regex.cfg', ) def test_git_submodule_detected_and_enabled_using_regex(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='asubmodule', expected_branch='asubbranch', entity=entity, config='git-submodules-enabled-using-regex.cfg', ) @log_capture() def test_git_submodule_detected_with_invalid_regex(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) entity = os.path.join(tempdir, 'git', 'asubmodule', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='master', entity=entity, config='git-submodules-invalid-regex.cfg', ) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for disable git submodules pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = 'WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for disable git submodules pattern: \\(invalid regex)' self.assertEquals(expected, actual) def test_git_worktree_detected(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-worktree', os.path.join(tempdir, 'git-wt')) shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git-wt', 'dot_git'), os.path.join(tempdir, 'git-wt', '.git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) entity = os.path.join(tempdir, 'git-wt', 'emptyfile.txt') self.shared( expected_project='git', expected_branch='worktree-detection-branch', entity=entity, ) def test_git_worktree_not_detected_when_commondir_missing(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-worktree', os.path.join(tempdir, 'git-wt')) shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git-wt', 'dot_git'), os.path.join(tempdir, 'git-wt', '.git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) os.remove(os.path.join(tempdir, 'git', '.git', 'worktrees', 'git-worktree', 'commondir')) entity = os.path.join(tempdir, 'git-wt', 'emptyfile.txt') self.shared( expected_project=None, expected_branch='worktree-detection-branch', entity=entity, ) @log_capture() def test_git_path_from_gitdir_link_file(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) path = os.path.join(tempdir, 'git', 'asubmodule') git = Git(None) result = git._path_from_gitdir_link_file(path) expected = os.path.realpath(os.path.join(tempdir, 'git', '.git', 'modules', 'asubmodule')) self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_git_path_from_gitdir_link_file_handles_exceptions(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) self.orig_open = open self.count = 0 with mock.patch('wakatime.projects.git.open') as mock_open: def side_effect_function(*args, **kwargs): self.count += 1 if self.count <= 1: raise IOError('') return self.orig_open(*args, **kwargs) mock_open.side_effect = side_effect_function git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) expected = os.path.realpath(os.path.join(tempdir, 'git', '.git', 'modules', 'asubmodule')) self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = UnicodeDecodeError('utf8', ''.encode('utf8'), 0, 0, '') git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) self.assertIsNone(result) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'UnicodeDecodeError' self.assertIn(expected, actual) with mock.patch('wakatime.projects.git.open') as mock_open: mock_open.side_effect = IOError('') git = Git(None) path = os.path.join(tempdir, 'git', 'asubmodule') result = git._path_from_gitdir_link_file(path) self.assertIsNone(result) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual) @log_capture() def test_git_path_from_gitdir_link_file_handles_invalid_link(self, logs): logging.disable(logging.NOTSET) tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-with-submodule', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'asubmodule', 'dot_git'), os.path.join(tempdir, 'git', 'asubmodule', '.git')) path = os.path.join(tempdir, 'git', 'asubmodule') git = Git(None) result = git._path_from_gitdir_link_file(path) expected = None self.assertEquals(expected, result) self.assertNothingPrinted() self.assertNothingLogged(logs) def test_git_branch_with_slash(self): tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git-branch-with-slash', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) self.shared( expected_project='git', expected_branch='branch/with/slash', entity=os.path.join(tempdir, 'git', 'emptyfile.txt'), ) @log_capture() def test_project_map(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_group_usage(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map42', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_with_invalid_regex(self, logs): logging.disable(logging.NOTSET) self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map_invalid.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (unexpected end of regular expression) for projectmap pattern: invalid[({regex') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unterminated character set at position 7) for projectmap pattern: invalid[({regex') self.assertEquals(expected, actual) @log_capture() def test_project_map_with_replacement_group_index_error(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map_malformed.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u('WakaTime WARNING Regex error (tuple index out of range) for projectmap pattern: proj-map{3}') self.assertEquals(expected, actual) @log_capture() def test_project_map_allows_duplicate_keys(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map_with_duplicate_keys.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map-duplicate-5', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_project_map_allows_colon_in_key(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map_with_colon_in_key.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map-match', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertNothingPrinted() self.assertNothingLogged(logs) @log_capture() def test_exclude_unknown_project_when_project_detected(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt')) config = 'tests/samples/configs/exclude_unknown_project.cfg' args = ['--file', entity, '--project', 'proj-arg', '--config', config, '--log-file', '~/.wakatime.log'] execute(args) self.assertNothingPrinted() self.assertNothingLogged(logs) self.assertEquals('proj-arg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) def test_generate_project_name(self): self.assertGreater(len(generate_project_name()), 1) self.assertNotEqual(generate_project_name(), generate_project_name())
true
true
f727a9f08929b08e1199a143d5fe11d7e1b8cf8a
2,647
py
Python
flask/tutorial/flaskr/blog.py
jianchengwang/todo-python
36bdaf6fae714531946047ececca995d60f86e4a
[ "MIT" ]
null
null
null
flask/tutorial/flaskr/blog.py
jianchengwang/todo-python
36bdaf6fae714531946047ececca995d60f86e4a
[ "MIT" ]
null
null
null
flask/tutorial/flaskr/blog.py
jianchengwang/todo-python
36bdaf6fae714531946047ececca995d60f86e4a
[ "MIT" ]
null
null
null
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint('blog', __name__) @bp.route('/') def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts) @bp.route('/create', methods=('GET', 'POST')) @login_required def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html') def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post @bp.route('/<int:id>/update', methods=('GET', 'POST')) @login_required def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post) @bp.route('/<int:id>/delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index'))
27.28866
69
0.530412
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint('blog', __name__) @bp.route('/') def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts) @bp.route('/create', methods=('GET', 'POST')) @login_required def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html') def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post @bp.route('/<int:id>/update', methods=('GET', 'POST')) @login_required def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post) @bp.route('/<int:id>/delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index'))
true
true
f727ad7b679d2e1f9b7546a04cf754276693bc15
418
py
Python
backend/wishlist/settings/development.py
oaguy1/wishlist.vote
3440cc05cfe039e905064fd2dfcb0ae06402e12c
[ "MIT" ]
null
null
null
backend/wishlist/settings/development.py
oaguy1/wishlist.vote
3440cc05cfe039e905064fd2dfcb0ae06402e12c
[ "MIT" ]
null
null
null
backend/wishlist/settings/development.py
oaguy1/wishlist.vote
3440cc05cfe039e905064fd2dfcb0ae06402e12c
[ "MIT" ]
null
null
null
from .base import * DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get("POSTGRES_DB"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': 5432, } }
20.9
63
0.593301
from .base import * DEBUG = True ALLOWED_HOSTS = [] S = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get("POSTGRES_DB"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': 5432, } }
true
true
f727af1c0db0d85bc6562a4f4ff54917e782503c
1,030
py
Python
annotater/memetext/decorators.py
stricoff92/annotater
8ca471477e2d567945e14f09d3d763d379e7587e
[ "MIT" ]
null
null
null
annotater/memetext/decorators.py
stricoff92/annotater
8ca471477e2d567945e14f09d3d763d379e7587e
[ "MIT" ]
null
null
null
annotater/memetext/decorators.py
stricoff92/annotater
8ca471477e2d567945e14f09d3d763d379e7587e
[ "MIT" ]
null
null
null
from functools import wraps from django.http import HttpResponse from rest_framework.response import Response from rest_framework import status from website.constants import WIDGET_NAMES def user_can_use_web_widget(function): @wraps(function) def decorator(request, *a, **k): if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext): return function(request, *a, **k) else: return HttpResponse( "<h1>ERROR 401: No access to this widget.</h1>", # should be 403 status=status.HTTP_401_UNAUTHORIZED, ) return decorator def user_can_use_api_widget(function): @wraps(function) def decorator(request, *a, **k): if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext): return function(request, *a, **k) else: return Response( "no access to this widget", status.HTTP_401_UNAUTHORIZED, # should be 403 ) return decorator
29.428571
80
0.646602
from functools import wraps from django.http import HttpResponse from rest_framework.response import Response from rest_framework import status from website.constants import WIDGET_NAMES def user_can_use_web_widget(function): @wraps(function) def decorator(request, *a, **k): if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext): return function(request, *a, **k) else: return HttpResponse( "<h1>ERROR 401: No access to this widget.</h1>", status=status.HTTP_401_UNAUTHORIZED, ) return decorator def user_can_use_api_widget(function): @wraps(function) def decorator(request, *a, **k): if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext): return function(request, *a, **k) else: return Response( "no access to this widget", status.HTTP_401_UNAUTHORIZED, ) return decorator
true
true
f727af8237ad53753e4c67cd9224b1cb5ed49267
4,059
py
Python
tests/module/fetch/test_init.py
mgorny/pkgcore
ab4a718aa1626f4edeb385383f5595a1e262b0dc
[ "BSD-3-Clause" ]
null
null
null
tests/module/fetch/test_init.py
mgorny/pkgcore
ab4a718aa1626f4edeb385383f5595a1e262b0dc
[ "BSD-3-Clause" ]
null
null
null
tests/module/fetch/test_init.py
mgorny/pkgcore
ab4a718aa1626f4edeb385383f5595a1e262b0dc
[ "BSD-3-Clause" ]
null
null
null
# Copyright: 2006 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD from snakeoil.sequences import iflatten_instance from snakeoil.test import TestCase from pkgcore import fetch class base(TestCase): def assertUri(self, obj, uri): uri = list(uri) self.assertEqual(list(iflatten_instance(obj)), uri) if uri: self.assertTrue(obj) else: self.assertFalse(obj) class TestFetchable(base): def test_init(self): o = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o.filename, "dar") self.assertUri(o.uri, ["asdf"]) self.assertEqual(o.chksums, {"asdf":1}) def test_eq_ne(self): o1 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o1, o1) o2 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o1, o2) self.assertNotEqual(o1, fetch.fetchable("dar1", uri=["asdf"], chksums={"asdf":1})) self.assertNotEqual(o1, fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1})) self.assertNotEqual(o1, fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1, "foon":1})) class TestMirror(base): kls = fetch.mirror default_mirrors = ["http://foon", "ftp://spoon"] def setUp(self): self.mirror = self.kls(self.default_mirrors, "fork") def test_init(self): self.assertEqual(self.mirror.mirror_name, "fork") # explicit test should any tuple like sequence show up self.assertInstance(self.mirror.mirrors, tuple) self.assertEqual(self.mirror.mirrors, tuple(self.default_mirrors)) def test_iter(self): self.assertEqual(list(self.mirror), self.default_mirrors) def test_len(self): self.assertEqual(len(self.mirror), len(self.default_mirrors)) def test_getitem(self): self.assertEqual(self.mirror[1], self.default_mirrors[1]) def test_eq_ne(self): self.assertEqual(self.mirror, self.kls(self.default_mirrors, 'fork')) self.assertNotEqual(self.mirror, self.kls(self.default_mirrors + ['http://fark'], 'fork')) class TestDefaultMirror(TestMirror): kls = fetch.default_mirror class Test_uri_list(base): def setUp(self): self.uril = fetch.uri_list("cows") @staticmethod def mk_uri_list(*iterable, **kwds): filename = kwds.get("filename", "asdf") obj = fetch.uri_list(filename) for x in iterable: if isinstance(x, fetch.mirror): obj.add_mirror(x) else: obj.add_uri(x) return obj def test_mirrors(self): self.assertRaises(TypeError, self.uril.add_mirror, "cows") mirror = fetch.mirror(["me", "WI"], "asdf") self.uril.add_mirror(mirror) self.assertEqual(list(self.uril), ["me/cows", "WI/cows"]) self.uril.add_mirror(mirror, "foon/boon") self.assertUri(self.uril, ["me/cows", "WI/cows", "me/foon/boon", "WI/foon/boon"]) def test_uris(self): self.uril.add_uri("blar") self.assertUri(self.uril, ["blar"]) def test_combined(self): l = ["blarn", "me/cows", "WI/cows", "madison", "belleville/cows", "verona/cows"] self.uril.add_uri("blarn") self.uril.add_mirror(fetch.mirror(["me", "WI"], "asdf")) self.uril.add_uri("madison") self.uril.add_mirror(fetch.default_mirror( ["belleville", "verona"], "foon")) self.assertUri(self.uril, l) def test_nonzero(self): self.assertTrue(self.mk_uri_list("asdf")) self.assertFalse(self.mk_uri_list()) self.assertFalse(self.mk_uri_list(fetch.mirror((), "mirror"))) def test_len(self): self.assertLen(self.mk_uri_list(), 0) self.assertLen(self.mk_uri_list("fdas"), 1) self.assertLen(self.mk_uri_list(fetch.mirror((), "mirror")), 0) self.assertLen(self.mk_uri_list(fetch.mirror(("asdf",), "mirror")), 1)
32.472
80
0.614437
from snakeoil.sequences import iflatten_instance from snakeoil.test import TestCase from pkgcore import fetch class base(TestCase): def assertUri(self, obj, uri): uri = list(uri) self.assertEqual(list(iflatten_instance(obj)), uri) if uri: self.assertTrue(obj) else: self.assertFalse(obj) class TestFetchable(base): def test_init(self): o = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o.filename, "dar") self.assertUri(o.uri, ["asdf"]) self.assertEqual(o.chksums, {"asdf":1}) def test_eq_ne(self): o1 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o1, o1) o2 = fetch.fetchable("dar", uri=["asdf"], chksums={"asdf":1}) self.assertEqual(o1, o2) self.assertNotEqual(o1, fetch.fetchable("dar1", uri=["asdf"], chksums={"asdf":1})) self.assertNotEqual(o1, fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1})) self.assertNotEqual(o1, fetch.fetchable("dar", uri=["asdf1"], chksums={"asdf":1, "foon":1})) class TestMirror(base): kls = fetch.mirror default_mirrors = ["http://foon", "ftp://spoon"] def setUp(self): self.mirror = self.kls(self.default_mirrors, "fork") def test_init(self): self.assertEqual(self.mirror.mirror_name, "fork") self.assertInstance(self.mirror.mirrors, tuple) self.assertEqual(self.mirror.mirrors, tuple(self.default_mirrors)) def test_iter(self): self.assertEqual(list(self.mirror), self.default_mirrors) def test_len(self): self.assertEqual(len(self.mirror), len(self.default_mirrors)) def test_getitem(self): self.assertEqual(self.mirror[1], self.default_mirrors[1]) def test_eq_ne(self): self.assertEqual(self.mirror, self.kls(self.default_mirrors, 'fork')) self.assertNotEqual(self.mirror, self.kls(self.default_mirrors + ['http://fark'], 'fork')) class TestDefaultMirror(TestMirror): kls = fetch.default_mirror class Test_uri_list(base): def setUp(self): self.uril = fetch.uri_list("cows") @staticmethod def mk_uri_list(*iterable, **kwds): filename = kwds.get("filename", "asdf") obj = fetch.uri_list(filename) for x in iterable: if isinstance(x, fetch.mirror): obj.add_mirror(x) else: obj.add_uri(x) return obj def test_mirrors(self): self.assertRaises(TypeError, self.uril.add_mirror, "cows") mirror = fetch.mirror(["me", "WI"], "asdf") self.uril.add_mirror(mirror) self.assertEqual(list(self.uril), ["me/cows", "WI/cows"]) self.uril.add_mirror(mirror, "foon/boon") self.assertUri(self.uril, ["me/cows", "WI/cows", "me/foon/boon", "WI/foon/boon"]) def test_uris(self): self.uril.add_uri("blar") self.assertUri(self.uril, ["blar"]) def test_combined(self): l = ["blarn", "me/cows", "WI/cows", "madison", "belleville/cows", "verona/cows"] self.uril.add_uri("blarn") self.uril.add_mirror(fetch.mirror(["me", "WI"], "asdf")) self.uril.add_uri("madison") self.uril.add_mirror(fetch.default_mirror( ["belleville", "verona"], "foon")) self.assertUri(self.uril, l) def test_nonzero(self): self.assertTrue(self.mk_uri_list("asdf")) self.assertFalse(self.mk_uri_list()) self.assertFalse(self.mk_uri_list(fetch.mirror((), "mirror"))) def test_len(self): self.assertLen(self.mk_uri_list(), 0) self.assertLen(self.mk_uri_list("fdas"), 1) self.assertLen(self.mk_uri_list(fetch.mirror((), "mirror")), 0) self.assertLen(self.mk_uri_list(fetch.mirror(("asdf",), "mirror")), 1)
true
true
f727aff556ad2c85d3ab130a226c9d8be9a26bce
5,527
py
Python
Practice/adapter_roberta_v4/adapter_model.py
accordproject/labs-cicero-classify
3a52ebaf45252515c417bf94a05e33fc1c2628b8
[ "Apache-2.0" ]
2
2021-07-07T01:06:18.000Z
2021-11-12T18:54:21.000Z
Practice/adapter_roberta_v4/adapter_model.py
accordproject/labs_cicero_classify
3a52ebaf45252515c417bf94a05e33fc1c2628b8
[ "Apache-2.0" ]
3
2021-06-25T12:40:23.000Z
2022-02-14T13:42:30.000Z
Practice/adapter_roberta_v4/adapter_model.py
accordproject/labs_cicero_classify
3a52ebaf45252515c417bf94a05e33fc1c2628b8
[ "Apache-2.0" ]
null
null
null
import pandas as pd import numpy as np import torch print(f"Torch Version: {torch.__version__}") import transformers print(f"transformers (Adapter) Version: {transformers.__version__}") from transformers import RobertaTokenizer import numpy as np tokenizer = RobertaTokenizer.from_pretrained("roberta-base") from transformers import RobertaTokenizer tokenizer = RobertaTokenizer.from_pretrained("roberta-base") def encode_batch(batch): """Encodes a batch of input data using the model tokenizer.""" return tokenizer(batch["text"], max_length=80, truncation=True, padding="max_length") data_path = "./NER_multilabel_data_v4.csv" df = pd.read_csv(data_path) all_tags = df.newTag all_tags = set(all_tags) all_tags = "|".join(all_tags) all_tags = all_tags.split("|") all_tags = set(all_tags) all_tags = list(all_tags) from ner_dataset import get_trainset_data_loader all_tags, trainset, trainloader = get_trainset_data_loader(tokenizer, BATCH_SIZE=128) from transformers import RobertaConfig, RobertaModelWithHeads config = RobertaConfig.from_pretrained( "roberta-base", num_labels=len(all_tags), label2id = trainset.label_map, id2label = trainset.id2label ) model = RobertaModelWithHeads.from_pretrained( "roberta-base", config=config, ) all_adapter_name = [] for tag in all_tags: adapter_name = f"{tag}_0731" name = model.load_adapter(f"./save_adapters/{adapter_name}") all_adapter_name.append(name) model.load_head(f"./save_heads/{adapter_name}") import re parallel_text = "','".join(all_adapter_name) result = re.findall(r'[;|(|)]',parallel_text) if len(result) != 0: raise(ValueError("Adapter Name must not contain \"" + '\", \"'.join(result) + '"')) from transformers.adapters.composition import Parallel parallel = eval("Parallel('" + "','".join(all_adapter_name) + "')") model.set_active_adapters(parallel) device = "cpu" def get_adapter_mapping(model): print(model.active_head) label_2_id_mapping = dict() id_2_label_mapping = dict() for i, head in enumerate(model.active_head): label_2_id_mapping[head] = i id_2_label_mapping[i] = head return label_2_id_mapping, id_2_label_mapping def model_predict(model, sentence, device = "cpu"): tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) with torch.no_grad(): outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) logits = outputs[1][0] return_tags_order = {} all_output = None for i, output in enumerate(outputs): return_tags_order[i] = (model.active_head[i]) output = outputs[i][0] if all_output != None: all_output = torch.cat((all_output, output), dim=2) else: all_output = output all_output = torch.sigmoid(all_output) output_array = np.array(all_output) output_array = output_array.reshape(output_array.shape[-2], output_array.shape[-1]) label_confidences = [] for label_confidence in list(output_array): label_confidences.append(list(label_confidence)) #Drop Head and End since it is start/stop Token label_confidences = label_confidences[1:-1] max_value = np.array(label_confidences).argmax(axis=1) trans_func = np.vectorize(lambda x: model.active_head[x]) out_labels = trans_func(max_value) out_sentence = tokenizer.tokenize(sentence) return out_sentence, out_labels, label_confidences, return_tags_order device = "cpu" def get_adapter_mapping(model): print(model.active_head) label_2_id_mapping = dict() id_2_label_mapping = dict() for i, head in enumerate(model.active_head): label_2_id_mapping[head] = i id_2_label_mapping[i] = head return label_2_id_mapping, id_2_label_mapping def model_predict(model, sentence, device = "cpu"): tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) with torch.no_grad(): outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) logits = outputs[1][0] return_tags_order = {} all_output = None for i, output in enumerate(outputs): return_tags_order[i] = (model.active_head[i]) output = outputs[i][0] if all_output != None: all_output = torch.cat((all_output, output), dim=2) else: all_output = output all_output = torch.sigmoid(all_output) output_array = np.array(all_output) output_array = output_array.reshape(output_array.shape[-2], output_array.shape[-1]) label_confidences = [] for label_confidence in list(output_array): label_confidences.append(list(label_confidence)) #Drop Head and End since it is start/stop Token label_confidences = label_confidences[1:-1] max_value = np.array(label_confidences).argmax(axis=1) trans_func = np.vectorize(lambda x: model.active_head[x]) out_labels = trans_func(max_value) out_sentence = tokenizer.tokenize(sentence) return out_sentence, out_labels, label_confidences, return_tags_order
29.875676
87
0.701646
import pandas as pd import numpy as np import torch print(f"Torch Version: {torch.__version__}") import transformers print(f"transformers (Adapter) Version: {transformers.__version__}") from transformers import RobertaTokenizer import numpy as np tokenizer = RobertaTokenizer.from_pretrained("roberta-base") from transformers import RobertaTokenizer tokenizer = RobertaTokenizer.from_pretrained("roberta-base") def encode_batch(batch): return tokenizer(batch["text"], max_length=80, truncation=True, padding="max_length") data_path = "./NER_multilabel_data_v4.csv" df = pd.read_csv(data_path) all_tags = df.newTag all_tags = set(all_tags) all_tags = "|".join(all_tags) all_tags = all_tags.split("|") all_tags = set(all_tags) all_tags = list(all_tags) from ner_dataset import get_trainset_data_loader all_tags, trainset, trainloader = get_trainset_data_loader(tokenizer, BATCH_SIZE=128) from transformers import RobertaConfig, RobertaModelWithHeads config = RobertaConfig.from_pretrained( "roberta-base", num_labels=len(all_tags), label2id = trainset.label_map, id2label = trainset.id2label ) model = RobertaModelWithHeads.from_pretrained( "roberta-base", config=config, ) all_adapter_name = [] for tag in all_tags: adapter_name = f"{tag}_0731" name = model.load_adapter(f"./save_adapters/{adapter_name}") all_adapter_name.append(name) model.load_head(f"./save_heads/{adapter_name}") import re parallel_text = "','".join(all_adapter_name) result = re.findall(r'[;|(|)]',parallel_text) if len(result) != 0: raise(ValueError("Adapter Name must not contain \"" + '\", \"'.join(result) + '"')) from transformers.adapters.composition import Parallel parallel = eval("Parallel('" + "','".join(all_adapter_name) + "')") model.set_active_adapters(parallel) device = "cpu" def get_adapter_mapping(model): print(model.active_head) label_2_id_mapping = dict() id_2_label_mapping = dict() for i, head in enumerate(model.active_head): label_2_id_mapping[head] = i id_2_label_mapping[i] = head return label_2_id_mapping, id_2_label_mapping def model_predict(model, sentence, device = "cpu"): tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) with torch.no_grad(): outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) logits = outputs[1][0] return_tags_order = {} all_output = None for i, output in enumerate(outputs): return_tags_order[i] = (model.active_head[i]) output = outputs[i][0] if all_output != None: all_output = torch.cat((all_output, output), dim=2) else: all_output = output all_output = torch.sigmoid(all_output) output_array = np.array(all_output) output_array = output_array.reshape(output_array.shape[-2], output_array.shape[-1]) label_confidences = [] for label_confidence in list(output_array): label_confidences.append(list(label_confidence)) label_confidences = label_confidences[1:-1] max_value = np.array(label_confidences).argmax(axis=1) trans_func = np.vectorize(lambda x: model.active_head[x]) out_labels = trans_func(max_value) out_sentence = tokenizer.tokenize(sentence) return out_sentence, out_labels, label_confidences, return_tags_order device = "cpu" def get_adapter_mapping(model): print(model.active_head) label_2_id_mapping = dict() id_2_label_mapping = dict() for i, head in enumerate(model.active_head): label_2_id_mapping[head] = i id_2_label_mapping[i] = head return label_2_id_mapping, id_2_label_mapping def model_predict(model, sentence, device = "cpu"): tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) with torch.no_grad(): outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) logits = outputs[1][0] return_tags_order = {} all_output = None for i, output in enumerate(outputs): return_tags_order[i] = (model.active_head[i]) output = outputs[i][0] if all_output != None: all_output = torch.cat((all_output, output), dim=2) else: all_output = output all_output = torch.sigmoid(all_output) output_array = np.array(all_output) output_array = output_array.reshape(output_array.shape[-2], output_array.shape[-1]) label_confidences = [] for label_confidence in list(output_array): label_confidences.append(list(label_confidence)) label_confidences = label_confidences[1:-1] max_value = np.array(label_confidences).argmax(axis=1) trans_func = np.vectorize(lambda x: model.active_head[x]) out_labels = trans_func(max_value) out_sentence = tokenizer.tokenize(sentence) return out_sentence, out_labels, label_confidences, return_tags_order
true
true
f727b1c8a4f7b616a8ac216e156b396852c3e415
23,151
py
Python
src/python/WMCore/MicroService/MSTransferor/RequestInfo.py
vkuznet/WMCore
001cc51651052405a7ecd811cde91da611b1dc57
[ "Apache-2.0" ]
null
null
null
src/python/WMCore/MicroService/MSTransferor/RequestInfo.py
vkuznet/WMCore
001cc51651052405a7ecd811cde91da611b1dc57
[ "Apache-2.0" ]
1
2018-10-30T16:23:07.000Z
2018-10-30T16:23:07.000Z
src/python/WMCore/MicroService/MSTransferor/RequestInfo.py
vkuznet/WMCore
001cc51651052405a7ecd811cde91da611b1dc57
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """ _RequestInfo_ Class to hold and parse all information related to a given request """ # futures from __future__ import division, print_function from future.utils import viewitems # system modules import datetime import time # WMCore modules from pprint import pformat from copy import deepcopy from Utils.IteratorTools import grouper from WMCore.DataStructs.LumiList import LumiList from WMCore.MicroService.MSTransferor.Workflow import Workflow from WMCore.MicroService.Tools.PycurlRucio import (getRucioToken, getPileupContainerSizesRucio, listReplicationRules, getBlocksAndSizeRucio) from WMCore.MicroService.Tools.Common import (elapsedTime, findBlockParents, findParent, getBlocksByDsetAndRun, getFileLumisInBlock, getRunsInBlock) from WMCore.MicroService.MSCore import MSCore class RequestInfo(MSCore): """ RequestInfo class provides functionality to access and manipulate requests. """ def __init__(self, msConfig, rucioObj, logger): """ Basic setup for this RequestInfo module """ extraArgs = {"skipReqMgr": True, "skipRucio": True} super(RequestInfo, self).__init__(msConfig, logger=logger, **extraArgs) self.rucio = rucioObj self.rucioToken = None self.tokenValidity = None def __call__(self, reqRecords): """ Run the unified transferor box :param reqRecords: input records :return: output records """ # obtain new unified Configuration uConfig = self.unifiedConfig() if not uConfig: self.logger.warning("Failed to fetch the latest unified config. Skipping this cycle") return [] self.logger.info("Going to process %d requests.", len(reqRecords)) # create a Workflow object representing the request workflows = [] for record in reqRecords: wflow = Workflow(record['RequestName'], record, logger=self.logger) workflows.append(wflow) msg = "Processing request: %s, with campaigns: %s, " % (wflow.getName(), wflow.getCampaigns()) msg += "and input data as:\n%s" % pformat(wflow.getDataCampaignMap()) self.logger.info(msg) # setup the Rucio token self.setupRucio() # get complete requests information (based on Unified Transferor logic) self.unified(workflows) return workflows def setupRucio(self): """ Check whether Rucio is enabled and create a new token, or renew it if needed """ if not self.tokenValidity: # a brand new token needs to be created. To be done in the coming lines... pass elif self.tokenValidity: # then check the token lifetime dateTimeNow = int(datetime.datetime.utcnow().strftime("%s")) timeDiff = self.tokenValidity - dateTimeNow if timeDiff > 30 * 60: # 30min # current token still valid for a while return self.rucioToken, self.tokenValidity = getRucioToken(self.msConfig['rucioAuthUrl'], self.msConfig['rucioAccount']) def unified(self, workflows): """ Unified Transferor black box :param workflows: input workflow objects """ # get aux info for dataset/blocks from inputs/parents/pileups # make subscriptions based on site white/black lists self.logger.info("Unified method processing %d requests", len(workflows)) orig = time.time() # start by finding what are the parent datasets for requests requiring it time0 = time.time() parentMap = self.getParentDatasets(workflows) self.setParentDatasets(workflows, parentMap) self.logger.debug(elapsedTime(time0, "### getParentDatasets")) # then check the secondary dataset sizes and locations time0 = time.time() sizeByDset, locationByDset = self.getSecondaryDatasets(workflows) locationByDset = self.resolveSecondaryRSEs(locationByDset) self.setSecondaryDatasets(workflows, sizeByDset, locationByDset) self.logger.debug(elapsedTime(time0, "### getSecondaryDatasets")) # get final primary and parent list of valid blocks, # considering run, block and lumi lists time0 = time.time() blocksByDset = self.getInputDataBlocks(workflows) self.setInputDataBlocks(workflows, blocksByDset) self.logger.debug(elapsedTime(time0, "### getInputDataBlocks")) # get a final list of parent blocks time0 = time.time() parentageMap = self.getParentChildBlocks(workflows) self.setParentChildBlocks(workflows, parentageMap) self.logger.debug(elapsedTime(time0, "### getParentChildBlocks")) self.logger.info(elapsedTime(orig, '### total time for unified method')) self.logger.info("Unified method successfully processed %d requests", len(workflows)) return workflows def _workflowRemoval(self, listOfWorkflows, workflowsToRetry): """ Receives the initial list of workflows and another list of workflows that failed somewhere in the MS processing (like fetching information from the data-services); and remove those workflows from this cycle of the MSTransferor, such that they can be retried in the next cycle. :param listOfWorkflows: reference to the list of the initial workflows :param workflowsToRetry: list of workflows with missing information :return: nothing, the workflow removal is done in place """ for wflow in set(workflowsToRetry): self.logger.warning("Removing workflow that failed processing in MSTransferor: %s", wflow.getName()) listOfWorkflows.remove(wflow) def getParentDatasets(self, workflows): """ Given a list of requests, find which requests need to process a parent dataset, and discover what the parent dataset name is. :return: dictionary with the child and the parent dataset """ retryWorkflows = [] retryDatasets = [] datasetByDbs = {} parentByDset = {} for wflow in workflows: if wflow.hasParents(): datasetByDbs.setdefault(wflow.getDbsUrl(), set()) datasetByDbs[wflow.getDbsUrl()].add(wflow.getInputDataset()) for dbsUrl, datasets in viewitems(datasetByDbs): self.logger.info("Resolving %d dataset parentage against DBS: %s", len(datasets), dbsUrl) # first find out what's the parent dataset name parentByDset.update(findParent(datasets, dbsUrl)) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dset, value in viewitems(parentByDset): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: if wflow.hasParents() and wflow.getInputDataset() in retryDatasets: retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) return parentByDset def setParentDatasets(self, workflows, parentageMap): """ Set the parent dataset for workflows requiring parents """ for wflow in workflows: if wflow.hasParents() and wflow.getInputDataset() in parentageMap: wflow.setParentDataset(parentageMap[wflow.getInputDataset()]) def getSecondaryDatasets(self, workflows): """ Given a list of requests, list all the pileup datasets and, find their total dataset sizes and which locations host completed and subscribed datasets. NOTE it only uses valid blocks (i.e., blocks with at least one replica!) :param workflows: a list of Workflow objects :return: two dictionaries keyed by the dataset. First contains dataset size as value. Second contains a list of locations as value. """ retryWorkflows = [] retryDatasets = [] datasets = set() for wflow in workflows: datasets = datasets | wflow.getPileupDatasets() # retrieve pileup container size and locations from Rucio self.logger.info("Fetching pileup dataset sizes for %d datasets against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) sizesByDset = getPileupContainerSizesRucio(datasets, self.msConfig['rucioUrl'], self.rucioToken) # then fetch data location for locked data, under our own rucio account self.logger.info("Fetching pileup container location for %d containers against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) locationsByDset = listReplicationRules(datasets, self.msConfig['rucioAccount'], grouping="A", rucioUrl=self.msConfig['rucioUrl'], rucioToken=self.rucioToken) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dset, value in viewitems(sizesByDset): if value is None: retryDatasets.append(dset) for dset, value in viewitems(locationsByDset): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: for pileup in wflow.getPileupDatasets(): if pileup in retryDatasets: retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) return sizesByDset, locationsByDset def resolveSecondaryRSEs(self, rsesByContainer): """ Given a dictionary with containers and their list of RSE expressions, resolve the RSE expressions into RSE names, dropping all the Tape RSEs. :param rsesByContainer: dict key'ed by the container with a list of expressions :return: a dictionary key'ed by the container name, with a flat list of unique RSE names. """ self.logger.info("Resolving Rucio RSE expressions for %d containers", len(rsesByContainer)) for contName in list(rsesByContainer): rseNames = [] for rseExpr in rsesByContainer[contName]: rseNames.extend(self.rucio.evaluateRSEExpression(rseExpr, returnTape=False)) rsesByContainer[contName] = list(set(rseNames)) return rsesByContainer def setSecondaryDatasets(self, workflows, sizesByDset, locationsByDset): """ Given dictionaries with the pileup dataset size and locations, set the workflow object accordingly. """ for wflow in workflows: for dsetName in wflow.getPileupDatasets(): wflow.setSecondarySummary(dsetName, sizesByDset[dsetName], locationsByDset[dsetName]) def getInputDataBlocks(self, workflows): """ Given a list of requests, list all the primary and parent datasets and, find their block sizes and which locations host completed and subscribed blocks NOTE it only uses valid blocks (i.e., blocks with at least one replica!) :param workflows: a list of Workflow objects :return: dictionary with dataset and a few block information """ retryWorkflows = [] retryDatasets = [] datasets = set() for wflow in workflows: for dataIn in wflow.getDataCampaignMap(): if dataIn['type'] in ["primary", "parent"]: datasets.add(dataIn['name']) # fetch all block names and their sizes from Rucio self.logger.info("Fetching parent/primary block sizes for %d containers against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) blocksByDset = getBlocksAndSizeRucio(datasets, self.msConfig['rucioUrl'], self.rucioToken) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dsetName in blocksByDset: if blocksByDset[dsetName] is None: retryDatasets.append(dsetName) if retryDatasets: for wflow in workflows: if wflow.getInputDataset() in retryDatasets or wflow.getParentDataset() in retryDatasets: retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) return blocksByDset def setInputDataBlocks(self, workflows, blocksByDset): """ Provided a dictionary structure of dictionary, block name, and a couple of block information, set the workflow attributes accordingly. """ retryWorkflows = [] for wflow in workflows: try: for dataIn in wflow.getDataCampaignMap(): if dataIn['type'] == "primary": newBlockDict = self._handleInputDataInfo(wflow, dataIn['name'], blocksByDset[dataIn['name']]) wflow.setPrimaryBlocks(newBlockDict) elif dataIn['type'] == "parent": newBlockDict = self._handleInputDataInfo(wflow, dataIn['name'], blocksByDset[dataIn['name']]) wflow.setParentBlocks(newBlockDict) except Exception: self.logger.error("Workflow: %s will be retried in the next cycle", wflow.getName()) retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) def _handleInputDataInfo(self, wflow, dset, blocksDict): """ Applies any run/block/lumi list on the primary and parent blocks provided. It's a convoluted logic, such as: 1) if there is no run/block/lumi list, just return the initial blocksDict 2) if it has lumi list, filter runs from it and run block discovery given a dataset name and a list of runs 3) if it has RunWhitelist, run block discovery for a given dataset name and a list of runs 4) if it has only RunBlacklist, discover the run list of all initial blocks provided in blocksDict and remove blocks matching only the black list 5) for the steps above, always check whether the block has replicas 6) NOW that the block data discovery is completed (considering runs): * if LumiList is not enabled, just return the current list of blocks * else, fetch file/run/lumi information in bulk of blocks and compare it to the LumiList, skipping blocks without a single file that matches it. Note that the LumiList check is dealt with in a similar way as done in the WorkQueue StartPolicyInterface/getMaskedBlocks: :param wflow: the Workflow object :param dset: dataset name :param blocksDict: dictionary of blocks, their size and location :return: dictionary of block names and block size """ finalBlocks = {} dbsUrl = wflow.getDbsUrl() runAllowedList = wflow.getRunWhitelist() runForbiddenList = set(wflow.getRunBlacklist()) lumiList = wflow.getLumilist() # if there is no filter on the input data, simply return it if not (lumiList or runAllowedList or runForbiddenList): return self._removeZeroSizeBlocks(blocksDict) if lumiList: # LumiList has precedence over RunWhitelist runAllowedList = [] for run in lumiList.getRuns(): runAllowedList.append(int(run)) runAllowedList = list(set(runAllowedList)) if runAllowedList: # Run number 1 is not supported by DBSServer if int(runAllowedList[0]) == 1: finalBlocks = deepcopy(blocksDict) else: runAllowedList = list(set(runAllowedList) - runForbiddenList) self.logger.info("Fetching blocks matching a list of runs for %s", wflow.getName()) try: blocks = getBlocksByDsetAndRun(dset, runAllowedList, dbsUrl) except Exception as exc: msg = "Failed to retrieve blocks by dataset '%s'and run: %s\n" % (dset, runAllowedList) msg += "Error details: %s" % str(exc) self.logger.error(msg) raise for block in blocks: if block in blocksDict: finalBlocks[block] = deepcopy(blocksDict[block]) else: self.logger.warning("Dropping block existent in DBS but not in Rucio: %s", block) elif runForbiddenList: # only run blacklist set self.logger.info("Fetching runs in blocks for RunBlacklist for %s", wflow.getName()) try: blockRuns = getRunsInBlock(list(blocksDict), dbsUrl) except Exception as exc: self.logger.error("Failed to bulk retrieve runs per block. Details: %s", str(exc)) raise for block, runs in viewitems(blockRuns): if not set(runs).difference(runForbiddenList): self.logger.info("Dropping block with only blacklisted runs: %s", block) elif block in blocksDict: finalBlocks[block] = deepcopy(blocksDict[block]) if lumiList: self.logger.info("Fetching block/lumi information for %d blocks in %s", len(finalBlocks), wflow.getName()) self.logger.debug("with the following run whitelist: %s", runAllowedList) goodBlocks = set() # now with a smaller set of blocks in hand, we collect their lumi # information and discard any blocks not matching the lumi list for blockSlice in grouper(finalBlocks, 10): try: blockFileLumis = getFileLumisInBlock(blockSlice, dbsUrl, validFileOnly=1) except Exception as exc: self.logger.error("Failed to bulk retrieve run/lumi per block. Details: %s", str(exc)) raise for block, fileLumis in viewitems(blockFileLumis): for fileLumi in fileLumis: if int(fileLumi['run_num']) not in runAllowedList: continue runNumber = str(fileLumi['run_num']) lumis = fileLumi['lumi_section_num'] fileMask = LumiList(runsAndLumis={runNumber: lumis}) if lumiList & fileMask: # then it has lumis that we need, keep this block and move on goodBlocks.add(block) break # last but not least, drop any blocks that are not in the good list for block in list(finalBlocks): if block not in goodBlocks: self.logger.info("Dropping block not matching LumiList: %s", block) finalBlocks.pop(block) return self._removeZeroSizeBlocks(finalBlocks) def _removeZeroSizeBlocks(self, blocksDict): """ Given a dictionary of blocks and their block size and location information, return only blocks with >0 bytes of block size (Rucio blocks with no replicas/ files result in blocks with None size). :return: dictionary of block names and block size """ finalBlocks = {} for blockName in blocksDict: if blocksDict[blockName]['blockSize']: finalBlocks[blockName] = blocksDict[blockName] else: self.logger.info("Dropping block: %s with no files and size: %s", blockName, blocksDict[blockName]['blockSize']) return finalBlocks def getParentChildBlocks(self, workflows): """ Given a list of requests, get their children block, discover their parent blocks and finally filter out any parent blocks with only invalid files (without any replicas) :param workflows: list of workflow objects :return: nothing, updates the workflow attributes in place """ retryWorkflows = [] retryDatasets = [] blocksByDbs = {} parentageMap = {} for wflow in workflows: blocksByDbs.setdefault(wflow.getDbsUrl(), set()) if wflow.getParentDataset(): blocksByDbs[wflow.getDbsUrl()] = blocksByDbs[wflow.getDbsUrl()] | set(wflow.getPrimaryBlocks().keys()) for dbsUrl, blocks in viewitems(blocksByDbs): if not blocks: continue self.logger.debug("Fetching DBS parent blocks for %d children blocks...", len(blocks)) # first find out what's the parent dataset name parentageMap.update(findBlockParents(blocks, dbsUrl)) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dset, value in viewitems(parentageMap): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: if wflow.getParentDataset() in retryDatasets: retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) return parentageMap def setParentChildBlocks(self, workflows, parentageMap): """ Provided a dictionary with the dataset, the child block and a set of the parent blocks, set the workflow attribute accordingly """ for wflow in workflows: if wflow.getParentDataset() and wflow.getInputDataset() in parentageMap: wflow.setChildToParentBlocks(parentageMap[wflow.getInputDataset()])
48.03112
118
0.619066
from __future__ import division, print_function from future.utils import viewitems import datetime import time from pprint import pformat from copy import deepcopy from Utils.IteratorTools import grouper from WMCore.DataStructs.LumiList import LumiList from WMCore.MicroService.MSTransferor.Workflow import Workflow from WMCore.MicroService.Tools.PycurlRucio import (getRucioToken, getPileupContainerSizesRucio, listReplicationRules, getBlocksAndSizeRucio) from WMCore.MicroService.Tools.Common import (elapsedTime, findBlockParents, findParent, getBlocksByDsetAndRun, getFileLumisInBlock, getRunsInBlock) from WMCore.MicroService.MSCore import MSCore class RequestInfo(MSCore): def __init__(self, msConfig, rucioObj, logger): extraArgs = {"skipReqMgr": True, "skipRucio": True} super(RequestInfo, self).__init__(msConfig, logger=logger, **extraArgs) self.rucio = rucioObj self.rucioToken = None self.tokenValidity = None def __call__(self, reqRecords): uConfig = self.unifiedConfig() if not uConfig: self.logger.warning("Failed to fetch the latest unified config. Skipping this cycle") return [] self.logger.info("Going to process %d requests.", len(reqRecords)) workflows = [] for record in reqRecords: wflow = Workflow(record['RequestName'], record, logger=self.logger) workflows.append(wflow) msg = "Processing request: %s, with campaigns: %s, " % (wflow.getName(), wflow.getCampaigns()) msg += "and input data as:\n%s" % pformat(wflow.getDataCampaignMap()) self.logger.info(msg) self.setupRucio() self.unified(workflows) return workflows def setupRucio(self): if not self.tokenValidity: pass elif self.tokenValidity: dateTimeNow = int(datetime.datetime.utcnow().strftime("%s")) timeDiff = self.tokenValidity - dateTimeNow if timeDiff > 30 * 60: return self.rucioToken, self.tokenValidity = getRucioToken(self.msConfig['rucioAuthUrl'], self.msConfig['rucioAccount']) def unified(self, workflows): self.logger.info("Unified method processing %d requests", len(workflows)) orig = time.time() time0 = time.time() parentMap = self.getParentDatasets(workflows) self.setParentDatasets(workflows, parentMap) self.logger.debug(elapsedTime(time0, "### getParentDatasets")) time0 = time.time() sizeByDset, locationByDset = self.getSecondaryDatasets(workflows) locationByDset = self.resolveSecondaryRSEs(locationByDset) self.setSecondaryDatasets(workflows, sizeByDset, locationByDset) self.logger.debug(elapsedTime(time0, "### getSecondaryDatasets")) time0 = time.time() blocksByDset = self.getInputDataBlocks(workflows) self.setInputDataBlocks(workflows, blocksByDset) self.logger.debug(elapsedTime(time0, "### getInputDataBlocks")) time0 = time.time() parentageMap = self.getParentChildBlocks(workflows) self.setParentChildBlocks(workflows, parentageMap) self.logger.debug(elapsedTime(time0, "### getParentChildBlocks")) self.logger.info(elapsedTime(orig, '### total time for unified method')) self.logger.info("Unified method successfully processed %d requests", len(workflows)) return workflows def _workflowRemoval(self, listOfWorkflows, workflowsToRetry): for wflow in set(workflowsToRetry): self.logger.warning("Removing workflow that failed processing in MSTransferor: %s", wflow.getName()) listOfWorkflows.remove(wflow) def getParentDatasets(self, workflows): retryWorkflows = [] retryDatasets = [] datasetByDbs = {} parentByDset = {} for wflow in workflows: if wflow.hasParents(): datasetByDbs.setdefault(wflow.getDbsUrl(), set()) datasetByDbs[wflow.getDbsUrl()].add(wflow.getInputDataset()) for dbsUrl, datasets in viewitems(datasetByDbs): self.logger.info("Resolving %d dataset parentage against DBS: %s", len(datasets), dbsUrl) parentByDset.update(findParent(datasets, dbsUrl)) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dset, value in viewitems(parentByDset): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: if wflow.hasParents() and wflow.getInputDataset() in retryDatasets: retryWorkflows.append(wflow) self._workflowRemoval(workflows, retryWorkflows) return parentByDset def setParentDatasets(self, workflows, parentageMap): for wflow in workflows: if wflow.hasParents() and wflow.getInputDataset() in parentageMap: wflow.setParentDataset(parentageMap[wflow.getInputDataset()]) def getSecondaryDatasets(self, workflows): retryWorkflows = [] retryDatasets = [] datasets = set() for wflow in workflows: datasets = datasets | wflow.getPileupDatasets() self.logger.info("Fetching pileup dataset sizes for %d datasets against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) sizesByDset = getPileupContainerSizesRucio(datasets, self.msConfig['rucioUrl'], self.rucioToken) self.logger.info("Fetching pileup container location for %d containers against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) locationsByDset = listReplicationRules(datasets, self.msConfig['rucioAccount'], grouping="A", rucioUrl=self.msConfig['rucioUrl'], rucioToken=self.rucioToken) for dset, value in viewitems(sizesByDset): if value is None: retryDatasets.append(dset) for dset, value in viewitems(locationsByDset): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: for pileup in wflow.getPileupDatasets(): if pileup in retryDatasets: retryWorkflows.append(wflow) # remove workflows that failed one or more of the bulk queries to the data-service self._workflowRemoval(workflows, retryWorkflows) return sizesByDset, locationsByDset def resolveSecondaryRSEs(self, rsesByContainer): self.logger.info("Resolving Rucio RSE expressions for %d containers", len(rsesByContainer)) for contName in list(rsesByContainer): rseNames = [] for rseExpr in rsesByContainer[contName]: rseNames.extend(self.rucio.evaluateRSEExpression(rseExpr, returnTape=False)) rsesByContainer[contName] = list(set(rseNames)) return rsesByContainer def setSecondaryDatasets(self, workflows, sizesByDset, locationsByDset): for wflow in workflows: for dsetName in wflow.getPileupDatasets(): wflow.setSecondarySummary(dsetName, sizesByDset[dsetName], locationsByDset[dsetName]) def getInputDataBlocks(self, workflows): retryWorkflows = [] retryDatasets = [] datasets = set() for wflow in workflows: for dataIn in wflow.getDataCampaignMap(): if dataIn['type'] in ["primary", "parent"]: datasets.add(dataIn['name']) # fetch all block names and their sizes from Rucio self.logger.info("Fetching parent/primary block sizes for %d containers against Rucio: %s", len(datasets), self.msConfig['rucioUrl']) blocksByDset = getBlocksAndSizeRucio(datasets, self.msConfig['rucioUrl'], self.rucioToken) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dsetName in blocksByDset: if blocksByDset[dsetName] is None: retryDatasets.append(dsetName) if retryDatasets: for wflow in workflows: if wflow.getInputDataset() in retryDatasets or wflow.getParentDataset() in retryDatasets: retryWorkflows.append(wflow) self._workflowRemoval(workflows, retryWorkflows) return blocksByDset def setInputDataBlocks(self, workflows, blocksByDset): retryWorkflows = [] for wflow in workflows: try: for dataIn in wflow.getDataCampaignMap(): if dataIn['type'] == "primary": newBlockDict = self._handleInputDataInfo(wflow, dataIn['name'], blocksByDset[dataIn['name']]) wflow.setPrimaryBlocks(newBlockDict) elif dataIn['type'] == "parent": newBlockDict = self._handleInputDataInfo(wflow, dataIn['name'], blocksByDset[dataIn['name']]) wflow.setParentBlocks(newBlockDict) except Exception: self.logger.error("Workflow: %s will be retried in the next cycle", wflow.getName()) retryWorkflows.append(wflow) self._workflowRemoval(workflows, retryWorkflows) def _handleInputDataInfo(self, wflow, dset, blocksDict): finalBlocks = {} dbsUrl = wflow.getDbsUrl() runAllowedList = wflow.getRunWhitelist() runForbiddenList = set(wflow.getRunBlacklist()) lumiList = wflow.getLumilist() if not (lumiList or runAllowedList or runForbiddenList): return self._removeZeroSizeBlocks(blocksDict) if lumiList: runAllowedList = [] for run in lumiList.getRuns(): runAllowedList.append(int(run)) runAllowedList = list(set(runAllowedList)) if runAllowedList: if int(runAllowedList[0]) == 1: finalBlocks = deepcopy(blocksDict) else: runAllowedList = list(set(runAllowedList) - runForbiddenList) self.logger.info("Fetching blocks matching a list of runs for %s", wflow.getName()) try: blocks = getBlocksByDsetAndRun(dset, runAllowedList, dbsUrl) except Exception as exc: msg = "Failed to retrieve blocks by dataset '%s'and run: %s\n" % (dset, runAllowedList) msg += "Error details: %s" % str(exc) self.logger.error(msg) raise for block in blocks: if block in blocksDict: finalBlocks[block] = deepcopy(blocksDict[block]) else: self.logger.warning("Dropping block existent in DBS but not in Rucio: %s", block) elif runForbiddenList: self.logger.info("Fetching runs in blocks for RunBlacklist for %s", wflow.getName()) try: blockRuns = getRunsInBlock(list(blocksDict), dbsUrl) except Exception as exc: self.logger.error("Failed to bulk retrieve runs per block. Details: %s", str(exc)) raise for block, runs in viewitems(blockRuns): if not set(runs).difference(runForbiddenList): self.logger.info("Dropping block with only blacklisted runs: %s", block) elif block in blocksDict: finalBlocks[block] = deepcopy(blocksDict[block]) if lumiList: self.logger.info("Fetching block/lumi information for %d blocks in %s", len(finalBlocks), wflow.getName()) self.logger.debug("with the following run whitelist: %s", runAllowedList) goodBlocks = set() for blockSlice in grouper(finalBlocks, 10): try: blockFileLumis = getFileLumisInBlock(blockSlice, dbsUrl, validFileOnly=1) except Exception as exc: self.logger.error("Failed to bulk retrieve run/lumi per block. Details: %s", str(exc)) raise for block, fileLumis in viewitems(blockFileLumis): for fileLumi in fileLumis: if int(fileLumi['run_num']) not in runAllowedList: continue runNumber = str(fileLumi['run_num']) lumis = fileLumi['lumi_section_num'] fileMask = LumiList(runsAndLumis={runNumber: lumis}) if lumiList & fileMask: goodBlocks.add(block) break for block in list(finalBlocks): if block not in goodBlocks: self.logger.info("Dropping block not matching LumiList: %s", block) finalBlocks.pop(block) return self._removeZeroSizeBlocks(finalBlocks) def _removeZeroSizeBlocks(self, blocksDict): finalBlocks = {} for blockName in blocksDict: if blocksDict[blockName]['blockSize']: finalBlocks[blockName] = blocksDict[blockName] else: self.logger.info("Dropping block: %s with no files and size: %s", blockName, blocksDict[blockName]['blockSize']) return finalBlocks def getParentChildBlocks(self, workflows): retryWorkflows = [] retryDatasets = [] blocksByDbs = {} parentageMap = {} for wflow in workflows: blocksByDbs.setdefault(wflow.getDbsUrl(), set()) if wflow.getParentDataset(): blocksByDbs[wflow.getDbsUrl()] = blocksByDbs[wflow.getDbsUrl()] | set(wflow.getPrimaryBlocks().keys()) for dbsUrl, blocks in viewitems(blocksByDbs): if not blocks: continue self.logger.debug("Fetching DBS parent blocks for %d children blocks...", len(blocks)) parentageMap.update(findBlockParents(blocks, dbsUrl)) # now check if any of our calls failed; if so, workflow needs to be skipped from this cycle # FIXME: isn't there a better way to do this?!? for dset, value in viewitems(parentageMap): if value is None: retryDatasets.append(dset) if retryDatasets: for wflow in workflows: if wflow.getParentDataset() in retryDatasets: retryWorkflows.append(wflow) self._workflowRemoval(workflows, retryWorkflows) return parentageMap def setParentChildBlocks(self, workflows, parentageMap): for wflow in workflows: if wflow.getParentDataset() and wflow.getInputDataset() in parentageMap: wflow.setChildToParentBlocks(parentageMap[wflow.getInputDataset()])
true
true
f727b49174b3a60786564bef9812ead45c308098
1,363
py
Python
database/migrations/0016_auto_20190113_0449.py
ccraddock/beiwe-backend-cc
b37c2604800aafcf81c93bc14673ada6aed17a39
[ "BSD-3-Clause" ]
null
null
null
database/migrations/0016_auto_20190113_0449.py
ccraddock/beiwe-backend-cc
b37c2604800aafcf81c93bc14673ada6aed17a39
[ "BSD-3-Clause" ]
null
null
null
database/migrations/0016_auto_20190113_0449.py
ccraddock/beiwe-backend-cc
b37c2604800aafcf81c93bc14673ada6aed17a39
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2019-01-13 04:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('database', '0015_auto_20190112_0251'), ] operations = [ migrations.CreateModel( name='ReceivedDataStats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models.BooleanField(default=False)), ('created_on', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now=True)), ('data_type', models.CharField(max_length=256)), ('last_upload_timestamp', models.DateTimeField()), ('number_of_uploads', models.PositiveIntegerField()), ('number_bytes_uploaded', models.PositiveIntegerField()), ('participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='received_data_stats', to='database.Participant')), ], ), migrations.AlterUniqueTogether( name='receiveddatastats', unique_together=set([('participant', 'data_type')]), ), ]
38.942857
159
0.623624
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('database', '0015_auto_20190112_0251'), ] operations = [ migrations.CreateModel( name='ReceivedDataStats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('deleted', models.BooleanField(default=False)), ('created_on', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now=True)), ('data_type', models.CharField(max_length=256)), ('last_upload_timestamp', models.DateTimeField()), ('number_of_uploads', models.PositiveIntegerField()), ('number_bytes_uploaded', models.PositiveIntegerField()), ('participant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='received_data_stats', to='database.Participant')), ], ), migrations.AlterUniqueTogether( name='receiveddatastats', unique_together=set([('participant', 'data_type')]), ), ]
true
true
f727b5c41eac8de45cd42818ceedba94bf6fbdec
427
py
Python
Extra Exercises/artbyraza.py
luizpavanello/python_udacity
6411af82db8123e5b6b731c5a3bced2c31dc2c57
[ "MIT" ]
null
null
null
Extra Exercises/artbyraza.py
luizpavanello/python_udacity
6411af82db8123e5b6b731c5a3bced2c31dc2c57
[ "MIT" ]
null
null
null
Extra Exercises/artbyraza.py
luizpavanello/python_udacity
6411af82db8123e5b6b731c5a3bced2c31dc2c57
[ "MIT" ]
null
null
null
import turtle t = turtle.Turtle() turtle.bgcolor('black') def triangle(): t.forward(100) t.left(120) t.forward(100) t.left(120) t.forward(100) t.left(120) t.forward(100) t.speed(0) t.pencolor('red') t.penup() t.goto(-350,250) t.pendown() for numbers in range(7): x = 250 - (86*numbers) t.penup() t.goto(-350,x) t.pendown() for number in range(7): triangle() turtle.done()
17.791667
27
0.59719
import turtle t = turtle.Turtle() turtle.bgcolor('black') def triangle(): t.forward(100) t.left(120) t.forward(100) t.left(120) t.forward(100) t.left(120) t.forward(100) t.speed(0) t.pencolor('red') t.penup() t.goto(-350,250) t.pendown() for numbers in range(7): x = 250 - (86*numbers) t.penup() t.goto(-350,x) t.pendown() for number in range(7): triangle() turtle.done()
true
true
f727b654f4653c3f574ae05040ca03e4ed0356f1
1,821
py
Python
setup.py
pauleveritt/wired
629f950176a9682a7ccb68efbb27cb2e23b4e93e
[ "MIT" ]
1
2021-01-09T00:05:54.000Z
2021-01-09T00:05:54.000Z
setup.py
pauleveritt/wired
629f950176a9682a7ccb68efbb27cb2e23b4e93e
[ "MIT" ]
null
null
null
setup.py
pauleveritt/wired
629f950176a9682a7ccb68efbb27cb2e23b4e93e
[ "MIT" ]
1
2019-04-22T14:22:39.000Z
2019-04-22T14:22:39.000Z
from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') requires = ['zope.interface'] docs_require = ['Sphinx', 'sphinx_rtd_theme'] tests_require = ['pytest', 'pytest-cov', 'venusian', 'sybil'] setup( name='wired', description=( 'An inversion-of-control (IoC) container for building decoupled, ' 'configurable, pluggable applications.' ), version='0.2', long_description=readme + '\n\n' + changes, long_description_content_type='text/x-rst', author='Michael Merickel', author_email='pylons-discuss@googlegroups.com', url='https://wired.readthedocs.io', packages=find_packages('src', exclude=['tests']), package_dir={'': 'src'}, include_package_data=True, python_requires='>=3.4', install_requires=requires, extras_require={'docs': docs_require, 'testing': tests_require}, zip_safe=False, keywords=','.join( [ 'ioc container', 'inversion of control', 'dependency injection', 'service locator', 'singleton', 'service factory', ] ), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], )
29.852459
74
0.606809
from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') requires = ['zope.interface'] docs_require = ['Sphinx', 'sphinx_rtd_theme'] tests_require = ['pytest', 'pytest-cov', 'venusian', 'sybil'] setup( name='wired', description=( 'An inversion-of-control (IoC) container for building decoupled, ' 'configurable, pluggable applications.' ), version='0.2', long_description=readme + '\n\n' + changes, long_description_content_type='text/x-rst', author='Michael Merickel', author_email='pylons-discuss@googlegroups.com', url='https://wired.readthedocs.io', packages=find_packages('src', exclude=['tests']), package_dir={'': 'src'}, include_package_data=True, python_requires='>=3.4', install_requires=requires, extras_require={'docs': docs_require, 'testing': tests_require}, zip_safe=False, keywords=','.join( [ 'ioc container', 'inversion of control', 'dependency injection', 'service locator', 'singleton', 'service factory', ] ), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], )
true
true
f727b7bdfdf05c7eb3a30b160d05ef9a20097bfc
227,887
py
Python
src/borg/testsuite/archiver.py
adrian5/borg
6f371d5522e515c738340c2cd6dc2473b644c4d2
[ "BSD-3-Clause" ]
1
2021-03-20T15:13:11.000Z
2021-03-20T15:13:11.000Z
src/borg/testsuite/archiver.py
adrian5/borg
6f371d5522e515c738340c2cd6dc2473b644c4d2
[ "BSD-3-Clause" ]
9
2020-12-05T01:08:44.000Z
2021-04-19T23:06:12.000Z
src/borg/testsuite/archiver.py
adrian5/borg
6f371d5522e515c738340c2cd6dc2473b644c4d2
[ "BSD-3-Clause" ]
null
null
null
import argparse import dateutil.tz import errno import io import json import logging import os import pstats import random import re import shutil import socket import stat import subprocess import sys import tempfile import time import unittest from binascii import unhexlify, b2a_base64 from configparser import ConfigParser from datetime import datetime from datetime import timezone from datetime import timedelta from hashlib import sha256 from io import BytesIO, StringIO from unittest.mock import patch import pytest import borg from .. import xattr, helpers, platform from ..archive import Archive, ChunkBuffer from ..archiver import Archiver, parse_storage_quota, PURE_PYTHON_MSGPACK_WARNING from ..cache import Cache, LocalCache from ..chunker import has_seek_hole from ..constants import * # NOQA from ..crypto.low_level import bytes_to_long, num_cipher_blocks from ..crypto.key import KeyfileKeyBase, RepoKey, KeyfileKey, Passphrase, TAMRequiredError from ..crypto.keymanager import RepoIdMismatch, NotABorgKeyFile from ..crypto.file_integrity import FileIntegrityError from ..helpers import Location, get_security_dir from ..helpers import Manifest, MandatoryFeatureUnsupported from ..helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR from ..helpers import bin_to_hex from ..helpers import MAX_S from ..helpers import msgpack from ..helpers import flags_noatime, flags_normal from ..nanorst import RstToTextLazy, rst_to_terminal from ..patterns import IECommand, PatternMatcher, parse_pattern from ..item import Item, ItemDiff from ..locking import LockFailed from ..logger import setup_logging from ..remote import RemoteRepository, PathNotAllowed from ..repository import Repository from . import has_lchflags, llfuse from . import BaseTestCase, changedir, environment_variable, no_selinux from . import are_symlinks_supported, are_hardlinks_supported, are_fifos_supported, is_utime_fully_supported, is_birthtime_fully_supported from .platform import fakeroot_detected from .upgrader import make_attic_repo from . import key src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) def exec_cmd(*args, archiver=None, fork=False, exe=None, input=b'', binary_output=False, **kw): if fork: try: if exe is None: borg = (sys.executable, '-m', 'borg.archiver') elif isinstance(exe, str): borg = (exe, ) elif not isinstance(exe, tuple): raise ValueError('exe must be None, a tuple or a str') output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT, input=input) ret = 0 except subprocess.CalledProcessError as e: output = e.output ret = e.returncode except SystemExit as e: # possibly raised by argparse output = '' ret = e.code if binary_output: return ret, output else: return ret, os.fsdecode(output) else: stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr try: sys.stdin = StringIO(input.decode()) sys.stdin.buffer = BytesIO(input) output = BytesIO() # Always use utf-8 here, to simply .decode() below output_text = sys.stdout = sys.stderr = io.TextIOWrapper(output, encoding='utf-8') if archiver is None: archiver = Archiver() archiver.prerun_checks = lambda *args: None archiver.exit_code = EXIT_SUCCESS helpers.exit_code = EXIT_SUCCESS try: args = archiver.parse_args(list(args)) # argparse parsing may raise SystemExit when the command line is bad or # actions that abort early (eg. --help) where given. Catch this and return # the error code as-if we invoked a Borg binary. except SystemExit as e: output_text.flush() return e.code, output.getvalue() if binary_output else output.getvalue().decode() ret = archiver.run(args) output_text.flush() return ret, output.getvalue() if binary_output else output.getvalue().decode() finally: sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr def have_gnutar(): if not shutil.which('tar'): return False popen = subprocess.Popen(['tar', '--version'], stdout=subprocess.PIPE) stdout, stderr = popen.communicate() return b'GNU tar' in stdout # check if the binary "borg.exe" is available (for local testing a symlink to virtualenv/bin/borg should do) try: exec_cmd('help', exe='borg.exe', fork=True) BORG_EXES = ['python', 'binary', ] except FileNotFoundError: BORG_EXES = ['python', ] @pytest.fixture(params=BORG_EXES) def cmd(request): if request.param == 'python': exe = None elif request.param == 'binary': exe = 'borg.exe' else: raise ValueError("param must be 'python' or 'binary'") def exec_fn(*args, **kw): return exec_cmd(*args, exe=exe, fork=True, **kw) return exec_fn def test_return_codes(cmd, tmpdir): repo = tmpdir.mkdir('repo') input = tmpdir.mkdir('input') output = tmpdir.mkdir('output') input.join('test_file').write('content') rc, out = cmd('init', '--encryption=none', '%s' % str(repo)) assert rc == EXIT_SUCCESS rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_SUCCESS with changedir(str(output)): rc, out = cmd('extract', '%s::archive' % repo) assert rc == EXIT_SUCCESS rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match') assert rc == EXIT_WARNING # pattern did not match rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_ERROR # duplicate archive name """ test_disk_full is very slow and not recommended to be included in daily testing. for this test, an empty, writable 16MB filesystem mounted on DF_MOUNT is required. for speed and other reasons, it is recommended that the underlying block device is in RAM, not a magnetic or flash disk. assuming /tmp is a tmpfs (in memory filesystem), one can use this: dd if=/dev/zero of=/tmp/borg-disk bs=16M count=1 mkfs.ext4 /tmp/borg-disk mkdir /tmp/borg-mount sudo mount /tmp/borg-disk /tmp/borg-mount if the directory does not exist, the test will be skipped. """ DF_MOUNT = '/tmp/borg-mount' @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT) def test_disk_full(cmd): def make_files(dir, count, size, rnd=True): shutil.rmtree(dir, ignore_errors=True) os.mkdir(dir) if rnd: count = random.randint(1, count) if size > 1: size = random.randint(1, size) for i in range(count): fn = os.path.join(dir, "file%03d" % i) with open(fn, 'wb') as f: data = os.urandom(size) f.write(data) with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='YES'): mount = DF_MOUNT assert os.path.exists(mount) repo = os.path.join(mount, 'repo') input = os.path.join(mount, 'input') reserve = os.path.join(mount, 'reserve') for j in range(100): shutil.rmtree(repo, ignore_errors=True) shutil.rmtree(input, ignore_errors=True) # keep some space and some inodes in reserve that we can free up later: make_files(reserve, 80, 100000, rnd=False) rc, out = cmd('init', repo) if rc != EXIT_SUCCESS: print('init', rc, out) assert rc == EXIT_SUCCESS try: success, i = True, 0 while success: i += 1 try: make_files(input, 20, 200000) except OSError as err: if err.errno == errno.ENOSPC: # already out of space break raise try: rc, out = cmd('create', '%s::test%03d' % (repo, i), input) success = rc == EXIT_SUCCESS if not success: print('create', rc, out) finally: # make sure repo is not locked shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True) os.remove(os.path.join(repo, 'lock.roster')) finally: # now some error happened, likely we are out of disk space. # free some space so we can expect borg to be able to work normally: shutil.rmtree(reserve, ignore_errors=True) rc, out = cmd('list', repo) if rc != EXIT_SUCCESS: print('list', rc, out) rc, out = cmd('check', '--repair', repo) if rc != EXIT_SUCCESS: print('check', rc, out) assert rc == EXIT_SUCCESS class ArchiverTestCaseBase(BaseTestCase): EXE = None # python source based FORK_DEFAULT = False prefix = '' def setUp(self): os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_PASSPHRASE'] = 'waytooeasyonlyfortests' self.archiver = not self.FORK_DEFAULT and Archiver() or None self.tmpdir = tempfile.mkdtemp() self.repository_path = os.path.join(self.tmpdir, 'repository') self.repository_location = self.prefix + self.repository_path self.input_path = os.path.join(self.tmpdir, 'input') self.output_path = os.path.join(self.tmpdir, 'output') self.keys_path = os.path.join(self.tmpdir, 'keys') self.cache_path = os.path.join(self.tmpdir, 'cache') self.exclude_file_path = os.path.join(self.tmpdir, 'excludes') self.patterns_file_path = os.path.join(self.tmpdir, 'patterns') os.environ['BORG_KEYS_DIR'] = self.keys_path os.environ['BORG_CACHE_DIR'] = self.cache_path os.mkdir(self.input_path) os.chmod(self.input_path, 0o777) # avoid troubles with fakeroot / FUSE os.mkdir(self.output_path) os.mkdir(self.keys_path) os.mkdir(self.cache_path) with open(self.exclude_file_path, 'wb') as fd: fd.write(b'input/file2\n# A comment line, then a blank line\n\n') with open(self.patterns_file_path, 'wb') as fd: fd.write(b'+input/file_important\n- input/file*\n# A comment line, then a blank line\n\n') self._old_wd = os.getcwd() os.chdir(self.tmpdir) def tearDown(self): os.chdir(self._old_wd) # note: ignore_errors=True as workaround for issue #862 shutil.rmtree(self.tmpdir, ignore_errors=True) setup_logging() def cmd(self, *args, **kw): exit_code = kw.pop('exit_code', 0) fork = kw.pop('fork', None) binary_output = kw.get('binary_output', False) if fork is None: fork = self.FORK_DEFAULT ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw) if ret != exit_code: print(output) self.assert_equal(ret, exit_code) # if tests are run with the pure-python msgpack, there will be warnings about # this in the output, which would make a lot of tests fail. pp_msg = PURE_PYTHON_MSGPACK_WARNING.encode() if binary_output else PURE_PYTHON_MSGPACK_WARNING empty = b'' if binary_output else '' output = empty.join(line for line in output.splitlines(keepends=True) if pp_msg not in line) return output def create_src_archive(self, name): self.cmd('create', '--compression=lz4', self.repository_location + '::' + name, src_dir) def open_archive(self, name): repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, name) return archive, repository def open_repository(self): return Repository(self.repository_path, exclusive=True) def create_regular_file(self, name, size=0, contents=None): assert not (size != 0 and contents and len(contents) != size), 'size and contents do not match' filename = os.path.join(self.input_path, name) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'wb') as fd: if contents is None: contents = b'X' * size fd.write(contents) def create_test_files(self): """Create a minimal test case including all supported file types """ # File self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('flagfile', size=1024) # Directory self.create_regular_file('dir2/file2', size=1024 * 80) # File mode os.chmod('input/file1', 0o4755) # Hard link if are_hardlinks_supported(): os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'hardlink')) # Symlink if are_symlinks_supported(): os.symlink('somewhere', os.path.join(self.input_path, 'link1')) self.create_regular_file('fusexattr', size=1) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): fn = os.fsencode(os.path.join(self.input_path, 'fusexattr')) # ironically, due to the way how fakeroot works, comparing FUSE file xattrs to orig file xattrs # will FAIL if fakeroot supports xattrs, thus we only set the xattr if XATTR_FAKEROOT is False. # This is because fakeroot with xattr-support does not propagate xattrs of the underlying file # into "fakeroot space". Because the xattrs exposed by borgfs are these of an underlying file # (from fakeroots point of view) they are invisible to the test process inside the fakeroot. xattr.setxattr(fn, b'user.foo', b'bar') xattr.setxattr(fn, b'user.empty', b'') # XXX this always fails for me # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot # same for newer ubuntu and centos. # if this is supported just on specific platform, platform should be checked first, # so that the test setup for all tests using it does not fail here always for others. # xattr.setxattr(os.path.join(self.input_path, 'link1'), b'user.foo_symlink', b'bar_symlink', follow_symlinks=False) # FIFO node if are_fifos_supported(): os.mkfifo(os.path.join(self.input_path, 'fifo1')) if has_lchflags: platform.set_flags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP) try: # Block device os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20)) # Char device os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40)) # File mode os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents # File owner os.chown('input/file1', 100, 200) # raises OSError invalid argument on cygwin have_root = True # we have (fake)root except PermissionError: have_root = False except OSError as e: # Note: ENOSYS "Function not implemented" happens as non-root on Win 10 Linux Subsystem. if e.errno not in (errno.EINVAL, errno.ENOSYS): raise have_root = False time.sleep(1) # "empty" must have newer timestamp than other files self.create_regular_file('empty', size=0) return have_root class ArchiverTestCase(ArchiverTestCaseBase): requires_hardlinks = pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_basic_functionality(self): have_root = self.create_test_files() # fork required to test show-rc output output = self.cmd('init', '--encryption=repokey', '--show-version', '--show-rc', self.repository_location, fork=True) self.assert_in('borgbackup version', output) self.assert_in('terminating with success status, rc 0', output) self.cmd('create', '--exclude-nodump', self.repository_location + '::test', 'input') output = self.cmd('create', '--exclude-nodump', '--stats', self.repository_location + '::test.2', 'input') self.assert_in('Archive name: test.2', output) self.assert_in('This archive: ', output) with changedir('output'): self.cmd('extract', self.repository_location + '::test') list_output = self.cmd('list', '--short', self.repository_location) self.assert_in('test', list_output) self.assert_in('test.2', list_output) expected = [ 'input', 'input/bdev', 'input/cdev', 'input/dir2', 'input/dir2/file2', 'input/empty', 'input/file1', 'input/flagfile', ] if are_fifos_supported(): expected.append('input/fifo1') if are_symlinks_supported(): expected.append('input/link1') if are_hardlinks_supported(): expected.append('input/hardlink') if not have_root: # we could not create these device files without (fake)root expected.remove('input/bdev') expected.remove('input/cdev') if has_lchflags: # remove the file we did not backup, so input and output become equal expected.remove('input/flagfile') # this file is UF_NODUMP os.remove(os.path.join('input', 'flagfile')) list_output = self.cmd('list', '--short', self.repository_location + '::test') for name in expected: self.assert_in(name, list_output) self.assert_dirs_equal('input', 'output/input') info_output = self.cmd('info', self.repository_location + '::test') item_count = 4 if has_lchflags else 5 # one file is UF_NODUMP self.assert_in('Number of files: %d' % item_count, info_output) shutil.rmtree(self.cache_path) info_output2 = self.cmd('info', self.repository_location + '::test') def filter(output): # filter for interesting "info" output, ignore cache rebuilding related stuff prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:', 'All archives:', 'Chunk index:', ] result = [] for line in output.splitlines(): for prefix in prefixes: if line.startswith(prefix): result.append(line) return '\n'.join(result) # the interesting parts of info_output2 and info_output should be same self.assert_equal(filter(info_output), filter(info_output2)) @requires_hardlinks def test_create_duplicate_root(self): # setup for #5603 path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') # give input twice! # test if created archive has 'input' contents twice: archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] # we have all fs items exactly once! assert sorted(paths) == ['input', 'input/a', 'input/a/hardlink', 'input/b', 'input/b/hardlink'] def test_init_parent_dirs(self): parent_path = os.path.join(self.tmpdir, 'parent1', 'parent2') repository_path = os.path.join(parent_path, 'repository') repository_location = self.prefix + repository_path with pytest.raises(Repository.ParentPathDoesNotExist): # normal borg init does NOT create missing parent dirs self.cmd('init', '--encryption=none', repository_location) # but if told so, it does: self.cmd('init', '--encryption=none', '--make-parent-dirs', repository_location) assert os.path.exists(parent_path) def test_unix_socket(self): self.cmd('init', '--encryption=repokey', self.repository_location) try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(os.path.join(self.input_path, 'unix-socket')) except PermissionError as err: if err.errno == errno.EPERM: pytest.skip('unix sockets disabled or not supported') elif err.errno == errno.EACCES: pytest.skip('permission denied to create unix sockets') self.cmd('create', self.repository_location + '::test', 'input') sock.close() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert not os.path.exists('input/unix-socket') @pytest.mark.skipif(not are_symlinks_supported(), reason='symlinks not supported') def test_symlink_extract(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.readlink('input/link1') == 'somewhere' @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') def test_atime(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: with open(os.open(some_file, flags_noatime)) as file: file.read() except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.create_test_files() atime, mtime = 123456780, 234567890 have_noatime = has_noatime('input/file1') os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--atime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 if have_noatime: assert sti.st_atime_ns == sto.st_atime_ns == atime * 1e9 else: # it touched the input file's atime while backing it up assert sto.st_atime_ns == atime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_birthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == int(sto.st_birthtime * 1e9) == birthtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_nobirthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--nobirthtime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == birthtime * 1e9 assert int(sto.st_birthtime * 1e9) == mtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 def _extract_repository_id(self, path): with Repository(self.repository_path) as repository: return repository.id def _set_repository_id(self, path, id): config = ConfigParser(interpolation=None) config.read(os.path.join(path, 'config')) config.set('repository', 'id', bin_to_hex(id)) with open(os.path.join(path, 'config'), 'w') as fd: config.write(fd) with Repository(self.repository_path) as repository: return repository.id def test_sparse_file(self): def is_sparse(fn, total_size, hole_size): st = os.stat(fn) assert st.st_size == total_size sparse = True if sparse and hasattr(st, 'st_blocks') and st.st_blocks * 512 >= st.st_size: sparse = False if sparse and has_seek_hole: with open(fn, 'rb') as fd: # only check if the first hole is as expected, because the 2nd hole check # is problematic on xfs due to its "dynamic speculative EOF preallocation try: if fd.seek(0, os.SEEK_HOLE) != 0: sparse = False if fd.seek(0, os.SEEK_DATA) != hole_size: sparse = False except OSError: # OS/FS does not really support SEEK_HOLE/SEEK_DATA sparse = False return sparse filename = os.path.join(self.input_path, 'sparse') content = b'foobar' hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers total_size = hole_size + len(content) + hole_size with open(filename, 'wb') as fd: # create a file that has a hole at the beginning and end (if the # OS and filesystem supports sparse files) fd.seek(hole_size, 1) fd.write(content) fd.seek(hole_size, 1) pos = fd.tell() fd.truncate(pos) # we first check if we could create a sparse input file: sparse_support = is_sparse(filename, total_size, hole_size) if sparse_support: # we could create a sparse input file, so creating a backup of it and # extracting it again (as sparse) should also work: self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir(self.output_path): self.cmd('extract', '--sparse', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') filename = os.path.join(self.output_path, 'input', 'sparse') with open(filename, 'rb') as fd: # check if file contents are as expected self.assert_equal(fd.read(hole_size), b'\0' * hole_size) self.assert_equal(fd.read(len(content)), content) self.assert_equal(fd.read(hole_size), b'\0' * hole_size) self.assert_true(is_sparse(filename, total_size, hole_size)) def test_unusual_filenames(self): filenames = ['normal', 'with some blanks', '(with_parens)', ] for filename in filenames: filename = os.path.join(self.input_path, filename) with open(filename, 'wb'): pass self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') for filename in filenames: with changedir('output'): self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename)) assert os.path.exists(os.path.join('output', 'input', filename)) def test_repository_swap_detection(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_no_cache(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) self.cmd('delete', '--cache-only', self.repository_location) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2_no_cache(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') self.cmd('delete', '--cache-only', self.repository_location + '_unencrypted') self.cmd('delete', '--cache-only', self.repository_location + '_encrypted') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_repokey_blank_passphrase(self): # Check that a repokey repo with a blank passphrase is considered like a plaintext repo. self.create_test_files() # User initializes her repository with her passphrase self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Attacker replaces it with her own repository, which is encrypted but has no passphrase set shutil.rmtree(self.repository_path) with environment_variable(BORG_PASSPHRASE=''): self.cmd('init', '--encryption=repokey', self.repository_location) # Delete cache & security database, AKA switch to user perspective self.cmd('delete', '--cache-only', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) shutil.rmtree(get_security_dir(repository_id)) with environment_variable(BORG_PASSPHRASE=None): # This is the part were the user would be tricked, e.g. she assumes that BORG_PASSPHRASE # is set, while it isn't. Previously this raised no warning, # since the repository is, technically, encrypted. if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_move(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) os.rename(self.repository_path, self.repository_path + '_new') with environment_variable(BORG_RELOCATED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location + '_new') security_dir = get_security_dir(repository_id) with open(os.path.join(security_dir, 'location')) as fd: location = fd.read() assert location == Location(self.repository_location + '_new').canonical_path() # Needs no confirmation anymore self.cmd('info', self.repository_location + '_new') shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location + '_new') shutil.rmtree(security_dir) self.cmd('info', self.repository_location + '_new') for file in ('location', 'key-type', 'manifest-timestamp'): assert os.path.exists(os.path.join(security_dir, file)) def test_security_dir_compat(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) security_dir = get_security_dir(repository_id) with open(os.path.join(security_dir, 'location'), 'w') as fd: fd.write('something outdated') # This is fine, because the cache still has the correct information. security_dir and cache can disagree # if older versions are used to confirm a renamed repository. self.cmd('info', self.repository_location) def test_unknown_unencrypted(self): self.cmd('init', '--encryption=none', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) security_dir = get_security_dir(repository_id) # Ok: repository is known self.cmd('info', self.repository_location) # Ok: repository is still known (through security_dir) shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location) # Needs confirmation: cache and security dir both gone (eg. another host or rm -rf ~) shutil.rmtree(self.cache_path) shutil.rmtree(security_dir) if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('info', self.repository_location) with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location) def test_strip_components(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '3') self.assert_true(not os.path.exists('file')) with self.assert_creates_file('file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') with self.assert_creates_file('dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '1') with self.assert_creates_file('input/dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '0') def _extract_hardlinks_setup(self): os.mkdir(os.path.join(self.input_path, 'dir1')) os.mkdir(os.path.join(self.input_path, 'dir1/subdir')) self.create_regular_file('source', contents=b'123456') os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'abba')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/hardlink')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/subdir/hardlink')) self.create_regular_file('dir1/source2') os.link(os.path.join(self.input_path, 'dir1/source2'), os.path.join(self.input_path, 'dir1/aaaa')) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') @requires_hardlinks @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_hardlinks(self): self._extract_hardlinks_setup() mountpoint = os.path.join(self.tmpdir, 'mountpoint') # we need to get rid of permissions checking because fakeroot causes issues with it. # On all platforms, borg defaults to "default_permissions" and we need to get rid of it via "ignore_permissions". # On macOS (darwin), we additionally need "defer_permissions" to switch off the checks in osxfuse. if sys.platform == 'darwin': ignore_perms = ['-o', 'ignore_permissions,defer_permissions'] else: ignore_perms = ['-o', 'ignore_permissions'] with self.fuse_mount(self.repository_location + '::test', mountpoint, '--strip-components=2', *ignore_perms), \ changedir(mountpoint): assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, 'input/dir1', *ignore_perms), \ changedir(mountpoint): assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, *ignore_perms), \ changedir(mountpoint): assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks1(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks2(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/dir1') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 @requires_hardlinks def test_extract_hardlinks_twice(self): # setup for #5603 path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') # give input twice! # now test extraction with changedir('output'): self.cmd('extract', self.repository_location + '::test') # if issue #5603 happens, extraction gives rc == 1 (triggering AssertionError) and warnings like: # input/a/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/a/hardlink' # input/b/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/b/hardlink' # otherwise, when fixed, the hardlinks should be there and have a link count of 2 assert os.stat('input/a/hardlink').st_nlink == 2 assert os.stat('input/b/hardlink').st_nlink == 2 def test_extract_include_exclude(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/file1', ) self.assert_equal(sorted(os.listdir('output/input')), ['file1']) with changedir('output'): self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) def test_extract_include_exclude_regex(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) # Create with regular expression exclusion for file4 self.cmd('create', '--exclude=re:input/file4$', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Extract with regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude=re:file3+', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Combine --exclude with fnmatch and regular expression with changedir('output'): self.cmd('extract', '--exclude=input/file2', '--exclude=re:file[01]', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3', 'file333']) shutil.rmtree('output/input') # Combine --exclude-from and regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, '--exclude=re:file1', '--exclude=re:file(\\d)\\1\\1$', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_include_exclude_regex_from_file(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) self.create_regular_file('aa:something', size=1024 * 80) # Create while excluding using mixed pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:input/file4$\n') fd.write(b'fm:*aa:*thing\n') self.cmd('create', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Exclude using regular expression with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file3+\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Mixed exclude pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file(\\d)\\1\\1$\n') fd.write(b'fm:nothingwillmatchthis\n') fd.write(b'*/file1\n') fd.write(b're:file2$\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_with_pattern(self): self.cmd("init", '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) self.create_regular_file("file333", size=1024 * 80) self.cmd("create", self.repository_location + "::test", "input") # Extract everything with regular expression with changedir("output"): self.cmd("extract", self.repository_location + "::test", "re:.*") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file3", "file333", "file4"]) shutil.rmtree("output/input") # Extract with pattern while also excluding files with changedir("output"): self.cmd("extract", "--exclude=re:file[34]$", self.repository_location + "::test", r"re:file\d$") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2"]) shutil.rmtree("output/input") # Combine --exclude with pattern for extraction with changedir("output"): self.cmd("extract", "--exclude=input/file1", self.repository_location + "::test", "re:file[12]$") self.assert_equal(sorted(os.listdir("output/input")), ["file2"]) shutil.rmtree("output/input") # Multiple pattern with changedir("output"): self.cmd("extract", self.repository_location + "::test", "fm:input/file1", "fm:*file33*", "input/file2") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file333"]) def test_extract_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--info', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', self.repository_location + '::test') self.assert_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', '--info', self.repository_location + '::test') self.assert_in("input/file", output) def test_extract_progress(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test', '--progress') assert 'Extracting:' in output def _create_test_caches(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('cache1/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('cache2/%s' % CACHE_TAG_NAME, contents=b'invalid signature') os.mkdir('input/cache3') if are_hardlinks_supported(): os.link('input/cache1/%s' % CACHE_TAG_NAME, 'input/cache3/%s' % CACHE_TAG_NAME) else: self.create_regular_file('cache3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') def test_create_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = b'\x00foo\n\nbar\n \n' self.cmd('create', self.repository_location + '::test', '-', input=input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) assert item['path'] == 'stdin' extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test', binary_output=True) assert extracted_data == input_data def test_create_content_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = 'some test content' name = 'a/b/c' self.cmd('create', '--stdin-name', name, '--content-from-command', self.repository_location + '::test', '--', 'echo', input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) + 1 # `echo` adds newline assert item['path'] == name extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test') assert extracted_data == input_data + '\n' def test_create_content_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_content_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_paths_from_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("dir1/file2", size=1024 * 80) self.create_regular_file("dir1/file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = b'input/file1\0input/dir1\0input/file4' self.cmd('create', '--paths-from-stdin', '--paths-delimiter', '\\0', self.repository_location + '::test', input=input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/dir1', 'input/file4'] def test_create_paths_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = 'input/file1\ninput/file2\ninput/file3' self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'echo', input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/file2', 'input/file3'] def test_create_paths_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_paths_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_without_root(self): """test create without a root""" self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', exit_code=2) def test_create_pattern_root(self): """test create with only a root pattern""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=R input', self.repository_location + '::test') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) def test_create_pattern(self): """test file patterns during create""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) def test_create_pattern_file(self): """test file patterns during create""" self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('otherfile', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=-input/otherfile', '--patterns-from=' + self.patterns_file_path, self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) self.assert_in('x input/otherfile', output) def test_create_pattern_exclude_folder_but_recurse(self): """test when patterns exclude a parent folder, but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_in('x input/x/a/foo_a', output) self.assert_in("A input/x/b/foo_b", output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_exclude_folder_no_recurse(self): """test when patterns exclude a parent folder and, but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n! input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_not_in('input/x/a/foo_a', output) self.assert_not_in('input/x/a', output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_intermediate_folders_first(self): """test that intermediate folders appear first when patterns exclude a parent folder but include a child""" self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/a\n+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) with changedir('input'): self.cmd('create', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', '.') # list the archive and verify that the "intermediate" folders appear before # their contents out = self.cmd('list', '--format', '{type} {path}{NL}', self.repository_location + '::test') out_list = out.splitlines() self.assert_in('d x/a', out_list) self.assert_in('d x/b', out_list) assert out_list.index('d x/a') < out_list.index('- x/a/foo_a') assert out_list.index('d x/b') < out_list.index('- x/b/foo_b') def test_create_no_cache_sync(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) create_json = json.loads(self.cmd('create', '--no-cache-sync', self.repository_location + '::test', 'input', '--json', '--error')) # ignore experimental warning info_json = json.loads(self.cmd('info', self.repository_location + '::test', '--json')) create_stats = create_json['cache']['stats'] info_stats = info_json['cache']['stats'] assert create_stats == info_stats self.cmd('delete', '--cache-only', self.repository_location) self.cmd('create', '--no-cache-sync', self.repository_location + '::test2', 'input') self.cmd('info', self.repository_location) self.cmd('check', self.repository_location) def test_extract_pattern_opt(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file_important']) def _assert_test_caches(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1']) self.assert_equal(sorted(os.listdir('output/input/cache2')), [CACHE_TAG_NAME]) def test_exclude_caches(self): self._create_test_caches() self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input') self._assert_test_caches() def test_recreate_exclude_caches(self): self._create_test_caches() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-caches', self.repository_location + '::test') self._assert_test_caches() def _create_test_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('tagged1/.NOBACKUP') self.create_regular_file('tagged2/00-NOBACKUP') self.create_regular_file('tagged3/.NOBACKUP/file2', size=1024) def _assert_test_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1']) def test_exclude_tagged(self): self._create_test_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input') self._assert_test_tagged() def test_recreate_exclude_tagged(self): self._create_test_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test') self._assert_test_tagged() def _create_test_keep_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file0', size=1024) self.create_regular_file('tagged1/.NOBACKUP1') self.create_regular_file('tagged1/file1', size=1024) self.create_regular_file('tagged2/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('tagged2/file2', size=1024) self.create_regular_file('tagged3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('tagged3/file3', size=1024) self.create_regular_file('taggedall/.NOBACKUP1') self.create_regular_file('taggedall/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('taggedall/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('taggedall/file4', size=1024) def _assert_test_keep_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall']) self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1']) self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2']) self.assert_equal(os.listdir('output/input/tagged3'), [CACHE_TAG_NAME]) self.assert_equal(sorted(os.listdir('output/input/taggedall')), ['.NOBACKUP1', '.NOBACKUP2', CACHE_TAG_NAME, ]) def test_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test', 'input') self._assert_test_keep_tagged() def test_recreate_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') self._assert_test_keep_tagged() @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_hardlinked_tags(self): # test for issue #4911 self.cmd('init', '--encryption=none', self.repository_location) self.create_regular_file('file1', contents=CACHE_TAG_CONTENTS) # "wrong" filename, but correct tag contents os.mkdir(os.path.join(self.input_path, 'subdir')) # to make sure the tag is encountered *after* file1 os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'subdir', CACHE_TAG_NAME)) # correct tag name, hardlink to file1 self.cmd('create', self.repository_location + '::test', 'input') # in the "test" archive, we now have, in this order: # - a regular file item for "file1" # - a hardlink item for "CACHEDIR.TAG" referring back to file1 for its contents self.cmd('recreate', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') # if issue #4911 is present, the recreate will crash with a KeyError for "input/file1" @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='Linux capabilities test, requires fakeroot >= 1.20.2') def test_extract_capabilities(self): fchown = os.fchown # We need to manually patch chown to get the behaviour Linux has, since fakeroot does not # accurately model the interaction of chown(2) and Linux capabilities, i.e. it does not remove them. def patched_fchown(fd, uid, gid): xattr.setxattr(fd, b'security.capability', b'', follow_symlinks=False) fchown(fd, uid, gid) # The capability descriptor used here is valid and taken from a /usr/bin/ping capabilities = b'\x01\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.create_regular_file('file') xattr.setxattr(b'input/file', b'security.capability', capabilities) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): with patch.object(os, 'fchown', patched_fchown): self.cmd('extract', self.repository_location + '::test') assert xattr.getxattr(b'input/file', b'security.capability') == capabilities @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='xattr not supported on this system or on this version of' 'fakeroot') def test_extract_xattrs_errors(self): def patched_setxattr_E2BIG(*args, **kwargs): raise OSError(errno.E2BIG, 'E2BIG') def patched_setxattr_ENOTSUP(*args, **kwargs): raise OSError(errno.ENOTSUP, 'ENOTSUP') def patched_setxattr_EACCES(*args, **kwargs): raise OSError(errno.EACCES, 'EACCES') self.create_regular_file('file') xattr.setxattr(b'input/file', b'user.attribute', b'value') self.cmd('init', self.repository_location, '-e' 'none') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): input_abspath = os.path.abspath('input/file') with patch.object(xattr, 'setxattr', patched_setxattr_E2BIG): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: too big for this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_ENOTSUP): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: xattrs not supported on this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_EACCES): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: Permission denied\n' in out assert os.path.isfile(input_abspath) def test_path_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir1/dir2/file', size=1024 * 80) with changedir('input/dir1/dir2'): self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..') output = self.cmd('list', self.repository_location + '::test') self.assert_not_in('..', output) self.assert_in(' input/dir1/dir2/file', output) def test_exclude_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) with changedir('input'): self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test1') self.assert_equal(sorted(os.listdir('output')), ['file2']) with changedir('input'): self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test2') self.assert_equal(sorted(os.listdir('output')), ['file2']) self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test3') self.assert_equal(sorted(os.listdir('output/input')), ['file2']) def test_repeated_files(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') def test_overwrite(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Overwriting regular files and directories should be supported os.mkdir('output/input') os.mkdir('output/input/file1') os.mkdir('output/input/dir2') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') # But non-empty dirs should fail os.unlink('output/input/file1') os.mkdir('output/input/file1') os.mkdir('output/input/file1/dir') with changedir('output'): self.cmd('extract', self.repository_location + '::test', exit_code=1) def test_rename(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test', 'test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test.2', 'test.4') self.cmd('extract', '--dry-run', self.repository_location + '::test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.4') # Make sure both archives have been renamed with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 2) self.assert_in('test.3', manifest.archives) self.assert_in('test.4', manifest.archives) def test_info(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = self.cmd('info', self.repository_location) assert 'All archives:' in info_repo info_archive = self.cmd('info', self.repository_location + '::test') assert 'Archive name: test\n' in info_archive info_archive = self.cmd('info', '--first', '1', self.repository_location) assert 'Archive name: test\n' in info_archive def test_info_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = json.loads(self.cmd('info', '--json', self.repository_location)) repository = info_repo['repository'] assert len(repository['id']) == 64 assert 'last_modified' in repository assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert info_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in info_repo['encryption'] cache = info_repo['cache'] stats = cache['stats'] assert all(isinstance(o, int) for o in stats.values()) assert all(key in stats for key in ('total_chunks', 'total_csize', 'total_size', 'total_unique_chunks', 'unique_csize', 'unique_size')) info_archive = json.loads(self.cmd('info', '--json', self.repository_location + '::test')) assert info_repo['repository'] == info_archive['repository'] assert info_repo['cache'] == info_archive['cache'] archives = info_archive['archives'] assert len(archives) == 1 archive = archives[0] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive assert datetime.strptime(archive['start'], ISO_FORMAT) assert datetime.strptime(archive['end'], ISO_FORMAT) def test_comment(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', '--comment', 'this is the comment', self.repository_location + '::test2', 'input') self.cmd('create', '--comment', '"deleted" comment', self.repository_location + '::test3', 'input') self.cmd('create', '--comment', 'preserved comment', self.repository_location + '::test4', 'input') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: this is the comment' in self.cmd('info', self.repository_location + '::test2') self.cmd('recreate', self.repository_location + '::test1', '--comment', 'added comment') self.cmd('recreate', self.repository_location + '::test2', '--comment', 'modified comment') self.cmd('recreate', self.repository_location + '::test3', '--comment', '') self.cmd('recreate', self.repository_location + '::test4', '12345') assert 'Comment: added comment' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: modified comment' in self.cmd('info', self.repository_location + '::test2') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test3') assert 'Comment: preserved comment' in self.cmd('info', self.repository_location + '::test4') def test_delete(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('create', self.repository_location + '::test.3', 'input') self.cmd('create', self.repository_location + '::another_test.1', 'input') self.cmd('create', self.repository_location + '::another_test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('delete', '--prefix', 'another_', self.repository_location) self.cmd('delete', '--last', '1', self.repository_location) self.cmd('delete', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') output = self.cmd('delete', '--stats', self.repository_location + '::test.2') self.assert_in('Deleted data:', output) # Make sure all data except the manifest has been deleted with Repository(self.repository_path) as repository: self.assert_equal(len(repository), 1) def test_delete_multiple(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('create', self.repository_location + '::test3', 'input') self.cmd('delete', self.repository_location + '::test1', 'test2') self.cmd('extract', '--dry-run', self.repository_location + '::test3') self.cmd('delete', self.repository_location, 'test3') assert not self.cmd('list', self.repository_location) def test_delete_repo(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'no' self.cmd('delete', self.repository_location, exit_code=2) assert os.path.exists(self.repository_path) os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' self.cmd('delete', self.repository_location) # Make sure the repo is gone self.assertFalse(os.path.exists(self.repository_path)) def test_delete_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) break else: assert False # missed the file repository.commit(compact=False) output = self.cmd('delete', '--force', self.repository_location + '::test') self.assert_in('deleted archive was corrupted', output) self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_delete_double_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') id = archive.metadata.items[0] repository.put(id, b'corrupted items metadata stream chunk') repository.commit(compact=False) self.cmd('delete', '--force', '--force', self.repository_location + '::test') self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_corrupted_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') self.cmd('extract', '--dry-run', self.repository_location + '::test') output = self.cmd('check', '--show-version', self.repository_location) self.assert_in('borgbackup version', output) # implied output even without --info given self.assert_not_in('Starting repository check', output) # --info not given for root logger name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[1] with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd: fd.seek(100) fd.write(b'XXXX') output = self.cmd('check', '--info', self.repository_location, exit_code=1) self.assert_in('Starting repository check', output) # --info given for root logger def test_readonly_check(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('check', '--verify-data', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('check', '--verify-data', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('check', '--verify-data', self.repository_location, '--bypass-lock') def test_readonly_diff(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('a') self.create_src_archive('b') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('diff', '%s::a' % self.repository_location, 'b', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('diff', '%s::a' % self.repository_location, 'b') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('diff', '%s::a' % self.repository_location, 'b', '--bypass-lock') def test_readonly_export_tar(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', '--bypass-lock') def test_readonly_extract(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('extract', '%s::test' % self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('extract', '%s::test' % self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('extract', '%s::test' % self.repository_location, '--bypass-lock') def test_readonly_info(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('info', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('info', self.repository_location, '--bypass-lock') def test_readonly_list(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('list', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('list', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('list', self.repository_location, '--bypass-lock') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_readonly_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: with self.fuse_mount(self.repository_location, exit_code=EXIT_ERROR): pass else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: # self.fuse_mount always assumes fork=True, so for this test we have to manually set fork=False with self.fuse_mount(self.repository_location, fork=False): pass if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock with self.fuse_mount(self.repository_location, None, '--bypass-lock'): pass @pytest.mark.skipif('BORG_TESTS_IGNORE_MODES' in os.environ, reason='modes unreliable') def test_umask(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') mode = os.stat(self.repository_path).st_mode self.assertEqual(stat.S_IMODE(mode), 0o700) def test_create_dry_run(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--dry-run', self.repository_location + '::test', 'input') # Make sure no archive has been created with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 0) def add_unknown_feature(self, operation): with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) manifest.config[b'feature_flags'] = {operation.value.encode(): {b'mandatory': [b'unknown-feature']}} manifest.write() repository.commit(compact=False) def cmd_raises_unknown_feature(self, args): if self.FORK_DEFAULT: self.cmd(*args, exit_code=EXIT_ERROR) else: with pytest.raises(MandatoryFeatureUnsupported) as excinfo: self.cmd(*args) assert excinfo.value.args == (['unknown-feature'],) def test_unknown_feature_on_create(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.WRITE) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_cache_sync(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) self.add_unknown_feature(Manifest.Operation.READ) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_change_passphrase(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['key', 'change-passphrase', self.repository_location]) def test_unknown_feature_on_read(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) with changedir('output'): self.cmd_raises_unknown_feature(['extract', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['list', self.repository_location]) self.cmd_raises_unknown_feature(['info', self.repository_location + '::test']) def test_unknown_feature_on_rename(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['rename', self.repository_location + '::test', 'other']) def test_unknown_feature_on_delete(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.DELETE) # delete of an archive raises self.cmd_raises_unknown_feature(['delete', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['prune', '--keep-daily=3', self.repository_location]) # delete of the whole repository ignores features self.cmd('delete', self.repository_location) @unittest.skipUnless(llfuse, 'llfuse not installed') def test_unknown_feature_on_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) mountpoint = os.path.join(self.tmpdir, 'mountpoint') os.mkdir(mountpoint) # XXX this might hang if it doesn't raise an error self.cmd_raises_unknown_feature(['mount', self.repository_location + '::test', mountpoint]) @pytest.mark.allow_cache_wipe def test_unknown_mandatory_feature_in_cache(self): if self.prefix: path_prefix = 'ssh://__testsuite__' else: path_prefix = '' print(self.cmd('init', '--encryption=repokey', self.repository_location)) with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: cache.begin_txn() cache.cache_config.mandatory_features = set(['unknown-feature']) cache.commit() if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test', 'input') else: called = False wipe_cache_safe = LocalCache.wipe_cache def wipe_wrapper(*args): nonlocal called called = True wipe_cache_safe(*args) with patch.object(LocalCache, 'wipe_cache', wipe_wrapper): self.cmd('create', self.repository_location + '::test', 'input') assert called with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: assert cache.cache_config.mandatory_features == set([]) def test_progress_on(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input') self.assert_in("\r", output) def test_progress_off(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', self.repository_location + '::test5', 'input') self.assert_not_in("\r", output) def test_file_status(self): """test that various file status show expected results clearly incomplete: only tests for the weird "unchanged" status for now""" self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) # should find first file as unmodified output = self.cmd('create', '--list', self.repository_location + '::test1', 'input') self.assert_in("U input/file1", output) # this is expected, although surprising, for why, see: # https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file self.assert_in("A input/file2", output) def test_file_status_cs_cache_mode(self): """test that a changed file with faked "previous" mtime still gets backed up in ctime,size cache_mode""" self.create_regular_file('file1', contents=b'123') time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test1', 'input') # modify file1, but cheat with the mtime (and atime) and also keep same size: st = os.stat('input/file1') self.create_regular_file('file1', contents=b'321') os.utime('input/file1', ns=(st.st_atime_ns, st.st_mtime_ns)) # this mode uses ctime for change detection, so it should find file1 as modified output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test2', 'input') self.assert_in("M input/file1", output) def test_file_status_ms_cache_mode(self): """test that a chmod'ed file with no content changes does not get chunked again in mtime,size cache_mode""" self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test1', 'input') # change mode of file1, no content change: st = os.stat('input/file1') os.chmod('input/file1', st.st_mode ^ stat.S_IRWXO) # this triggers a ctime change, but mtime is unchanged # this mode uses mtime for change detection, so it should find file1 as unmodified output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test2', 'input') self.assert_in("U input/file1", output) def test_file_status_rc_cache_mode(self): """test that files get rechunked unconditionally in rechunk,ctime cache mode""" self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test1', 'input') # no changes here, but this mode rechunks unconditionally output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test2', 'input') self.assert_in("A input/file1", output) def test_file_status_excluded(self): """test that excluded paths are listed""" self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) if has_lchflags: self.create_regular_file('file3', size=1024 * 80) platform.set_flags(os.path.join(self.input_path, 'file3'), stat.UF_NODUMP) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) # should find second file as excluded output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test1', 'input', '--exclude', '*/file2') self.assert_in("U input/file1", output) self.assert_in("x input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) def test_create_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) create_info = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) # The usual keys assert 'encryption' in create_info assert 'repository' in create_info assert 'cache' in create_info assert 'last_modified' in create_info['repository'] archive = create_info['archive'] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive def test_create_topical(self): self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) # no listing by default output = self.cmd('create', self.repository_location + '::test', 'input') self.assert_not_in('file1', output) # shouldn't be listed even if unchanged output = self.cmd('create', self.repository_location + '::test0', 'input') self.assert_not_in('file1', output) # should list the file as unchanged output = self.cmd('create', '--list', '--filter=U', self.repository_location + '::test1', 'input') self.assert_in('file1', output) # should *not* list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test2', 'input') self.assert_not_in('file1', output) # change the file self.create_regular_file('file1', size=1024 * 100) # should list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test3', 'input') self.assert_in('file1', output) @pytest.mark.skipif(not are_fifos_supported(), reason='FIFOs not supported') def test_create_read_special_symlink(self): from threading import Thread def fifo_feeder(fifo_fn, data): fd = os.open(fifo_fn, os.O_WRONLY) try: os.write(fd, data) finally: os.close(fd) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' data = b'foobar' * 1000 fifo_fn = os.path.join(self.input_path, 'fifo') link_fn = os.path.join(self.input_path, 'link_fifo') os.mkfifo(fifo_fn) os.symlink(fifo_fn, link_fn) t = Thread(target=fifo_feeder, args=(fifo_fn, data)) t.start() try: self.cmd('create', '--read-special', archive, 'input/link_fifo') finally: t.join() with changedir('output'): self.cmd('extract', archive) fifo_fn = 'input/link_fifo' with open(fifo_fn, 'rb') as f: extracted_data = f.read() assert extracted_data == data def test_create_read_special_broken_symlink(self): os.symlink('somewhere does not exist', os.path.join(self.input_path, 'link')) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '--read-special', archive, 'input') output = self.cmd('list', archive) assert 'input/link -> somewhere does not exist' in output # def test_cmdline_compatibility(self): # self.create_regular_file('file1', size=1024 * 80) # self.cmd('init', '--encryption=repokey', self.repository_location) # self.cmd('create', self.repository_location + '::test', 'input') # output = self.cmd('foo', self.repository_location, '--old') # self.assert_in('"--old" has been deprecated. Use "--new" instead', output) def test_prune_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test3.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) self.cmd('create', self.repository_location + '::test4.checkpoint', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Would prune:\s+test1', output) # must keep the latest non-checkpoint archive: assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) # must keep the latest checkpoint archive: assert re.search(r'Keeping checkpoint archive:\s+test4.checkpoint', output) output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.assert_in('test3.checkpoint', output) self.assert_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) self.cmd('prune', self.repository_location, '--keep-daily=1') output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_not_in('test1', output) # the latest non-checkpoint archive must be still there: self.assert_in('test2', output) # only the latest checkpoint archive must still be there: self.assert_not_in('test3.checkpoint', output) self.assert_not_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) # now we supercede the latest checkpoint by a successful backup: self.cmd('create', self.repository_location + '::test5', src_dir) self.cmd('prune', self.repository_location, '--keep-daily=2') output = self.cmd('list', '--consider-checkpoints', self.repository_location) # all checkpoints should be gone now: self.assert_not_in('checkpoint', output) # the latest archive must be still there self.assert_in('test5', output) # Given a date and time in local tz, create a UTC timestamp string suitable # for create --timestamp command line option def _to_utc_timestamp(self, year, month, day, hour, minute, second): dtime = datetime(year, month, day, hour, minute, second, 0, dateutil.tz.gettz()) return dtime.astimezone(dateutil.tz.UTC).strftime("%Y-%m-%dT%H:%M:%S") def _create_archive_ts(self, name, y, m, d, H=0, M=0, S=0): loc = self.repository_location + '::' + name self.cmd('create', '--timestamp', self._to_utc_timestamp(y, m, d, H, M, S), loc, src_dir) # This test must match docs/misc/prune-example.txt def test_prune_repository_example(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Archives that will be kept, per the example # Oldest archive self._create_archive_ts('test01', 2015, 1, 1) # 6 monthly archives self._create_archive_ts('test02', 2015, 6, 30) self._create_archive_ts('test03', 2015, 7, 31) self._create_archive_ts('test04', 2015, 8, 31) self._create_archive_ts('test05', 2015, 9, 30) self._create_archive_ts('test06', 2015, 10, 31) self._create_archive_ts('test07', 2015, 11, 30) # 14 daily archives self._create_archive_ts('test08', 2015, 12, 17) self._create_archive_ts('test09', 2015, 12, 18) self._create_archive_ts('test10', 2015, 12, 20) self._create_archive_ts('test11', 2015, 12, 21) self._create_archive_ts('test12', 2015, 12, 22) self._create_archive_ts('test13', 2015, 12, 23) self._create_archive_ts('test14', 2015, 12, 24) self._create_archive_ts('test15', 2015, 12, 25) self._create_archive_ts('test16', 2015, 12, 26) self._create_archive_ts('test17', 2015, 12, 27) self._create_archive_ts('test18', 2015, 12, 28) self._create_archive_ts('test19', 2015, 12, 29) self._create_archive_ts('test20', 2015, 12, 30) self._create_archive_ts('test21', 2015, 12, 31) # Additional archives that would be pruned # The second backup of the year self._create_archive_ts('test22', 2015, 1, 2) # The next older monthly backup self._create_archive_ts('test23', 2015, 5, 31) # The next older daily backup self._create_archive_ts('test24', 2015, 12, 16) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') # Prune second backup of the year assert re.search(r'Would prune:\s+test22', output) # Prune next older monthly and daily backups assert re.search(r'Would prune:\s+test23', output) assert re.search(r'Would prune:\s+test24', output) # Must keep the other 21 backups # Yearly is kept as oldest archive assert re.search(r'Keeping archive \(rule: yearly\[oldest\] #1\):\s+test01', output) for i in range(1, 7): assert re.search(r'Keeping archive \(rule: monthly #' + str(i) + r'\):\s+test' + ("%02d" % (8-i)), output) for i in range(1, 15): assert re.search(r'Keeping archive \(rule: daily #' + str(i) + r'\):\s+test' + ("%02d" % (22-i)), output) output = self.cmd('list', self.repository_location) # Nothing pruned after dry run for i in range(1, 25): self.assert_in('test%02d' % i, output) self.cmd('prune', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') output = self.cmd('list', self.repository_location) # All matching backups plus oldest kept for i in range(1, 22): self.assert_in('test%02d' % i, output) # Other backups have been pruned for i in range(22, 25): self.assert_not_in('test%02d' % i, output) # With an initial and daily backup, prune daily until oldest is replaced by a monthly backup def test_prune_retain_and_expire_oldest(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Initial backup self._create_archive_ts('original_archive', 2020, 9, 1, 11, 15) # Archive and prune daily for 30 days for i in range(1, 31): self._create_archive_ts('september%02d' % i, 2020, 9, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Archive and prune 6 days into the next month for i in range(1, 7): self._create_archive_ts('october%02d' % i, 2020, 10, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Oldest backup is still retained output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly\[oldest\] #1' + r'\):\s+original_archive', output) # Archive one more day and prune. self._create_archive_ts('october07', 2020, 10, 7, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Last day of previous month is retained as monthly, and oldest is expired. output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly #1\):\s+september30', output) self.assert_not_in('original_archive', output) def test_prune_repository_save_space(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) assert re.search(r'Would prune:\s+test1', output) output = self.cmd('list', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=1') output = self.cmd('list', self.repository_location) self.assert_not_in('test1', output) self.assert_in('test2', output) def test_prune_repository_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--prefix=foo-') assert re.search(r'Keeping archive \(rule: daily #1\):\s+foo-2015-08-12-20:00', output) assert re.search(r'Would prune:\s+foo-2015-08-12-10:00', output) output = self.cmd('list', self.repository_location) self.assert_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--prefix=foo-') output = self.cmd('list', self.repository_location) self.assert_not_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) def test_prune_repository_glob(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::2015-08-12-10:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-10:00-bar', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-bar', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') assert re.search(r'Keeping archive \(rule: daily #1\):\s+2015-08-12-20:00-foo', output) assert re.search(r'Would prune:\s+2015-08-12-10:00-foo', output) output = self.cmd('list', self.repository_location) self.assert_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') output = self.cmd('list', self.repository_location) self.assert_not_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) def test_list_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test-1', src_dir) self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir) self.cmd('create', self.repository_location + '::test-2', src_dir) output = self.cmd('list', '--prefix=test-', self.repository_location) self.assert_in('test-1', output) self.assert_in('test-2', output) self.assert_not_in('something-else', output) def test_list_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, src_dir) output_1 = self.cmd('list', test_archive) output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {mtime} {path}{extra}{NEWLINE}', test_archive) output_3 = self.cmd('list', '--format', '{mtime:%s} {path}{NL}', test_archive) self.assertEqual(output_1, output_2) self.assertNotEqual(output_1, output_3) def test_list_repository_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--comment', 'comment 1', self.repository_location + '::test-1', src_dir) self.cmd('create', '--comment', 'comment 2', self.repository_location + '::test-2', src_dir) output_1 = self.cmd('list', self.repository_location) output_2 = self.cmd('list', '--format', '{archive:<36} {time} [{id}]{NL}', self.repository_location) self.assertEqual(output_1, output_2) output_1 = self.cmd('list', '--short', self.repository_location) self.assertEqual(output_1, 'test-1\ntest-2\n') output_1 = self.cmd('list', '--format', '{barchive}/', self.repository_location) self.assertEqual(output_1, 'test-1/test-2/') output_3 = self.cmd('list', '--format', '{name} {comment}{NL}', self.repository_location) self.assert_in('test-1 comment 1\n', output_3) self.assert_in('test-2 comment 2\n', output_3) def test_list_hash(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('amb', contents=b'a' * 1000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{sha256} {path}{NL}', test_archive) assert "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 input/amb" in output assert "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 input/empty_file" in output def test_list_consider_checkpoints(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test2.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) output = self.cmd('list', self.repository_location) assert "test1" in output assert "test2.checkpoint" not in output assert "test3.checkpoint.1" not in output output = self.cmd('list', '--consider-checkpoints', self.repository_location) assert "test1" in output assert "test2.checkpoint" in output assert "test3.checkpoint.1" in output def test_list_chunk_counts(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('two_chunks') with open(os.path.join(self.input_path, 'two_chunks'), 'wb') as fd: fd.write(b'abba' * 2000000) fd.write(b'baab' * 2000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{num_chunks} {unique_chunks} {path}{NL}', test_archive) assert "0 0 input/empty_file" in output assert "2 2 input/two_chunks" in output def test_list_size(self): self.create_regular_file('compressible_file', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', '-C', 'lz4', test_archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {dsize} {dcsize} {path}{NL}', test_archive) size, csize, dsize, dcsize, path = output.split("\n")[1].split(" ") assert int(csize) < int(size) assert int(dcsize) < int(dsize) assert int(dsize) <= int(size) assert int(dcsize) <= int(csize) def test_list_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list_repo = json.loads(self.cmd('list', '--json', self.repository_location)) repository = list_repo['repository'] assert len(repository['id']) == 64 assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert list_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in list_repo['encryption'] archive0 = list_repo['archives'][0] assert datetime.strptime(archive0['time'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['size'] == 81920 assert datetime.strptime(file1['mtime'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', '--format={sha256}', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['sha256'] == 'b2915eb69f260d8d3c25249195f2c8f4f716ea82ec760ae929732c0262442b2b' def test_list_json_args(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('list', '--json-lines', self.repository_location, exit_code=2) self.cmd('list', '--json', self.repository_location + '::archive', exit_code=2) def test_log_json(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('create', '--log-json', self.repository_location + '::test', 'input', '--list', '--debug') messages = {} # type -> message, one of each kind for line in log.splitlines(): msg = json.loads(line) messages[msg['type']] = msg file_status = messages['file_status'] assert 'status' in file_status assert file_status['path'].startswith('input') log_message = messages['log_message'] assert isinstance(log_message['time'], float) assert log_message['levelname'] == 'DEBUG' # there should only be DEBUG messages assert isinstance(log_message['message'], str) def test_debug_profile(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '--debug-profile=create.prof') self.cmd('debug', 'convert-profile', 'create.prof', 'create.pyprof') stats = pstats.Stats('create.pyprof') stats.strip_dirs() stats.sort_stats('cumtime') self.cmd('create', self.repository_location + '::test2', 'input', '--debug-profile=create.pyprof') stats = pstats.Stats('create.pyprof') # Only do this on trusted data! stats.strip_dirs() stats.sort_stats('cumtime') def test_common_options(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('--debug', 'create', self.repository_location + '::test', 'input') assert 'security: read previous location' in log def _get_sizes(self, compression, compressible, size=10000): if compressible: contents = b'X' * size else: contents = os.urandom(size) self.create_regular_file('file', contents=contents) self.cmd('init', '--encryption=none', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '-C', compression, archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {path}{NL}', archive) size, csize, path = output.split("\n")[1].split(" ") return int(size), int(csize) def test_compression_none_compressible(self): size, csize = self._get_sizes('none', compressible=True) assert csize == size + 3 def test_compression_none_uncompressible(self): size, csize = self._get_sizes('none', compressible=False) assert csize == size + 3 def test_compression_zlib_compressible(self): size, csize = self._get_sizes('zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 def test_compression_zlib_uncompressible(self): size, csize = self._get_sizes('zlib', compressible=False) assert csize >= size def test_compression_auto_compressible(self): size, csize = self._get_sizes('auto,zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 # same as compression 'zlib' def test_compression_auto_uncompressible(self): size, csize = self._get_sizes('auto,zlib', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lz4_compressible(self): size, csize = self._get_sizes('lz4', compressible=True) assert csize < size * 0.1 def test_compression_lz4_uncompressible(self): size, csize = self._get_sizes('lz4', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lzma_compressible(self): size, csize = self._get_sizes('lzma', compressible=True) assert csize < size * 0.1 def test_compression_lzma_uncompressible(self): size, csize = self._get_sizes('lzma', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_zstd_compressible(self): size, csize = self._get_sizes('zstd', compressible=True) assert csize < size * 0.1 def test_compression_zstd_uncompressible(self): size, csize = self._get_sizes('zstd', compressible=False) assert csize == size + 3 # same as compression 'none' def test_change_passphrase(self): self.cmd('init', '--encryption=repokey', self.repository_location) os.environ['BORG_NEW_PASSPHRASE'] = 'newpassphrase' # here we have both BORG_PASSPHRASE and BORG_NEW_PASSPHRASE set: self.cmd('key', 'change-passphrase', self.repository_location) os.environ['BORG_PASSPHRASE'] = 'newpassphrase' self.cmd('list', self.repository_location) def test_break_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('break-lock', self.repository_location) def test_usage(self): self.cmd() self.cmd('-h') def test_help(self): assert 'Borg' in self.cmd('help') assert 'patterns' in self.cmd('help', 'patterns') assert 'Initialize' in self.cmd('help', 'init') assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only') assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: os.close(os.open(some_file, flags_noatime)) except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.cmd('init', '--encryption=repokey', self.repository_location) self.create_test_files() have_noatime = has_noatime('input/file1') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive', 'input') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive2', 'input') if has_lchflags: # remove the file we did not backup, so input and output become equal os.remove(os.path.join('input', 'flagfile')) mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in archivename subdirs of mountpoint: with self.fuse_mount(self.repository_location, mountpoint): # flags are not supported by the FUSE mount # we also ignore xattrs here, they are tested separately self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'), ignore_flags=True, ignore_xattrs=True) self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'), ignore_flags=True, ignore_xattrs=True) # mount only 1 archive, its contents shall show up directly in mountpoint: with self.fuse_mount(self.repository_location + '::archive', mountpoint): self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'), ignore_flags=True, ignore_xattrs=True) # regular file in_fn = 'input/file1' out_fn = os.path.join(mountpoint, 'input', 'file1') # stat sti1 = os.stat(in_fn) sto1 = os.stat(out_fn) assert sti1.st_mode == sto1.st_mode assert sti1.st_uid == sto1.st_uid assert sti1.st_gid == sto1.st_gid assert sti1.st_size == sto1.st_size if have_noatime: assert sti1.st_atime == sto1.st_atime assert sti1.st_ctime == sto1.st_ctime assert sti1.st_mtime == sto1.st_mtime if are_hardlinks_supported(): # note: there is another hardlink to this, see below assert sti1.st_nlink == sto1.st_nlink == 2 # read with open(in_fn, 'rb') as in_f, open(out_fn, 'rb') as out_f: assert in_f.read() == out_f.read() # hardlink (to 'input/file1') if are_hardlinks_supported(): in_fn = 'input/hardlink' out_fn = os.path.join(mountpoint, 'input', 'hardlink') sti2 = os.stat(in_fn) sto2 = os.stat(out_fn) assert sti2.st_nlink == sto2.st_nlink == 2 assert sto1.st_ino == sto2.st_ino # symlink if are_symlinks_supported(): in_fn = 'input/link1' out_fn = os.path.join(mountpoint, 'input', 'link1') sti = os.stat(in_fn, follow_symlinks=False) sto = os.stat(out_fn, follow_symlinks=False) assert sti.st_size == len('somewhere') assert sto.st_size == len('somewhere') assert stat.S_ISLNK(sti.st_mode) assert stat.S_ISLNK(sto.st_mode) assert os.readlink(in_fn) == os.readlink(out_fn) # FIFO if are_fifos_supported(): out_fn = os.path.join(mountpoint, 'input', 'fifo1') sto = os.stat(out_fn) assert stat.S_ISFIFO(sto.st_mode) # list/read xattrs try: in_fn = 'input/fusexattr' out_fn = os.fsencode(os.path.join(mountpoint, 'input', 'fusexattr')) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): assert sorted(no_selinux(xattr.listxattr(out_fn))) == [b'user.empty', b'user.foo', ] assert xattr.getxattr(out_fn, b'user.foo') == b'bar' assert xattr.getxattr(out_fn, b'user.empty') == b'' else: assert no_selinux(xattr.listxattr(out_fn)) == [] try: xattr.getxattr(out_fn, b'user.foo') except OSError as e: assert e.errno == llfuse.ENOATTR else: assert False, "expected OSError(ENOATTR), but no error was raised" except OSError as err: if sys.platform.startswith(('nothing_here_now', )) and err.errno == errno.ENOTSUP: # some systems have no xattr support on FUSE pass else: raise @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_versions_view(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('test', contents=b'first') if are_hardlinks_supported(): self.create_regular_file('hardlink1', contents=b'123456') os.link('input/hardlink1', 'input/hardlink2') os.link('input/hardlink1', 'input/hardlink3') self.cmd('create', self.repository_location + '::archive1', 'input') self.create_regular_file('test', contents=b'second') self.cmd('create', self.repository_location + '::archive2', 'input') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in versioned view: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions'): path = os.path.join(mountpoint, 'input', 'test') # filename shows up as directory ... files = os.listdir(path) assert all(f.startswith('test.') for f in files) # ... with files test.xxxxx in there assert {b'first', b'second'} == {open(os.path.join(path, f), 'rb').read() for f in files} if are_hardlinks_supported(): hl1 = os.path.join(mountpoint, 'input', 'hardlink1', 'hardlink1.00001') hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl1).st_ino == os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' # similar again, but exclude the hardlink master: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions', '-e', 'input/hardlink1'): if are_hardlinks_supported(): hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_allow_damaged_files(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive') # Get rid of a chunk and repair it archive, repository = self.open_archive('archive') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) path = item.path # store full path for later break else: assert False # missed the file repository.commit(compact=False) self.cmd('check', '--repair', self.repository_location, exit_code=0) mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location + '::archive', mountpoint): with pytest.raises(OSError) as excinfo: open(os.path.join(mountpoint, path)) assert excinfo.value.errno == errno.EIO with self.fuse_mount(self.repository_location + '::archive', mountpoint, '-o', 'allow_damaged_files'): open(os.path.join(mountpoint, path)).close() @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_options(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('arch11') self.create_src_archive('arch12') self.create_src_archive('arch21') self.create_src_archive('arch22') mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location, mountpoint, '--first=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--last=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch1'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch2'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12', 'arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=nope'): assert sorted(os.listdir(os.path.join(mountpoint))) == [] @unittest.skipUnless(llfuse, 'llfuse not installed') def test_migrate_lock_alive(self): """Both old_id and new_id must not be stale during lock migration / daemonization.""" from functools import wraps import pickle import traceback # Check results are communicated from the borg mount background process # to the pytest process by means of a serialized dict object stored in this file. assert_data_file = os.path.join(self.tmpdir, 'migrate_lock_assert_data.pickle') # Decorates Lock.migrate_lock() with process_alive() checks before and after. # (We don't want to mix testing code into runtime.) def write_assert_data(migrate_lock): @wraps(migrate_lock) def wrapper(self, old_id, new_id): wrapper.num_calls += 1 assert_data = { 'num_calls': wrapper.num_calls, 'old_id': old_id, 'new_id': new_id, 'before': { 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}, 'exception': None, 'exception.extr_tb': None, 'after': { 'old_id_alive': None, 'new_id_alive': None}} try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass try: return migrate_lock(self, old_id, new_id) except BaseException as e: assert_data['exception'] = e assert_data['exception.extr_tb'] = traceback.extract_tb(e.__traceback__) finally: assert_data['after'].update({ 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}) try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass wrapper.num_calls = 0 return wrapper # Decorate borg.locking.Lock.migrate_lock = write_assert_data(borg.locking.Lock.migrate_lock) try: self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('arch') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # In order that the decoration is kept for the borg mount process, we must not spawn, but actually fork; # not to be confused with the forking in borg.helpers.daemonize() which is done as well. with self.fuse_mount(self.repository_location, mountpoint, os_fork=True): pass with open(assert_data_file, 'rb') as _in: assert_data = pickle.load(_in) print('\nLock.migrate_lock(): assert_data = %r.' % (assert_data, ), file=sys.stderr, flush=True) exception = assert_data['exception'] if exception is not None: extracted_tb = assert_data['exception.extr_tb'] print( 'Lock.migrate_lock() raised an exception:\n', 'Traceback (most recent call last):\n', *traceback.format_list(extracted_tb), *traceback.format_exception(exception.__class__, exception, None), sep='', end='', file=sys.stderr, flush=True) assert assert_data['num_calls'] == 1, "Lock.migrate_lock() must be called exactly once." assert exception is None, "Lock.migrate_lock() may not raise an exception." assert_data_before = assert_data['before'] assert assert_data_before['old_id_alive'], "old_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert assert_data_before['new_id_alive'], "new_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert_data_after = assert_data['after'] assert assert_data_after['old_id_alive'], "old_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." assert assert_data_after['new_id_alive'], "new_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." finally: # Undecorate borg.locking.Lock.migrate_lock = borg.locking.Lock.migrate_lock.__wrapped__ def verify_aes_counter_uniqueness(self, method): seen = set() # Chunks already seen used = set() # counter values already used def verify_uniqueness(): with Repository(self.repository_path) as repository: for id, _ in repository.open_index(repository.get_transaction_id()).iteritems(): data = repository.get(id) hash = sha256(data).digest() if hash not in seen: seen.add(hash) num_blocks = num_cipher_blocks(len(data) - 41) nonce = bytes_to_long(data[33:41]) for counter in range(nonce, nonce + num_blocks): self.assert_not_in(counter, used) used.add(counter) self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=' + method, self.repository_location) verify_uniqueness() self.cmd('create', self.repository_location + '::test', 'input') verify_uniqueness() self.cmd('create', self.repository_location + '::test.2', 'input') verify_uniqueness() self.cmd('delete', self.repository_location + '::test.2') verify_uniqueness() def test_aes_counter_uniqueness_keyfile(self): self.verify_aes_counter_uniqueness('keyfile') def test_aes_counter_uniqueness_passphrase(self): self.verify_aes_counter_uniqueness('repokey') def test_debug_dump_archive_items(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-archive-items', self.repository_location + '::test') output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('000000_') assert 'Done.' in output def test_debug_dump_repo_objs(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-repo-objs', self.repository_location) output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('00000000_') assert 'Done.' in output def test_debug_put_get_delete_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) data = b'some data' hexkey = sha256(data).hexdigest() self.create_regular_file('file', contents=data) output = self.cmd('debug', 'put-obj', self.repository_location, 'input/file') assert hexkey in output output = self.cmd('debug', 'get-obj', self.repository_location, hexkey, 'output/file') assert hexkey in output with open('output/file', 'rb') as f: data_read = f.read() assert data == data_read output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "deleted" in output output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "not found" in output output = self.cmd('debug', 'delete-obj', self.repository_location, 'invalid') assert "is invalid" in output def test_init_interrupt(self): def raise_eof(*args): raise EOFError with patch.object(KeyfileKeyBase, 'create', raise_eof): self.cmd('init', '--encryption=repokey', self.repository_location, exit_code=1) assert not os.path.exists(self.repository_location) def test_init_requires_encryption_option(self): self.cmd('init', self.repository_location, exit_code=2) def test_init_nested_repositories(self): self.cmd('init', '--encryption=repokey', self.repository_location) if self.FORK_DEFAULT: self.cmd('init', '--encryption=repokey', self.repository_location + '/nested', exit_code=2) else: with pytest.raises(Repository.AlreadyExists): self.cmd('init', '--encryption=repokey', self.repository_location + '/nested') def check_cache(self): # First run a regular borg check self.cmd('check', self.repository_location) # Then check that the cache on disk matches exactly what's in the repo. with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: original_chunks = cache.chunks Cache.destroy(repository) with Cache(repository, key, manifest) as cache: correct_chunks = cache.chunks assert original_chunks is not correct_chunks seen = set() for id, (refcount, size, csize) in correct_chunks.iteritems(): o_refcount, o_size, o_csize = original_chunks[id] assert refcount == o_refcount assert size == o_size assert csize == o_csize seen.add(id) for id, (refcount, size, csize) in original_chunks.iteritems(): assert id in seen def test_check_cache(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: cache.begin_txn() cache.chunks.incref(list(cache.chunks.iteritems())[0][0]) cache.commit() with pytest.raises(AssertionError): self.check_cache() def test_recreate_target_rc(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('recreate', self.repository_location, '--target=asdf', exit_code=2) assert 'Need to specify single archive' in output def test_recreate_target(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.check_cache() archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.check_cache() original_archive = self.cmd('list', self.repository_location) self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3', '--target=new-archive') self.check_cache() archives = self.cmd('list', self.repository_location) assert original_archive in archives assert 'new-archive' in archives archive = self.repository_location + '::new-archive' listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing def test_recreate_basic(self): self.create_test_files() self.create_regular_file('dir2/file3', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3') self.check_cache() listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_subtree_hardlinks(self): # This is essentially the same problem set as in test_extract_hardlinks self._extract_hardlinks_setup() self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('recreate', self.repository_location + '::test', 'input/dir1') self.check_cache() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test2') assert os.stat('input/dir1/hardlink').st_nlink == 4 def test_recreate_rechunkify(self): with open(os.path.join(self.input_path, 'large_file'), 'wb') as fd: fd.write(b'a' * 280) fd.write(b'b' * 280) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--chunker-params', '7,9,8,128', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input', '--files-cache=disabled') list = self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{num_chunks} {unique_chunks}') num_chunks, unique_chunks = map(int, list.split(' ')) # test1 and test2 do not deduplicate assert num_chunks == unique_chunks self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() # test1 and test2 do deduplicate after recreate assert int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format={size}')) assert not int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{unique_chunks}')) def test_recreate_recompress(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '-C', 'none') file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_before = file_list.split(' ') assert int(csize) >= int(size) # >= due to metadata overhead self.cmd('recreate', self.repository_location, '-C', 'lz4', '--recompress') self.check_cache() file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_after = file_list.split(' ') assert int(csize) < int(size) assert sha256_before == sha256_after def test_recreate_timestamp(self): local_timezone = datetime.now(timezone(timedelta(0))).astimezone().tzinfo self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', '--timestamp', "1970-01-02T00:00:00", '--comment', 'test', archive) info = self.cmd('info', archive).splitlines() dtime = datetime(1970, 1, 2) + local_timezone.utcoffset(None) s_time = dtime.strftime("%Y-%m-%d") assert any([re.search(r'Time \(start\).+ %s' % s_time, item) for item in info]) assert any([re.search(r'Time \(end\).+ %s' % s_time, item) for item in info]) def test_recreate_dry_run(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') archives_before = self.cmd('list', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '-n', '-e', 'input/compressible') self.check_cache() archives_after = self.cmd('list', self.repository_location + '::test') assert archives_after == archives_before def test_recreate_skips_nothing_to_do(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_before = self.cmd('info', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() info_after = self.cmd('info', self.repository_location + '::test') assert info_before == info_after # includes archive ID def test_with_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) lock_path = os.path.join(self.repository_path, 'lock.exclusive') cmd = 'python3', '-c', 'import os, sys; sys.exit(42 if os.path.exists("%s") else 23)' % lock_path self.cmd('with-lock', self.repository_location, *cmd, fork=True, exit_code=42) def test_recreate_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=0) self.create_regular_file('file2', size=0) self.create_regular_file('file3', size=0) self.create_regular_file('file4', size=0) self.create_regular_file('file5', size=0) self.cmd('create', self.repository_location + '::test', 'input') output = self.cmd('recreate', '--list', '--info', self.repository_location + '::test', '-e', 'input/file2') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file2", output) output = self.cmd('recreate', '--list', self.repository_location + '::test', '-e', 'input/file3') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file3", output) output = self.cmd('recreate', self.repository_location + '::test', '-e', 'input/file4') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file4", output) output = self.cmd('recreate', '--info', self.repository_location + '::test', '-e', 'input/file5') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file5", output) def test_bad_filters(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('delete', '--first', '1', '--last', '1', self.repository_location, fork=True, exit_code=2) def test_key_export_keyfile(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'r') as fd: key_contents = fd.read() assert key_contents == export_contents os.unlink(key_file) self.cmd('key', 'import', self.repository_location, export_file) with open(key_file, 'r') as fd: key_contents2 = fd.read() assert key_contents2 == key_contents def test_key_import_keyfile_with_borg_key_file(self): self.cmd('init', self.repository_location, '--encryption', 'keyfile') exported_key_file = os.path.join(self.output_path, 'exported') self.cmd('key', 'export', self.repository_location, exported_key_file) key_file = os.path.join(self.keys_path, os.listdir(self.keys_path)[0]) with open(key_file, 'r') as fd: key_contents = fd.read() os.unlink(key_file) imported_key_file = os.path.join(self.output_path, 'imported') with environment_variable(BORG_KEY_FILE=imported_key_file): self.cmd('key', 'import', self.repository_location, exported_key_file) assert not os.path.isfile(key_file), '"borg key import" should respect BORG_KEY_FILE' with open(imported_key_file, 'r') as fd: imported_key_contents = fd.read() assert imported_key_contents == key_contents def test_key_export_repokey(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') with Repository(self.repository_path) as repository: repo_key = RepoKey(repository) repo_key.load(None, Passphrase.env_passphrase()) backup_key = KeyfileKey(key.TestKey.MockRepository()) backup_key.load(export_file, Passphrase.env_passphrase()) assert repo_key.enc_key == backup_key.enc_key with Repository(self.repository_path) as repository: repository.save_key(b'') self.cmd('key', 'import', self.repository_location, export_file) with Repository(self.repository_path) as repository: repo_key2 = RepoKey(repository) repo_key2.load(None, Passphrase.env_passphrase()) assert repo_key2.enc_key == repo_key2.enc_key def test_key_export_qr(self): export_file = self.output_path + '/exported.html' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', '--qr-html', self.repository_location, export_file) with open(export_file, 'r', encoding='utf-8') as fd: export_contents = fd.read() assert bin_to_hex(repo_id) in export_contents assert export_contents.startswith('<!doctype html>') assert export_contents.endswith('</html>\n') def test_key_export_directory(self): export_directory = self.output_path + '/exported' os.mkdir(export_directory) self.cmd('init', self.repository_location, '--encryption', 'repokey') self.cmd('key', 'export', self.repository_location, export_directory, exit_code=EXIT_ERROR) def test_key_import_errors(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self.cmd('key', 'import', self.repository_location, export_file, exit_code=EXIT_ERROR) with open(export_file, 'w') as fd: fd.write('something not a key\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(NotABorgKeyFile): self.cmd('key', 'import', self.repository_location, export_file) with open(export_file, 'w') as fd: fd.write('BORG_KEY a0a0a0\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(RepoIdMismatch): self.cmd('key', 'import', self.repository_location, export_file) def test_key_export_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) self.cmd('key', 'export', '--paper', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents == """To restore key use borg key import --paper /path/to/repo BORG PAPER KEY v1 id: 2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02 1: 616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d 2: 737475 - 88 """ def test_key_import_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) typed_input = ( b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 02\n' # Forgot to type "-" b'2 / e29442 3506da 4e1ea7 25f62a 5a3d41 - 02\n' # Forgot to type second "/" b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d42 - 02\n' # Typo (..42 not ..41) b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' # Correct! Congratulations b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'\n\n' # Abort [yN] => N b'737475 88\n' # missing "-" b'73747i - 88\n' # typo b'73747 - 88\n' # missing nibble b'73 74 75 - 89\n' # line checksum mismatch b'00a1 - 88\n' # line hash collision - overall hash mismatch, have to start over b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'73 74 75 - 88\n' ) # In case that this has to change, here is a quick way to find a colliding line hash: # # from hashlib import sha256 # hash_fn = lambda x: sha256(b'\x00\x02' + x).hexdigest()[:2] # for i in range(1000): # if hash_fn(i.to_bytes(2, byteorder='big')) == '88': # 88 = line hash # print(i.to_bytes(2, 'big')) # break self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) # Test abort paths typed_input = b'\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) typed_input = b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) def test_debug_dump_manifest(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-manifest', self.repository_location, dump_file) assert output == "" with open(dump_file, "r") as f: result = json.load(f) assert 'archives' in result assert 'config' in result assert 'item_keys' in result assert 'timestamp' in result assert 'version' in result def test_debug_dump_archive(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-archive', self.repository_location + "::test", dump_file) assert output == "" with open(dump_file, "r") as f: result = json.load(f) assert '_name' in result assert '_manifest_entry' in result assert '_meta' in result assert '_items' in result def test_debug_refcount_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('debug', 'refcount-obj', self.repository_location, '0' * 64).strip() assert output == 'object 0000000000000000000000000000000000000000000000000000000000000000 not found [info from chunks cache].' create_json = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) archive_id = create_json['archive']['id'] output = self.cmd('debug', 'refcount-obj', self.repository_location, archive_id).strip() assert output == 'object ' + archive_id + ' has 1 referrers [info from chunks cache].' # Invalid IDs do not abort or return an error output = self.cmd('debug', 'refcount-obj', self.repository_location, '124', 'xyza').strip() assert output == 'object id 124 is invalid.\nobject id xyza is invalid.' def test_debug_info(self): output = self.cmd('debug', 'info') assert 'CRC implementation' in output assert 'Python' in output def test_benchmark_crud(self): self.cmd('init', '--encryption=repokey', self.repository_location) with environment_variable(_BORG_BENCHMARK_CRUD_TEST='YES'): self.cmd('benchmark', 'crud', self.repository_location, self.input_path) def test_config(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('config', '--list', self.repository_location) self.assert_in('[repository]', output) self.assert_in('version', output) self.assert_in('segments_per_dir', output) self.assert_in('storage_quota', output) self.assert_in('append_only', output) self.assert_in('additional_free_space', output) self.assert_in('id', output) self.assert_not_in('last_segment_checked', output) output = self.cmd('config', self.repository_location, 'last_segment_checked', exit_code=1) self.assert_in('No option ', output) self.cmd('config', self.repository_location, 'last_segment_checked', '123') output = self.cmd('config', self.repository_location, 'last_segment_checked') assert output == '123' + '\n' output = self.cmd('config', '--list', self.repository_location) self.assert_in('last_segment_checked', output) self.cmd('config', '--delete', self.repository_location, 'last_segment_checked') for cfg_key, cfg_value in [ ('additional_free_space', '2G'), ('repository.append_only', '1'), ]: output = self.cmd('config', self.repository_location, cfg_key) assert output == '0' + '\n' self.cmd('config', self.repository_location, cfg_key, cfg_value) output = self.cmd('config', self.repository_location, cfg_key) assert output == cfg_value + '\n' self.cmd('config', '--delete', self.repository_location, cfg_key) self.cmd('config', self.repository_location, cfg_key, exit_code=1) self.cmd('config', '--list', '--delete', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, 'invalid-option', exit_code=1) requires_gnutar = pytest.mark.skipif(not have_gnutar(), reason='GNU tar must be installed for this test.') requires_gzip = pytest.mark.skipif(not shutil.which('gzip'), reason='gzip must be installed for this test.') @requires_gnutar def test_export_tar(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--progress') with changedir('output'): # This probably assumes GNU tar. Note -p switch to extract permissions regardless of umask. subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar @requires_gzip def test_export_tar_gz(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar.gz', '--list') assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar.gz', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar def test_export_tar_strip_components(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--strip-components=1', '--list') # --list's path are those before processing with --strip-components assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_hardlinks @requires_gnutar def test_export_tar_strip_components_links(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', '--strip-components=2') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 @requires_hardlinks @requires_gnutar def test_extract_hardlinks_tar(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', 'input/dir1') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 def test_detect_attic_repo(self): path = make_attic_repo(self.repository_path) cmds = [ ['create', path + '::test', self.tmpdir], ['extract', path + '::test'], ['check', path], ['rename', path + '::test', 'newname'], ['list', path], ['delete', path], ['prune', path], ['info', path + '::test'], ['key', 'export', path, 'exported'], ['key', 'import', path, 'import'], ['key', 'change-passphrase', path], ['break-lock', path], ] for args in cmds: output = self.cmd(*args, fork=True, exit_code=2) assert 'Attic repository detected.' in output @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available') class ArchiverTestCaseBinary(ArchiverTestCase): EXE = 'borg.exe' FORK_DEFAULT = True @unittest.skip('does not raise Exception, but sets rc==2') def test_init_parent_dirs(self): pass @unittest.skip('patches objects') def test_init_interrupt(self): pass @unittest.skip('patches objects') def test_extract_capabilities(self): pass @unittest.skip('patches objects') def test_extract_xattrs_errors(self): pass @unittest.skip('test_basic_functionality seems incompatible with fakeroot and/or the binary.') def test_basic_functionality(self): pass @unittest.skip('test_overwrite seems incompatible with fakeroot and/or the binary.') def test_overwrite(self): pass def test_fuse(self): if fakeroot_detected(): unittest.skip('test_fuse with the binary is not compatible with fakeroot') else: super().test_fuse() class ArchiverCheckTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1') self.create_src_archive('archive2') def test_check_usage(self): output = self.cmd('check', '-v', '--progress', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) self.assert_in('Checking segments', output) # reset logging to new process default to avoid need for fork=True on next check logging.getLogger('borg.output.progress').setLevel(logging.NOTSET) output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_not_in('Starting archive consistency check', output) self.assert_not_in('Checking segments', output) output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0) self.assert_not_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) output = self.cmd('check', '-v', '--archives-only', '--prefix=archive2', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) output = self.cmd('check', '-v', '--archives-only', '--first=1', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_not_in('archive2', output) output = self.cmd('check', '-v', '--archives-only', '--last=1', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) self.assert_in('archive2', output) def test_missing_file_chunk(self): archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): valid_chunks = item.chunks killed_chunk = valid_chunks[-1] repository.delete(killed_chunk.id) break else: self.fail('should not happen') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '--repair', self.repository_location, exit_code=0) self.assert_in('New missing file chunk detected', output) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_in('broken#', output) # check that the file in the old archives has now a different chunk list without the killed chunk for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_not_equal(valid_chunks, item.chunks) self.assert_not_in(killed_chunk, item.chunks) break else: self.fail('should not happen') # do a fresh backup (that will include the killed chunk) with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.create_src_archive('archive3') # check should be able to heal the file now: output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('Healed previously missing file chunk', output) self.assert_in('testsuite/archiver.py: Completely healed previously damaged file!', output) # check that the file in the old archives has the correct chunks again for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_equal(valid_chunks, item.chunks) break else: self.fail('should not happen') # list is also all-healthy again output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_not_in('broken#', output) def test_missing_archive_item_chunk(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.metadata.items[0]) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_archive_metadata(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.id) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_manifest(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(Manifest.MANIFEST_ID) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_corrupted_manifest(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_corrupted_chunk(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) chunk = repository.get(archive.id) corrupted_chunk = chunk + b'corrupted!' repository.put(archive.id, corrupted_chunk) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_duplicate_archive(self): archive, repository = self.open_archive('archive1') key = archive.key with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) archive = msgpack.packb({ 'cmdline': [], 'items': [], 'hostname': 'foo', 'username': 'bar', 'name': 'archive1', 'time': '2016-12-15T18:49:51.849711', 'version': 1, }) archive_id = key.id_hash(archive) repository.put(archive_id, key.encrypt(archive)) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) output = self.cmd('list', self.repository_location) self.assert_in('archive1', output) self.assert_in('archive1.1', output) self.assert_in('archive2', output) def test_extra_chunks(self): self.cmd('check', self.repository_location, exit_code=0) with Repository(self.repository_location, exclusive=True) as repository: repository.put(b'01234567890123456789012345678901', b'xxxx') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0) def _test_verify_data(self, *init_args): shutil.rmtree(self.repository_path) self.cmd('init', self.repository_location, *init_args) self.create_src_archive('archive1') archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): chunk = item.chunks[-1] data = repository.get(chunk.id) + b'1234' repository.put(chunk.id, data) break repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('check', '--verify-data', self.repository_location, exit_code=1) assert bin_to_hex(chunk.id) + ', integrity error' in output # repair (heal is tested in another test) output = self.cmd('check', '--repair', '--verify-data', self.repository_location, exit_code=0) assert bin_to_hex(chunk.id) + ', integrity error' in output assert 'testsuite/archiver.py: New missing file chunk detected' in output def test_verify_data(self): self._test_verify_data('--encryption', 'repokey') def test_verify_data_unencrypted(self): self._test_verify_data('--encryption', 'none') def test_empty_repository(self): with Repository(self.repository_location, exclusive=True) as repository: for id_ in repository.list(): repository.delete(id_) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) def test_attic013_acl_bug(self): # Attic up to release 0.13 contained a bug where every item unintentionally received # a b'acl'=None key-value pair. # This bug can still live on in Borg repositories (through borg upgrade). class Attic013Item: def as_dict(self): return { # These are required b'path': '1234', b'mtime': 0, b'mode': 0, b'user': b'0', b'group': b'0', b'uid': 0, b'gid': 0, # acl is the offending key. b'acl': None, } archive, repository = self.open_archive('archive1') with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: archive = Archive(repository, key, manifest, '0.13', cache=cache, create=True) archive.items_buffer.add(Attic013Item()) archive.save() self.cmd('check', self.repository_location, exit_code=0) self.cmd('list', self.repository_location + '::0.13', exit_code=0) class ManifestAuthenticationTest(ArchiverTestCaseBase): def spoof_manifest(self, repository): with repository: _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'config': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) def test_fresh_init_tam_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) def test_not_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) with repository: shutil.rmtree(get_security_dir(bin_to_hex(repository.id))) _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) key.tam_required = False key.change_passphrase(key._passphrase) manifest = msgpack.unpackb(key.decrypt(None, repository.get(Manifest.MANIFEST_ID))) del manifest[b'tam'] repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb(manifest))) repository.commit(compact=False) output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM not found and not required' in output # Run upgrade self.cmd('upgrade', '--tam', self.repository_location) # Manifest must be authenticated now output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM-verified manifest' in output # Try to spoof / modify pre-1.0.9 self.spoof_manifest(repository) # Fails with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) # Force upgrade self.cmd('upgrade', '--tam', '--force', self.repository_location) self.cmd('list', self.repository_location) def test_disable(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') self.cmd('upgrade', '--disable-tam', self.repository_location) repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) assert not self.cmd('list', self.repository_location) def test_disable2(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) self.cmd('upgrade', '--disable-tam', self.repository_location) assert not self.cmd('list', self.repository_location) class RemoteArchiverTestCase(ArchiverTestCase): prefix = '__testsuite__:' def open_repository(self): return RemoteRepository(Location(self.repository_location)) def test_remote_repo_restrict_to_path(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) # restricted to repo directory itself, fail for other directories with same prefix: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_0') # restricted to a completely different path: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_1') path_prefix = os.path.dirname(self.repository_path) # restrict to repo directory's parent directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_2') # restrict to repo directory's parent directory and another directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_3') def test_remote_repo_restrict_to_repository(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) parent_path = os.path.join(self.repository_path, '..') with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', parent_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location) @unittest.skip('only works locally') def test_debug_put_get_delete_obj(self): pass @unittest.skip('only works locally') def test_config(self): pass @unittest.skip('only works locally') def test_migrate_lock_alive(self): pass def test_strip_components_doesnt_leak(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file', contents=b"test file contents 1") self.create_regular_file('dir/file2', contents=b"test file contents 2") self.create_regular_file('skipped-file1', contents=b"test file contents 3") self.create_regular_file('skipped-file2', contents=b"test file contents 4") self.create_regular_file('skipped-file3', contents=b"test file contents 5") self.cmd('create', self.repository_location + '::test', 'input') marker = 'cached responses left in RemoteRepository' with changedir('output'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '3') self.assert_true(marker not in res) with self.assert_creates_file('file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '2') self.assert_true(marker not in res) with self.assert_creates_file('dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '1') self.assert_true(marker not in res) with self.assert_creates_file('input/dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '0') self.assert_true(marker not in res) class ArchiverCorruptionTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cache_path = json.loads(self.cmd('info', self.repository_location, '--json'))['cache']['path'] def corrupt(self, file, amount=1): with open(file, 'r+b') as fd: fd.seek(-amount, io.SEEK_END) corrupted = bytes(255-c for c in fd.read(amount)) fd.seek(-amount, io.SEEK_END) fd.write(corrupted) def test_cache_chunks(self): self.corrupt(os.path.join(self.cache_path, 'chunks')) if self.FORK_DEFAULT: out = self.cmd('info', self.repository_location, exit_code=2) assert 'failed integrity check' in out else: with pytest.raises(FileIntegrityError): self.cmd('info', self.repository_location) def test_cache_files(self): self.cmd('create', self.repository_location + '::test', 'input') self.corrupt(os.path.join(self.cache_path, 'files')) out = self.cmd('create', self.repository_location + '::test1', 'input') # borg warns about the corrupt files cache, but then continues without files cache. assert 'files cache is corrupted' in out def test_chunks_archive(self): self.cmd('create', self.repository_location + '::test1', 'input') # Find ID of test1 so we can corrupt it later :) target_id = self.cmd('list', self.repository_location, '--format={id}{LF}').strip() self.cmd('create', self.repository_location + '::test2', 'input') # Force cache sync, creating archive chunks of test1 and test2 in chunks.archive.d self.cmd('delete', '--cache-only', self.repository_location) self.cmd('info', self.repository_location, '--json') chunks_archive = os.path.join(self.cache_path, 'chunks.archive.d') assert len(os.listdir(chunks_archive)) == 4 # two archives, one chunks cache and one .integrity file each self.corrupt(os.path.join(chunks_archive, target_id + '.compact')) # Trigger cache sync by changing the manifest ID in the cache config config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) # Cache sync notices corrupted archive chunks, but automatically recovers. out = self.cmd('create', '-v', self.repository_location + '::test3', 'input', exit_code=1) assert 'Reading cached archive chunk index for test1' in out assert 'Cached archive chunk index of test1 is corrupted' in out assert 'Fetching and building archive index for test1' in out def test_old_version_interfered(self): # Modify the main manifest ID without touching the manifest ID in the integrity section. # This happens if a version without integrity checking modifies the cache. config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) out = self.cmd('info', self.repository_location) assert 'Cache integrity data not available: old Borg version modified the cache.' in out class DiffArchiverTestCase(ArchiverTestCaseBase): def test_basic_functionality(self): # Setup files for the first snapshot self.create_regular_file('empty', size=0) self.create_regular_file('file_unchanged', size=128) self.create_regular_file('file_removed', size=256) self.create_regular_file('file_removed2', size=512) self.create_regular_file('file_replaced', size=1024) os.mkdir('input/dir_replaced_with_file') os.chmod('input/dir_replaced_with_file', stat.S_IFDIR | 0o755) os.mkdir('input/dir_removed') if are_symlinks_supported(): os.mkdir('input/dir_replaced_with_link') os.symlink('input/dir_replaced_with_file', 'input/link_changed') os.symlink('input/file_unchanged', 'input/link_removed') os.symlink('input/file_removed2', 'input/link_target_removed') os.symlink('input/empty', 'input/link_target_contents_changed') os.symlink('input/empty', 'input/link_replaced_by_file') if are_hardlinks_supported(): os.link('input/file_replaced', 'input/hardlink_target_replaced') os.link('input/empty', 'input/hardlink_contents_changed') os.link('input/file_removed', 'input/hardlink_removed') os.link('input/file_removed2', 'input/hardlink_target_removed') self.cmd('init', '--encryption=repokey', self.repository_location) # Create the first snapshot self.cmd('create', self.repository_location + '::test0', 'input') # Setup files for the second snapshot self.create_regular_file('file_added', size=2048) self.create_regular_file('file_empty_added', size=0) os.unlink('input/file_replaced') self.create_regular_file('file_replaced', contents=b'0' * 4096) os.unlink('input/file_removed') os.unlink('input/file_removed2') os.rmdir('input/dir_replaced_with_file') self.create_regular_file('dir_replaced_with_file', size=8192) os.chmod('input/dir_replaced_with_file', stat.S_IFREG | 0o755) os.mkdir('input/dir_added') os.rmdir('input/dir_removed') if are_symlinks_supported(): os.rmdir('input/dir_replaced_with_link') os.symlink('input/dir_added', 'input/dir_replaced_with_link') os.unlink('input/link_changed') os.symlink('input/dir_added', 'input/link_changed') os.symlink('input/dir_added', 'input/link_added') os.unlink('input/link_replaced_by_file') self.create_regular_file('link_replaced_by_file', size=16384) os.unlink('input/link_removed') if are_hardlinks_supported(): os.unlink('input/hardlink_removed') os.link('input/file_added', 'input/hardlink_added') with open('input/empty', 'ab') as fd: fd.write(b'appended_data') # Create the second snapshot self.cmd('create', self.repository_location + '::test1a', 'input') self.cmd('create', '--chunker-params', '16,18,17,4095', self.repository_location + '::test1b', 'input') def do_asserts(output, can_compare_ids): # File contents changed (deleted and replaced with a new file) change = 'B' if can_compare_ids else '{:<19}'.format('modified') assert 'file_replaced' in output # added to debug #3494 assert '{} input/file_replaced'.format(change) in output # File unchanged assert 'input/file_unchanged' not in output # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert '[drwxr-xr-x -> -rwxr-xr-x] input/dir_replaced_with_file' in output # Basic directory cases assert 'added directory input/dir_added' in output assert 'removed directory input/dir_removed' in output if are_symlinks_supported(): # Basic symlink cases assert 'changed link input/link_changed' in output assert 'added link input/link_added' in output assert 'removed link input/link_removed' in output # Symlink replacing or being replaced assert '] input/dir_replaced_with_link' in output assert '] input/link_replaced_by_file' in output # Symlink target removed. Should not affect the symlink at all. assert 'input/link_target_removed' not in output # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. change = '0 B' if can_compare_ids else '{:<19}'.format('modified') assert '{} input/empty'.format(change) in output if are_hardlinks_supported(): assert '{} input/hardlink_contents_changed'.format(change) in output if are_symlinks_supported(): assert 'input/link_target_contents_changed' not in output # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert 'added 2.05 kB input/file_added' in output if are_hardlinks_supported(): assert 'added 2.05 kB input/hardlink_added' in output # check if a diff between non-existent and empty new file is found assert 'added 0 B input/file_empty_added' in output # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert 'removed 256 B input/file_removed' in output if are_hardlinks_supported(): assert 'removed 256 B input/hardlink_removed' in output # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_removed' not in output # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_replaced' not in output def do_json_asserts(output, can_compare_ids): def get_changes(filename, data): chgsets = [j['changes'] for j in data if j['path'] == filename] assert len(chgsets) < 2 # return a flattened list of changes for given filename return [chg for chgset in chgsets for chg in chgset] # convert output to list of dicts joutput = [json.loads(line) for line in output.split('\n') if line] # File contents changed (deleted and replaced with a new file) expected = {'type': 'modified', 'added': 4096, 'removed': 1024} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/file_replaced', joutput) # File unchanged assert not any(get_changes('input/file_unchanged', joutput)) # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert {'type': 'mode', 'old_mode': 'drwxr-xr-x', 'new_mode': '-rwxr-xr-x'} in \ get_changes('input/dir_replaced_with_file', joutput) # Basic directory cases assert {'type': 'added directory'} in get_changes('input/dir_added', joutput) assert {'type': 'removed directory'} in get_changes('input/dir_removed', joutput) if are_symlinks_supported(): # Basic symlink cases assert {'type': 'changed link'} in get_changes('input/link_changed', joutput) assert {'type': 'added link'} in get_changes('input/link_added', joutput) assert {'type': 'removed link'} in get_changes('input/link_removed', joutput) # Symlink replacing or being replaced assert any(chg['type'] == 'mode' and chg['new_mode'].startswith('l') for chg in get_changes('input/dir_replaced_with_link', joutput)) assert any(chg['type'] == 'mode' and chg['old_mode'].startswith('l') for chg in get_changes('input/link_replaced_by_file', joutput)) # Symlink target removed. Should not affect the symlink at all. assert not any(get_changes('input/link_target_removed', joutput)) # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. expected = {'type': 'modified', 'added': 13, 'removed': 0} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/empty', joutput) if are_hardlinks_supported(): assert expected in get_changes('input/hardlink_contents_changed', joutput) if are_symlinks_supported(): assert not any(get_changes('input/link_target_contents_changed', joutput)) # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert {'type': 'added', 'size': 2048} in get_changes('input/file_added', joutput) if are_hardlinks_supported(): assert {'type': 'added', 'size': 2048} in get_changes('input/hardlink_added', joutput) # check if a diff between non-existent and empty new file is found assert {'type': 'added', 'size': 0} in get_changes('input/file_empty_added', joutput) # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert {'type': 'removed', 'size': 256} in get_changes('input/file_removed', joutput) if are_hardlinks_supported(): assert {'type': 'removed', 'size': 256} in get_changes('input/hardlink_removed', joutput) # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_removed', joutput)) # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_replaced', joutput)) do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a'), True) # We expect exit_code=1 due to the chunker params warning do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1b', exit_code=1), False) do_json_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a', '--json-lines'), True) def test_sort_option(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('a_file_removed', size=8) self.create_regular_file('f_file_removed', size=16) self.create_regular_file('c_file_changed', size=32) self.create_regular_file('e_file_changed', size=64) self.cmd('create', self.repository_location + '::test0', 'input') os.unlink('input/a_file_removed') os.unlink('input/f_file_removed') os.unlink('input/c_file_changed') os.unlink('input/e_file_changed') self.create_regular_file('c_file_changed', size=512) self.create_regular_file('e_file_changed', size=1024) self.create_regular_file('b_file_added', size=128) self.create_regular_file('d_file_added', size=256) self.cmd('create', self.repository_location + '::test1', 'input') output = self.cmd('diff', '--sort', self.repository_location + '::test0', 'test1') expected = [ 'a_file_removed', 'b_file_added', 'c_file_changed', 'd_file_added', 'e_file_changed', 'f_file_removed', ] assert all(x in line for x, line in zip(expected, output.splitlines())) def test_get_args(): archiver = Archiver() # everything normal: # first param is argv as produced by ssh forced command, # second param is like from SSH_ORIGINAL_COMMAND env variable args = archiver.get_args(['borg', 'serve', '--umask=0027', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --info') assert args.func == archiver.do_serve assert args.restrict_to_paths == ['/p1', '/p2'] assert args.umask == 0o027 assert args.log_level == 'info' # similar, but with --restrict-to-repository args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --info --umask=0027') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break out of path restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --restrict-to-path=/') assert args.restrict_to_paths == ['/p1', '/p2'] # trying to cheat - break out of repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break below repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/r1/below') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - try to execute different subcommand args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg init --encryption=repokey /') assert args.func == archiver.do_serve # Check that environment variables in the forced command don't cause issues. If the command # were not forced, environment variables would be interpreted by the shell, but this does not # happen for forced commands - we get the verbatim command line and need to deal with env vars. args = archiver.get_args(['borg', 'serve', ], 'BORG_FOO=bar borg serve --info') assert args.func == archiver.do_serve def test_chunk_content_equal(): def ccc(a, b): chunks_a = [data for data in a] chunks_b = [data for data in b] compare1 = ItemDiff._chunk_content_equal(iter(chunks_a), iter(chunks_b)) compare2 = ItemDiff._chunk_content_equal(iter(chunks_b), iter(chunks_a)) assert compare1 == compare2 return compare1 assert ccc([ b'1234', b'567A', b'bC' ], [ b'1', b'23', b'4567A', b'b', b'C' ]) # one iterator exhausted before the other assert not ccc([ b'12345', ], [ b'1234', b'56' ]) # content mismatch assert not ccc([ b'1234', b'65' ], [ b'1234', b'56' ]) # first is the prefix of second assert not ccc([ b'1234', b'56' ], [ b'1234', b'565' ]) class TestBuildFilter: @staticmethod def peek_and_store_hardlink_masters(item, matched): pass def test_basic(self): matcher = PatternMatcher() matcher.add([parse_pattern('included')], IECommand.Include) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='included')) assert filter(Item(path='included/file')) assert not filter(Item(path='something else')) def test_empty(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='anything')) def test_strip_components(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, strip_components=1) assert not filter(Item(path='shallow')) assert not filter(Item(path='shallow/')) # can this even happen? paths are normalized... assert filter(Item(path='deep enough/file')) assert filter(Item(path='something/dir/file')) class TestCommonOptions: @staticmethod def define_common_options(add_common_option): add_common_option('-h', '--help', action='help', help='show this help message and exit') add_common_option('--critical', dest='log_level', help='foo', action='store_const', const='critical', default='warning') add_common_option('--error', dest='log_level', help='foo', action='store_const', const='error', default='warning') add_common_option('--append', dest='append', help='foo', action='append', metavar='TOPIC', default=[]) add_common_option('-p', '--progress', dest='progress', action='store_true', help='foo') add_common_option('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1, help='(default: %(default)d).') @pytest.fixture def basic_parser(self): parser = argparse.ArgumentParser(prog='test', description='test parser', add_help=False) parser.common_options = Archiver.CommonOptions(self.define_common_options, suffix_precedence=('_level0', '_level1')) return parser @pytest.fixture def subparsers(self, basic_parser): if sys.version_info >= (3, 7): # py37 pre-release defaults to unwanted required=True, in 3.7.0+ it was fixed to =False return basic_parser.add_subparsers(title='required arguments', metavar='<command>', required=False) else: # py36 does not support required=... argument (but behaves like required=False). # note: use below call for 3.6 and 3.7 when there are no alphas/betas/RCs of 3.7.0 around any more. return basic_parser.add_subparsers(title='required arguments', metavar='<command>') @pytest.fixture def parser(self, basic_parser): basic_parser.common_options.add_common_group(basic_parser, '_level0', provide_defaults=True) return basic_parser @pytest.fixture def common_parser(self, parser): common_parser = argparse.ArgumentParser(add_help=False, prog='test') parser.common_options.add_common_group(common_parser, '_level1') return common_parser @pytest.fixture def parse_vars_from_line(self, parser, subparsers, common_parser): subparser = subparsers.add_parser('subcommand', parents=[common_parser], add_help=False, description='foo', epilog='bar', help='baz', formatter_class=argparse.RawDescriptionHelpFormatter) subparser.set_defaults(func=1234) subparser.add_argument('--append-only', dest='append_only', action='store_true') def parse_vars_from_line(*line): print(line) args = parser.parse_args(line) parser.common_options.resolve(args) return vars(args) return parse_vars_from_line def test_simple(self, parse_vars_from_line): assert parse_vars_from_line('--error') == { 'append': [], 'lock_wait': 1, 'log_level': 'error', 'progress': False } assert parse_vars_from_line('--error', 'subcommand', '--critical') == { 'append': [], 'lock_wait': 1, 'log_level': 'critical', 'progress': False, 'append_only': False, 'func': 1234, } with pytest.raises(SystemExit): parse_vars_from_line('--append-only', 'subcommand') assert parse_vars_from_line('--append=foo', '--append', 'bar', 'subcommand', '--append', 'baz') == { 'append': ['foo', 'bar', 'baz'], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } @pytest.mark.parametrize('position', ('before', 'after', 'both')) @pytest.mark.parametrize('flag,args_key,args_value', ( ('-p', 'progress', True), ('--lock-wait=3', 'lock_wait', 3), )) def test_flag_position_independence(self, parse_vars_from_line, position, flag, args_key, args_value): line = [] if position in ('before', 'both'): line.append(flag) line.append('subcommand') if position in ('after', 'both'): line.append(flag) result = { 'append': [], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } result[args_key] = args_value assert parse_vars_from_line(*line) == result def test_parse_storage_quota(): assert parse_storage_quota('50M') == 50 * 1000**2 with pytest.raises(argparse.ArgumentTypeError): parse_storage_quota('5M') def get_all_parsers(): """ Return dict mapping command to parser. """ parser = Archiver(prog='borg').build_parser() borgfs_parser = Archiver(prog='borgfs').build_parser() parsers = {} def discover_level(prefix, parser, Archiver, extra_choices=None): choices = {} for action in parser._actions: if action.choices is not None and 'SubParsersAction' in str(action.__class__): for cmd, parser in action.choices.items(): choices[prefix + cmd] = parser if extra_choices is not None: choices.update(extra_choices) if prefix and not choices: return for command, parser in sorted(choices.items()): discover_level(command + " ", parser, Archiver) parsers[command] = parser discover_level("", parser, Archiver, {'borgfs': borgfs_parser}) return parsers @pytest.mark.parametrize('command, parser', list(get_all_parsers().items())) def test_help_formatting(command, parser): if isinstance(parser.epilog, RstToTextLazy): assert parser.epilog.rst @pytest.mark.parametrize('topic, helptext', list(Archiver.helptext.items())) def test_help_formatting_helptexts(topic, helptext): assert str(rst_to_terminal(helptext))
51.418547
148
0.630304
import argparse import dateutil.tz import errno import io import json import logging import os import pstats import random import re import shutil import socket import stat import subprocess import sys import tempfile import time import unittest from binascii import unhexlify, b2a_base64 from configparser import ConfigParser from datetime import datetime from datetime import timezone from datetime import timedelta from hashlib import sha256 from io import BytesIO, StringIO from unittest.mock import patch import pytest import borg from .. import xattr, helpers, platform from ..archive import Archive, ChunkBuffer from ..archiver import Archiver, parse_storage_quota, PURE_PYTHON_MSGPACK_WARNING from ..cache import Cache, LocalCache from ..chunker import has_seek_hole from ..constants import * from ..crypto.low_level import bytes_to_long, num_cipher_blocks from ..crypto.key import KeyfileKeyBase, RepoKey, KeyfileKey, Passphrase, TAMRequiredError from ..crypto.keymanager import RepoIdMismatch, NotABorgKeyFile from ..crypto.file_integrity import FileIntegrityError from ..helpers import Location, get_security_dir from ..helpers import Manifest, MandatoryFeatureUnsupported from ..helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR from ..helpers import bin_to_hex from ..helpers import MAX_S from ..helpers import msgpack from ..helpers import flags_noatime, flags_normal from ..nanorst import RstToTextLazy, rst_to_terminal from ..patterns import IECommand, PatternMatcher, parse_pattern from ..item import Item, ItemDiff from ..locking import LockFailed from ..logger import setup_logging from ..remote import RemoteRepository, PathNotAllowed from ..repository import Repository from . import has_lchflags, llfuse from . import BaseTestCase, changedir, environment_variable, no_selinux from . import are_symlinks_supported, are_hardlinks_supported, are_fifos_supported, is_utime_fully_supported, is_birthtime_fully_supported from .platform import fakeroot_detected from .upgrader import make_attic_repo from . import key src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) def exec_cmd(*args, archiver=None, fork=False, exe=None, input=b'', binary_output=False, **kw): if fork: try: if exe is None: borg = (sys.executable, '-m', 'borg.archiver') elif isinstance(exe, str): borg = (exe, ) elif not isinstance(exe, tuple): raise ValueError('exe must be None, a tuple or a str') output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT, input=input) ret = 0 except subprocess.CalledProcessError as e: output = e.output ret = e.returncode except SystemExit as e: output = '' ret = e.code if binary_output: return ret, output else: return ret, os.fsdecode(output) else: stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr try: sys.stdin = StringIO(input.decode()) sys.stdin.buffer = BytesIO(input) output = BytesIO() output_text = sys.stdout = sys.stderr = io.TextIOWrapper(output, encoding='utf-8') if archiver is None: archiver = Archiver() archiver.prerun_checks = lambda *args: None archiver.exit_code = EXIT_SUCCESS helpers.exit_code = EXIT_SUCCESS try: args = archiver.parse_args(list(args)) except SystemExit as e: output_text.flush() return e.code, output.getvalue() if binary_output else output.getvalue().decode() ret = archiver.run(args) output_text.flush() return ret, output.getvalue() if binary_output else output.getvalue().decode() finally: sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr def have_gnutar(): if not shutil.which('tar'): return False popen = subprocess.Popen(['tar', '--version'], stdout=subprocess.PIPE) stdout, stderr = popen.communicate() return b'GNU tar' in stdout try: exec_cmd('help', exe='borg.exe', fork=True) BORG_EXES = ['python', 'binary', ] except FileNotFoundError: BORG_EXES = ['python', ] @pytest.fixture(params=BORG_EXES) def cmd(request): if request.param == 'python': exe = None elif request.param == 'binary': exe = 'borg.exe' else: raise ValueError("param must be 'python' or 'binary'") def exec_fn(*args, **kw): return exec_cmd(*args, exe=exe, fork=True, **kw) return exec_fn def test_return_codes(cmd, tmpdir): repo = tmpdir.mkdir('repo') input = tmpdir.mkdir('input') output = tmpdir.mkdir('output') input.join('test_file').write('content') rc, out = cmd('init', '--encryption=none', '%s' % str(repo)) assert rc == EXIT_SUCCESS rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_SUCCESS with changedir(str(output)): rc, out = cmd('extract', '%s::archive' % repo) assert rc == EXIT_SUCCESS rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match') assert rc == EXIT_WARNING rc, out = cmd('create', '%s::archive' % repo, str(input)) assert rc == EXIT_ERROR DF_MOUNT = '/tmp/borg-mount' @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT) def test_disk_full(cmd): def make_files(dir, count, size, rnd=True): shutil.rmtree(dir, ignore_errors=True) os.mkdir(dir) if rnd: count = random.randint(1, count) if size > 1: size = random.randint(1, size) for i in range(count): fn = os.path.join(dir, "file%03d" % i) with open(fn, 'wb') as f: data = os.urandom(size) f.write(data) with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='YES'): mount = DF_MOUNT assert os.path.exists(mount) repo = os.path.join(mount, 'repo') input = os.path.join(mount, 'input') reserve = os.path.join(mount, 'reserve') for j in range(100): shutil.rmtree(repo, ignore_errors=True) shutil.rmtree(input, ignore_errors=True) make_files(reserve, 80, 100000, rnd=False) rc, out = cmd('init', repo) if rc != EXIT_SUCCESS: print('init', rc, out) assert rc == EXIT_SUCCESS try: success, i = True, 0 while success: i += 1 try: make_files(input, 20, 200000) except OSError as err: if err.errno == errno.ENOSPC: break raise try: rc, out = cmd('create', '%s::test%03d' % (repo, i), input) success = rc == EXIT_SUCCESS if not success: print('create', rc, out) finally: shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True) os.remove(os.path.join(repo, 'lock.roster')) finally: shutil.rmtree(reserve, ignore_errors=True) rc, out = cmd('list', repo) if rc != EXIT_SUCCESS: print('list', rc, out) rc, out = cmd('check', '--repair', repo) if rc != EXIT_SUCCESS: print('check', rc, out) assert rc == EXIT_SUCCESS class ArchiverTestCaseBase(BaseTestCase): EXE = None FORK_DEFAULT = False prefix = '' def setUp(self): os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' os.environ['BORG_PASSPHRASE'] = 'waytooeasyonlyfortests' self.archiver = not self.FORK_DEFAULT and Archiver() or None self.tmpdir = tempfile.mkdtemp() self.repository_path = os.path.join(self.tmpdir, 'repository') self.repository_location = self.prefix + self.repository_path self.input_path = os.path.join(self.tmpdir, 'input') self.output_path = os.path.join(self.tmpdir, 'output') self.keys_path = os.path.join(self.tmpdir, 'keys') self.cache_path = os.path.join(self.tmpdir, 'cache') self.exclude_file_path = os.path.join(self.tmpdir, 'excludes') self.patterns_file_path = os.path.join(self.tmpdir, 'patterns') os.environ['BORG_KEYS_DIR'] = self.keys_path os.environ['BORG_CACHE_DIR'] = self.cache_path os.mkdir(self.input_path) os.chmod(self.input_path, 0o777) os.mkdir(self.output_path) os.mkdir(self.keys_path) os.mkdir(self.cache_path) with open(self.exclude_file_path, 'wb') as fd: fd.write(b'input/file2\n# A comment line, then a blank line\n\n') with open(self.patterns_file_path, 'wb') as fd: fd.write(b'+input/file_important\n- input/file*\n# A comment line, then a blank line\n\n') self._old_wd = os.getcwd() os.chdir(self.tmpdir) def tearDown(self): os.chdir(self._old_wd) shutil.rmtree(self.tmpdir, ignore_errors=True) setup_logging() def cmd(self, *args, **kw): exit_code = kw.pop('exit_code', 0) fork = kw.pop('fork', None) binary_output = kw.get('binary_output', False) if fork is None: fork = self.FORK_DEFAULT ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw) if ret != exit_code: print(output) self.assert_equal(ret, exit_code) pp_msg = PURE_PYTHON_MSGPACK_WARNING.encode() if binary_output else PURE_PYTHON_MSGPACK_WARNING empty = b'' if binary_output else '' output = empty.join(line for line in output.splitlines(keepends=True) if pp_msg not in line) return output def create_src_archive(self, name): self.cmd('create', '--compression=lz4', self.repository_location + '::' + name, src_dir) def open_archive(self, name): repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, name) return archive, repository def open_repository(self): return Repository(self.repository_path, exclusive=True) def create_regular_file(self, name, size=0, contents=None): assert not (size != 0 and contents and len(contents) != size), 'size and contents do not match' filename = os.path.join(self.input_path, name) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'wb') as fd: if contents is None: contents = b'X' * size fd.write(contents) def create_test_files(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('flagfile', size=1024) self.create_regular_file('dir2/file2', size=1024 * 80) os.chmod('input/file1', 0o4755) if are_hardlinks_supported(): os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'hardlink')) if are_symlinks_supported(): os.symlink('somewhere', os.path.join(self.input_path, 'link1')) self.create_regular_file('fusexattr', size=1) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): fn = os.fsencode(os.path.join(self.input_path, 'fusexattr')) xattr.setxattr(fn, b'user.foo', b'bar') xattr.setxattr(fn, b'user.empty', b'') if are_fifos_supported(): os.mkfifo(os.path.join(self.input_path, 'fifo1')) if has_lchflags: platform.set_flags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP) try: os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20)) os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40)) os.chmod('input/dir2', 0o555) os.chown('input/file1', 100, 200) have_root = True except PermissionError: have_root = False except OSError as e: if e.errno not in (errno.EINVAL, errno.ENOSYS): raise have_root = False time.sleep(1) self.create_regular_file('empty', size=0) return have_root class ArchiverTestCase(ArchiverTestCaseBase): requires_hardlinks = pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_basic_functionality(self): have_root = self.create_test_files() output = self.cmd('init', '--encryption=repokey', '--show-version', '--show-rc', self.repository_location, fork=True) self.assert_in('borgbackup version', output) self.assert_in('terminating with success status, rc 0', output) self.cmd('create', '--exclude-nodump', self.repository_location + '::test', 'input') output = self.cmd('create', '--exclude-nodump', '--stats', self.repository_location + '::test.2', 'input') self.assert_in('Archive name: test.2', output) self.assert_in('This archive: ', output) with changedir('output'): self.cmd('extract', self.repository_location + '::test') list_output = self.cmd('list', '--short', self.repository_location) self.assert_in('test', list_output) self.assert_in('test.2', list_output) expected = [ 'input', 'input/bdev', 'input/cdev', 'input/dir2', 'input/dir2/file2', 'input/empty', 'input/file1', 'input/flagfile', ] if are_fifos_supported(): expected.append('input/fifo1') if are_symlinks_supported(): expected.append('input/link1') if are_hardlinks_supported(): expected.append('input/hardlink') if not have_root: expected.remove('input/bdev') expected.remove('input/cdev') if has_lchflags: expected.remove('input/flagfile') os.remove(os.path.join('input', 'flagfile')) list_output = self.cmd('list', '--short', self.repository_location + '::test') for name in expected: self.assert_in(name, list_output) self.assert_dirs_equal('input', 'output/input') info_output = self.cmd('info', self.repository_location + '::test') item_count = 4 if has_lchflags else 5 self.assert_in('Number of files: %d' % item_count, info_output) shutil.rmtree(self.cache_path) info_output2 = self.cmd('info', self.repository_location + '::test') def filter(output): prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:', 'All archives:', 'Chunk index:', ] result = [] for line in output.splitlines(): for prefix in prefixes: if line.startswith(prefix): result.append(line) return '\n'.join(result) self.assert_equal(filter(info_output), filter(info_output2)) @requires_hardlinks def test_create_duplicate_root(self): path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert sorted(paths) == ['input', 'input/a', 'input/a/hardlink', 'input/b', 'input/b/hardlink'] def test_init_parent_dirs(self): parent_path = os.path.join(self.tmpdir, 'parent1', 'parent2') repository_path = os.path.join(parent_path, 'repository') repository_location = self.prefix + repository_path with pytest.raises(Repository.ParentPathDoesNotExist): self.cmd('init', '--encryption=none', repository_location) self.cmd('init', '--encryption=none', '--make-parent-dirs', repository_location) assert os.path.exists(parent_path) def test_unix_socket(self): self.cmd('init', '--encryption=repokey', self.repository_location) try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(os.path.join(self.input_path, 'unix-socket')) except PermissionError as err: if err.errno == errno.EPERM: pytest.skip('unix sockets disabled or not supported') elif err.errno == errno.EACCES: pytest.skip('permission denied to create unix sockets') self.cmd('create', self.repository_location + '::test', 'input') sock.close() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert not os.path.exists('input/unix-socket') @pytest.mark.skipif(not are_symlinks_supported(), reason='symlinks not supported') def test_symlink_extract(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.readlink('input/link1') == 'somewhere' @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') def test_atime(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: with open(os.open(some_file, flags_noatime)) as file: file.read() except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.create_test_files() atime, mtime = 123456780, 234567890 have_noatime = has_noatime('input/file1') os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--atime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 if have_noatime: assert sti.st_atime_ns == sto.st_atime_ns == atime * 1e9 else: assert sto.st_atime_ns == atime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_birthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == int(sto.st_birthtime * 1e9) == birthtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 @pytest.mark.skipif(not is_utime_fully_supported(), reason='cannot properly setup and execute test without utime') @pytest.mark.skipif(not is_birthtime_fully_supported(), reason='cannot properly setup and execute test without birthtime') def test_nobirthtime(self): self.create_test_files() birthtime, mtime, atime = 946598400, 946684800, 946771200 os.utime('input/file1', (atime, birthtime)) os.utime('input/file1', (atime, mtime)) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--nobirthtime', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') sti = os.stat('input/file1') sto = os.stat('output/input/file1') assert int(sti.st_birthtime * 1e9) == birthtime * 1e9 assert int(sto.st_birthtime * 1e9) == mtime * 1e9 assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9 def _extract_repository_id(self, path): with Repository(self.repository_path) as repository: return repository.id def _set_repository_id(self, path, id): config = ConfigParser(interpolation=None) config.read(os.path.join(path, 'config')) config.set('repository', 'id', bin_to_hex(id)) with open(os.path.join(path, 'config'), 'w') as fd: config.write(fd) with Repository(self.repository_path) as repository: return repository.id def test_sparse_file(self): def is_sparse(fn, total_size, hole_size): st = os.stat(fn) assert st.st_size == total_size sparse = True if sparse and hasattr(st, 'st_blocks') and st.st_blocks * 512 >= st.st_size: sparse = False if sparse and has_seek_hole: with open(fn, 'rb') as fd: # only check if the first hole is as expected, because the 2nd hole check # is problematic on xfs due to its "dynamic speculative EOF preallocation try: if fd.seek(0, os.SEEK_HOLE) != 0: sparse = False if fd.seek(0, os.SEEK_DATA) != hole_size: sparse = False except OSError: # OS/FS does not really support SEEK_HOLE/SEEK_DATA sparse = False return sparse filename = os.path.join(self.input_path, 'sparse') content = b'foobar' hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers total_size = hole_size + len(content) + hole_size with open(filename, 'wb') as fd: # create a file that has a hole at the beginning and end (if the # OS and filesystem supports sparse files) fd.seek(hole_size, 1) fd.write(content) fd.seek(hole_size, 1) pos = fd.tell() fd.truncate(pos) # we first check if we could create a sparse input file: sparse_support = is_sparse(filename, total_size, hole_size) if sparse_support: # we could create a sparse input file, so creating a backup of it and # extracting it again (as sparse) should also work: self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir(self.output_path): self.cmd('extract', '--sparse', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') filename = os.path.join(self.output_path, 'input', 'sparse') with open(filename, 'rb') as fd: # check if file contents are as expected self.assert_equal(fd.read(hole_size), b'\0' * hole_size) self.assert_equal(fd.read(len(content)), content) self.assert_equal(fd.read(hole_size), b'\0' * hole_size) self.assert_true(is_sparse(filename, total_size, hole_size)) def test_unusual_filenames(self): filenames = ['normal', 'with some blanks', '(with_parens)', ] for filename in filenames: filename = os.path.join(self.input_path, filename) with open(filename, 'wb'): pass self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') for filename in filenames: with changedir('output'): self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename)) assert os.path.exists(os.path.join('output', 'input', filename)) def test_repository_swap_detection(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_no_cache(self): self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = self._extract_repository_id(self.repository_path) self.cmd('create', self.repository_location + '::test', 'input') shutil.rmtree(self.repository_path) self.cmd('init', '--encryption=none', self.repository_location) self._set_repository_id(self.repository_path, repository_id) self.assert_equal(repository_id, self._extract_repository_id(self.repository_path)) self.cmd('delete', '--cache-only', self.repository_location) if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.EncryptionMethodMismatch): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_swap_detection2_no_cache(self): self.create_test_files() self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted') os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted') self.cmd('create', self.repository_location + '_encrypted::test', 'input') self.cmd('delete', '--cache-only', self.repository_location + '_unencrypted') self.cmd('delete', '--cache-only', self.repository_location + '_encrypted') shutil.rmtree(self.repository_path + '_encrypted') os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted') if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.RepositoryAccessAborted): self.cmd('create', self.repository_location + '_encrypted::test.2', 'input') def test_repository_swap_detection_repokey_blank_passphrase(self): # Check that a repokey repo with a blank passphrase is considered like a plaintext repo. self.create_test_files() # User initializes her repository with her passphrase self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Attacker replaces it with her own repository, which is encrypted but has no passphrase set shutil.rmtree(self.repository_path) with environment_variable(BORG_PASSPHRASE=''): self.cmd('init', '--encryption=repokey', self.repository_location) # Delete cache & security database, AKA switch to user perspective self.cmd('delete', '--cache-only', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) shutil.rmtree(get_security_dir(repository_id)) with environment_variable(BORG_PASSPHRASE=None): # This is the part were the user would be tricked, e.g. she assumes that BORG_PASSPHRASE # is set, while it isn't. Previously this raised no warning, # since the repository is, technically, encrypted. if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('create', self.repository_location + '::test.2', 'input') def test_repository_move(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) os.rename(self.repository_path, self.repository_path + '_new') with environment_variable(BORG_RELOCATED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location + '_new') security_dir = get_security_dir(repository_id) with open(os.path.join(security_dir, 'location')) as fd: location = fd.read() assert location == Location(self.repository_location + '_new').canonical_path() # Needs no confirmation anymore self.cmd('info', self.repository_location + '_new') shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location + '_new') shutil.rmtree(security_dir) self.cmd('info', self.repository_location + '_new') for file in ('location', 'key-type', 'manifest-timestamp'): assert os.path.exists(os.path.join(security_dir, file)) def test_security_dir_compat(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) security_dir = get_security_dir(repository_id) with open(os.path.join(security_dir, 'location'), 'w') as fd: fd.write('something outdated') # This is fine, because the cache still has the correct information. security_dir and cache can disagree # if older versions are used to confirm a renamed repository. self.cmd('info', self.repository_location) def test_unknown_unencrypted(self): self.cmd('init', '--encryption=none', self.repository_location) repository_id = bin_to_hex(self._extract_repository_id(self.repository_path)) security_dir = get_security_dir(repository_id) # Ok: repository is known self.cmd('info', self.repository_location) # Ok: repository is still known (through security_dir) shutil.rmtree(self.cache_path) self.cmd('info', self.repository_location) # Needs confirmation: cache and security dir both gone (eg. another host or rm -rf ~) shutil.rmtree(self.cache_path) shutil.rmtree(security_dir) if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises(Cache.CacheInitAbortedError): self.cmd('info', self.repository_location) with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='yes'): self.cmd('info', self.repository_location) def test_strip_components(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '3') self.assert_true(not os.path.exists('file')) with self.assert_creates_file('file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') with self.assert_creates_file('dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '1') with self.assert_creates_file('input/dir/file'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '0') def _extract_hardlinks_setup(self): os.mkdir(os.path.join(self.input_path, 'dir1')) os.mkdir(os.path.join(self.input_path, 'dir1/subdir')) self.create_regular_file('source', contents=b'123456') os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'abba')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/hardlink')) os.link(os.path.join(self.input_path, 'source'), os.path.join(self.input_path, 'dir1/subdir/hardlink')) self.create_regular_file('dir1/source2') os.link(os.path.join(self.input_path, 'dir1/source2'), os.path.join(self.input_path, 'dir1/aaaa')) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') @requires_hardlinks @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_hardlinks(self): self._extract_hardlinks_setup() mountpoint = os.path.join(self.tmpdir, 'mountpoint') # we need to get rid of permissions checking because fakeroot causes issues with it. # On all platforms, borg defaults to "default_permissions" and we need to get rid of it via "ignore_permissions". # On macOS (darwin), we additionally need "defer_permissions" to switch off the checks in osxfuse. if sys.platform == 'darwin': ignore_perms = ['-o', 'ignore_permissions,defer_permissions'] else: ignore_perms = ['-o', 'ignore_permissions'] with self.fuse_mount(self.repository_location + '::test', mountpoint, '--strip-components=2', *ignore_perms), \ changedir(mountpoint): assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, 'input/dir1', *ignore_perms), \ changedir(mountpoint): assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with self.fuse_mount(self.repository_location + '::test', mountpoint, *ignore_perms), \ changedir(mountpoint): assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks1(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/source').st_nlink == 4 assert os.stat('input/abba').st_nlink == 4 assert os.stat('input/dir1/hardlink').st_nlink == 4 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 4 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' @requires_hardlinks def test_extract_hardlinks2(self): self._extract_hardlinks_setup() with changedir('output'): self.cmd('extract', self.repository_location + '::test', '--strip-components', '2') assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert open('subdir/hardlink', 'rb').read() == b'123456' assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/dir1') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert open('input/dir1/subdir/hardlink', 'rb').read() == b'123456' assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 @requires_hardlinks def test_extract_hardlinks_twice(self): # setup for #5603 path_a = os.path.join(self.input_path, 'a') path_b = os.path.join(self.input_path, 'b') os.mkdir(path_a) os.mkdir(path_b) hl_a = os.path.join(path_a, 'hardlink') hl_b = os.path.join(path_b, 'hardlink') self.create_regular_file(hl_a, contents=b'123456') os.link(hl_a, hl_b) self.cmd('init', '--encryption=none', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') # give input twice! # now test extraction with changedir('output'): self.cmd('extract', self.repository_location + '::test') # if issue #5603 happens, extraction gives rc == 1 (triggering AssertionError) and warnings like: # input/a/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/a/hardlink' # input/b/hardlink: link: [Errno 2] No such file or directory: 'input/a/hardlink' -> 'input/b/hardlink' # otherwise, when fixed, the hardlinks should be there and have a link count of 2 assert os.stat('input/a/hardlink').st_nlink == 2 assert os.stat('input/b/hardlink').st_nlink == 2 def test_extract_include_exclude(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test', 'input/file1', ) self.assert_equal(sorted(os.listdir('output/input')), ['file1']) with changedir('output'): self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3']) def test_extract_include_exclude_regex(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) # Create with regular expression exclusion for file4 self.cmd('create', '--exclude=re:input/file4$', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Extract with regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude=re:file3+', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Combine --exclude with fnmatch and regular expression with changedir('output'): self.cmd('extract', '--exclude=input/file2', '--exclude=re:file[01]', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3', 'file333']) shutil.rmtree('output/input') # Combine --exclude-from and regular expression exclusion with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, '--exclude=re:file1', '--exclude=re:file(\\d)\\1\\1$', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_include_exclude_regex_from_file(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file3', size=1024 * 80) self.create_regular_file('file4', size=1024 * 80) self.create_regular_file('file333', size=1024 * 80) self.create_regular_file('aa:something', size=1024 * 80) # Create while excluding using mixed pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:input/file4$\n') fd.write(b'fm:*aa:*thing\n') self.cmd('create', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333']) shutil.rmtree('output/input') # Exclude using regular expression with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file3+\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2']) shutil.rmtree('output/input') # Mixed exclude pattern styles with open(self.exclude_file_path, 'wb') as fd: fd.write(b're:file(\\d)\\1\\1$\n') fd.write(b'fm:nothingwillmatchthis\n') fd.write(b'*/file1\n') fd.write(b're:file2$\n') with changedir('output'): self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file3']) def test_extract_with_pattern(self): self.cmd("init", '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) self.create_regular_file("file333", size=1024 * 80) self.cmd("create", self.repository_location + "::test", "input") # Extract everything with regular expression with changedir("output"): self.cmd("extract", self.repository_location + "::test", "re:.*") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file3", "file333", "file4"]) shutil.rmtree("output/input") # Extract with pattern while also excluding files with changedir("output"): self.cmd("extract", "--exclude=re:file[34]$", self.repository_location + "::test", r"re:file\d$") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2"]) shutil.rmtree("output/input") # Combine --exclude with pattern for extraction with changedir("output"): self.cmd("extract", "--exclude=input/file1", self.repository_location + "::test", "re:file[12]$") self.assert_equal(sorted(os.listdir("output/input")), ["file2"]) shutil.rmtree("output/input") # Multiple pattern with changedir("output"): self.cmd("extract", self.repository_location + "::test", "fm:input/file1", "fm:*file33*", "input/file2") self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file333"]) def test_extract_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--info', self.repository_location + '::test') self.assert_not_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', self.repository_location + '::test') self.assert_in("input/file", output) shutil.rmtree('output/input') with changedir('output'): output = self.cmd('extract', '--list', '--info', self.repository_location + '::test') self.assert_in("input/file", output) def test_extract_progress(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('extract', self.repository_location + '::test', '--progress') assert 'Extracting:' in output def _create_test_caches(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('cache1/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('cache2/%s' % CACHE_TAG_NAME, contents=b'invalid signature') os.mkdir('input/cache3') if are_hardlinks_supported(): os.link('input/cache1/%s' % CACHE_TAG_NAME, 'input/cache3/%s' % CACHE_TAG_NAME) else: self.create_regular_file('cache3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') def test_create_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = b'\x00foo\n\nbar\n \n' self.cmd('create', self.repository_location + '::test', '-', input=input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) assert item['path'] == 'stdin' extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test', binary_output=True) assert extracted_data == input_data def test_create_content_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) input_data = 'some test content' name = 'a/b/c' self.cmd('create', '--stdin-name', name, '--content-from-command', self.repository_location + '::test', '--', 'echo', input_data) item = json.loads(self.cmd('list', '--json-lines', self.repository_location + '::test')) assert item['uid'] == 0 assert item['gid'] == 0 assert item['size'] == len(input_data) + 1 # `echo` adds newline assert item['path'] == name extracted_data = self.cmd('extract', '--stdout', self.repository_location + '::test') assert extracted_data == input_data + '\n' def test_create_content_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_content_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--content-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_paths_from_stdin(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("dir1/file2", size=1024 * 80) self.create_regular_file("dir1/file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = b'input/file1\0input/dir1\0input/file4' self.cmd('create', '--paths-from-stdin', '--paths-delimiter', '\\0', self.repository_location + '::test', input=input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/dir1', 'input/file4'] def test_create_paths_from_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file("file1", size=1024 * 80) self.create_regular_file("file2", size=1024 * 80) self.create_regular_file("file3", size=1024 * 80) self.create_regular_file("file4", size=1024 * 80) input_data = 'input/file1\ninput/file2\ninput/file3' self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'echo', input_data) archive_list = self.cmd('list', '--json-lines', self.repository_location + '::test') paths = [json.loads(line)['path'] for line in archive_list.split('\n') if line] assert paths == ['input/file1', 'input/file2', 'input/file3'] def test_create_paths_from_command_with_failed_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', '--', 'sh', '-c', 'exit 73;', exit_code=2) assert output.endswith("Command 'sh' exited with status 73\n") archive_list = json.loads(self.cmd('list', '--json', self.repository_location)) assert archive_list['archives'] == [] def test_create_paths_from_command_missing_command(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--paths-from-command', self.repository_location + '::test', exit_code=2) assert output.endswith('No command given.\n') def test_create_without_root(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', exit_code=2) def test_create_pattern_root(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=R input', self.repository_location + '::test') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) def test_create_pattern(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) def test_create_pattern_file(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('otherfile', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--pattern=-input/otherfile', '--patterns-from=' + self.patterns_file_path, self.repository_location + '::test', 'input') self.assert_in("A input/file_important", output) self.assert_in('x input/file1', output) self.assert_in('x input/file2', output) self.assert_in('x input/otherfile', output) def test_create_pattern_exclude_folder_but_recurse(self): self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_in('x input/x/a/foo_a', output) self.assert_in("A input/x/b/foo_b", output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_exclude_folder_no_recurse(self): self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/b\n! input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) self.create_regular_file('y/foo_y', size=1024 * 80) output = self.cmd('create', '-v', '--list', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', 'input') self.assert_not_in('input/x/a/foo_a', output) self.assert_not_in('input/x/a', output) self.assert_in('A input/y/foo_y', output) def test_create_pattern_intermediate_folders_first(self): self.patterns_file_path2 = os.path.join(self.tmpdir, 'patterns2') with open(self.patterns_file_path2, 'wb') as fd: fd.write(b'+ input/x/a\n+ input/x/b\n- input/x*\n') self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('x/a/foo_a', size=1024 * 80) self.create_regular_file('x/b/foo_b', size=1024 * 80) with changedir('input'): self.cmd('create', '--patterns-from=' + self.patterns_file_path2, self.repository_location + '::test', '.') # list the archive and verify that the "intermediate" folders appear before # their contents out = self.cmd('list', '--format', '{type} {path}{NL}', self.repository_location + '::test') out_list = out.splitlines() self.assert_in('d x/a', out_list) self.assert_in('d x/b', out_list) assert out_list.index('d x/a') < out_list.index('- x/a/foo_a') assert out_list.index('d x/b') < out_list.index('- x/b/foo_b') def test_create_no_cache_sync(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) create_json = json.loads(self.cmd('create', '--no-cache-sync', self.repository_location + '::test', 'input', '--json', '--error')) # ignore experimental warning info_json = json.loads(self.cmd('info', self.repository_location + '::test', '--json')) create_stats = create_json['cache']['stats'] info_stats = info_json['cache']['stats'] assert create_stats == info_stats self.cmd('delete', '--cache-only', self.repository_location) self.cmd('create', '--no-cache-sync', self.repository_location + '::test2', 'input') self.cmd('info', self.repository_location) self.cmd('check', self.repository_location) def test_extract_pattern_opt(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) self.create_regular_file('file_important', size=1024 * 80) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): self.cmd('extract', '--pattern=+input/file_important', '--pattern=-input/file*', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file_important']) def _assert_test_caches(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1']) self.assert_equal(sorted(os.listdir('output/input/cache2')), [CACHE_TAG_NAME]) def test_exclude_caches(self): self._create_test_caches() self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input') self._assert_test_caches() def test_recreate_exclude_caches(self): self._create_test_caches() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-caches', self.repository_location + '::test') self._assert_test_caches() def _create_test_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('tagged1/.NOBACKUP') self.create_regular_file('tagged2/00-NOBACKUP') self.create_regular_file('tagged3/.NOBACKUP/file2', size=1024) def _assert_test_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file1']) def test_exclude_tagged(self): self._create_test_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input') self._assert_test_tagged() def test_recreate_exclude_tagged(self): self._create_test_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test') self._assert_test_tagged() def _create_test_keep_tagged(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file0', size=1024) self.create_regular_file('tagged1/.NOBACKUP1') self.create_regular_file('tagged1/file1', size=1024) self.create_regular_file('tagged2/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('tagged2/file2', size=1024) self.create_regular_file('tagged3/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('tagged3/file3', size=1024) self.create_regular_file('taggedall/.NOBACKUP1') self.create_regular_file('taggedall/.NOBACKUP2/subfile1', size=1024) self.create_regular_file('taggedall/%s' % CACHE_TAG_NAME, contents=CACHE_TAG_CONTENTS + b' extra stuff') self.create_regular_file('taggedall/file4', size=1024) def _assert_test_keep_tagged(self): with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall']) self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1']) self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2']) self.assert_equal(os.listdir('output/input/tagged3'), [CACHE_TAG_NAME]) self.assert_equal(sorted(os.listdir('output/input/taggedall')), ['.NOBACKUP1', '.NOBACKUP2', CACHE_TAG_NAME, ]) def test_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test', 'input') self._assert_test_keep_tagged() def test_recreate_exclude_keep_tagged(self): self._create_test_keep_tagged() self.cmd('create', self.repository_location + '::test', 'input') self.cmd('recreate', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') self._assert_test_keep_tagged() @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_hardlinked_tags(self): # test for issue #4911 self.cmd('init', '--encryption=none', self.repository_location) self.create_regular_file('file1', contents=CACHE_TAG_CONTENTS) # "wrong" filename, but correct tag contents os.mkdir(os.path.join(self.input_path, 'subdir')) # to make sure the tag is encountered *after* file1 os.link(os.path.join(self.input_path, 'file1'), os.path.join(self.input_path, 'subdir', CACHE_TAG_NAME)) # correct tag name, hardlink to file1 self.cmd('create', self.repository_location + '::test', 'input') # in the "test" archive, we now have, in this order: # - a regular file item for "file1" # - a hardlink item for "CACHEDIR.TAG" referring back to file1 for its contents self.cmd('recreate', '--exclude-caches', '--keep-exclude-tags', self.repository_location + '::test') # if issue #4911 is present, the recreate will crash with a KeyError for "input/file1" @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='Linux capabilities test, requires fakeroot >= 1.20.2') def test_extract_capabilities(self): fchown = os.fchown # We need to manually patch chown to get the behaviour Linux has, since fakeroot does not # accurately model the interaction of chown(2) and Linux capabilities, i.e. it does not remove them. def patched_fchown(fd, uid, gid): xattr.setxattr(fd, b'security.capability', b'', follow_symlinks=False) fchown(fd, uid, gid) # The capability descriptor used here is valid and taken from a /usr/bin/ping capabilities = b'\x01\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' self.create_regular_file('file') xattr.setxattr(b'input/file', b'security.capability', capabilities) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): with patch.object(os, 'fchown', patched_fchown): self.cmd('extract', self.repository_location + '::test') assert xattr.getxattr(b'input/file', b'security.capability') == capabilities @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='xattr not supported on this system or on this version of' 'fakeroot') def test_extract_xattrs_errors(self): def patched_setxattr_E2BIG(*args, **kwargs): raise OSError(errno.E2BIG, 'E2BIG') def patched_setxattr_ENOTSUP(*args, **kwargs): raise OSError(errno.ENOTSUP, 'ENOTSUP') def patched_setxattr_EACCES(*args, **kwargs): raise OSError(errno.EACCES, 'EACCES') self.create_regular_file('file') xattr.setxattr(b'input/file', b'user.attribute', b'value') self.cmd('init', self.repository_location, '-e' 'none') self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): input_abspath = os.path.abspath('input/file') with patch.object(xattr, 'setxattr', patched_setxattr_E2BIG): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: too big for this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_ENOTSUP): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: xattrs not supported on this filesystem\n' in out os.remove(input_abspath) with patch.object(xattr, 'setxattr', patched_setxattr_EACCES): out = self.cmd('extract', self.repository_location + '::test', exit_code=EXIT_WARNING) assert ': when setting extended attribute user.attribute: Permission denied\n' in out assert os.path.isfile(input_abspath) def test_path_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir1/dir2/file', size=1024 * 80) with changedir('input/dir1/dir2'): self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..') output = self.cmd('list', self.repository_location + '::test') self.assert_not_in('..', output) self.assert_in(' input/dir1/dir2/file', output) def test_exclude_normalization(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('file2', size=1024 * 80) with changedir('input'): self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test1') self.assert_equal(sorted(os.listdir('output')), ['file2']) with changedir('input'): self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.') with changedir('output'): self.cmd('extract', self.repository_location + '::test2') self.assert_equal(sorted(os.listdir('output')), ['file2']) self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input') with changedir('output'): self.cmd('extract', self.repository_location + '::test3') self.assert_equal(sorted(os.listdir('output/input')), ['file2']) def test_repeated_files(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', 'input') def test_overwrite(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') # Overwriting regular files and directories should be supported os.mkdir('output/input') os.mkdir('output/input/file1') os.mkdir('output/input/dir2') with changedir('output'): self.cmd('extract', self.repository_location + '::test') self.assert_dirs_equal('input', 'output/input') # But non-empty dirs should fail os.unlink('output/input/file1') os.mkdir('output/input/file1') os.mkdir('output/input/file1/dir') with changedir('output'): self.cmd('extract', self.repository_location + '::test', exit_code=1) def test_rename(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test', 'test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('rename', self.repository_location + '::test.2', 'test.4') self.cmd('extract', '--dry-run', self.repository_location + '::test.3') self.cmd('extract', '--dry-run', self.repository_location + '::test.4') # Make sure both archives have been renamed with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 2) self.assert_in('test.3', manifest.archives) self.assert_in('test.4', manifest.archives) def test_info(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = self.cmd('info', self.repository_location) assert 'All archives:' in info_repo info_archive = self.cmd('info', self.repository_location + '::test') assert 'Archive name: test\n' in info_archive info_archive = self.cmd('info', '--first', '1', self.repository_location) assert 'Archive name: test\n' in info_archive def test_info_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_repo = json.loads(self.cmd('info', '--json', self.repository_location)) repository = info_repo['repository'] assert len(repository['id']) == 64 assert 'last_modified' in repository assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert info_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in info_repo['encryption'] cache = info_repo['cache'] stats = cache['stats'] assert all(isinstance(o, int) for o in stats.values()) assert all(key in stats for key in ('total_chunks', 'total_csize', 'total_size', 'total_unique_chunks', 'unique_csize', 'unique_size')) info_archive = json.loads(self.cmd('info', '--json', self.repository_location + '::test')) assert info_repo['repository'] == info_archive['repository'] assert info_repo['cache'] == info_archive['cache'] archives = info_archive['archives'] assert len(archives) == 1 archive = archives[0] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive assert datetime.strptime(archive['start'], ISO_FORMAT) assert datetime.strptime(archive['end'], ISO_FORMAT) def test_comment(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', '--comment', 'this is the comment', self.repository_location + '::test2', 'input') self.cmd('create', '--comment', '"deleted" comment', self.repository_location + '::test3', 'input') self.cmd('create', '--comment', 'preserved comment', self.repository_location + '::test4', 'input') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: this is the comment' in self.cmd('info', self.repository_location + '::test2') self.cmd('recreate', self.repository_location + '::test1', '--comment', 'added comment') self.cmd('recreate', self.repository_location + '::test2', '--comment', 'modified comment') self.cmd('recreate', self.repository_location + '::test3', '--comment', '') self.cmd('recreate', self.repository_location + '::test4', '12345') assert 'Comment: added comment' in self.cmd('info', self.repository_location + '::test1') assert 'Comment: modified comment' in self.cmd('info', self.repository_location + '::test2') assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test3') assert 'Comment: preserved comment' in self.cmd('info', self.repository_location + '::test4') def test_delete(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') self.cmd('create', self.repository_location + '::test.3', 'input') self.cmd('create', self.repository_location + '::another_test.1', 'input') self.cmd('create', self.repository_location + '::another_test.2', 'input') self.cmd('extract', '--dry-run', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') self.cmd('delete', '--prefix', 'another_', self.repository_location) self.cmd('delete', '--last', '1', self.repository_location) self.cmd('delete', self.repository_location + '::test') self.cmd('extract', '--dry-run', self.repository_location + '::test.2') output = self.cmd('delete', '--stats', self.repository_location + '::test.2') self.assert_in('Deleted data:', output) # Make sure all data except the manifest has been deleted with Repository(self.repository_path) as repository: self.assert_equal(len(repository), 1) def test_delete_multiple(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('create', self.repository_location + '::test3', 'input') self.cmd('delete', self.repository_location + '::test1', 'test2') self.cmd('extract', '--dry-run', self.repository_location + '::test3') self.cmd('delete', self.repository_location, 'test3') assert not self.cmd('list', self.repository_location) def test_delete_repo(self): self.create_regular_file('file1', size=1024 * 80) self.create_regular_file('dir2/file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('create', self.repository_location + '::test.2', 'input') os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'no' self.cmd('delete', self.repository_location, exit_code=2) assert os.path.exists(self.repository_path) os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES' self.cmd('delete', self.repository_location) # Make sure the repo is gone self.assertFalse(os.path.exists(self.repository_path)) def test_delete_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) break else: assert False # missed the file repository.commit(compact=False) output = self.cmd('delete', '--force', self.repository_location + '::test') self.assert_in('deleted archive was corrupted', output) self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_delete_double_force(self): self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('test') with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) archive = Archive(repository, key, manifest, 'test') id = archive.metadata.items[0] repository.put(id, b'corrupted items metadata stream chunk') repository.commit(compact=False) self.cmd('delete', '--force', '--force', self.repository_location + '::test') self.cmd('check', '--repair', self.repository_location) output = self.cmd('list', self.repository_location) self.assert_not_in('test', output) def test_corrupted_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') self.cmd('extract', '--dry-run', self.repository_location + '::test') output = self.cmd('check', '--show-version', self.repository_location) self.assert_in('borgbackup version', output) # implied output even without --info given self.assert_not_in('Starting repository check', output) # --info not given for root logger name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[1] with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd: fd.seek(100) fd.write(b'XXXX') output = self.cmd('check', '--info', self.repository_location, exit_code=1) self.assert_in('Starting repository check', output) # --info given for root logger def test_readonly_check(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('check', '--verify-data', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('check', '--verify-data', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('check', '--verify-data', self.repository_location, '--bypass-lock') def test_readonly_diff(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('a') self.create_src_archive('b') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('diff', '%s::a' % self.repository_location, 'b', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('diff', '%s::a' % self.repository_location, 'b') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('diff', '%s::a' % self.repository_location, 'b', '--bypass-lock') def test_readonly_export_tar(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar') if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('export-tar', '%s::test' % self.repository_location, 'test.tar', '--bypass-lock') def test_readonly_extract(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('extract', '%s::test' % self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('extract', '%s::test' % self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('extract', '%s::test' % self.repository_location, '--bypass-lock') def test_readonly_info(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('info', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('info', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('info', self.repository_location, '--bypass-lock') def test_readonly_list(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: self.cmd('list', self.repository_location, exit_code=EXIT_ERROR) else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: self.cmd('list', self.repository_location) if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock self.cmd('list', self.repository_location, '--bypass-lock') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_readonly_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('test') with self.read_only(self.repository_path): # verify that command normally doesn't work with read-only repo if self.FORK_DEFAULT: with self.fuse_mount(self.repository_location, exit_code=EXIT_ERROR): pass else: with pytest.raises((LockFailed, RemoteRepository.RPCError)) as excinfo: # self.fuse_mount always assumes fork=True, so for this test we have to manually set fork=False with self.fuse_mount(self.repository_location, fork=False): pass if isinstance(excinfo.value, RemoteRepository.RPCError): assert excinfo.value.exception_class == 'LockFailed' # verify that command works with read-only repo when using --bypass-lock with self.fuse_mount(self.repository_location, None, '--bypass-lock'): pass @pytest.mark.skipif('BORG_TESTS_IGNORE_MODES' in os.environ, reason='modes unreliable') def test_umask(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') mode = os.stat(self.repository_path).st_mode self.assertEqual(stat.S_IMODE(mode), 0o700) def test_create_dry_run(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--dry-run', self.repository_location + '::test', 'input') # Make sure no archive has been created with Repository(self.repository_path) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) self.assert_equal(len(manifest.archives), 0) def add_unknown_feature(self, operation): with Repository(self.repository_path, exclusive=True) as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) manifest.config[b'feature_flags'] = {operation.value.encode(): {b'mandatory': [b'unknown-feature']}} manifest.write() repository.commit(compact=False) def cmd_raises_unknown_feature(self, args): if self.FORK_DEFAULT: self.cmd(*args, exit_code=EXIT_ERROR) else: with pytest.raises(MandatoryFeatureUnsupported) as excinfo: self.cmd(*args) assert excinfo.value.args == (['unknown-feature'],) def test_unknown_feature_on_create(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.WRITE) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_cache_sync(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('delete', '--cache-only', self.repository_location) self.add_unknown_feature(Manifest.Operation.READ) self.cmd_raises_unknown_feature(['create', self.repository_location + '::test', 'input']) def test_unknown_feature_on_change_passphrase(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['key', 'change-passphrase', self.repository_location]) def test_unknown_feature_on_read(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) with changedir('output'): self.cmd_raises_unknown_feature(['extract', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['list', self.repository_location]) self.cmd_raises_unknown_feature(['info', self.repository_location + '::test']) def test_unknown_feature_on_rename(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.CHECK) self.cmd_raises_unknown_feature(['rename', self.repository_location + '::test', 'other']) def test_unknown_feature_on_delete(self): print(self.cmd('init', '--encryption=repokey', self.repository_location)) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.DELETE) # delete of an archive raises self.cmd_raises_unknown_feature(['delete', self.repository_location + '::test']) self.cmd_raises_unknown_feature(['prune', '--keep-daily=3', self.repository_location]) # delete of the whole repository ignores features self.cmd('delete', self.repository_location) @unittest.skipUnless(llfuse, 'llfuse not installed') def test_unknown_feature_on_mount(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.add_unknown_feature(Manifest.Operation.READ) mountpoint = os.path.join(self.tmpdir, 'mountpoint') os.mkdir(mountpoint) # XXX this might hang if it doesn't raise an error self.cmd_raises_unknown_feature(['mount', self.repository_location + '::test', mountpoint]) @pytest.mark.allow_cache_wipe def test_unknown_mandatory_feature_in_cache(self): if self.prefix: path_prefix = 'ssh://__testsuite__' else: path_prefix = '' print(self.cmd('init', '--encryption=repokey', self.repository_location)) with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: cache.begin_txn() cache.cache_config.mandatory_features = set(['unknown-feature']) cache.commit() if self.FORK_DEFAULT: self.cmd('create', self.repository_location + '::test', 'input') else: called = False wipe_cache_safe = LocalCache.wipe_cache def wipe_wrapper(*args): nonlocal called called = True wipe_cache_safe(*args) with patch.object(LocalCache, 'wipe_cache', wipe_wrapper): self.cmd('create', self.repository_location + '::test', 'input') assert called with Repository(self.repository_path, exclusive=True) as repository: if path_prefix: repository._location = Location(self.repository_location) manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: assert cache.cache_config.mandatory_features == set([]) def test_progress_on(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input') self.assert_in("\r", output) def test_progress_off(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', self.repository_location + '::test5', 'input') self.assert_not_in("\r", output) def test_file_status(self): self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) # should find first file as unmodified output = self.cmd('create', '--list', self.repository_location + '::test1', 'input') self.assert_in("U input/file1", output) # this is expected, although surprising, for why, see: # https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file self.assert_in("A input/file2", output) def test_file_status_cs_cache_mode(self): self.create_regular_file('file1', contents=b'123') time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test1', 'input') # modify file1, but cheat with the mtime (and atime) and also keep same size: st = os.stat('input/file1') self.create_regular_file('file1', contents=b'321') os.utime('input/file1', ns=(st.st_atime_ns, st.st_mtime_ns)) # this mode uses ctime for change detection, so it should find file1 as modified output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test2', 'input') self.assert_in("M input/file1", output) def test_file_status_ms_cache_mode(self): self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test1', 'input') # change mode of file1, no content change: st = os.stat('input/file1') os.chmod('input/file1', st.st_mode ^ stat.S_IRWXO) # this triggers a ctime change, but mtime is unchanged # this mode uses mtime for change detection, so it should find file1 as unmodified output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test2', 'input') self.assert_in("U input/file1", output) def test_file_status_rc_cache_mode(self): self.create_regular_file('file1', size=10) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=10) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test1', 'input') # no changes here, but this mode rechunks unconditionally output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test2', 'input') self.assert_in("A input/file1", output) def test_file_status_excluded(self): self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) if has_lchflags: self.create_regular_file('file3', size=1024 * 80) platform.set_flags(os.path.join(self.input_path, 'file3'), stat.UF_NODUMP) self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test', 'input') self.assert_in("A input/file1", output) self.assert_in("A input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) # should find second file as excluded output = self.cmd('create', '--list', '--exclude-nodump', self.repository_location + '::test1', 'input', '--exclude', '*/file2') self.assert_in("U input/file1", output) self.assert_in("x input/file2", output) if has_lchflags: self.assert_in("x input/file3", output) def test_create_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) create_info = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) # The usual keys assert 'encryption' in create_info assert 'repository' in create_info assert 'cache' in create_info assert 'last_modified' in create_info['repository'] archive = create_info['archive'] assert archive['name'] == 'test' assert isinstance(archive['command_line'], list) assert isinstance(archive['duration'], float) assert len(archive['id']) == 64 assert 'stats' in archive def test_create_topical(self): self.create_regular_file('file1', size=1024 * 80) time.sleep(1) # file2 must have newer timestamps than file1 self.create_regular_file('file2', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) # no listing by default output = self.cmd('create', self.repository_location + '::test', 'input') self.assert_not_in('file1', output) # shouldn't be listed even if unchanged output = self.cmd('create', self.repository_location + '::test0', 'input') self.assert_not_in('file1', output) # should list the file as unchanged output = self.cmd('create', '--list', '--filter=U', self.repository_location + '::test1', 'input') self.assert_in('file1', output) # should *not* list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test2', 'input') self.assert_not_in('file1', output) # change the file self.create_regular_file('file1', size=1024 * 100) # should list the file as changed output = self.cmd('create', '--list', '--filter=AM', self.repository_location + '::test3', 'input') self.assert_in('file1', output) @pytest.mark.skipif(not are_fifos_supported(), reason='FIFOs not supported') def test_create_read_special_symlink(self): from threading import Thread def fifo_feeder(fifo_fn, data): fd = os.open(fifo_fn, os.O_WRONLY) try: os.write(fd, data) finally: os.close(fd) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' data = b'foobar' * 1000 fifo_fn = os.path.join(self.input_path, 'fifo') link_fn = os.path.join(self.input_path, 'link_fifo') os.mkfifo(fifo_fn) os.symlink(fifo_fn, link_fn) t = Thread(target=fifo_feeder, args=(fifo_fn, data)) t.start() try: self.cmd('create', '--read-special', archive, 'input/link_fifo') finally: t.join() with changedir('output'): self.cmd('extract', archive) fifo_fn = 'input/link_fifo' with open(fifo_fn, 'rb') as f: extracted_data = f.read() assert extracted_data == data def test_create_read_special_broken_symlink(self): os.symlink('somewhere does not exist', os.path.join(self.input_path, 'link')) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '--read-special', archive, 'input') output = self.cmd('list', archive) assert 'input/link -> somewhere does not exist' in output # def test_cmdline_compatibility(self): # self.create_regular_file('file1', size=1024 * 80) # self.cmd('init', '--encryption=repokey', self.repository_location) # self.cmd('create', self.repository_location + '::test', 'input') # output = self.cmd('foo', self.repository_location, '--old') # self.assert_in('"--old" has been deprecated. Use "--new" instead', output) def test_prune_repository(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test3.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) self.cmd('create', self.repository_location + '::test4.checkpoint', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Would prune:\s+test1', output) # must keep the latest non-checkpoint archive: assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) # must keep the latest checkpoint archive: assert re.search(r'Keeping checkpoint archive:\s+test4.checkpoint', output) output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.assert_in('test3.checkpoint', output) self.assert_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) self.cmd('prune', self.repository_location, '--keep-daily=1') output = self.cmd('list', '--consider-checkpoints', self.repository_location) self.assert_not_in('test1', output) # the latest non-checkpoint archive must be still there: self.assert_in('test2', output) # only the latest checkpoint archive must still be there: self.assert_not_in('test3.checkpoint', output) self.assert_not_in('test3.checkpoint.1', output) self.assert_in('test4.checkpoint', output) # now we supercede the latest checkpoint by a successful backup: self.cmd('create', self.repository_location + '::test5', src_dir) self.cmd('prune', self.repository_location, '--keep-daily=2') output = self.cmd('list', '--consider-checkpoints', self.repository_location) # all checkpoints should be gone now: self.assert_not_in('checkpoint', output) # the latest archive must be still there self.assert_in('test5', output) # Given a date and time in local tz, create a UTC timestamp string suitable # for create --timestamp command line option def _to_utc_timestamp(self, year, month, day, hour, minute, second): dtime = datetime(year, month, day, hour, minute, second, 0, dateutil.tz.gettz()) return dtime.astimezone(dateutil.tz.UTC).strftime("%Y-%m-%dT%H:%M:%S") def _create_archive_ts(self, name, y, m, d, H=0, M=0, S=0): loc = self.repository_location + '::' + name self.cmd('create', '--timestamp', self._to_utc_timestamp(y, m, d, H, M, S), loc, src_dir) # This test must match docs/misc/prune-example.txt def test_prune_repository_example(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Archives that will be kept, per the example # Oldest archive self._create_archive_ts('test01', 2015, 1, 1) # 6 monthly archives self._create_archive_ts('test02', 2015, 6, 30) self._create_archive_ts('test03', 2015, 7, 31) self._create_archive_ts('test04', 2015, 8, 31) self._create_archive_ts('test05', 2015, 9, 30) self._create_archive_ts('test06', 2015, 10, 31) self._create_archive_ts('test07', 2015, 11, 30) # 14 daily archives self._create_archive_ts('test08', 2015, 12, 17) self._create_archive_ts('test09', 2015, 12, 18) self._create_archive_ts('test10', 2015, 12, 20) self._create_archive_ts('test11', 2015, 12, 21) self._create_archive_ts('test12', 2015, 12, 22) self._create_archive_ts('test13', 2015, 12, 23) self._create_archive_ts('test14', 2015, 12, 24) self._create_archive_ts('test15', 2015, 12, 25) self._create_archive_ts('test16', 2015, 12, 26) self._create_archive_ts('test17', 2015, 12, 27) self._create_archive_ts('test18', 2015, 12, 28) self._create_archive_ts('test19', 2015, 12, 29) self._create_archive_ts('test20', 2015, 12, 30) self._create_archive_ts('test21', 2015, 12, 31) # Additional archives that would be pruned # The second backup of the year self._create_archive_ts('test22', 2015, 1, 2) # The next older monthly backup self._create_archive_ts('test23', 2015, 5, 31) # The next older daily backup self._create_archive_ts('test24', 2015, 12, 16) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') # Prune second backup of the year assert re.search(r'Would prune:\s+test22', output) # Prune next older monthly and daily backups assert re.search(r'Would prune:\s+test23', output) assert re.search(r'Would prune:\s+test24', output) # Must keep the other 21 backups # Yearly is kept as oldest archive assert re.search(r'Keeping archive \(rule: yearly\[oldest\] #1\):\s+test01', output) for i in range(1, 7): assert re.search(r'Keeping archive \(rule: monthly #' + str(i) + r'\):\s+test' + ("%02d" % (8-i)), output) for i in range(1, 15): assert re.search(r'Keeping archive \(rule: daily #' + str(i) + r'\):\s+test' + ("%02d" % (22-i)), output) output = self.cmd('list', self.repository_location) # Nothing pruned after dry run for i in range(1, 25): self.assert_in('test%02d' % i, output) self.cmd('prune', self.repository_location, '--keep-daily=14', '--keep-monthly=6', '--keep-yearly=1') output = self.cmd('list', self.repository_location) # All matching backups plus oldest kept for i in range(1, 22): self.assert_in('test%02d' % i, output) # Other backups have been pruned for i in range(22, 25): self.assert_not_in('test%02d' % i, output) # With an initial and daily backup, prune daily until oldest is replaced by a monthly backup def test_prune_retain_and_expire_oldest(self): self.cmd('init', '--encryption=repokey', self.repository_location) # Initial backup self._create_archive_ts('original_archive', 2020, 9, 1, 11, 15) # Archive and prune daily for 30 days for i in range(1, 31): self._create_archive_ts('september%02d' % i, 2020, 9, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Archive and prune 6 days into the next month for i in range(1, 7): self._create_archive_ts('october%02d' % i, 2020, 10, i, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Oldest backup is still retained output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly\[oldest\] #1' + r'\):\s+original_archive', output) # Archive one more day and prune. self._create_archive_ts('october07', 2020, 10, 7, 12) self.cmd('prune', self.repository_location, '--keep-daily=7', '--keep-monthly=1') # Last day of previous month is retained as monthly, and oldest is expired. output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=7', '--keep-monthly=1') assert re.search(r'Keeping archive \(rule: monthly #1\):\s+september30', output) self.assert_not_in('original_archive', output) def test_prune_repository_save_space(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) self.cmd('create', self.repository_location + '::test2', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1') assert re.search(r'Keeping archive \(rule: daily #1\):\s+test2', output) assert re.search(r'Would prune:\s+test1', output) output = self.cmd('list', self.repository_location) self.assert_in('test1', output) self.assert_in('test2', output) self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=1') output = self.cmd('list', self.repository_location) self.assert_not_in('test1', output) self.assert_in('test2', output) def test_prune_repository_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir) self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--prefix=foo-') assert re.search(r'Keeping archive \(rule: daily #1\):\s+foo-2015-08-12-20:00', output) assert re.search(r'Would prune:\s+foo-2015-08-12-10:00', output) output = self.cmd('list', self.repository_location) self.assert_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--prefix=foo-') output = self.cmd('list', self.repository_location) self.assert_not_in('foo-2015-08-12-10:00', output) self.assert_in('foo-2015-08-12-20:00', output) self.assert_in('bar-2015-08-12-10:00', output) self.assert_in('bar-2015-08-12-20:00', output) def test_prune_repository_glob(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::2015-08-12-10:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-foo', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-10:00-bar', src_dir) self.cmd('create', self.repository_location + '::2015-08-12-20:00-bar', src_dir) output = self.cmd('prune', '--list', '--dry-run', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') assert re.search(r'Keeping archive \(rule: daily #1\):\s+2015-08-12-20:00-foo', output) assert re.search(r'Would prune:\s+2015-08-12-10:00-foo', output) output = self.cmd('list', self.repository_location) self.assert_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) self.cmd('prune', self.repository_location, '--keep-daily=1', '--glob-archives=2015-*-foo') output = self.cmd('list', self.repository_location) self.assert_not_in('2015-08-12-10:00-foo', output) self.assert_in('2015-08-12-20:00-foo', output) self.assert_in('2015-08-12-10:00-bar', output) self.assert_in('2015-08-12-20:00-bar', output) def test_list_prefix(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test-1', src_dir) self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir) self.cmd('create', self.repository_location + '::test-2', src_dir) output = self.cmd('list', '--prefix=test-', self.repository_location) self.assert_in('test-1', output) self.assert_in('test-2', output) self.assert_not_in('something-else', output) def test_list_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, src_dir) output_1 = self.cmd('list', test_archive) output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {mtime} {path}{extra}{NEWLINE}', test_archive) output_3 = self.cmd('list', '--format', '{mtime:%s} {path}{NL}', test_archive) self.assertEqual(output_1, output_2) self.assertNotEqual(output_1, output_3) def test_list_repository_format(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--comment', 'comment 1', self.repository_location + '::test-1', src_dir) self.cmd('create', '--comment', 'comment 2', self.repository_location + '::test-2', src_dir) output_1 = self.cmd('list', self.repository_location) output_2 = self.cmd('list', '--format', '{archive:<36} {time} [{id}]{NL}', self.repository_location) self.assertEqual(output_1, output_2) output_1 = self.cmd('list', '--short', self.repository_location) self.assertEqual(output_1, 'test-1\ntest-2\n') output_1 = self.cmd('list', '--format', '{barchive}/', self.repository_location) self.assertEqual(output_1, 'test-1/test-2/') output_3 = self.cmd('list', '--format', '{name} {comment}{NL}', self.repository_location) self.assert_in('test-1 comment 1\n', output_3) self.assert_in('test-2 comment 2\n', output_3) def test_list_hash(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('amb', contents=b'a' * 1000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{sha256} {path}{NL}', test_archive) assert "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 input/amb" in output assert "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 input/empty_file" in output def test_list_consider_checkpoints(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test1', src_dir) # these are not really a checkpoints, but they look like some: self.cmd('create', self.repository_location + '::test2.checkpoint', src_dir) self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir) output = self.cmd('list', self.repository_location) assert "test1" in output assert "test2.checkpoint" not in output assert "test3.checkpoint.1" not in output output = self.cmd('list', '--consider-checkpoints', self.repository_location) assert "test1" in output assert "test2.checkpoint" in output assert "test3.checkpoint.1" in output def test_list_chunk_counts(self): self.create_regular_file('empty_file', size=0) self.create_regular_file('two_chunks') with open(os.path.join(self.input_path, 'two_chunks'), 'wb') as fd: fd.write(b'abba' * 2000000) fd.write(b'baab' * 2000000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', test_archive, 'input') output = self.cmd('list', '--format', '{num_chunks} {unique_chunks} {path}{NL}', test_archive) assert "0 0 input/empty_file" in output assert "2 2 input/two_chunks" in output def test_list_size(self): self.create_regular_file('compressible_file', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) test_archive = self.repository_location + '::test' self.cmd('create', '-C', 'lz4', test_archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {dsize} {dcsize} {path}{NL}', test_archive) size, csize, dsize, dcsize, path = output.split("\n")[1].split(" ") assert int(csize) < int(size) assert int(dcsize) < int(dsize) assert int(dsize) <= int(size) assert int(dcsize) <= int(csize) def test_list_json(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list_repo = json.loads(self.cmd('list', '--json', self.repository_location)) repository = list_repo['repository'] assert len(repository['id']) == 64 assert datetime.strptime(repository['last_modified'], ISO_FORMAT) # must not raise assert list_repo['encryption']['mode'] == 'repokey' assert 'keyfile' not in list_repo['encryption'] archive0 = list_repo['archives'][0] assert datetime.strptime(archive0['time'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['size'] == 81920 assert datetime.strptime(file1['mtime'], ISO_FORMAT) # must not raise list_archive = self.cmd('list', '--json-lines', '--format={sha256}', self.repository_location + '::test') items = [json.loads(s) for s in list_archive.splitlines()] assert len(items) == 2 file1 = items[1] assert file1['path'] == 'input/file1' assert file1['sha256'] == 'b2915eb69f260d8d3c25249195f2c8f4f716ea82ec760ae929732c0262442b2b' def test_list_json_args(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('list', '--json-lines', self.repository_location, exit_code=2) self.cmd('list', '--json', self.repository_location + '::archive', exit_code=2) def test_log_json(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('create', '--log-json', self.repository_location + '::test', 'input', '--list', '--debug') messages = {} # type -> message, one of each kind for line in log.splitlines(): msg = json.loads(line) messages[msg['type']] = msg file_status = messages['file_status'] assert 'status' in file_status assert file_status['path'].startswith('input') log_message = messages['log_message'] assert isinstance(log_message['time'], float) assert log_message['levelname'] == 'DEBUG' # there should only be DEBUG messages assert isinstance(log_message['message'], str) def test_debug_profile(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '--debug-profile=create.prof') self.cmd('debug', 'convert-profile', 'create.prof', 'create.pyprof') stats = pstats.Stats('create.pyprof') stats.strip_dirs() stats.sort_stats('cumtime') self.cmd('create', self.repository_location + '::test2', 'input', '--debug-profile=create.pyprof') stats = pstats.Stats('create.pyprof') # Only do this on trusted data! stats.strip_dirs() stats.sort_stats('cumtime') def test_common_options(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) log = self.cmd('--debug', 'create', self.repository_location + '::test', 'input') assert 'security: read previous location' in log def _get_sizes(self, compression, compressible, size=10000): if compressible: contents = b'X' * size else: contents = os.urandom(size) self.create_regular_file('file', contents=contents) self.cmd('init', '--encryption=none', self.repository_location) archive = self.repository_location + '::test' self.cmd('create', '-C', compression, archive, 'input') output = self.cmd('list', '--format', '{size} {csize} {path}{NL}', archive) size, csize, path = output.split("\n")[1].split(" ") return int(size), int(csize) def test_compression_none_compressible(self): size, csize = self._get_sizes('none', compressible=True) assert csize == size + 3 def test_compression_none_uncompressible(self): size, csize = self._get_sizes('none', compressible=False) assert csize == size + 3 def test_compression_zlib_compressible(self): size, csize = self._get_sizes('zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 def test_compression_zlib_uncompressible(self): size, csize = self._get_sizes('zlib', compressible=False) assert csize >= size def test_compression_auto_compressible(self): size, csize = self._get_sizes('auto,zlib', compressible=True) assert csize < size * 0.1 assert csize == 35 # same as compression 'zlib' def test_compression_auto_uncompressible(self): size, csize = self._get_sizes('auto,zlib', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lz4_compressible(self): size, csize = self._get_sizes('lz4', compressible=True) assert csize < size * 0.1 def test_compression_lz4_uncompressible(self): size, csize = self._get_sizes('lz4', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_lzma_compressible(self): size, csize = self._get_sizes('lzma', compressible=True) assert csize < size * 0.1 def test_compression_lzma_uncompressible(self): size, csize = self._get_sizes('lzma', compressible=False) assert csize == size + 3 # same as compression 'none' def test_compression_zstd_compressible(self): size, csize = self._get_sizes('zstd', compressible=True) assert csize < size * 0.1 def test_compression_zstd_uncompressible(self): size, csize = self._get_sizes('zstd', compressible=False) assert csize == size + 3 # same as compression 'none' def test_change_passphrase(self): self.cmd('init', '--encryption=repokey', self.repository_location) os.environ['BORG_NEW_PASSPHRASE'] = 'newpassphrase' # here we have both BORG_PASSPHRASE and BORG_NEW_PASSPHRASE set: self.cmd('key', 'change-passphrase', self.repository_location) os.environ['BORG_PASSPHRASE'] = 'newpassphrase' self.cmd('list', self.repository_location) def test_break_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('break-lock', self.repository_location) def test_usage(self): self.cmd() self.cmd('-h') def test_help(self): assert 'Borg' in self.cmd('help') assert 'patterns' in self.cmd('help', 'patterns') assert 'Initialize' in self.cmd('help', 'init') assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only') assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only') @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse(self): def has_noatime(some_file): atime_before = os.stat(some_file).st_atime_ns try: os.close(os.open(some_file, flags_noatime)) except PermissionError: return False else: atime_after = os.stat(some_file).st_atime_ns noatime_used = flags_noatime != flags_normal return noatime_used and atime_before == atime_after self.cmd('init', '--encryption=repokey', self.repository_location) self.create_test_files() have_noatime = has_noatime('input/file1') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive', 'input') self.cmd('create', '--exclude-nodump', '--atime', self.repository_location + '::archive2', 'input') if has_lchflags: # remove the file we did not backup, so input and output become equal os.remove(os.path.join('input', 'flagfile')) mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in archivename subdirs of mountpoint: with self.fuse_mount(self.repository_location, mountpoint): # flags are not supported by the FUSE mount # we also ignore xattrs here, they are tested separately self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'), ignore_flags=True, ignore_xattrs=True) self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'), ignore_flags=True, ignore_xattrs=True) # mount only 1 archive, its contents shall show up directly in mountpoint: with self.fuse_mount(self.repository_location + '::archive', mountpoint): self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'), ignore_flags=True, ignore_xattrs=True) # regular file in_fn = 'input/file1' out_fn = os.path.join(mountpoint, 'input', 'file1') # stat sti1 = os.stat(in_fn) sto1 = os.stat(out_fn) assert sti1.st_mode == sto1.st_mode assert sti1.st_uid == sto1.st_uid assert sti1.st_gid == sto1.st_gid assert sti1.st_size == sto1.st_size if have_noatime: assert sti1.st_atime == sto1.st_atime assert sti1.st_ctime == sto1.st_ctime assert sti1.st_mtime == sto1.st_mtime if are_hardlinks_supported(): # note: there is another hardlink to this, see below assert sti1.st_nlink == sto1.st_nlink == 2 # read with open(in_fn, 'rb') as in_f, open(out_fn, 'rb') as out_f: assert in_f.read() == out_f.read() # hardlink (to 'input/file1') if are_hardlinks_supported(): in_fn = 'input/hardlink' out_fn = os.path.join(mountpoint, 'input', 'hardlink') sti2 = os.stat(in_fn) sto2 = os.stat(out_fn) assert sti2.st_nlink == sto2.st_nlink == 2 assert sto1.st_ino == sto2.st_ino # symlink if are_symlinks_supported(): in_fn = 'input/link1' out_fn = os.path.join(mountpoint, 'input', 'link1') sti = os.stat(in_fn, follow_symlinks=False) sto = os.stat(out_fn, follow_symlinks=False) assert sti.st_size == len('somewhere') assert sto.st_size == len('somewhere') assert stat.S_ISLNK(sti.st_mode) assert stat.S_ISLNK(sto.st_mode) assert os.readlink(in_fn) == os.readlink(out_fn) # FIFO if are_fifos_supported(): out_fn = os.path.join(mountpoint, 'input', 'fifo1') sto = os.stat(out_fn) assert stat.S_ISFIFO(sto.st_mode) # list/read xattrs try: in_fn = 'input/fusexattr' out_fn = os.fsencode(os.path.join(mountpoint, 'input', 'fusexattr')) if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path): assert sorted(no_selinux(xattr.listxattr(out_fn))) == [b'user.empty', b'user.foo', ] assert xattr.getxattr(out_fn, b'user.foo') == b'bar' assert xattr.getxattr(out_fn, b'user.empty') == b'' else: assert no_selinux(xattr.listxattr(out_fn)) == [] try: xattr.getxattr(out_fn, b'user.foo') except OSError as e: assert e.errno == llfuse.ENOATTR else: assert False, "expected OSError(ENOATTR), but no error was raised" except OSError as err: if sys.platform.startswith(('nothing_here_now', )) and err.errno == errno.ENOTSUP: # some systems have no xattr support on FUSE pass else: raise @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_versions_view(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('test', contents=b'first') if are_hardlinks_supported(): self.create_regular_file('hardlink1', contents=b'123456') os.link('input/hardlink1', 'input/hardlink2') os.link('input/hardlink1', 'input/hardlink3') self.cmd('create', self.repository_location + '::archive1', 'input') self.create_regular_file('test', contents=b'second') self.cmd('create', self.repository_location + '::archive2', 'input') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # mount the whole repository, archive contents shall show up in versioned view: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions'): path = os.path.join(mountpoint, 'input', 'test') # filename shows up as directory ... files = os.listdir(path) assert all(f.startswith('test.') for f in files) # ... with files test.xxxxx in there assert {b'first', b'second'} == {open(os.path.join(path, f), 'rb').read() for f in files} if are_hardlinks_supported(): hl1 = os.path.join(mountpoint, 'input', 'hardlink1', 'hardlink1.00001') hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl1).st_ino == os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' # similar again, but exclude the hardlink master: with self.fuse_mount(self.repository_location, mountpoint, '-o', 'versions', '-e', 'input/hardlink1'): if are_hardlinks_supported(): hl2 = os.path.join(mountpoint, 'input', 'hardlink2', 'hardlink2.00001') hl3 = os.path.join(mountpoint, 'input', 'hardlink3', 'hardlink3.00001') assert os.stat(hl2).st_ino == os.stat(hl3).st_ino assert open(hl3, 'rb').read() == b'123456' @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_allow_damaged_files(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive') # Get rid of a chunk and repair it archive, repository = self.open_archive('archive') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): repository.delete(item.chunks[-1].id) path = item.path # store full path for later break else: assert False # missed the file repository.commit(compact=False) self.cmd('check', '--repair', self.repository_location, exit_code=0) mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location + '::archive', mountpoint): with pytest.raises(OSError) as excinfo: open(os.path.join(mountpoint, path)) assert excinfo.value.errno == errno.EIO with self.fuse_mount(self.repository_location + '::archive', mountpoint, '-o', 'allow_damaged_files'): open(os.path.join(mountpoint, path)).close() @unittest.skipUnless(llfuse, 'llfuse not installed') def test_fuse_mount_options(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('arch11') self.create_src_archive('arch12') self.create_src_archive('arch21') self.create_src_archive('arch22') mountpoint = os.path.join(self.tmpdir, 'mountpoint') with self.fuse_mount(self.repository_location, mountpoint, '--first=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--last=2', '--sort=name'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch1'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch2'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=arch'): assert sorted(os.listdir(os.path.join(mountpoint))) == ['arch11', 'arch12', 'arch21', 'arch22'] with self.fuse_mount(self.repository_location, mountpoint, '--prefix=nope'): assert sorted(os.listdir(os.path.join(mountpoint))) == [] @unittest.skipUnless(llfuse, 'llfuse not installed') def test_migrate_lock_alive(self): from functools import wraps import pickle import traceback # Check results are communicated from the borg mount background process # to the pytest process by means of a serialized dict object stored in this file. assert_data_file = os.path.join(self.tmpdir, 'migrate_lock_assert_data.pickle') # Decorates Lock.migrate_lock() with process_alive() checks before and after. # (We don't want to mix testing code into runtime.) def write_assert_data(migrate_lock): @wraps(migrate_lock) def wrapper(self, old_id, new_id): wrapper.num_calls += 1 assert_data = { 'num_calls': wrapper.num_calls, 'old_id': old_id, 'new_id': new_id, 'before': { 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}, 'exception': None, 'exception.extr_tb': None, 'after': { 'old_id_alive': None, 'new_id_alive': None}} try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass try: return migrate_lock(self, old_id, new_id) except BaseException as e: assert_data['exception'] = e assert_data['exception.extr_tb'] = traceback.extract_tb(e.__traceback__) finally: assert_data['after'].update({ 'old_id_alive': platform.process_alive(*old_id), 'new_id_alive': platform.process_alive(*new_id)}) try: with open(assert_data_file, 'wb') as _out: pickle.dump(assert_data, _out) except: pass wrapper.num_calls = 0 return wrapper # Decorate borg.locking.Lock.migrate_lock = write_assert_data(borg.locking.Lock.migrate_lock) try: self.cmd('init', '--encryption=none', self.repository_location) self.create_src_archive('arch') mountpoint = os.path.join(self.tmpdir, 'mountpoint') # In order that the decoration is kept for the borg mount process, we must not spawn, but actually fork; # not to be confused with the forking in borg.helpers.daemonize() which is done as well. with self.fuse_mount(self.repository_location, mountpoint, os_fork=True): pass with open(assert_data_file, 'rb') as _in: assert_data = pickle.load(_in) print('\nLock.migrate_lock(): assert_data = %r.' % (assert_data, ), file=sys.stderr, flush=True) exception = assert_data['exception'] if exception is not None: extracted_tb = assert_data['exception.extr_tb'] print( 'Lock.migrate_lock() raised an exception:\n', 'Traceback (most recent call last):\n', *traceback.format_list(extracted_tb), *traceback.format_exception(exception.__class__, exception, None), sep='', end='', file=sys.stderr, flush=True) assert assert_data['num_calls'] == 1, "Lock.migrate_lock() must be called exactly once." assert exception is None, "Lock.migrate_lock() may not raise an exception." assert_data_before = assert_data['before'] assert assert_data_before['old_id_alive'], "old_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert assert_data_before['new_id_alive'], "new_id must be alive (=must not be stale) when calling Lock.migrate_lock()." assert_data_after = assert_data['after'] assert assert_data_after['old_id_alive'], "old_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." assert assert_data_after['new_id_alive'], "new_id must be alive (=must not be stale) when Lock.migrate_lock() has returned." finally: # Undecorate borg.locking.Lock.migrate_lock = borg.locking.Lock.migrate_lock.__wrapped__ def verify_aes_counter_uniqueness(self, method): seen = set() # Chunks already seen used = set() # counter values already used def verify_uniqueness(): with Repository(self.repository_path) as repository: for id, _ in repository.open_index(repository.get_transaction_id()).iteritems(): data = repository.get(id) hash = sha256(data).digest() if hash not in seen: seen.add(hash) num_blocks = num_cipher_blocks(len(data) - 41) nonce = bytes_to_long(data[33:41]) for counter in range(nonce, nonce + num_blocks): self.assert_not_in(counter, used) used.add(counter) self.create_test_files() os.environ['BORG_PASSPHRASE'] = 'passphrase' self.cmd('init', '--encryption=' + method, self.repository_location) verify_uniqueness() self.cmd('create', self.repository_location + '::test', 'input') verify_uniqueness() self.cmd('create', self.repository_location + '::test.2', 'input') verify_uniqueness() self.cmd('delete', self.repository_location + '::test.2') verify_uniqueness() def test_aes_counter_uniqueness_keyfile(self): self.verify_aes_counter_uniqueness('keyfile') def test_aes_counter_uniqueness_passphrase(self): self.verify_aes_counter_uniqueness('repokey') def test_debug_dump_archive_items(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-archive-items', self.repository_location + '::test') output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('000000_') assert 'Done.' in output def test_debug_dump_repo_objs(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with changedir('output'): output = self.cmd('debug', 'dump-repo-objs', self.repository_location) output_dir = sorted(os.listdir('output')) assert len(output_dir) > 0 and output_dir[0].startswith('00000000_') assert 'Done.' in output def test_debug_put_get_delete_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) data = b'some data' hexkey = sha256(data).hexdigest() self.create_regular_file('file', contents=data) output = self.cmd('debug', 'put-obj', self.repository_location, 'input/file') assert hexkey in output output = self.cmd('debug', 'get-obj', self.repository_location, hexkey, 'output/file') assert hexkey in output with open('output/file', 'rb') as f: data_read = f.read() assert data == data_read output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "deleted" in output output = self.cmd('debug', 'delete-obj', self.repository_location, hexkey) assert "not found" in output output = self.cmd('debug', 'delete-obj', self.repository_location, 'invalid') assert "is invalid" in output def test_init_interrupt(self): def raise_eof(*args): raise EOFError with patch.object(KeyfileKeyBase, 'create', raise_eof): self.cmd('init', '--encryption=repokey', self.repository_location, exit_code=1) assert not os.path.exists(self.repository_location) def test_init_requires_encryption_option(self): self.cmd('init', self.repository_location, exit_code=2) def test_init_nested_repositories(self): self.cmd('init', '--encryption=repokey', self.repository_location) if self.FORK_DEFAULT: self.cmd('init', '--encryption=repokey', self.repository_location + '/nested', exit_code=2) else: with pytest.raises(Repository.AlreadyExists): self.cmd('init', '--encryption=repokey', self.repository_location + '/nested') def check_cache(self): # First run a regular borg check self.cmd('check', self.repository_location) # Then check that the cache on disk matches exactly what's in the repo. with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: original_chunks = cache.chunks Cache.destroy(repository) with Cache(repository, key, manifest) as cache: correct_chunks = cache.chunks assert original_chunks is not correct_chunks seen = set() for id, (refcount, size, csize) in correct_chunks.iteritems(): o_refcount, o_size, o_csize = original_chunks[id] assert refcount == o_refcount assert size == o_size assert csize == o_csize seen.add(id) for id, (refcount, size, csize) in original_chunks.iteritems(): assert id in seen def test_check_cache(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') with self.open_repository() as repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest, sync=False) as cache: cache.begin_txn() cache.chunks.incref(list(cache.chunks.iteritems())[0][0]) cache.commit() with pytest.raises(AssertionError): self.check_cache() def test_recreate_target_rc(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('recreate', self.repository_location, '--target=asdf', exit_code=2) assert 'Need to specify single archive' in output def test_recreate_target(self): self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.check_cache() archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.check_cache() original_archive = self.cmd('list', self.repository_location) self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3', '--target=new-archive') self.check_cache() archives = self.cmd('list', self.repository_location) assert original_archive in archives assert 'new-archive' in archives archive = self.repository_location + '::new-archive' listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing def test_recreate_basic(self): self.create_test_files() self.create_regular_file('dir2/file3', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3') self.check_cache() listing = self.cmd('list', '--short', archive) assert 'file1' not in listing assert 'dir2/file2' in listing assert 'dir2/file3' not in listing @pytest.mark.skipif(not are_hardlinks_supported(), reason='hardlinks not supported') def test_recreate_subtree_hardlinks(self): # This is essentially the same problem set as in test_extract_hardlinks self._extract_hardlinks_setup() self.cmd('create', self.repository_location + '::test2', 'input') self.cmd('recreate', self.repository_location + '::test', 'input/dir1') self.check_cache() with changedir('output'): self.cmd('extract', self.repository_location + '::test') assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 with changedir('output'): self.cmd('extract', self.repository_location + '::test2') assert os.stat('input/dir1/hardlink').st_nlink == 4 def test_recreate_rechunkify(self): with open(os.path.join(self.input_path, 'large_file'), 'wb') as fd: fd.write(b'a' * 280) fd.write(b'b' * 280) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', '--chunker-params', '7,9,8,128', self.repository_location + '::test1', 'input') self.cmd('create', self.repository_location + '::test2', 'input', '--files-cache=disabled') list = self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{num_chunks} {unique_chunks}') num_chunks, unique_chunks = map(int, list.split(' ')) # test1 and test2 do not deduplicate assert num_chunks == unique_chunks self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() # test1 and test2 do deduplicate after recreate assert int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format={size}')) assert not int(self.cmd('list', self.repository_location + '::test1', 'input/large_file', '--format', '{unique_chunks}')) def test_recreate_recompress(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input', '-C', 'none') file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_before = file_list.split(' ') assert int(csize) >= int(size) # >= due to metadata overhead self.cmd('recreate', self.repository_location, '-C', 'lz4', '--recompress') self.check_cache() file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible', '--format', '{size} {csize} {sha256}') size, csize, sha256_after = file_list.split(' ') assert int(csize) < int(size) assert sha256_before == sha256_after def test_recreate_timestamp(self): local_timezone = datetime.now(timezone(timedelta(0))).astimezone().tzinfo self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) archive = self.repository_location + '::test0' self.cmd('create', archive, 'input') self.cmd('recreate', '--timestamp', "1970-01-02T00:00:00", '--comment', 'test', archive) info = self.cmd('info', archive).splitlines() dtime = datetime(1970, 1, 2) + local_timezone.utcoffset(None) s_time = dtime.strftime("%Y-%m-%d") assert any([re.search(r'Time \(start\).+ %s' % s_time, item) for item in info]) assert any([re.search(r'Time \(end\).+ %s' % s_time, item) for item in info]) def test_recreate_dry_run(self): self.create_regular_file('compressible', size=10000) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') archives_before = self.cmd('list', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '-n', '-e', 'input/compressible') self.check_cache() archives_after = self.cmd('list', self.repository_location + '::test') assert archives_after == archives_before def test_recreate_skips_nothing_to_do(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') info_before = self.cmd('info', self.repository_location + '::test') self.cmd('recreate', self.repository_location, '--chunker-params', 'default') self.check_cache() info_after = self.cmd('info', self.repository_location + '::test') assert info_before == info_after # includes archive ID def test_with_lock(self): self.cmd('init', '--encryption=repokey', self.repository_location) lock_path = os.path.join(self.repository_path, 'lock.exclusive') cmd = 'python3', '-c', 'import os, sys; sys.exit(42 if os.path.exists("%s") else 23)' % lock_path self.cmd('with-lock', self.repository_location, *cmd, fork=True, exit_code=42) def test_recreate_list_output(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('file1', size=0) self.create_regular_file('file2', size=0) self.create_regular_file('file3', size=0) self.create_regular_file('file4', size=0) self.create_regular_file('file5', size=0) self.cmd('create', self.repository_location + '::test', 'input') output = self.cmd('recreate', '--list', '--info', self.repository_location + '::test', '-e', 'input/file2') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file2", output) output = self.cmd('recreate', '--list', self.repository_location + '::test', '-e', 'input/file3') self.check_cache() self.assert_in("input/file1", output) self.assert_in("x input/file3", output) output = self.cmd('recreate', self.repository_location + '::test', '-e', 'input/file4') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file4", output) output = self.cmd('recreate', '--info', self.repository_location + '::test', '-e', 'input/file5') self.check_cache() self.assert_not_in("input/file1", output) self.assert_not_in("x input/file5", output) def test_bad_filters(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('delete', '--first', '1', '--last', '1', self.repository_location, fork=True, exit_code=2) def test_key_export_keyfile(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'r') as fd: key_contents = fd.read() assert key_contents == export_contents os.unlink(key_file) self.cmd('key', 'import', self.repository_location, export_file) with open(key_file, 'r') as fd: key_contents2 = fd.read() assert key_contents2 == key_contents def test_key_import_keyfile_with_borg_key_file(self): self.cmd('init', self.repository_location, '--encryption', 'keyfile') exported_key_file = os.path.join(self.output_path, 'exported') self.cmd('key', 'export', self.repository_location, exported_key_file) key_file = os.path.join(self.keys_path, os.listdir(self.keys_path)[0]) with open(key_file, 'r') as fd: key_contents = fd.read() os.unlink(key_file) imported_key_file = os.path.join(self.output_path, 'imported') with environment_variable(BORG_KEY_FILE=imported_key_file): self.cmd('key', 'import', self.repository_location, exported_key_file) assert not os.path.isfile(key_file), '"borg key import" should respect BORG_KEY_FILE' with open(imported_key_file, 'r') as fd: imported_key_contents = fd.read() assert imported_key_contents == key_contents def test_key_export_repokey(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n') with Repository(self.repository_path) as repository: repo_key = RepoKey(repository) repo_key.load(None, Passphrase.env_passphrase()) backup_key = KeyfileKey(key.TestKey.MockRepository()) backup_key.load(export_file, Passphrase.env_passphrase()) assert repo_key.enc_key == backup_key.enc_key with Repository(self.repository_path) as repository: repository.save_key(b'') self.cmd('key', 'import', self.repository_location, export_file) with Repository(self.repository_path) as repository: repo_key2 = RepoKey(repository) repo_key2.load(None, Passphrase.env_passphrase()) assert repo_key2.enc_key == repo_key2.enc_key def test_key_export_qr(self): export_file = self.output_path + '/exported.html' self.cmd('init', self.repository_location, '--encryption', 'repokey') repo_id = self._extract_repository_id(self.repository_path) self.cmd('key', 'export', '--qr-html', self.repository_location, export_file) with open(export_file, 'r', encoding='utf-8') as fd: export_contents = fd.read() assert bin_to_hex(repo_id) in export_contents assert export_contents.startswith('<!doctype html>') assert export_contents.endswith('</html>\n') def test_key_export_directory(self): export_directory = self.output_path + '/exported' os.mkdir(export_directory) self.cmd('init', self.repository_location, '--encryption', 'repokey') self.cmd('key', 'export', self.repository_location, export_directory, exit_code=EXIT_ERROR) def test_key_import_errors(self): export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self.cmd('key', 'import', self.repository_location, export_file, exit_code=EXIT_ERROR) with open(export_file, 'w') as fd: fd.write('something not a key\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(NotABorgKeyFile): self.cmd('key', 'import', self.repository_location, export_file) with open(export_file, 'w') as fd: fd.write('BORG_KEY a0a0a0\n') if self.FORK_DEFAULT: self.cmd('key', 'import', self.repository_location, export_file, exit_code=2) else: with pytest.raises(RepoIdMismatch): self.cmd('key', 'import', self.repository_location, export_file) def test_key_export_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' export_file = self.output_path + '/exported' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) self.cmd('key', 'export', '--paper', self.repository_location, export_file) with open(export_file, 'r') as fd: export_contents = fd.read() assert export_contents == """To restore key use borg key import --paper /path/to/repo BORG PAPER KEY v1 id: 2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02 1: 616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d 2: 737475 - 88 """ def test_key_import_paperkey(self): repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239' self.cmd('init', self.repository_location, '--encryption', 'keyfile') self._set_repository_id(self.repository_path, unhexlify(repo_id)) key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0] with open(key_file, 'w') as fd: fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n') fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode()) typed_input = ( b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 02\n' # Forgot to type "-" b'2 / e29442 3506da 4e1ea7 25f62a 5a3d41 - 02\n' # Forgot to type second "/" b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d42 - 02\n' # Typo (..42 not ..41) b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' # Correct! Congratulations b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'\n\n' # Abort [yN] => N b'737475 88\n' # missing "-" b'73747i - 88\n' # typo b'73747 - 88\n' # missing nibble b'73 74 75 - 89\n' # line checksum mismatch b'00a1 - 88\n' # line hash collision - overall hash mismatch, have to start over b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n' b'616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d\n' b'73 74 75 - 88\n' ) # In case that this has to change, here is a quick way to find a colliding line hash: # # from hashlib import sha256 # hash_fn = lambda x: sha256(b'\x00\x02' + x).hexdigest()[:2] # for i in range(1000): # if hash_fn(i.to_bytes(2, byteorder='big')) == '88': # 88 = line hash # print(i.to_bytes(2, 'big')) # break self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) # Test abort paths typed_input = b'\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) typed_input = b'2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02\n\ny\n' self.cmd('key', 'import', '--paper', self.repository_location, input=typed_input) def test_debug_dump_manifest(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-manifest', self.repository_location, dump_file) assert output == "" with open(dump_file, "r") as f: result = json.load(f) assert 'archives' in result assert 'config' in result assert 'item_keys' in result assert 'timestamp' in result assert 'version' in result def test_debug_dump_archive(self): self.create_regular_file('file1', size=1024 * 80) self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') dump_file = self.output_path + '/dump' output = self.cmd('debug', 'dump-archive', self.repository_location + "::test", dump_file) assert output == "" with open(dump_file, "r") as f: result = json.load(f) assert '_name' in result assert '_manifest_entry' in result assert '_meta' in result assert '_items' in result def test_debug_refcount_obj(self): self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('debug', 'refcount-obj', self.repository_location, '0' * 64).strip() assert output == 'object 0000000000000000000000000000000000000000000000000000000000000000 not found [info from chunks cache].' create_json = json.loads(self.cmd('create', '--json', self.repository_location + '::test', 'input')) archive_id = create_json['archive']['id'] output = self.cmd('debug', 'refcount-obj', self.repository_location, archive_id).strip() assert output == 'object ' + archive_id + ' has 1 referrers [info from chunks cache].' # Invalid IDs do not abort or return an error output = self.cmd('debug', 'refcount-obj', self.repository_location, '124', 'xyza').strip() assert output == 'object id 124 is invalid.\nobject id xyza is invalid.' def test_debug_info(self): output = self.cmd('debug', 'info') assert 'CRC implementation' in output assert 'Python' in output def test_benchmark_crud(self): self.cmd('init', '--encryption=repokey', self.repository_location) with environment_variable(_BORG_BENCHMARK_CRUD_TEST='YES'): self.cmd('benchmark', 'crud', self.repository_location, self.input_path) def test_config(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) output = self.cmd('config', '--list', self.repository_location) self.assert_in('[repository]', output) self.assert_in('version', output) self.assert_in('segments_per_dir', output) self.assert_in('storage_quota', output) self.assert_in('append_only', output) self.assert_in('additional_free_space', output) self.assert_in('id', output) self.assert_not_in('last_segment_checked', output) output = self.cmd('config', self.repository_location, 'last_segment_checked', exit_code=1) self.assert_in('No option ', output) self.cmd('config', self.repository_location, 'last_segment_checked', '123') output = self.cmd('config', self.repository_location, 'last_segment_checked') assert output == '123' + '\n' output = self.cmd('config', '--list', self.repository_location) self.assert_in('last_segment_checked', output) self.cmd('config', '--delete', self.repository_location, 'last_segment_checked') for cfg_key, cfg_value in [ ('additional_free_space', '2G'), ('repository.append_only', '1'), ]: output = self.cmd('config', self.repository_location, cfg_key) assert output == '0' + '\n' self.cmd('config', self.repository_location, cfg_key, cfg_value) output = self.cmd('config', self.repository_location, cfg_key) assert output == cfg_value + '\n' self.cmd('config', '--delete', self.repository_location, cfg_key) self.cmd('config', self.repository_location, cfg_key, exit_code=1) self.cmd('config', '--list', '--delete', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, exit_code=2) self.cmd('config', self.repository_location, 'invalid-option', exit_code=1) requires_gnutar = pytest.mark.skipif(not have_gnutar(), reason='GNU tar must be installed for this test.') requires_gzip = pytest.mark.skipif(not shutil.which('gzip'), reason='gzip must be installed for this test.') @requires_gnutar def test_export_tar(self): self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--progress') with changedir('output'): # This probably assumes GNU tar. Note -p switch to extract permissions regardless of umask. subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar @requires_gzip def test_export_tar_gz(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar.gz', '--list') assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar.gz', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/input', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_gnutar def test_export_tar_strip_components(self): if not shutil.which('gzip'): pytest.skip('gzip is not installed') self.create_test_files() os.unlink('input/flagfile') self.cmd('init', '--encryption=repokey', self.repository_location) self.cmd('create', self.repository_location + '::test', 'input') list = self.cmd('export-tar', self.repository_location + '::test', 'simple.tar', '--strip-components=1', '--list') # --list's path are those before processing with --strip-components assert 'input/file1\n' in list assert 'input/dir2\n' in list with changedir('output'): subprocess.check_call(['tar', 'xpf', '../simple.tar', '--warning=no-timestamp']) self.assert_dirs_equal('input', 'output/', ignore_flags=True, ignore_xattrs=True, ignore_ns=True) @requires_hardlinks @requires_gnutar def test_export_tar_strip_components_links(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', '--strip-components=2') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('hardlink').st_nlink == 2 assert os.stat('subdir/hardlink').st_nlink == 2 assert os.stat('aaaa').st_nlink == 2 assert os.stat('source2').st_nlink == 2 @requires_hardlinks @requires_gnutar def test_extract_hardlinks_tar(self): self._extract_hardlinks_setup() self.cmd('export-tar', self.repository_location + '::test', 'output.tar', 'input/dir1') with changedir('output'): subprocess.check_call(['tar', 'xpf', '../output.tar', '--warning=no-timestamp']) assert os.stat('input/dir1/hardlink').st_nlink == 2 assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2 assert os.stat('input/dir1/aaaa').st_nlink == 2 assert os.stat('input/dir1/source2').st_nlink == 2 def test_detect_attic_repo(self): path = make_attic_repo(self.repository_path) cmds = [ ['create', path + '::test', self.tmpdir], ['extract', path + '::test'], ['check', path], ['rename', path + '::test', 'newname'], ['list', path], ['delete', path], ['prune', path], ['info', path + '::test'], ['key', 'export', path, 'exported'], ['key', 'import', path, 'import'], ['key', 'change-passphrase', path], ['break-lock', path], ] for args in cmds: output = self.cmd(*args, fork=True, exit_code=2) assert 'Attic repository detected.' in output @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available') class ArchiverTestCaseBinary(ArchiverTestCase): EXE = 'borg.exe' FORK_DEFAULT = True @unittest.skip('does not raise Exception, but sets rc==2') def test_init_parent_dirs(self): pass @unittest.skip('patches objects') def test_init_interrupt(self): pass @unittest.skip('patches objects') def test_extract_capabilities(self): pass @unittest.skip('patches objects') def test_extract_xattrs_errors(self): pass @unittest.skip('test_basic_functionality seems incompatible with fakeroot and/or the binary.') def test_basic_functionality(self): pass @unittest.skip('test_overwrite seems incompatible with fakeroot and/or the binary.') def test_overwrite(self): pass def test_fuse(self): if fakeroot_detected(): unittest.skip('test_fuse with the binary is not compatible with fakeroot') else: super().test_fuse() class ArchiverCheckTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1') self.create_src_archive('archive2') def test_check_usage(self): output = self.cmd('check', '-v', '--progress', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) self.assert_in('Checking segments', output) # reset logging to new process default to avoid need for fork=True on next check logging.getLogger('borg.output.progress').setLevel(logging.NOTSET) output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0) self.assert_in('Starting repository check', output) self.assert_not_in('Starting archive consistency check', output) self.assert_not_in('Checking segments', output) output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0) self.assert_not_in('Starting repository check', output) self.assert_in('Starting archive consistency check', output) output = self.cmd('check', '-v', '--archives-only', '--prefix=archive2', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) output = self.cmd('check', '-v', '--archives-only', '--first=1', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_not_in('archive2', output) output = self.cmd('check', '-v', '--archives-only', '--last=1', self.repository_location, exit_code=0) self.assert_not_in('archive1', output) self.assert_in('archive2', output) def test_missing_file_chunk(self): archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): valid_chunks = item.chunks killed_chunk = valid_chunks[-1] repository.delete(killed_chunk.id) break else: self.fail('should not happen') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '--repair', self.repository_location, exit_code=0) self.assert_in('New missing file chunk detected', output) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_in('broken#', output) # check that the file in the old archives has now a different chunk list without the killed chunk for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_not_equal(valid_chunks, item.chunks) self.assert_not_in(killed_chunk, item.chunks) break else: self.fail('should not happen') # do a fresh backup (that will include the killed chunk) with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10): self.create_src_archive('archive3') # check should be able to heal the file now: output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('Healed previously missing file chunk', output) self.assert_in('testsuite/archiver.py: Completely healed previously damaged file!', output) # check that the file in the old archives has the correct chunks again for archive_name in ('archive1', 'archive2'): archive, repository = self.open_archive(archive_name) with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): self.assert_equal(valid_chunks, item.chunks) break else: self.fail('should not happen') # list is also all-healthy again output = self.cmd('list', '--format={health}#{path}{LF}', self.repository_location + '::archive1', exit_code=0) self.assert_not_in('broken#', output) def test_missing_archive_item_chunk(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.metadata.items[0]) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_archive_metadata(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(archive.id) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) def test_missing_manifest(self): archive, repository = self.open_archive('archive1') with repository: repository.delete(Manifest.MANIFEST_ID) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_corrupted_manifest(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive1', output) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_corrupted_chunk(self): archive, repository = self.open_archive('archive1') with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) chunk = repository.get(archive.id) corrupted_chunk = chunk + b'corrupted!' repository.put(archive.id, corrupted_chunk) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0) self.assert_in('archive2', output) self.cmd('check', self.repository_location, exit_code=0) def test_manifest_rebuild_duplicate_archive(self): archive, repository = self.open_archive('archive1') key = archive.key with repository: manifest = repository.get(Manifest.MANIFEST_ID) corrupted_manifest = manifest + b'corrupted!' repository.put(Manifest.MANIFEST_ID, corrupted_manifest) archive = msgpack.packb({ 'cmdline': [], 'items': [], 'hostname': 'foo', 'username': 'bar', 'name': 'archive1', 'time': '2016-12-15T18:49:51.849711', 'version': 1, }) archive_id = key.id_hash(archive) repository.put(archive_id, key.encrypt(archive)) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) output = self.cmd('list', self.repository_location) self.assert_in('archive1', output) self.assert_in('archive1.1', output) self.assert_in('archive2', output) def test_extra_chunks(self): self.cmd('check', self.repository_location, exit_code=0) with Repository(self.repository_location, exclusive=True) as repository: repository.put(b'01234567890123456789012345678901', b'xxxx') repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', self.repository_location, exit_code=1) self.cmd('check', '--repair', self.repository_location, exit_code=0) self.cmd('check', self.repository_location, exit_code=0) self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0) def _test_verify_data(self, *init_args): shutil.rmtree(self.repository_path) self.cmd('init', self.repository_location, *init_args) self.create_src_archive('archive1') archive, repository = self.open_archive('archive1') with repository: for item in archive.iter_items(): if item.path.endswith('testsuite/archiver.py'): chunk = item.chunks[-1] data = repository.get(chunk.id) + b'1234' repository.put(chunk.id, data) break repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=0) output = self.cmd('check', '--verify-data', self.repository_location, exit_code=1) assert bin_to_hex(chunk.id) + ', integrity error' in output # repair (heal is tested in another test) output = self.cmd('check', '--repair', '--verify-data', self.repository_location, exit_code=0) assert bin_to_hex(chunk.id) + ', integrity error' in output assert 'testsuite/archiver.py: New missing file chunk detected' in output def test_verify_data(self): self._test_verify_data('--encryption', 'repokey') def test_verify_data_unencrypted(self): self._test_verify_data('--encryption', 'none') def test_empty_repository(self): with Repository(self.repository_location, exclusive=True) as repository: for id_ in repository.list(): repository.delete(id_) repository.commit(compact=False) self.cmd('check', self.repository_location, exit_code=1) def test_attic013_acl_bug(self): # Attic up to release 0.13 contained a bug where every item unintentionally received # a b'acl'=None key-value pair. # This bug can still live on in Borg repositories (through borg upgrade). class Attic013Item: def as_dict(self): return { # These are required b'path': '1234', b'mtime': 0, b'mode': 0, b'user': b'0', b'group': b'0', b'uid': 0, b'gid': 0, # acl is the offending key. b'acl': None, } archive, repository = self.open_archive('archive1') with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) with Cache(repository, key, manifest) as cache: archive = Archive(repository, key, manifest, '0.13', cache=cache, create=True) archive.items_buffer.add(Attic013Item()) archive.save() self.cmd('check', self.repository_location, exit_code=0) self.cmd('list', self.repository_location + '::0.13', exit_code=0) class ManifestAuthenticationTest(ArchiverTestCaseBase): def spoof_manifest(self, repository): with repository: _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'config': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) def test_fresh_init_tam_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) repository = Repository(self.repository_path, exclusive=True) with repository: manifest, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({ 'version': 1, 'archives': {}, 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT), }))) repository.commit(compact=False) with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) def test_not_required(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) with repository: shutil.rmtree(get_security_dir(bin_to_hex(repository.id))) _, key = Manifest.load(repository, Manifest.NO_OPERATION_CHECK) key.tam_required = False key.change_passphrase(key._passphrase) manifest = msgpack.unpackb(key.decrypt(None, repository.get(Manifest.MANIFEST_ID))) del manifest[b'tam'] repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb(manifest))) repository.commit(compact=False) output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM not found and not required' in output # Run upgrade self.cmd('upgrade', '--tam', self.repository_location) # Manifest must be authenticated now output = self.cmd('list', '--debug', self.repository_location) assert 'archive1234' in output assert 'TAM-verified manifest' in output # Try to spoof / modify pre-1.0.9 self.spoof_manifest(repository) # Fails with pytest.raises(TAMRequiredError): self.cmd('list', self.repository_location) # Force upgrade self.cmd('upgrade', '--tam', '--force', self.repository_location) self.cmd('list', self.repository_location) def test_disable(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') self.cmd('upgrade', '--disable-tam', self.repository_location) repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) assert not self.cmd('list', self.repository_location) def test_disable2(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_src_archive('archive1234') repository = Repository(self.repository_path, exclusive=True) self.spoof_manifest(repository) self.cmd('upgrade', '--disable-tam', self.repository_location) assert not self.cmd('list', self.repository_location) class RemoteArchiverTestCase(ArchiverTestCase): prefix = '__testsuite__:' def open_repository(self): return RemoteRepository(Location(self.repository_location)) def test_remote_repo_restrict_to_path(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) # restricted to repo directory itself, fail for other directories with same prefix: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_0') # restricted to a completely different path: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location + '_1') path_prefix = os.path.dirname(self.repository_path) # restrict to repo directory's parent directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_2') # restrict to repo directory's parent directory and another directory: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]): self.cmd('init', '--encryption=repokey', self.repository_location + '_3') def test_remote_repo_restrict_to_repository(self): # restricted to repo directory itself: with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', self.repository_path]): self.cmd('init', '--encryption=repokey', self.repository_location) parent_path = os.path.join(self.repository_path, '..') with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-repository', parent_path]): with pytest.raises(PathNotAllowed): self.cmd('init', '--encryption=repokey', self.repository_location) @unittest.skip('only works locally') def test_debug_put_get_delete_obj(self): pass @unittest.skip('only works locally') def test_config(self): pass @unittest.skip('only works locally') def test_migrate_lock_alive(self): pass def test_strip_components_doesnt_leak(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('dir/file', contents=b"test file contents 1") self.create_regular_file('dir/file2', contents=b"test file contents 2") self.create_regular_file('skipped-file1', contents=b"test file contents 3") self.create_regular_file('skipped-file2', contents=b"test file contents 4") self.create_regular_file('skipped-file3', contents=b"test file contents 5") self.cmd('create', self.repository_location + '::test', 'input') marker = 'cached responses left in RemoteRepository' with changedir('output'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '3') self.assert_true(marker not in res) with self.assert_creates_file('file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '2') self.assert_true(marker not in res) with self.assert_creates_file('dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '1') self.assert_true(marker not in res) with self.assert_creates_file('input/dir/file'): res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '0') self.assert_true(marker not in res) class ArchiverCorruptionTestCase(ArchiverTestCaseBase): def setUp(self): super().setUp() self.create_test_files() self.cmd('init', '--encryption=repokey', self.repository_location) self.cache_path = json.loads(self.cmd('info', self.repository_location, '--json'))['cache']['path'] def corrupt(self, file, amount=1): with open(file, 'r+b') as fd: fd.seek(-amount, io.SEEK_END) corrupted = bytes(255-c for c in fd.read(amount)) fd.seek(-amount, io.SEEK_END) fd.write(corrupted) def test_cache_chunks(self): self.corrupt(os.path.join(self.cache_path, 'chunks')) if self.FORK_DEFAULT: out = self.cmd('info', self.repository_location, exit_code=2) assert 'failed integrity check' in out else: with pytest.raises(FileIntegrityError): self.cmd('info', self.repository_location) def test_cache_files(self): self.cmd('create', self.repository_location + '::test', 'input') self.corrupt(os.path.join(self.cache_path, 'files')) out = self.cmd('create', self.repository_location + '::test1', 'input') # borg warns about the corrupt files cache, but then continues without files cache. assert 'files cache is corrupted' in out def test_chunks_archive(self): self.cmd('create', self.repository_location + '::test1', 'input') # Find ID of test1 so we can corrupt it later :) target_id = self.cmd('list', self.repository_location, '--format={id}{LF}').strip() self.cmd('create', self.repository_location + '::test2', 'input') # Force cache sync, creating archive chunks of test1 and test2 in chunks.archive.d self.cmd('delete', '--cache-only', self.repository_location) self.cmd('info', self.repository_location, '--json') chunks_archive = os.path.join(self.cache_path, 'chunks.archive.d') assert len(os.listdir(chunks_archive)) == 4 # two archives, one chunks cache and one .integrity file each self.corrupt(os.path.join(chunks_archive, target_id + '.compact')) # Trigger cache sync by changing the manifest ID in the cache config config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) # Cache sync notices corrupted archive chunks, but automatically recovers. out = self.cmd('create', '-v', self.repository_location + '::test3', 'input', exit_code=1) assert 'Reading cached archive chunk index for test1' in out assert 'Cached archive chunk index of test1 is corrupted' in out assert 'Fetching and building archive index for test1' in out def test_old_version_interfered(self): # Modify the main manifest ID without touching the manifest ID in the integrity section. # This happens if a version without integrity checking modifies the cache. config_path = os.path.join(self.cache_path, 'config') config = ConfigParser(interpolation=None) config.read(config_path) config.set('cache', 'manifest', bin_to_hex(bytes(32))) with open(config_path, 'w') as fd: config.write(fd) out = self.cmd('info', self.repository_location) assert 'Cache integrity data not available: old Borg version modified the cache.' in out class DiffArchiverTestCase(ArchiverTestCaseBase): def test_basic_functionality(self): # Setup files for the first snapshot self.create_regular_file('empty', size=0) self.create_regular_file('file_unchanged', size=128) self.create_regular_file('file_removed', size=256) self.create_regular_file('file_removed2', size=512) self.create_regular_file('file_replaced', size=1024) os.mkdir('input/dir_replaced_with_file') os.chmod('input/dir_replaced_with_file', stat.S_IFDIR | 0o755) os.mkdir('input/dir_removed') if are_symlinks_supported(): os.mkdir('input/dir_replaced_with_link') os.symlink('input/dir_replaced_with_file', 'input/link_changed') os.symlink('input/file_unchanged', 'input/link_removed') os.symlink('input/file_removed2', 'input/link_target_removed') os.symlink('input/empty', 'input/link_target_contents_changed') os.symlink('input/empty', 'input/link_replaced_by_file') if are_hardlinks_supported(): os.link('input/file_replaced', 'input/hardlink_target_replaced') os.link('input/empty', 'input/hardlink_contents_changed') os.link('input/file_removed', 'input/hardlink_removed') os.link('input/file_removed2', 'input/hardlink_target_removed') self.cmd('init', '--encryption=repokey', self.repository_location) # Create the first snapshot self.cmd('create', self.repository_location + '::test0', 'input') # Setup files for the second snapshot self.create_regular_file('file_added', size=2048) self.create_regular_file('file_empty_added', size=0) os.unlink('input/file_replaced') self.create_regular_file('file_replaced', contents=b'0' * 4096) os.unlink('input/file_removed') os.unlink('input/file_removed2') os.rmdir('input/dir_replaced_with_file') self.create_regular_file('dir_replaced_with_file', size=8192) os.chmod('input/dir_replaced_with_file', stat.S_IFREG | 0o755) os.mkdir('input/dir_added') os.rmdir('input/dir_removed') if are_symlinks_supported(): os.rmdir('input/dir_replaced_with_link') os.symlink('input/dir_added', 'input/dir_replaced_with_link') os.unlink('input/link_changed') os.symlink('input/dir_added', 'input/link_changed') os.symlink('input/dir_added', 'input/link_added') os.unlink('input/link_replaced_by_file') self.create_regular_file('link_replaced_by_file', size=16384) os.unlink('input/link_removed') if are_hardlinks_supported(): os.unlink('input/hardlink_removed') os.link('input/file_added', 'input/hardlink_added') with open('input/empty', 'ab') as fd: fd.write(b'appended_data') # Create the second snapshot self.cmd('create', self.repository_location + '::test1a', 'input') self.cmd('create', '--chunker-params', '16,18,17,4095', self.repository_location + '::test1b', 'input') def do_asserts(output, can_compare_ids): # File contents changed (deleted and replaced with a new file) change = 'B' if can_compare_ids else '{:<19}'.format('modified') assert 'file_replaced' in output # added to debug #3494 assert '{} input/file_replaced'.format(change) in output # File unchanged assert 'input/file_unchanged' not in output # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert '[drwxr-xr-x -> -rwxr-xr-x] input/dir_replaced_with_file' in output # Basic directory cases assert 'added directory input/dir_added' in output assert 'removed directory input/dir_removed' in output if are_symlinks_supported(): # Basic symlink cases assert 'changed link input/link_changed' in output assert 'added link input/link_added' in output assert 'removed link input/link_removed' in output # Symlink replacing or being replaced assert '] input/dir_replaced_with_link' in output assert '] input/link_replaced_by_file' in output # Symlink target removed. Should not affect the symlink at all. assert 'input/link_target_removed' not in output # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. change = '0 B' if can_compare_ids else '{:<19}'.format('modified') assert '{} input/empty'.format(change) in output if are_hardlinks_supported(): assert '{} input/hardlink_contents_changed'.format(change) in output if are_symlinks_supported(): assert 'input/link_target_contents_changed' not in output # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert 'added 2.05 kB input/file_added' in output if are_hardlinks_supported(): assert 'added 2.05 kB input/hardlink_added' in output # check if a diff between non-existent and empty new file is found assert 'added 0 B input/file_empty_added' in output # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert 'removed 256 B input/file_removed' in output if are_hardlinks_supported(): assert 'removed 256 B input/hardlink_removed' in output # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_removed' not in output # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert 'input/hardlink_target_replaced' not in output def do_json_asserts(output, can_compare_ids): def get_changes(filename, data): chgsets = [j['changes'] for j in data if j['path'] == filename] assert len(chgsets) < 2 # return a flattened list of changes for given filename return [chg for chgset in chgsets for chg in chgset] # convert output to list of dicts joutput = [json.loads(line) for line in output.split('\n') if line] # File contents changed (deleted and replaced with a new file) expected = {'type': 'modified', 'added': 4096, 'removed': 1024} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/file_replaced', joutput) # File unchanged assert not any(get_changes('input/file_unchanged', joutput)) # Directory replaced with a regular file if 'BORG_TESTS_IGNORE_MODES' not in os.environ: assert {'type': 'mode', 'old_mode': 'drwxr-xr-x', 'new_mode': '-rwxr-xr-x'} in \ get_changes('input/dir_replaced_with_file', joutput) # Basic directory cases assert {'type': 'added directory'} in get_changes('input/dir_added', joutput) assert {'type': 'removed directory'} in get_changes('input/dir_removed', joutput) if are_symlinks_supported(): # Basic symlink cases assert {'type': 'changed link'} in get_changes('input/link_changed', joutput) assert {'type': 'added link'} in get_changes('input/link_added', joutput) assert {'type': 'removed link'} in get_changes('input/link_removed', joutput) # Symlink replacing or being replaced assert any(chg['type'] == 'mode' and chg['new_mode'].startswith('l') for chg in get_changes('input/dir_replaced_with_link', joutput)) assert any(chg['type'] == 'mode' and chg['old_mode'].startswith('l') for chg in get_changes('input/link_replaced_by_file', joutput)) # Symlink target removed. Should not affect the symlink at all. assert not any(get_changes('input/link_target_removed', joutput)) # The inode has two links and the file contents changed. Borg # should notice the changes in both links. However, the symlink # pointing to the file is not changed. expected = {'type': 'modified', 'added': 13, 'removed': 0} if can_compare_ids else {'type': 'modified'} assert expected in get_changes('input/empty', joutput) if are_hardlinks_supported(): assert expected in get_changes('input/hardlink_contents_changed', joutput) if are_symlinks_supported(): assert not any(get_changes('input/link_target_contents_changed', joutput)) # Added a new file and a hard link to it. Both links to the same # inode should appear as separate files. assert {'type': 'added', 'size': 2048} in get_changes('input/file_added', joutput) if are_hardlinks_supported(): assert {'type': 'added', 'size': 2048} in get_changes('input/hardlink_added', joutput) # check if a diff between non-existent and empty new file is found assert {'type': 'added', 'size': 0} in get_changes('input/file_empty_added', joutput) # The inode has two links and both of them are deleted. They should # appear as two deleted files. assert {'type': 'removed', 'size': 256} in get_changes('input/file_removed', joutput) if are_hardlinks_supported(): assert {'type': 'removed', 'size': 256} in get_changes('input/hardlink_removed', joutput) # Another link (marked previously as the source in borg) to the # same inode was removed. This should not change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_removed', joutput)) # Another link (marked previously as the source in borg) to the # same inode was replaced with a new regular file. This should not # change this link at all. if are_hardlinks_supported(): assert not any(get_changes('input/hardlink_target_replaced', joutput)) do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a'), True) # We expect exit_code=1 due to the chunker params warning do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1b', exit_code=1), False) do_json_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a', '--json-lines'), True) def test_sort_option(self): self.cmd('init', '--encryption=repokey', self.repository_location) self.create_regular_file('a_file_removed', size=8) self.create_regular_file('f_file_removed', size=16) self.create_regular_file('c_file_changed', size=32) self.create_regular_file('e_file_changed', size=64) self.cmd('create', self.repository_location + '::test0', 'input') os.unlink('input/a_file_removed') os.unlink('input/f_file_removed') os.unlink('input/c_file_changed') os.unlink('input/e_file_changed') self.create_regular_file('c_file_changed', size=512) self.create_regular_file('e_file_changed', size=1024) self.create_regular_file('b_file_added', size=128) self.create_regular_file('d_file_added', size=256) self.cmd('create', self.repository_location + '::test1', 'input') output = self.cmd('diff', '--sort', self.repository_location + '::test0', 'test1') expected = [ 'a_file_removed', 'b_file_added', 'c_file_changed', 'd_file_added', 'e_file_changed', 'f_file_removed', ] assert all(x in line for x, line in zip(expected, output.splitlines())) def test_get_args(): archiver = Archiver() # everything normal: # first param is argv as produced by ssh forced command, # second param is like from SSH_ORIGINAL_COMMAND env variable args = archiver.get_args(['borg', 'serve', '--umask=0027', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --info') assert args.func == archiver.do_serve assert args.restrict_to_paths == ['/p1', '/p2'] assert args.umask == 0o027 assert args.log_level == 'info' # similar, but with --restrict-to-repository args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --info --umask=0027') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break out of path restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg serve --restrict-to-path=/') assert args.restrict_to_paths == ['/p1', '/p2'] # trying to cheat - break out of repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - break below repository restriction args = archiver.get_args(['borg', 'serve', '--restrict-to-repository=/r1', '--restrict-to-repository=/r2', ], 'borg serve --restrict-to-repository=/r1/below') assert args.restrict_to_repositories == ['/r1', '/r2'] # trying to cheat - try to execute different subcommand args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ], 'borg init --encryption=repokey /') assert args.func == archiver.do_serve # Check that environment variables in the forced command don't cause issues. If the command # were not forced, environment variables would be interpreted by the shell, but this does not # happen for forced commands - we get the verbatim command line and need to deal with env vars. args = archiver.get_args(['borg', 'serve', ], 'BORG_FOO=bar borg serve --info') assert args.func == archiver.do_serve def test_chunk_content_equal(): def ccc(a, b): chunks_a = [data for data in a] chunks_b = [data for data in b] compare1 = ItemDiff._chunk_content_equal(iter(chunks_a), iter(chunks_b)) compare2 = ItemDiff._chunk_content_equal(iter(chunks_b), iter(chunks_a)) assert compare1 == compare2 return compare1 assert ccc([ b'1234', b'567A', b'bC' ], [ b'1', b'23', b'4567A', b'b', b'C' ]) # one iterator exhausted before the other assert not ccc([ b'12345', ], [ b'1234', b'56' ]) # content mismatch assert not ccc([ b'1234', b'65' ], [ b'1234', b'56' ]) # first is the prefix of second assert not ccc([ b'1234', b'56' ], [ b'1234', b'565' ]) class TestBuildFilter: @staticmethod def peek_and_store_hardlink_masters(item, matched): pass def test_basic(self): matcher = PatternMatcher() matcher.add([parse_pattern('included')], IECommand.Include) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='included')) assert filter(Item(path='included/file')) assert not filter(Item(path='something else')) def test_empty(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, 0) assert filter(Item(path='anything')) def test_strip_components(self): matcher = PatternMatcher(fallback=True) filter = Archiver.build_filter(matcher, self.peek_and_store_hardlink_masters, strip_components=1) assert not filter(Item(path='shallow')) assert not filter(Item(path='shallow/')) # can this even happen? paths are normalized... assert filter(Item(path='deep enough/file')) assert filter(Item(path='something/dir/file')) class TestCommonOptions: @staticmethod def define_common_options(add_common_option): add_common_option('-h', '--help', action='help', help='show this help message and exit') add_common_option('--critical', dest='log_level', help='foo', action='store_const', const='critical', default='warning') add_common_option('--error', dest='log_level', help='foo', action='store_const', const='error', default='warning') add_common_option('--append', dest='append', help='foo', action='append', metavar='TOPIC', default=[]) add_common_option('-p', '--progress', dest='progress', action='store_true', help='foo') add_common_option('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1, help='(default: %(default)d).') @pytest.fixture def basic_parser(self): parser = argparse.ArgumentParser(prog='test', description='test parser', add_help=False) parser.common_options = Archiver.CommonOptions(self.define_common_options, suffix_precedence=('_level0', '_level1')) return parser @pytest.fixture def subparsers(self, basic_parser): if sys.version_info >= (3, 7): # py37 pre-release defaults to unwanted required=True, in 3.7.0+ it was fixed to =False return basic_parser.add_subparsers(title='required arguments', metavar='<command>', required=False) else: # py36 does not support required=... argument (but behaves like required=False). # note: use below call for 3.6 and 3.7 when there are no alphas/betas/RCs of 3.7.0 around any more. return basic_parser.add_subparsers(title='required arguments', metavar='<command>') @pytest.fixture def parser(self, basic_parser): basic_parser.common_options.add_common_group(basic_parser, '_level0', provide_defaults=True) return basic_parser @pytest.fixture def common_parser(self, parser): common_parser = argparse.ArgumentParser(add_help=False, prog='test') parser.common_options.add_common_group(common_parser, '_level1') return common_parser @pytest.fixture def parse_vars_from_line(self, parser, subparsers, common_parser): subparser = subparsers.add_parser('subcommand', parents=[common_parser], add_help=False, description='foo', epilog='bar', help='baz', formatter_class=argparse.RawDescriptionHelpFormatter) subparser.set_defaults(func=1234) subparser.add_argument('--append-only', dest='append_only', action='store_true') def parse_vars_from_line(*line): print(line) args = parser.parse_args(line) parser.common_options.resolve(args) return vars(args) return parse_vars_from_line def test_simple(self, parse_vars_from_line): assert parse_vars_from_line('--error') == { 'append': [], 'lock_wait': 1, 'log_level': 'error', 'progress': False } assert parse_vars_from_line('--error', 'subcommand', '--critical') == { 'append': [], 'lock_wait': 1, 'log_level': 'critical', 'progress': False, 'append_only': False, 'func': 1234, } with pytest.raises(SystemExit): parse_vars_from_line('--append-only', 'subcommand') assert parse_vars_from_line('--append=foo', '--append', 'bar', 'subcommand', '--append', 'baz') == { 'append': ['foo', 'bar', 'baz'], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } @pytest.mark.parametrize('position', ('before', 'after', 'both')) @pytest.mark.parametrize('flag,args_key,args_value', ( ('-p', 'progress', True), ('--lock-wait=3', 'lock_wait', 3), )) def test_flag_position_independence(self, parse_vars_from_line, position, flag, args_key, args_value): line = [] if position in ('before', 'both'): line.append(flag) line.append('subcommand') if position in ('after', 'both'): line.append(flag) result = { 'append': [], 'lock_wait': 1, 'log_level': 'warning', 'progress': False, 'append_only': False, 'func': 1234, } result[args_key] = args_value assert parse_vars_from_line(*line) == result def test_parse_storage_quota(): assert parse_storage_quota('50M') == 50 * 1000**2 with pytest.raises(argparse.ArgumentTypeError): parse_storage_quota('5M') def get_all_parsers(): parser = Archiver(prog='borg').build_parser() borgfs_parser = Archiver(prog='borgfs').build_parser() parsers = {} def discover_level(prefix, parser, Archiver, extra_choices=None): choices = {} for action in parser._actions: if action.choices is not None and 'SubParsersAction' in str(action.__class__): for cmd, parser in action.choices.items(): choices[prefix + cmd] = parser if extra_choices is not None: choices.update(extra_choices) if prefix and not choices: return for command, parser in sorted(choices.items()): discover_level(command + " ", parser, Archiver) parsers[command] = parser discover_level("", parser, Archiver, {'borgfs': borgfs_parser}) return parsers @pytest.mark.parametrize('command, parser', list(get_all_parsers().items())) def test_help_formatting(command, parser): if isinstance(parser.epilog, RstToTextLazy): assert parser.epilog.rst @pytest.mark.parametrize('topic, helptext', list(Archiver.helptext.items())) def test_help_formatting_helptexts(topic, helptext): assert str(rst_to_terminal(helptext))
true
true
f727b88af81bc3a82c519d895f95d0e68a9f59ab
1,583
py
Python
sandbox/lib/jumpscale/JumpScale9Lib/clients/atyourservice/ays/ClientFactory.py
Jumpscale/sandbox_linux
2aacd36b467ef30ac83718abfa82c6883b67a02f
[ "Apache-2.0" ]
2
2017-06-07T08:11:47.000Z
2017-11-10T02:19:48.000Z
JumpScale9Lib/clients/atyourservice/ays/ClientFactory.py
Jumpscale/lib9
82224784ef2a7071faeb48349007211c367bc673
[ "Apache-2.0" ]
188
2017-06-21T06:16:13.000Z
2020-06-17T14:20:24.000Z
sandbox/lib/jumpscale/JumpScale9Lib/clients/atyourservice/ays/ClientFactory.py
Jumpscale/sandbox_linux
2aacd36b467ef30ac83718abfa82c6883b67a02f
[ "Apache-2.0" ]
3
2018-06-12T05:18:28.000Z
2019-09-24T06:49:17.000Z
from js9 import j from .client import Client JSConfigBase = j.tools.configmanager.base_class_configs JSBASE = j.application.jsbase_get_class() class ClientFactory(JSConfigBase): def __init__(self): self.__jslocation__ = 'j.clients.ays' JSConfigBase.__init__(self, Client) # def get(self, url=DEFAULT_URL, client_id=None, client_secret=None, validity=3600): # """ # Get an AYS client to interact with a local or remote AYS server. # Args: # client_id: client ID of the API access key of the ItsYou.online organization protecting the AYS RESTful API; defaults to None # client_secret: secret of the API access key of the ItsYou.online organization protecting the AYS RESTful API; defaults to None # url: url of the AYS RESTful API, e.g. `http://172.25.0.238:5000`; defaults to https://localhost:5000 # validity: validity of the JWT that will be created based on the given client ID and secret, defaults to 3600 (seconds) # """ # return Client(url=url, jwt=None, clientID=client_id, secret=client_secret, validity=validity) # def get_with_jwt(self, instance='main'): # """ # Get an AYS client to interact with a local or remote AYS server. # Args: # url: url of the AYS RESTful API, e.g. `http://172.25.0.238:5000`; defaults to https://localhost:5000 # jwt: JSON Web Token for the ItsYou.online organization protecting the AYS RESTful API; defaults to None # """ # return Client(instance=instance)
45.228571
140
0.672142
from js9 import j from .client import Client JSConfigBase = j.tools.configmanager.base_class_configs JSBASE = j.application.jsbase_get_class() class ClientFactory(JSConfigBase): def __init__(self): self.__jslocation__ = 'j.clients.ays' JSConfigBase.__init__(self, Client) # Get an AYS client to interact with a local or remote AYS server. # Args: # client_id: client ID of the API access key of the ItsYou.online organization protecting the AYS RESTful API; defaults to None # client_secret: secret of the API access key of the ItsYou.online organization protecting the AYS RESTful API; defaults to None # url: url of the AYS RESTful API, e.g. `http://172.25.0.238:5000`; defaults to https://localhost:5000 # validity: validity of the JWT that will be created based on the given client ID and secret, defaults to 3600 (seconds) # """ # Get an AYS client to interact with a local or remote AYS server. # Args: # url: url of the AYS RESTful API, e.g. `http://172.25.0.238:5000`; defaults to https://localhost:5000 # jwt: JSON Web Token for the ItsYou.online organization protecting the AYS RESTful API; defaults to None # """
true
true
f727b91907659f8e5e86ad39633e0f340dedda64
3,175
py
Python
models/object_detection/model_templates/horizontal-text-detection/tools/draw_recall_graph.py
dqawami/openvino_training_extensions
dddda1dfd651eaae2d59cecda84275b1b03bd0ad
[ "Apache-2.0" ]
256
2020-09-09T03:27:57.000Z
2022-03-30T10:06:06.000Z
models/object_detection/model_templates/horizontal-text-detection/tools/draw_recall_graph.py
dqawami/openvino_training_extensions
dddda1dfd651eaae2d59cecda84275b1b03bd0ad
[ "Apache-2.0" ]
604
2020-09-08T12:29:49.000Z
2022-03-31T21:51:08.000Z
models/object_detection/model_templates/horizontal-text-detection/tools/draw_recall_graph.py
dqawami/openvino_training_extensions
dddda1dfd651eaae2d59cecda84275b1b03bd0ad
[ "Apache-2.0" ]
160
2020-09-09T14:06:07.000Z
2022-03-30T14:50:48.000Z
# Copyright (C) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions # and limitations under the License. """ This script draws a graph of the detected words number (recall) depending on their width. It helps to see the detection quality of the small, normal or large inscriptions. Also for your convenience you may visualize the detections straight away.""" import argparse from os.path import exists import subprocess import mmcv from mmdet.datasets import build_dataset # pylint: disable=import-error from mmdet.core.evaluation.text_evaluation import text_eval # pylint: disable=import-error def parse_args(): """ Parses input arguments. """ parser = argparse.ArgumentParser( description='This script draws a histogram of the detected words ' 'number (recall) depending on their width. It helps to ' 'see the detection quality of the small, normal or large ' 'inscriptions. Also for your convenience you may ' 'visualize the detections straight away.') parser.add_argument('config', help='test config file path') parser.add_argument('snapshot', help='path to snapshot to be tested') parser.add_argument('--draw_graph', action='store_true', help='draw histogram of recall') parser.add_argument('--visualize', action='store_true', help='show detection result on images') args = parser.parse_args() return args def main(): """ Main function. """ args = parse_args() detection_file = 'horizontal_text_detection' if not exists(f'{detection_file}.bbox.json'): subprocess.run( f'python ../../../../../external/mmdetection/tools/test.py' f' {args.config} {args.snapshot}' f' --options jsonfile_prefix={detection_file}' f' --format-only', check=True, shell=True ) cfg = mmcv.Config.fromfile(args.config) dataset = build_dataset(cfg.data.test) results = mmcv.load(f'{detection_file}.bbox.json') coco = dataset.coco coco_dets = coco.loadRes(results) predictions = coco_dets.imgToAnns gt_annotations = coco.imgToAnns if args.visualize: img_paths = [dataset.img_prefix + image['file_name'] for image in coco_dets.dataset['images']] else: img_paths = None recall, precision, hmean, _ = text_eval( predictions, gt_annotations, cfg.model.test_cfg.score_thr, images=img_paths, show_recall_graph=args.draw_graph) print('Text detection recall={:.4f} precision={:.4f} hmean={:.4f}'. format(recall, precision, hmean)) if __name__ == '__main__': main()
36.918605
99
0.68
import argparse from os.path import exists import subprocess import mmcv from mmdet.datasets import build_dataset from mmdet.core.evaluation.text_evaluation import text_eval def parse_args(): parser = argparse.ArgumentParser( description='This script draws a histogram of the detected words ' 'number (recall) depending on their width. It helps to ' 'see the detection quality of the small, normal or large ' 'inscriptions. Also for your convenience you may ' 'visualize the detections straight away.') parser.add_argument('config', help='test config file path') parser.add_argument('snapshot', help='path to snapshot to be tested') parser.add_argument('--draw_graph', action='store_true', help='draw histogram of recall') parser.add_argument('--visualize', action='store_true', help='show detection result on images') args = parser.parse_args() return args def main(): args = parse_args() detection_file = 'horizontal_text_detection' if not exists(f'{detection_file}.bbox.json'): subprocess.run( f'python ../../../../../external/mmdetection/tools/test.py' f' {args.config} {args.snapshot}' f' --options jsonfile_prefix={detection_file}' f' --format-only', check=True, shell=True ) cfg = mmcv.Config.fromfile(args.config) dataset = build_dataset(cfg.data.test) results = mmcv.load(f'{detection_file}.bbox.json') coco = dataset.coco coco_dets = coco.loadRes(results) predictions = coco_dets.imgToAnns gt_annotations = coco.imgToAnns if args.visualize: img_paths = [dataset.img_prefix + image['file_name'] for image in coco_dets.dataset['images']] else: img_paths = None recall, precision, hmean, _ = text_eval( predictions, gt_annotations, cfg.model.test_cfg.score_thr, images=img_paths, show_recall_graph=args.draw_graph) print('Text detection recall={:.4f} precision={:.4f} hmean={:.4f}'. format(recall, precision, hmean)) if __name__ == '__main__': main()
true
true
f727b9d4cab59ebd33276d381d0c931725d42173
2,391
py
Python
session8/bloomfilter.py
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
153
2017-09-27T01:10:19.000Z
2022-03-17T12:13:59.000Z
session8/bloomfilter.py
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
3
2018-11-10T20:04:13.000Z
2022-02-15T23:12:53.000Z
session8/bloomfilter.py
zhiweih/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
[ "BSD-2-Clause" ]
85
2017-10-09T16:18:00.000Z
2022-02-09T14:21:08.000Z
from unittest import TestCase from helper import bit_field_to_bytes, encode_varint, int_to_little_endian, murmur3 from network import GenericMessage BIP37_CONSTANT = 0xfba4c795 class BloomFilter: def __init__(self, size, function_count, tweak): self.size = size self.bit_field = [0] * (size * 8) self.function_count = function_count self.tweak = tweak def add(self, item): '''Add an item to the filter''' # iterate self.function_count number of times for i in range(self.function_count): # BIP0037 spec seed is i*BIP37_CONSTANT + self.tweak seed = i * BIP37_CONSTANT + self.tweak # get the murmur3 hash given that seed h = murmur3(item, seed=seed) # set the bit at the hash mod the bitfield size (self.size*8) self.bit_field[h % (self.size * 8)] = 1 # set the bit field at bit to be 1 def filter_bytes(self): return bit_field_to_bytes(self.bit_field) def filterload(self, flag=1): '''Return a network message whose command is filterload''' # encode_varint self.size result = encode_varint(self.size) # next is the self.filter_bytes() result += self.filter_bytes() # function count is 4 bytes little endian result += int_to_little_endian(self.function_count, 4) # tweak is 4 bytes little endian result += int_to_little_endian(self.tweak, 4) # flag is 1 byte little endian result += int_to_little_endian(flag, 1) # return a GenericMessage with b'filterload' as the command return GenericMessage(b'filterload', result) class BloomFilterTest(TestCase): def test_add(self): bf = BloomFilter(10, 5, 99) item = b'Hello World' bf.add(item) expected = '0000000a080000000140' self.assertEqual(bf.filter_bytes().hex(), expected) item = b'Goodbye!' bf.add(item) expected = '4000600a080000010940' self.assertEqual(bf.filter_bytes().hex(), expected) def test_filterload(self): bf = BloomFilter(10, 5, 99) item = b'Hello World' bf.add(item) item = b'Goodbye!' bf.add(item) expected = '0a4000600a080000010940050000006300000001' self.assertEqual(bf.filterload().serialize().hex(), expected)
34.157143
83
0.634463
from unittest import TestCase from helper import bit_field_to_bytes, encode_varint, int_to_little_endian, murmur3 from network import GenericMessage BIP37_CONSTANT = 0xfba4c795 class BloomFilter: def __init__(self, size, function_count, tweak): self.size = size self.bit_field = [0] * (size * 8) self.function_count = function_count self.tweak = tweak def add(self, item): for i in range(self.function_count): seed = i * BIP37_CONSTANT + self.tweak h = murmur3(item, seed=seed) self.bit_field[h % (self.size * 8)] = 1 def filter_bytes(self): return bit_field_to_bytes(self.bit_field) def filterload(self, flag=1): result = encode_varint(self.size) result += self.filter_bytes() result += int_to_little_endian(self.function_count, 4) result += int_to_little_endian(self.tweak, 4) result += int_to_little_endian(flag, 1) return GenericMessage(b'filterload', result) class BloomFilterTest(TestCase): def test_add(self): bf = BloomFilter(10, 5, 99) item = b'Hello World' bf.add(item) expected = '0000000a080000000140' self.assertEqual(bf.filter_bytes().hex(), expected) item = b'Goodbye!' bf.add(item) expected = '4000600a080000010940' self.assertEqual(bf.filter_bytes().hex(), expected) def test_filterload(self): bf = BloomFilter(10, 5, 99) item = b'Hello World' bf.add(item) item = b'Goodbye!' bf.add(item) expected = '0a4000600a080000010940050000006300000001' self.assertEqual(bf.filterload().serialize().hex(), expected)
true
true
f727ba6681f8dfea391e57c63b138af4829f136b
301
py
Python
Communication/temp_driver.py
Forence1999/SmartWalker
635410bf44234eead9fd1e2fe226eb8eafa9d27d
[ "MIT" ]
2
2021-11-13T14:16:06.000Z
2022-01-12T06:07:32.000Z
Communication/temp_driver.py
Forence1999/SmartWalker
635410bf44234eead9fd1e2fe226eb8eafa9d27d
[ "MIT" ]
null
null
null
Communication/temp_driver.py
Forence1999/SmartWalker
635410bf44234eead9fd1e2fe226eb8eafa9d27d
[ "MIT" ]
3
2021-08-30T04:40:39.000Z
2022-01-09T11:34:04.000Z
import os, sys pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..") sys.path.append(father_path) from Communication.Modules.Driver_recv import DriverRecv if __name__ == "__main__": drv_recv = DriverRecv() drv_recv.start()
27.363636
72
0.734219
import os, sys pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..") sys.path.append(father_path) from Communication.Modules.Driver_recv import DriverRecv if __name__ == "__main__": drv_recv = DriverRecv() drv_recv.start()
true
true
f727bb216c7cc0427cc558d690825ceffb291a96
4,961
py
Python
src/vw/tools/extract_modis_images.py
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
318
2015-01-02T16:37:34.000Z
2022-03-17T07:12:20.000Z
src/vw/tools/extract_modis_images.py
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
39
2015-07-30T22:22:42.000Z
2021-03-23T16:11:55.000Z
src/vw/tools/extract_modis_images.py
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
135
2015-01-19T00:57:20.000Z
2022-03-18T13:51:40.000Z
#!/usr/bin/env python # __BEGIN_LICENSE__ # Copyright (c) 2006-2013, United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The NASA Vision Workbench is 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. # __END_LICENSE__ import os, sys, optparse, subprocess DESIRED_CHANNELS = ['sur_refl_b01_1', 'sur_refl_b02_1', 'sur_refl_b03_1', 'sur_refl_b04_1', 'sur_refl_b05_1', 'sur_refl_b06_1', 'sur_refl_b07_1', 'QC_500m_1', 'sur_refl_b01_1', 'sur_refl_b02_1', 'QC_250m_1'#, # -- We need these, but GDAL won't open them!!!!!!!!!!!!! #'state_1km_1', #'gflags_1', # -- We don't need these #obscov_500m_1 #iobs_res_1 #q_scan_1 #num_observations #num_observations_1km #num_observations_500m #obscov_1 ] # TODO: Only write high res images from high res input! def find_dataset_names(path): '''Returns the list of desired datasets contained in a file''' # Load info about the file cmd = ['gdalinfo', path] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) textOutput, err = p.communicate() #print textOutput datasets = [] sizes = [] for line in textOutput.split(): if not ('SUBDATASET' in line): continue if ('NAME' in line): start = line.find('=') + 1 datasets.append(line[start:]) else: start = line.find('[') + 1 stop = line.find('x', start) size = int(line[start:stop]) sizes.append(size) #print line[start:] if len(datasets) != len(sizes): raise Exception('Error: dataset sizes mismatch!') return zip(datasets, sizes) def prune_datasets(datasets): '''Remove duplicate datasets and undesired datasets.''' outputs = [] for d in datasets: name = d[0] size = d[1] # Check if the name is on the desired channel list found = False for c in DESIRED_CHANNELS: if c in name: found = True break if not found: continue # Look for duplicates keep = True for dO in datasets: nameO = dO[0] sizeO = dO[1] if ((name == nameO) and (sizeO > size)): keep = False break if not keep: continue outputs.append(d) return outputs def extract_datasets(path, datasets, options): '''Extract the desired datasets to the output folder''' for d in datasets: text = d[0] name = text[text.rfind(':')+1:] outputPath = options.prefix + name + '.tif' if (options.overwrite or (not os.path.exists(outputPath))): cmd = "gdal_translate -of GTiff '" + text + "' " + outputPath print cmd os.system(cmd) def main(): #try: usage = "usage: extract_modis_images.py [options]\n" parser = optparse.OptionParser(usage=usage) parser.add_option("--prefix", dest="prefix", default="", help="Output prefix to use.") parser.add_option("--overwrite", dest="overwrite", default=False, action='store_true', help="Overwrite existing output files.") (options, args) = parser.parse_args() if not args: parser.error("need .input files") # Handle input arguments input_paths = args output_dir = os.path.dirname(options.prefix) if not os.path.exists(output_dir): os.system('mkdir -p ' + output_dir) print 'Starting processing' # Loop through the input files for path in input_paths: # Extract all the subdatasets datasets = find_dataset_names(path) datasets = prune_datasets(datasets) extract_datasets(path, datasets, options) print 'Finished!' #except: # print usage # return -1 if __name__ == "__main__": sys.exit(main())
28.511494
90
0.555936
subprocess DESIRED_CHANNELS = ['sur_refl_b01_1', 'sur_refl_b02_1', 'sur_refl_b03_1', 'sur_refl_b04_1', 'sur_refl_b05_1', 'sur_refl_b06_1', 'sur_refl_b07_1', 'QC_500m_1', 'sur_refl_b01_1', 'sur_refl_b02_1', 'QC_250m_1' #'state_1km_1', #'gflags_1', # -- We don't need these ] def find_dataset_names(path): '''Returns the list of desired datasets contained in a file''' cmd = ['gdalinfo', path] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) textOutput, err = p.communicate() datasets = [] sizes = [] for line in textOutput.split(): if not ('SUBDATASET' in line): continue if ('NAME' in line): start = line.find('=') + 1 datasets.append(line[start:]) else: start = line.find('[') + 1 stop = line.find('x', start) size = int(line[start:stop]) sizes.append(size) if len(datasets) != len(sizes): raise Exception('Error: dataset sizes mismatch!') return zip(datasets, sizes) def prune_datasets(datasets): '''Remove duplicate datasets and undesired datasets.''' outputs = [] for d in datasets: name = d[0] size = d[1] found = False for c in DESIRED_CHANNELS: if c in name: found = True break if not found: continue keep = True for dO in datasets: nameO = dO[0] sizeO = dO[1] if ((name == nameO) and (sizeO > size)): keep = False break if not keep: continue outputs.append(d) return outputs def extract_datasets(path, datasets, options): '''Extract the desired datasets to the output folder''' for d in datasets: text = d[0] name = text[text.rfind(':')+1:] outputPath = options.prefix + name + '.tif' if (options.overwrite or (not os.path.exists(outputPath))): cmd = "gdal_translate -of GTiff '" + text + "' " + outputPath print cmd os.system(cmd) def main(): usage = "usage: extract_modis_images.py [options]\n" parser = optparse.OptionParser(usage=usage) parser.add_option("--prefix", dest="prefix", default="", help="Output prefix to use.") parser.add_option("--overwrite", dest="overwrite", default=False, action='store_true', help="Overwrite existing output files.") (options, args) = parser.parse_args() if not args: parser.error("need .input files") input_paths = args output_dir = os.path.dirname(options.prefix) if not os.path.exists(output_dir): os.system('mkdir -p ' + output_dir) print 'Starting processing' for path in input_paths: datasets = find_dataset_names(path) datasets = prune_datasets(datasets) extract_datasets(path, datasets, options) print 'Finished!' if __name__ == "__main__": sys.exit(main())
false
true
f727bbf4f042610f878f6f2a4448221ae54ed568
147
py
Python
yc166/525.py
c-yan/yukicoder
cdbbd65402177225dd989df7fe01f67908484a69
[ "MIT" ]
null
null
null
yc166/525.py
c-yan/yukicoder
cdbbd65402177225dd989df7fe01f67908484a69
[ "MIT" ]
null
null
null
yc166/525.py
c-yan/yukicoder
cdbbd65402177225dd989df7fe01f67908484a69
[ "MIT" ]
null
null
null
T = input() hh, mm = map(int, T.split(':')) mm += 5 if mm > 59: hh += 1 mm %= 60 if hh > 23: hh %= 24 print('%02d:%02d' % (hh, mm))
11.307692
31
0.428571
T = input() hh, mm = map(int, T.split(':')) mm += 5 if mm > 59: hh += 1 mm %= 60 if hh > 23: hh %= 24 print('%02d:%02d' % (hh, mm))
true
true
f727bc6b391386643fcb9047d7e3f34d29e75ee1
3,712
py
Python
intersight/models/hyperflex_ucsm_config_policy_ref.py
ategaw-cisco/intersight-python
9d6476620507281b1dc358e29ac452d56081bbb0
[ "Apache-2.0" ]
null
null
null
intersight/models/hyperflex_ucsm_config_policy_ref.py
ategaw-cisco/intersight-python
9d6476620507281b1dc358e29ac452d56081bbb0
[ "Apache-2.0" ]
null
null
null
intersight/models/hyperflex_ucsm_config_policy_ref.py
ategaw-cisco/intersight-python
9d6476620507281b1dc358e29ac452d56081bbb0
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ Intersight REST API This is Intersight REST API OpenAPI spec version: 1.0.9-262 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class HyperflexUcsmConfigPolicyRef(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'moid': 'str', 'object_type': 'str' } attribute_map = { 'moid': 'Moid', 'object_type': 'ObjectType' } def __init__(self, moid=None, object_type=None): """ HyperflexUcsmConfigPolicyRef - a model defined in Swagger """ self._moid = None self._object_type = None if moid is not None: self.moid = moid if object_type is not None: self.object_type = object_type @property def moid(self): """ Gets the moid of this HyperflexUcsmConfigPolicyRef. :return: The moid of this HyperflexUcsmConfigPolicyRef. :rtype: str """ return self._moid @moid.setter def moid(self, moid): """ Sets the moid of this HyperflexUcsmConfigPolicyRef. :param moid: The moid of this HyperflexUcsmConfigPolicyRef. :type: str """ self._moid = moid @property def object_type(self): """ Gets the object_type of this HyperflexUcsmConfigPolicyRef. :return: The object_type of this HyperflexUcsmConfigPolicyRef. :rtype: str """ return self._object_type @object_type.setter def object_type(self, object_type): """ Sets the object_type of this HyperflexUcsmConfigPolicyRef. :param object_type: The object_type of this HyperflexUcsmConfigPolicyRef. :type: str """ self._object_type = object_type 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, HyperflexUcsmConfigPolicyRef): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
24.746667
81
0.554149
from pprint import pformat from six import iteritems import re class HyperflexUcsmConfigPolicyRef(object): swagger_types = { 'moid': 'str', 'object_type': 'str' } attribute_map = { 'moid': 'Moid', 'object_type': 'ObjectType' } def __init__(self, moid=None, object_type=None): self._moid = None self._object_type = None if moid is not None: self.moid = moid if object_type is not None: self.object_type = object_type @property def moid(self): return self._moid @moid.setter def moid(self, moid): self._moid = moid @property def object_type(self): return self._object_type @object_type.setter def object_type(self, object_type): self._object_type = object_type def to_dict(self): 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): return pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, HyperflexUcsmConfigPolicyRef): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f727bc6fd1864b3db8c69008ff273cd86317a3fd
545
py
Python
conda_verify/package/test_files.py
soapy1/conda-verify
4941b8ea37bf4afa5ca16366ae855f756037f230
[ "BSD-3-Clause" ]
null
null
null
conda_verify/package/test_files.py
soapy1/conda-verify
4941b8ea37bf4afa5ca16366ae855f756037f230
[ "BSD-3-Clause" ]
null
null
null
conda_verify/package/test_files.py
soapy1/conda-verify
4941b8ea37bf4afa5ca16366ae855f756037f230
[ "BSD-3-Clause" ]
1
2020-02-03T12:43:17.000Z
2020-02-03T12:43:17.000Z
from conda_verify.conda_package_check import CondaPackageCheck def verify(path_to_package=None, verbose=True, **kwargs): package_check = CondaPackageCheck(path_to_package, verbose) package_check.info_files() package_check.no_hardlinks() package_check.not_allowed_files() package_check.index_json() package_check.no_bat_and_exe() package_check.list_packages() pedantic = kwargs.get("pedantic") if "pedantic" in kwargs.keys() else True package_check.has_prefix(pedantic=pedantic) package_check.t.close()
34.0625
78
0.774312
from conda_verify.conda_package_check import CondaPackageCheck def verify(path_to_package=None, verbose=True, **kwargs): package_check = CondaPackageCheck(path_to_package, verbose) package_check.info_files() package_check.no_hardlinks() package_check.not_allowed_files() package_check.index_json() package_check.no_bat_and_exe() package_check.list_packages() pedantic = kwargs.get("pedantic") if "pedantic" in kwargs.keys() else True package_check.has_prefix(pedantic=pedantic) package_check.t.close()
true
true
f727be7b1536a7590641b1a6b3f2745fd7b98775
433
py
Python
src/batch_iterator.py
thealah/imdb-import
fd51d7fbefc419c134277bc0c85b59dcbb457350
[ "MIT" ]
null
null
null
src/batch_iterator.py
thealah/imdb-import
fd51d7fbefc419c134277bc0c85b59dcbb457350
[ "MIT" ]
null
null
null
src/batch_iterator.py
thealah/imdb-import
fd51d7fbefc419c134277bc0c85b59dcbb457350
[ "MIT" ]
null
null
null
def batch_iterator(iterable, size=100, filter_expression=None): current_batch = [] for x in iterable: if filter_expression: if filter_expression(x): current_batch.append(x) else: current_batch.append(x) if len(current_batch) == size: yield current_batch current_batch = [] if current_batch: yield current_batch
27.0625
63
0.575058
def batch_iterator(iterable, size=100, filter_expression=None): current_batch = [] for x in iterable: if filter_expression: if filter_expression(x): current_batch.append(x) else: current_batch.append(x) if len(current_batch) == size: yield current_batch current_batch = [] if current_batch: yield current_batch
true
true
f727be9a5c7b0dee1552109b912eec3664b93ab0
3,227
py
Python
exavault/models/share_relationships_notification.py
ExaVault/evapi-python
769bfa9fbb683f2b4653ca2564029ffb72445c8c
[ "MIT" ]
null
null
null
exavault/models/share_relationships_notification.py
ExaVault/evapi-python
769bfa9fbb683f2b4653ca2564029ffb72445c8c
[ "MIT" ]
3
2017-07-13T20:58:05.000Z
2019-08-02T19:08:37.000Z
exavault/models/share_relationships_notification.py
ExaVault/evapi-python
769bfa9fbb683f2b4653ca2564029ffb72445c8c
[ "MIT" ]
4
2016-11-16T00:14:23.000Z
2020-09-24T14:50:46.000Z
# coding: utf-8 """ ExaVault API See our API reference documentation at https://www.exavault.com/developer/api-docs/ # noqa: E501 OpenAPI spec version: 2.0 Contact: support@exavault.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ShareRelationshipsNotification(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'data': 'ShareRelationshipsData' } attribute_map = { 'data': 'data' } def __init__(self, data=None): # noqa: E501 """ShareRelationshipsNotification - a model defined in Swagger""" # noqa: E501 self._data = None self.discriminator = None if data is not None: self.data = data @property def data(self): """Gets the data of this ShareRelationshipsNotification. # noqa: E501 :return: The data of this ShareRelationshipsNotification. # noqa: E501 :rtype: ShareRelationshipsData """ return self._data @data.setter def data(self, data): """Sets the data of this ShareRelationshipsNotification. :param data: The data of this ShareRelationshipsNotification. # noqa: E501 :type: ShareRelationshipsData """ self._data = data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ShareRelationshipsNotification, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ShareRelationshipsNotification): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
29.072072
101
0.575147
import pprint import re import six class ShareRelationshipsNotification(object): swagger_types = { 'data': 'ShareRelationshipsData' } attribute_map = { 'data': 'data' } def __init__(self, data=None): self._data = None self.discriminator = None if data is not None: self.data = data @property def data(self): return self._data @data.setter def data(self, data): self._data = data def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ShareRelationshipsNotification, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, ShareRelationshipsNotification): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f727bf0787af05ae30dd3c315f89a1ffc68b1a5f
126
py
Python
models.py
banr1jnts/kaggle-youtube2nd
21248d563afcf707cc7665703a987d71c94f4c5a
[ "MIT" ]
null
null
null
models.py
banr1jnts/kaggle-youtube2nd
21248d563afcf707cc7665703a987d71c94f4c5a
[ "MIT" ]
null
null
null
models.py
banr1jnts/kaggle-youtube2nd
21248d563afcf707cc7665703a987d71c94f4c5a
[ "MIT" ]
null
null
null
class BaseModel(object): def create_model(self, unused_model_input, **unused_params): raise NotImplementedError()
31.5
64
0.746032
class BaseModel(object): def create_model(self, unused_model_input, **unused_params): raise NotImplementedError()
true
true