code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
from django.urls import include, re_path from rest_framework.routers import SimpleRouter from rest_framework_nested.routers import NestedSimpleRouter from olympia.bandwagon.views import CollectionAddonViewSet, CollectionViewSet from . import views accounts = SimpleRouter() accounts.register(r'account', views.AccountViewSet, basename='account') collections = NestedSimpleRouter(accounts, r'account', lookup='user') collections.register(r'collections', CollectionViewSet, basename='collection') sub_collections = NestedSimpleRouter(collections, r'collections', lookup='collection') sub_collections.register('addons', CollectionAddonViewSet, basename='collection-addon') notifications = NestedSimpleRouter(accounts, r'account', lookup='user') notifications.register( r'notifications', views.AccountNotificationViewSet, basename='notification' ) accounts_v4 = [ re_path( r'^login/start/$', views.LoginStartView.as_view(), name='accounts.login_start' ), re_path(r'^session/$', views.SessionView.as_view(), name='accounts.session'), re_path(r'', include(accounts.urls)), re_path(r'^profile/$', views.ProfileView.as_view(), name='account-profile'), re_path( r'^super-create/$', views.AccountSuperCreate.as_view(), name='accounts.super-create', ), re_path( r'^unsubscribe/$', views.AccountNotificationUnsubscribeView.as_view(), name='account-unsubscribe', ), re_path(r'', include(collections.urls)), re_path(r'', include(sub_collections.urls)), re_path(r'', include(notifications.urls)), ] accounts_v3 = accounts_v4 + [ re_path( r'^authenticate/$', views.AuthenticateView.as_view(), name='accounts.authenticate', ), ] auth_urls = [ re_path( r'^authenticate-callback/$', views.AuthenticateView.as_view(), name='accounts.authenticate', ), re_path( r'^fxa-notification', views.FxaNotificationView.as_view(), name='fxa-notification', ), ]
wagnerand/addons-server
src/olympia/accounts/urls.py
Python
bsd-3-clause
2,043
import sys sys.path.append('..') from dojo.tools.generic.parser import GenericFindingUploadCsvParser from dojo.models import Finding from dojo.models import Test import unittest import datetime import csv import StringIO class TestFile(object): def read(self): return self.content def __init__(self, name, content): self.name = name self.content = content class TestGenericFindingUploadCsvParser(unittest.TestCase): def setUp(self): self.parser = GenericFindingUploadCsvParser(None, Test()) def test_parse_no_csv_content_no_findings(self): findings = "" file = TestFile("findings.csv", findings) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(0, len(self.parser.items)) def test_parse_csv_with_only_headers_results_in_no_findings(self): content = "Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified" file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(0, len(self.parser.items)) def test_parse_csv_with_single_vulnerability_results_in_single_finding(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/16,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(1, len(self.parser.items)) def test_parse_csv_with_multiple_vulnerabilities_results_in_multiple_findings(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/16,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE 11/7/16,Potential SQL Injection,112,,High,"FileName: UserData.cs Description: Potential SQL Injection Vulnerability Line:42 Code Line: strSQL=""SELECT * FROM users WHERE user_id="" + request_user_id",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(2, len(self.parser.items)) def test_parse_csv_with_duplicates_results_in_single_findings(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/16,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE 11/7/16,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(1, len(self.parser.items)) def test_parsed_finding_has_date(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(datetime.date(2015, 11,7), self.parser.items[0].date) def test_parsed_finding_has_title(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('Potential XSS Vulnerability', self.parser.items[0].title) def test_parsed_finding_has_cwe(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,,High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(79, self.parser.items[0].cwe) def test_parsed_finding_has_url(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('http://localhost/default.aspx', self.parser.items[0].url) def test_parsed_finding_has_severity(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('High', self.parser.items[0].severity) def test_parsed_finding_with_invalid_severity_has_info_severity(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",Unknown,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('Info', self.parser.items[0].severity) def test_parsed_finding_has_description(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);",None,,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('FileName: default.aspx.cs\nDescription: Potential XSS Vulnerability\nLine:18\nCode Line: Response.Write(output);', self.parser.items[0].description) def test_parsed_finding_has_mitigation(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available",,,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('None Currently Available', self.parser.items[0].mitigation) def test_parsed_finding_has_impact(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown",,TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('Impact is currently unknown', self.parser.items[0].impact) def test_parsed_finding_has_references(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual('Finding has references.', self.parser.items[0].references) def test_parsed_finding_has_positive_active_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",TRUE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(True, self.parser.items[0].active) def test_parsed_finding_has_negative_active_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(False, self.parser.items[0].active) def test_parsed_finding_has_positive_verified_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,TRUE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(True, self.parser.items[0].verified) def test_parsed_finding_has_negative_verified_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(False, self.parser.items[0].verified) def test_parsed_finding_has_positive_false_positive_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified,FalsePositive 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE,TRUE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(True, self.parser.items[0].false_p) def test_parsed_finding_has_negative_false_positive_status(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified,FalsePositive 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(False, self.parser.items[0].false_p) def test_parsed_finding_is_duplicate_has_positive_value(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified,FalsePositive,Duplicate 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE,FALSE,TRUE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(True, self.parser.items[0].duplicate) def test_parsed_finding_is_duplicate_has_negative_value(self): content = """Date,Title,CweId,Url,Severity,Description,Mitigation,Impact,References,Active,Verified,FalsePositive,Duplicate 11/7/2015,Potential XSS Vulnerability,79,"http://localhost/default.aspx",High,"FileName: default.aspx.cs Description: Potential XSS Vulnerability Line:18 Code Line: Response.Write(output);","None Currently Available","Impact is currently unknown","Finding has references.",FALSE,FALSE,FALSE,FALSE """ file = TestFile("findings.csv", content) self.parser = GenericFindingUploadCsvParser(file, Test()) self.assertEqual(False, self.parser.items[0].duplicate)
yan99uic/django-DefectDojo
tests/generic_finding_upload_unit_test.py
Python
bsd-3-clause
14,167
# -*- coding: utf-8 -*- from __future__ import print_function, division import matplotlib.pyplot as plot import numpy from numpy.polynomial.polynomial import polyfit,polyadd,Polynomial import yaml INCHES_PER_ML = 0.078 VOLTS_PER_ADC_UNIT = 0.0049 def load_numpy_data(path): with open(path,'r') as fid: header = fid.readline().rstrip().split(',') dt = numpy.dtype({'names':header,'formats':['S25']*len(header)}) numpy_data = numpy.loadtxt(path,dtype=dt,delimiter=",",skiprows=1) return numpy_data # ----------------------------------------------------------------------------------------- if __name__ == '__main__': # Load VA data data_file = 'hall_effect_data_va.csv' hall_effect_data_va = load_numpy_data(data_file) distances_va = numpy.float64(hall_effect_data_va['distance']) A1_VA = numpy.float64(hall_effect_data_va['A1']) A9_VA = numpy.float64(hall_effect_data_va['A9']) A4_VA = numpy.float64(hall_effect_data_va['A4']) A12_VA = numpy.float64(hall_effect_data_va['A12']) A2_VA = numpy.float64(hall_effect_data_va['A2']) A10_VA = numpy.float64(hall_effect_data_va['A10']) A5_VA = numpy.float64(hall_effect_data_va['A5']) A13_VA = numpy.float64(hall_effect_data_va['A13']) # Massage VA data volumes_va = distances_va/INCHES_PER_ML A1_VA = numpy.reshape(A1_VA,(-1,1)) A9_VA = numpy.reshape(A9_VA,(-1,1)) A4_VA = numpy.reshape(A4_VA,(-1,1)) A12_VA = numpy.reshape(A12_VA,(-1,1)) A2_VA = numpy.reshape(A2_VA,(-1,1)) A10_VA = numpy.reshape(A10_VA,(-1,1)) A5_VA = numpy.reshape(A5_VA,(-1,1)) A13_VA = numpy.reshape(A13_VA,(-1,1)) data_va = numpy.hstack((A1_VA,A9_VA,A4_VA,A12_VA,A2_VA,A10_VA,A5_VA,A13_VA)) data_va = data_va/VOLTS_PER_ADC_UNIT # Load OA data data_file = 'hall_effect_data_oa.csv' hall_effect_data_oa = load_numpy_data(data_file) distances_oa = numpy.float64(hall_effect_data_oa['distance']) A9_OA = numpy.float64(hall_effect_data_oa['A9']) A10_OA = numpy.float64(hall_effect_data_oa['A10']) A11_OA = numpy.float64(hall_effect_data_oa['A11']) A12_OA = numpy.float64(hall_effect_data_oa['A12']) # Massage OA data volumes_oa = distances_oa/INCHES_PER_ML A9_OA = numpy.reshape(A9_OA,(-1,1)) A10_OA = numpy.reshape(A10_OA,(-1,1)) A11_OA = numpy.reshape(A11_OA,(-1,1)) A12_OA = numpy.reshape(A12_OA,(-1,1)) data_oa = numpy.hstack((A9_OA,A10_OA,A11_OA,A12_OA)) data_oa = data_oa/VOLTS_PER_ADC_UNIT # Create figure fig = plot.figure() fig.suptitle('hall effect sensors',fontsize=14,fontweight='bold') fig.subplots_adjust(top=0.85) colors = ['b','g','r','c','m','y','k','b'] markers = ['o','o','o','o','o','o','o','^'] # Axis 1 ax1 = fig.add_subplot(121) for column_index in range(0,data_va.shape[1]): color = colors[column_index] marker = markers[column_index] ax1.plot(data_va[:,column_index],volumes_va,marker=marker,linestyle='--',color=color) # for column_index in range(0,data_oa.shape[1]): # color = colors[column_index] # marker = markers[column_index] # ax1.plot(data_oa[:,column_index],volumes_oa,marker=marker,linestyle='--',color=color) ax1.set_xlabel('mean signals (ADC units)') ax1.set_ylabel('volume (ml)') ax1.grid(True) # Axis 2 for column_index in range(0,data_va.shape[1]): data_va[:,column_index] -= data_va[:,column_index].min() MAX_VA = 120 data_va = data_va[numpy.all(data_va<MAX_VA,axis=1)] length = data_va.shape[0] volumes_va = volumes_va[-length:] # for column_index in range(0,data_oa.shape[1]): # data_oa[:,column_index] -= data_oa[:,column_index].max() ax2 = fig.add_subplot(122) for column_index in range(0,data_va.shape[1]): color = colors[column_index] marker = markers[column_index] ax2.plot(data_va[:,column_index],volumes_va,marker=marker,linestyle='--',color=color) # for column_index in range(0,data_oa.shape[1]): # color = colors[column_index] # marker = markers[column_index] # ax2.plot(data_oa[:,column_index],volumes_oa,marker=marker,linestyle='--',color=color) ax2.set_xlabel('offset mean signals (ADC units)') ax2.set_ylabel('volume (ml)') ax2.grid(True) order = 3 sum_va = None for column_index in range(0,data_va.shape[1]): coefficients_va = polyfit(data_va[:,column_index],volumes_va,order) if sum_va is None: sum_va = coefficients_va else: sum_va = polyadd(sum_va,coefficients_va) average_va = sum_va/data_va.shape[1] with open('adc_to_volume_va.yaml', 'w') as f: yaml.dump(average_va, f, default_flow_style=False) round_digits = 8 average_va = [round(i,round_digits) for i in average_va] poly = Polynomial(average_va) ys_va = poly(data_va[:,-1]) ax2.plot(data_va[:,-1],ys_va,'r',linewidth=3) ax2.text(5,7.5,r'$v = c_0 + c_1s + c_2s^2 + c_3s^3$',fontsize=20) ax2.text(5,6.5,str(average_va),fontsize=18,color='r') plot.show()
JaneliaSciComp/hybridizer
tests/adc_to_volume.py
Python
bsd-3-clause
5,112
#!/usr/bin/python3 ############################################################ # etcdlib.py -- etcdlib provides a python etcd client # author : Bao Li <libao14@pku.edu.cn>, UniAS, SEI, PKU # license : BSD License ############################################################ import urllib.request, urllib.error import random, json, time #import sys # send http request to etcd server and get the json result # url : url # data : data to send by POST/PUT # method : method used by http request def dorequest(url, data = "", method = 'GET'): try: if method == 'GET': response = urllib.request.urlopen(url, timeout=10).read() else: # use PUT/DELETE/POST, data should be encoded in ascii/bytes request = urllib.request.Request(url, data = data.encode('ascii'), method = method) response = urllib.request.urlopen(request, timeout=10).read() # etcd may return json result with response http error code # http error code will raise exception in urlopen # catch the HTTPError and get the json result except urllib.error.HTTPError as e: # e.fp must be read() in this except block. # the e will be deleted and e.fp will be closed after this block response = e.fp.read() # response is encoded in bytes. # recoded in utf-8 and loaded in json result = json.loads(str(response, encoding='utf-8')) return result # client to use etcd # not all APIs are implemented below. just implement what we want class Client(object): # server is a string of one server IP and PORT, like 192.168.4.12:2379 def __init__(self, server, prefix = ""): self.clientid = str(random.random()) self.server = "http://"+server prefix = prefix.strip("/") if prefix == "": self.keysurl = self.server+"/v2/keys/" else: self.keysurl = self.server+"/v2/keys/"+prefix+"/" self.members = self.getmembers() def getmembers(self): out = dorequest(self.server+"/v2/members") result = [] for one in out['members']: result.append(one['clientURLs'][0]) return result # list etcd servers def listmembers(self): return self.members def clean(self): [baseurl, dirname] = self.keysurl.split("/v2/keys/", maxsplit=1) dirname = dirname.strip("/") if dirname == '': # clean root content [status, result] = self.listdir("") if status: for one in result: if 'dir' in one: self.deldir(one['key']) else: self.delkey(one['key']) if self.isdir("_lock"): self.deldir("_lock") else: # clean a directory if self.isdir("")[0]: self.deldir("") self.createdir("") def getkey(self, key): key = key.strip("/") out = dorequest(self.keysurl+key) if 'action' not in out: return [False, "key not found"] else: return [True, out['node']['value']] def setkey(self, key, value, ttl=0): key = key.strip("/") if ttl == 0: out = dorequest(self.keysurl+key, 'value='+str(value), 'PUT') else: out = dorequest(self.keysurl+key, 'value='+str(value)+"&ttl="+str(ttl), 'PUT') if 'action' not in out: return [False, 'set key failed'] else: return [True, out['node']['value']] def delkey(self, key): key = key.strip("/") out = dorequest(self.keysurl+key, method='DELETE') if 'action' not in out: return [False, 'delete key failed'] else: return [True, out['node']['key']] def isdir(self, dirname): dirname = dirname.strip("/") out = dorequest(self.keysurl+dirname) if 'action' not in out: return [False, dirname+" not found"] if 'dir' not in out['node']: return [False, dirname+" is a key"] return [True, dirname] def createdir(self, dirname): dirname = dirname.strip("/") out = dorequest(self.keysurl+dirname, 'dir=true', 'PUT') if 'action' not in out: return [False, 'create dir failed'] else: return [True, out['node']['key']] # list key-value in the directory. BUT not recursive. # if necessary, recursive can be supported by add ?recursive=true in url def listdir(self, dirname): dirname = dirname.strip("/") out = dorequest(self.keysurl+dirname) if 'action' not in out: return [False, 'list directory failed'] else: if "dir" not in out['node']: return [False, dirname+" is a key"] if 'nodes' not in out['node']: return [True, []] result=[] for kv in out['node']['nodes']: if 'dir' in kv: result.append({"key":kv['key'], 'dir':True}) else: result.append({"key":kv['key'], 'value':kv['value']}) return [True, result] # del directory with recursive=true def deldir(self, dirname): dirname = dirname.strip("/") out = dorequest(self.keysurl+dirname+"?recursive=true", method='DELETE') if 'action' not in out: return [False, 'delete directory failed'] else: return [True, out['node']['key']] # watch a key or directory when it changes. # recursive=true means anything in the directory changes, it will return def watch(self, key): key = key.strip("/") out = dorequest(self.keysurl+key+"?wait=true&recursive=true") if 'action' not in out: return [False, 'watch key failed'] else: return [True, out['node']['value']] # atomic create a key. return immediately with True or False def atomiccreate(self, key, value='atom'): key = key.strip("/") out = dorequest(self.keysurl+key+"?prevExist=false", 'value='+value, method='PUT') if 'action' not in out: return [False, 'atomic create key failed'] else: return [True, out['node']['key']] ################# Lock ################## # lockref(key) : get a reference of a lock named key in etcd. # not need to create this lock. it is automatical. # acquire(lockref) : acquire this lock by lockref. # blocked if lock is holded by others # release(lockref) : release this lock by lockref # only can be released by holder ######################################### def lockref(self, key): key = key.strip("/") return "_lock/"+key def acquire(self, lockref): while(True): if self.atomiccreate(lockref, self.clientid)[0]: return [True, 'get lock'] else: time.sleep(0.01) def release(self, lockref): value = self.getkey(lockref) if value[0]: if value[1] == self.clientid: self.delkey(lockref) return [True, 'release lock'] else: return [False, 'you are not lock holder'] else: return [False, 'no one holds this lock']
FirmlyReality/docklet
src/utils/etcdlib.py
Python
bsd-3-clause
7,437
class KeyInvalidException(Exception): pass class KeyDisabledException(Exception): pass class FastQueryException(Exception): def __init__(self, last_access=None): self.last_access = last_access
krautradio/PyRfK
lib/rfk/exc/api.py
Python
bsd-3-clause
217
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os from shutil import rmtree import nibabel as nif import numpy as np from tempfile import mkdtemp from nipype.testing import assert_equal, assert_raises, skipif import nipype.interfaces.freesurfer as freesurfer def create_files_in_directory(): outdir = os.path.realpath(mkdtemp()) cwd = os.getcwd() os.chdir(outdir) filelist = ['a.nii', 'b.nii'] for f in filelist: hdr = nif.Nifti1Header() shape = (3, 3, 3, 4) hdr.set_data_shape(shape) img = np.random.random(shape) nif.save(nif.Nifti1Image(img, np.eye(4), hdr), os.path.join(outdir, f)) return filelist, outdir, cwd def clean_directory(outdir, old_wd): if os.path.exists(outdir): rmtree(outdir) os.chdir(old_wd) @skipif(freesurfer.no_freesurfer) def test_robustregister(): filelist, outdir, cwd = create_files_in_directory() reg = freesurfer.RobustRegister() # make sure command gets called yield assert_equal, reg.cmd, 'mri_robust_register' # test raising error with mandatory args absent yield assert_raises, ValueError, reg.run # .inputs based parameters setting reg.inputs.source_file = filelist[0] reg.inputs.target_file = filelist[1] reg.inputs.auto_sens = True yield assert_equal, reg.cmdline, ('mri_robust_register ' '--satit --lta %s_robustreg.lta --mov %s --dst %s' % (filelist[0][:-4], filelist[0], filelist[1])) # constructor based parameter setting reg2 = freesurfer.RobustRegister(source_file=filelist[0], target_file=filelist[1], outlier_sens=3.0, out_reg_file='foo.lta', half_targ=True) yield assert_equal, reg2.cmdline, ('mri_robust_register --halfdst %s_halfway.nii --lta foo.lta ' '--sat 3.0000 --mov %s --dst %s' % (os.path.join(outdir, filelist[1][:-4]), filelist[0], filelist[1])) clean_directory(outdir, cwd) @skipif(freesurfer.no_freesurfer) def test_fitmsparams(): filelist, outdir, cwd = create_files_in_directory() fit = freesurfer.FitMSParams() # make sure command gets called yield assert_equal, fit.cmd, 'mri_ms_fitparms' # test raising error with mandatory args absent yield assert_raises, ValueError, fit.run # .inputs based parameters setting fit.inputs.in_files = filelist fit.inputs.out_dir = outdir yield assert_equal, fit.cmdline, 'mri_ms_fitparms %s %s %s' % (filelist[0], filelist[1], outdir) # constructor based parameter setting fit2 = freesurfer.FitMSParams(in_files=filelist, te_list=[1.5, 3.5], flip_list=[20, 30], out_dir=outdir) yield assert_equal, fit2.cmdline, ('mri_ms_fitparms -te %.3f -fa %.1f %s -te %.3f -fa %.1f %s %s' % (1.500, 20.0, filelist[0], 3.500, 30.0, filelist[1], outdir)) clean_directory(outdir, cwd) @skipif(freesurfer.no_freesurfer) def test_synthesizeflash(): filelist, outdir, cwd = create_files_in_directory() syn = freesurfer.SynthesizeFLASH() # make sure command gets called yield assert_equal, syn.cmd, 'mri_synthesize' # test raising error with mandatory args absent yield assert_raises, ValueError, syn.run # .inputs based parameters setting syn.inputs.t1_image = filelist[0] syn.inputs.pd_image = filelist[1] syn.inputs.flip_angle = 30 syn.inputs.te = 4.5 syn.inputs.tr = 20 yield assert_equal, syn.cmdline, ('mri_synthesize 20.00 30.00 4.500 %s %s %s' % (filelist[0], filelist[1], os.path.join(outdir, 'synth-flash_30.mgz'))) # constructor based parameters setting syn2 = freesurfer.SynthesizeFLASH(t1_image=filelist[0], pd_image=filelist[1], flip_angle=20, te=5, tr=25) yield assert_equal, syn2.cmdline, ('mri_synthesize 25.00 20.00 5.000 %s %s %s' % (filelist[0], filelist[1], os.path.join(outdir, 'synth-flash_20.mgz')))
sgiavasis/nipype
nipype/interfaces/freesurfer/tests/test_preprocess.py
Python
bsd-3-clause
4,150
from __future__ import unicode_literals, division, absolute_import from datetime import datetime import logging import re import sys from path import Path from flexget import plugin from flexget.config_schema import one_or_more from flexget.event import event from flexget.entry import Entry log = logging.getLogger('find') class InputFind(object): """ Uses local path content as an input, recurses through directories and creates entries for files that match mask. You can specify either the mask key, in shell file matching format, (see python fnmatch module,) or regexp key. Example:: find: path: /storage/movies/ mask: *.avi Example:: find: path: - /storage/movies/ - /storage/tv/ regexp: .*\.(avi|mkv)$ """ schema = { 'type': 'object', 'properties': { 'path': one_or_more({'type': 'string', 'format': 'path'}), 'mask': {'type': 'string'}, 'regexp': {'type': 'string', 'format': 'regex'}, 'recursive': {'type': 'boolean'} }, 'required': ['path'], 'additionalProperties': False } def prepare_config(self, config): from fnmatch import translate # If only a single path is passed turn it into a 1 element list if isinstance(config['path'], basestring): config['path'] = [config['path']] config.setdefault('recursive', False) # If mask was specified, turn it in to a regexp if config.get('mask'): config['regexp'] = translate(config['mask']) # If no mask or regexp specified, accept all files if not config.get('regexp'): config['regexp'] = '.' def on_task_input(self, task, config): self.prepare_config(config) entries = [] match = re.compile(config['regexp'], re.IGNORECASE).match for folder in config['path']: folder = Path(folder).expanduser() log.debug('scanning %s' % folder) if config['recursive']: files = folder.walk(errors='ignore') else: files = folder.listdir() for item in files: e = Entry() try: # TODO: config for listing files/dirs/both if item.isdir(): continue except UnicodeError as e: log.warning('Filename `%s` in `%s` is not decodable by declared filesystem encoding `%s`. ' 'Either your environment does not declare the correct encoding, or this filename ' 'is incorrectly encoded.' % (item.name, item.dirname(), sys.getfilesystemencoding())) continue e['title'] = item.namebase # If mask fails continue if not match(item.name): continue try: e['timestamp'] = datetime.fromtimestamp(item.getmtime()) except ValueError as e: log.debug('Error setting timestamp for %s: %s' % (item, e)) e['location'] = item # Windows paths need an extra / prepended to them for url if not item.startswith('/'): item = '/' + item e['url'] = 'file://%s' % item entries.append(e) return entries @event('plugin.register') def register_plugin(): plugin.register(InputFind, 'find', api_ver=2)
xfouloux/Flexget
flexget/plugins/input/find.py
Python
mit
3,623
import re from .utils import validator ip_middle_octet = r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5]))" ip_last_octet = r"(?:\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5]))" regex = re.compile( # noqa: W605 r"^" # protocol identifier r"(?:(?:https?|ftp)://)" # user:pass authentication r"(?:[-a-z\u00a1-\uffff0-9._~%!$&'()*+,;=:]+" r"(?::[-a-z0-9._~%!$&'()*+,;=:]*)?@)?" r"(?:" r"(?P<private_ip>" # IP address exclusion # private & local networks r"(?:(?:10|127)" + ip_middle_octet + r"{2}" + ip_last_octet + r")|" r"(?:(?:169\.254|192\.168)" + ip_middle_octet + ip_last_octet + r")|" r"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + r"))" r"|" # private & local hosts r"(?P<private_host>" r"(?:localhost))" r"|" # IP address dotted notation octets # excludes loopback network 0.0.0.0 # excludes reserved space >= 224.0.0.0 # excludes network & broadcast addresses # (first & last IP address of each class) r"(?P<public_ip>" r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" r"" + ip_middle_octet + r"{2}" r"" + ip_last_octet + r")" r"|" # IPv6 RegEx from https://stackoverflow.com/a/17871737 r"\[(" # 1:2:3:4:5:6:7:8 r"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" # 1:: 1:2:3:4:5:6:7:: r"([0-9a-fA-F]{1,4}:){1,7}:|" # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8 r"([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8 r"([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8 r"([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|" # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8 r"([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8 r"([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|" # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8 r"[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: r":((:[0-9a-fA-F]{1,4}){1,7}|:)|" # fe80::7:8%eth0 fe80::7:8%1 # (link-local IPv6 addresses with zone index) r"fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|" r"::(ffff(:0{1,4}){0,1}:){0,1}" r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}" # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 # (IPv4-mapped IPv6 addresses and IPv4-translated addresses) r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|" r"([0-9a-fA-F]{1,4}:){1,4}:" r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}" # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 # (IPv4-Embedded IPv6 Address) r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])" r")\]|" # host name r"(?:(?:(?:xn--)|[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]-?)*" r"[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]+)" # domain name r"(?:\.(?:(?:xn--)|[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]-?)*" r"[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]+)*" # TLD identifier r"(?:\.(?:(?:xn--[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]{2,})|" r"[a-z\u00a1-\uffff\U00010000-\U0010ffff]{2,}))" r")" # port number r"(?::\d{2,5})?" # resource path r"(?:/[-a-z\u00a1-\uffff\U00010000-\U0010ffff0-9._~%!$&'()*+,;=:@/]*)?" # query string r"(?:\?\S*)?" # fragment r"(?:#\S*)?" r"$", re.UNICODE | re.IGNORECASE ) pattern = re.compile(regex) @validator def url(value, public=False): """ Return whether or not given value is a valid URL. If the value is valid URL this function returns ``True``, otherwise :class:`~validators.utils.ValidationFailure`. This validator is based on the wonderful `URL validator of dperini`_. .. _URL validator of dperini: https://gist.github.com/dperini/729294 Examples:: >>> url('http://foobar.dk') True >>> url('ftp://foobar.dk') True >>> url('http://10.0.0.1') True >>> url('http://foobar.d') ValidationFailure(func=url, ...) >>> url('http://10.0.0.1', public=True) ValidationFailure(func=url, ...) .. versionadded:: 0.2 .. versionchanged:: 0.10.2 Added support for various exotic URLs and fixed various false positives. .. versionchanged:: 0.10.3 Added ``public`` parameter. .. versionchanged:: 0.11.0 Made the regular expression this function uses case insensitive. .. versionchanged:: 0.11.3 Added support for URLs containing localhost :param value: URL address string to validate :param public: (default=False) Set True to only allow a public IP address """ result = pattern.match(value) if not public: return result return result and not any( (result.groupdict().get(key) for key in ('private_ip', 'private_host')) )
kvesteri/validators
validators/url.py
Python
mit
4,913
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: proxysql_mysql_users version_added: "2.3" author: "Ben Mildren (@bmildren)" short_description: Adds or removes mysql users from proxysql admin interface. description: - The M(proxysql_mysql_users) module adds or removes mysql users using the proxysql admin interface. options: username: description: - Name of the user connecting to the mysqld or ProxySQL instance. required: True password: description: - Password of the user connecting to the mysqld or ProxySQL instance. active: description: - A user with I(active) set to C(False) will be tracked in the database, but will be never loaded in the in-memory data structures. If omitted the proxysql database default for I(active) is C(True). type: bool use_ssl: description: - If I(use_ssl) is set to C(True), connections by this user will be made using SSL connections. If omitted the proxysql database default for I(use_ssl) is C(False). type: bool default_hostgroup: description: - If there is no matching rule for the queries sent by this user, the traffic it generates is sent to the specified hostgroup. If omitted the proxysql database default for I(use_ssl) is 0. default_schema: description: - The schema to which the connection should change to by default. transaction_persistent: description: - If this is set for the user with which the MySQL client is connecting to ProxySQL (thus a "frontend" user), transactions started within a hostgroup will remain within that hostgroup regardless of any other rules. If omitted the proxysql database default for I(transaction_persistent) is C(False). type: bool fast_forward: description: - If I(fast_forward) is set to C(True), I(fast_forward) will bypass the query processing layer (rewriting, caching) and pass through the query directly as is to the backend server. If omitted the proxysql database default for I(fast_forward) is C(False). type: bool backend: description: - If I(backend) is set to C(True), this (username, password) pair is used for authenticating to the ProxySQL instance. default: True type: bool frontend: description: - If I(frontend) is set to C(True), this (username, password) pair is used for authenticating to the mysqld servers against any hostgroup. default: True type: bool max_connections: description: - The maximum number of connections ProxySQL will open to the backend for this user. If omitted the proxysql database default for I(max_connections) is 10000. state: description: - When C(present) - adds the user, when C(absent) - removes the user. choices: [ "present", "absent" ] default: present extends_documentation_fragment: - proxysql.managing_config - proxysql.connectivity ''' EXAMPLES = ''' --- # This example adds a user, it saves the mysql user config to disk, but # avoids loading the mysql user config to runtime (this might be because # several users are being added and the user wants to push the config to # runtime in a single batch using the M(proxysql_manage_config) module). It # uses supplied credentials to connect to the proxysql admin interface. - proxysql_mysql_users: login_user: 'admin' login_password: 'admin' username: 'productiondba' state: present load_to_runtime: False # This example removes a user, saves the mysql user config to disk, and # dynamically loads the mysql user config to runtime. It uses credentials # in a supplied config file to connect to the proxysql admin interface. - proxysql_mysql_users: config_file: '~/proxysql.cnf' username: 'mysqlboy' state: absent ''' RETURN = ''' stdout: description: The mysql user modified or removed from proxysql returned: On create/update will return the newly modified user, on delete it will return the deleted record. type: dict sample: changed: true msg: Added user to mysql_users state: present user: active: 1 backend: 1 default_hostgroup: 1 default_schema: null fast_forward: 0 frontend: 1 max_connections: 10000 password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER schema_locked: 0 transaction_persistent: 0 use_ssl: 0 username: guest_ro username: guest_ro ''' ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.mysql import mysql_connect, mysql_driver, mysql_driver_fail_msg from ansible.module_utils.six import iteritems from ansible.module_utils._text import to_native # =========================================== # proxysql module specific support methods. # def perform_checks(module): if module.params["login_port"] < 0 \ or module.params["login_port"] > 65535: module.fail_json( msg="login_port must be a valid unix port number (0-65535)" ) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) def save_config_to_disk(cursor): cursor.execute("SAVE MYSQL USERS TO DISK") return True def load_config_to_runtime(cursor): cursor.execute("LOAD MYSQL USERS TO RUNTIME") return True class ProxySQLUser(object): def __init__(self, module): self.state = module.params["state"] self.save_to_disk = module.params["save_to_disk"] self.load_to_runtime = module.params["load_to_runtime"] self.username = module.params["username"] self.backend = module.params["backend"] self.frontend = module.params["frontend"] config_data_keys = ["password", "active", "use_ssl", "default_hostgroup", "default_schema", "transaction_persistent", "fast_forward", "max_connections"] self.config_data = dict((k, module.params[k]) for k in config_data_keys) def check_user_config_exists(self, cursor): query_string = \ """SELECT count(*) AS `user_count` FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) check_count = cursor.fetchone() return (int(check_count['user_count']) > 0) def check_user_privs(self, cursor): query_string = \ """SELECT count(*) AS `user_count` FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] for col, val in iteritems(self.config_data): if val is not None: query_data.append(val) query_string += "\n AND " + col + " = %s" cursor.execute(query_string, query_data) check_count = cursor.fetchone() return (int(check_count['user_count']) > 0) def get_user_config(self, cursor): query_string = \ """SELECT * FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) user = cursor.fetchone() return user def create_user_config(self, cursor): query_string = \ """INSERT INTO mysql_users ( username, backend, frontend""" cols = 3 query_data = \ [self.username, self.backend, self.frontend] for col, val in iteritems(self.config_data): if val is not None: cols += 1 query_data.append(val) query_string += ",\n" + col query_string += \ (")\n" + "VALUES (" + "%s ," * cols) query_string = query_string[:-2] query_string += ")" cursor.execute(query_string, query_data) return True def update_user_config(self, cursor): query_string = """UPDATE mysql_users""" cols = 0 query_data = [] for col, val in iteritems(self.config_data): if val is not None: cols += 1 query_data.append(val) if cols == 1: query_string += "\nSET " + col + "= %s," else: query_string += "\n " + col + " = %s," query_string = query_string[:-1] query_string += ("\nWHERE username = %s\n AND backend = %s" + "\n AND frontend = %s") query_data.append(self.username) query_data.append(self.backend) query_data.append(self.frontend) cursor.execute(query_string, query_data) return True def delete_user_config(self, cursor): query_string = \ """DELETE FROM mysql_users WHERE username = %s AND backend = %s AND frontend = %s""" query_data = \ [self.username, self.backend, self.frontend] cursor.execute(query_string, query_data) return True def manage_config(self, cursor, state): if state: if self.save_to_disk: save_config_to_disk(cursor) if self.load_to_runtime: load_config_to_runtime(cursor) def create_user(self, check_mode, result, cursor): if not check_mode: result['changed'] = \ self.create_user_config(cursor) result['msg'] = "Added user to mysql_users" result['user'] = \ self.get_user_config(cursor) self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been added to" + " mysql_users, however check_mode" + " is enabled.") def update_user(self, check_mode, result, cursor): if not check_mode: result['changed'] = \ self.update_user_config(cursor) result['msg'] = "Updated user in mysql_users" result['user'] = \ self.get_user_config(cursor) self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been updated in" + " mysql_users, however check_mode" + " is enabled.") def delete_user(self, check_mode, result, cursor): if not check_mode: result['user'] = \ self.get_user_config(cursor) result['changed'] = \ self.delete_user_config(cursor) result['msg'] = "Deleted user from mysql_users" self.manage_config(cursor, result['changed']) else: result['changed'] = True result['msg'] = ("User would have been deleted from" + " mysql_users, however check_mode is" + " enabled.") # =========================================== # Module execution. # def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default='', type='path'), username=dict(required=True, type='str'), password=dict(no_log=True, type='str'), active=dict(type='bool'), use_ssl=dict(type='bool'), default_hostgroup=dict(type='int'), default_schema=dict(type='str'), transaction_persistent=dict(type='bool'), fast_forward=dict(type='bool'), backend=dict(default=True, type='bool'), frontend=dict(default=True, type='bool'), max_connections=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool') ), supports_check_mode=True ) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class=mysql_driver.cursors.DictCursor) except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e) ) proxysql_user = ProxySQLUser(module) result = {} result['state'] = proxysql_user.state if proxysql_user.username: result['username'] = proxysql_user.username if proxysql_user.state == "present": try: if not proxysql_user.check_user_privs(cursor): if not proxysql_user.check_user_config_exists(cursor): proxysql_user.create_user(module.check_mode, result, cursor) else: proxysql_user.update_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user already exists in mysql_users" + " and doesn't need to be updated.") result['user'] = \ proxysql_user.get_user_config(cursor) except mysql_driver.Error as e: module.fail_json( msg="unable to modify user.. %s" % to_native(e) ) elif proxysql_user.state == "absent": try: if proxysql_user.check_user_config_exists(cursor): proxysql_user.delete_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user is already absent from the" + " mysql_users memory configuration") except mysql_driver.Error as e: module.fail_json( msg="unable to remove user.. %s" % to_native(e) ) module.exit_json(**result) if __name__ == '__main__': main()
kustodian/ansible
lib/ansible/modules/database/proxysql/proxysql_mysql_users.py
Python
gpl-3.0
16,216
# -*- coding: utf-8 -*- from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo class WarserverCz(DeadHoster): __name__ = "WarserverCz" __type__ = "hoster" __version__ = "0.13" __pattern__ = r'http://(?:www\.)?warserver\.cz/stahnout/\d+' __description__ = """Warserver.cz hoster plugin""" __license__ = "GPLv3" __authors__ = [("Walter Purcaro", "vuolter@gmail.com")] getInfo = create_getInfo(WarserverCz)
sebdelsol/pyload
module/plugins/hoster/WarserverCz.py
Python
gpl-3.0
472
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Brian Coca <bcoca@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' module: systemd author: - "Ansible Core Team" version_added: "2.2" short_description: Manage services. description: - Controls systemd services on remote hosts. options: name: required: true description: - Name of the service. When using in a chroot environment you always need to specify the full name i.e. (crond.service). aliases: ['unit', 'service'] state: required: false default: null choices: [ 'started', 'stopped', 'restarted', 'reloaded' ] description: - C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload. enabled: required: false choices: [ "yes", "no" ] default: null description: - Whether the service should start on boot. B(At least one of state and enabled are required.) masked: required: false choices: [ "yes", "no" ] default: null description: - Whether the unit should be masked or not, a masked unit is impossible to start. daemon_reload: required: false default: no choices: [ "yes", "no" ] description: - run daemon-reload before doing any other operations, to make sure systemd has read any changes. aliases: ['daemon-reload'] user: required: false default: no choices: [ "yes", "no" ] description: - run systemctl talking to the service manager of the calling user, rather than the service manager of the system. no_block: required: false default: no choices: [ "yes", "no" ] description: - Do not synchronously wait for the requested operation to finish. Enqueued job will continue without Ansible blocking on its completion. version_added: "2.3" notes: - One option other than name is required. requirements: - A system managed by systemd ''' EXAMPLES = ''' # Example action to start service httpd, if not running - systemd: state=started name=httpd # Example action to stop service cron on debian, if running - systemd: name=cron state=stopped # Example action to restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes - systemd: state: restarted daemon_reload: yes name: crond # Example action to reload service httpd, in all cases - systemd: name: httpd state: reloaded # Example action to enable service httpd and ensure it is not masked - systemd: name: httpd enabled: yes masked: no # Example action to enable a timer for dnf-automatic - systemd: name: dnf-automatic.timer state: started enabled: True ''' RETURN = ''' status: description: A dictionary with the key=value pairs returned from `systemctl show` returned: success type: complex sample: { "ActiveEnterTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ActiveEnterTimestampMonotonic": "8135942", "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "auditd.service systemd-user-sessions.service time-sync.target systemd-journald.socket basic.target system.slice", "AllowIsolate": "no", "Before": "shutdown.target multi-user.target", "BlockIOAccounting": "no", "BlockIOWeight": "1000", "CPUAccounting": "no", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "1024", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "yes", "ConditionTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ConditionTimestampMonotonic": "7902742", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/crond.service", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "Command Scheduler", "DevicePolicy": "auto", "EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "595", "ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ExecMainStartTimestampMonotonic": "8134990", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FragmentPath": "/usr/lib/systemd/system/crond.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "crond.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT", "InactiveExitTimestampMonotonic": "8135942", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "15", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "3902", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "3902", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "595", "MemoryAccounting": "no", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "crond.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureIsolate": "no", "PermissionsStartOnly": "no", "PrivateNetwork": "no", "PrivateTmp": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "simple", "UMask": "0022", "UnitFileState": "enabled", "WantedBy": "multi-user.target", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0", } ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.service import sysv_exists, sysv_is_enabled, fail_if_missing from ansible.module_utils._text import to_native def is_running_service(service_status): return service_status['ActiveState'] in set(['active', 'activating']) # =========================================== # Main control flow def main(): # initialize module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['unit', 'service']), state = dict(choices=[ 'started', 'stopped', 'restarted', 'reloaded'], type='str'), enabled = dict(type='bool'), masked = dict(type='bool'), daemon_reload = dict(type='bool', default=False, aliases=['daemon-reload']), user = dict(type='bool', default=False), no_block = dict(type='bool', default=False), ), supports_check_mode=True, required_one_of=[['state', 'enabled', 'masked', 'daemon_reload']], ) systemctl = module.get_bin_path('systemctl', True) if module.params['user']: systemctl = systemctl + " --user" if module.params['no_block']: systemctl = systemctl + " --no-block" unit = module.params['name'] rc = 0 out = err = '' result = { 'name': unit, 'changed': False, 'status': {}, } # Run daemon-reload first, if requested if module.params['daemon_reload']: (rc, out, err) = module.run_command("%s daemon-reload" % (systemctl)) if rc != 0: module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err)) found = False is_initd = sysv_exists(unit) is_systemd = False # check service data, cannot error out on rc as it changes across versions, assume not found (rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit)) if out.find('ignoring request') != -1: # fallback list-unit-files as show does not work on some systems (chroot) # not used as primary as it skips some services (like those using init.d) and requires .service/etc notation (rc, out, err) = module.run_command("%s list-unit-files '%s'" % (systemctl, unit)) if rc == 0: is_systemd = True elif rc == 0: # load return of systemctl show into dictionary for easy access and return multival = [] if out: k = None for line in to_native(out).split('\n'): # systemd can have multiline values delimited with {} if line.strip(): if k is None: if '=' in line: k,v = line.split('=', 1) if v.lstrip().startswith('{'): if not v.rstrip().endswith('}'): multival.append(line) continue result['status'][k] = v.strip() k = None else: if line.rstrip().endswith('}'): result['status'][k] = '\n'.join(multival).strip() multival = [] k = None else: multival.append(line) is_systemd = 'LoadState' in result['status'] and result['status']['LoadState'] != 'not-found' # Check for loading error if is_systemd and 'LoadError' in result['status']: module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError'])) else: # Check for systemctl command module.run_command(systemctl, check_rc=True) # Does service exist? found = is_systemd or is_initd if is_initd and not is_systemd: module.warn('The service (%s) is actually an init script but the system is managed by systemd' % unit) # mask/unmask the service, if requested, can operate on services before they are installed if module.params['masked'] is not None: # state is not masked unless systemd affirms otherwise masked = ('LoadState' in result['status'] and result['status']['LoadState'] == 'masked') if masked != module.params['masked']: result['changed'] = True if module.params['masked']: action = 'mask' else: action = 'unmask' if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: # some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't fail_if_missing(module, found, unit, msg='host') # Enable/disable service startup at boot if requested if module.params['enabled'] is not None: if module.params['enabled']: action = 'enable' else: action = 'disable' fail_if_missing(module, found, unit, msg='host') # do we need to enable the service? enabled = False (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) # check systemctl result or if it is a init script if rc == 0: enabled = True elif rc == 1: # if not a user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries if not module.params['user'] and \ is_initd and \ (not out.strip().endswith('disabled') or sysv_is_enabled(unit)): enabled = True # default to current state result['enabled'] = enabled # Change enable/disable if needed if enabled != module.params['enabled']: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err)) result['enabled'] = not enabled # set service state if requested if module.params['state'] is not None: fail_if_missing(module, found, unit, msg="host") # default to desired state result['state'] = module.params['state'] # What is current service state? if 'ActiveState' in result['status']: action = None if module.params['state'] == 'started': if not is_running_service(result['status']): action = 'start' elif module.params['state'] == 'stopped': if is_running_service(result['status']): action = 'stop' else: if not is_running_service(result['status']): action = 'start' else: action = module.params['state'][:-2] # remove 'ed' from restarted/reloaded result['state'] = 'started' if action: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, err)) else: # this should not happen? module.fail_json(msg="Service is in unknown state", status=result['status']) module.exit_json(**result) if __name__ == '__main__': main()
cmelange/ansible
lib/ansible/modules/system/systemd.py
Python
gpl-3.0
16,941
# -*- coding: utf-8 -*- # # manage.py # # Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # Deluge is free software. # # You may redistribute it and/or modify it under the terms of the # GNU General Public License, as published by the Free Software # Foundation; either version 3 of the License, or (at your option) # any later version. # # deluge is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with deluge. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. # # from twisted.internet import defer from deluge.ui.console.main import BaseCommand import deluge.ui.console.colors as colors from deluge.ui.client import client import deluge.component as component from deluge.log import LOG as log from optparse import make_option import re torrent_options = { "max_download_speed": float, "max_upload_speed": float, "max_connections": int, "max_upload_slots": int, "private": bool, "prioritize_first_last": bool, "is_auto_managed": bool, "stop_at_ratio": bool, "stop_ratio": float, "remove_at_ratio": bool, "move_on_completed": bool, "move_on_completed_path": str } class Command(BaseCommand): """Show and manage per-torrent options""" option_list = BaseCommand.option_list + ( make_option('-s', '--set', action='store', nargs=2, dest='set', help='set value for key'), ) usage = "Usage: manage <torrent-id> [<key1> [<key2> ...]]\n"\ " manage <torrent-id> --set <key> <value>" def handle(self, *args, **options): self.console = component.get("ConsoleUI") if options['set']: return self._set_option(*args, **options) else: return self._get_option(*args, **options) def _get_option(self, *args, **options): def on_torrents_status(status): for torrentid, data in status.items(): self.console.write('') if 'name' in data: self.console.write('{!info!}Name: {!input!}%s' % data.get('name')) self.console.write('{!info!}ID: {!input!}%s' % torrentid) for k, v in data.items(): if k != 'name': self.console.write('{!info!}%s: {!input!}%s' % (k, v)) def on_torrents_status_fail(reason): self.console.write('{!error!}Failed to get torrent data.') torrent_ids = [] torrent_ids.extend(self.console.match_torrent(args[0])) request_options = [] for opt in args[1:]: if opt not in torrent_options: self.console.write('{!error!}Unknown torrent option: %s' % opt) return request_options.append(opt) if not request_options: request_options = [ opt for opt in torrent_options.keys() ] request_options.append('name') d = client.core.get_torrents_status({"id": torrent_ids}, request_options) d.addCallback(on_torrents_status) d.addErrback(on_torrents_status_fail) return d def _set_option(self, *args, **options): deferred = defer.Deferred() torrent_ids = [] torrent_ids.extend(self.console.match_torrent(args[0])) key = options["set"][0] val = options["set"][1] + " " .join(args[1:]) if key not in torrent_options: self.console.write("{!error!}The key '%s' is invalid!" % key) return val = torrent_options[key](val) def on_set_config(result): self.console.write("{!success!}Torrent option successfully updated.") deferred.callback(True) self.console.write("Setting %s to %s for torrents %s.." % (key, val, torrent_ids)) for tid in torrent_ids: if key == "move_on_completed_path": client.core.set_torrent_move_completed_path(tid, val).addCallback(on_set_config) elif key == "move_on_completed": client.core.set_torrent_move_completed(tid, val).addCallback(on_set_config) elif key == "is_auto_managed": client.core.set_torrent_auto_managed(tid, val).addCallback(on_set_config) elif key == "remove_at_ratio": client.core.set_torrent_remove_at_ratio(tid, val).addCallback(on_set_config) elif key == "prioritize_first_last": client.core.set_torrent_prioritize_first_last(tid, val).addCallback(on_set_config) else: client.core.set_torrent_options(torrent_ids, {key: val}).addCallback(on_set_config) break return deferred def complete(self, line): # We use the ConsoleUI torrent tab complete method return component.get("ConsoleUI").tab_complete_torrent(line)
ctruchi/deluge-webui2
deluge/ui/console/commands/manage.py
Python
gpl-3.0
5,820
# Copyright 2009-2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. """Communicate with one MongoDB server in a topology.""" import contextlib from datetime import datetime from pymongo.errors import ConfigurationError from pymongo.message import _Query, _convert_exception from pymongo.response import Response, ExhaustResponse from pymongo.server_type import SERVER_TYPE class Server(object): def __init__(self, server_description, pool, monitor, topology_id=None, listeners=None, events=None): """Represent one MongoDB server.""" self._description = server_description self._pool = pool self._monitor = monitor self._topology_id = topology_id self._publish = listeners is not None and listeners.enabled_for_server self._listener = listeners self._events = None if self._publish: self._events = events() def open(self): """Start monitoring, or restart after a fork. Multiple calls have no effect. """ self._monitor.open() def reset(self): """Clear the connection pool.""" self.pool.reset() def close(self): """Clear the connection pool and stop the monitor. Reconnect with open(). """ if self._publish: self._events.put((self._listener.publish_server_closed, (self._description.address, self._topology_id))) self._monitor.close() self._pool.reset() def request_check(self): """Check the server's state soon.""" self._monitor.request_check() def send_message(self, message, all_credentials): """Send an unacknowledged message to MongoDB. Can raise ConnectionFailure. :Parameters: - `message`: (request_id, data). - `all_credentials`: dict, maps auth source to MongoCredential. """ _, data, max_doc_size = self._split_message(message) with self.get_socket(all_credentials) as sock_info: sock_info.send_message(data, max_doc_size) def send_message_with_response( self, operation, set_slave_okay, all_credentials, listeners, exhaust=False): """Send a message to MongoDB and return a Response object. Can raise ConnectionFailure. :Parameters: - `operation`: A _Query or _GetMore object. - `set_slave_okay`: Pass to operation.get_message. - `all_credentials`: dict, maps auth source to MongoCredential. - `listeners`: Instance of _EventListeners or None. - `exhaust` (optional): If True, the socket used stays checked out. It is returned along with its Pool in the Response. """ with self.get_socket(all_credentials, exhaust) as sock_info: duration = None publish = listeners.enabled_for_commands if publish: start = datetime.now() use_find_cmd = False if sock_info.max_wire_version >= 4: if not exhaust: use_find_cmd = True elif (isinstance(operation, _Query) and not operation.read_concern.ok_for_legacy): raise ConfigurationError( 'read concern level of %s is not valid ' 'with a max wire version of %d.' % (operation.read_concern.level, sock_info.max_wire_version)) message = operation.get_message( set_slave_okay, sock_info.is_mongos, use_find_cmd) request_id, data, max_doc_size = self._split_message(message) if publish: encoding_duration = datetime.now() - start cmd, dbn = operation.as_command() listeners.publish_command_start( cmd, dbn, request_id, sock_info.address) start = datetime.now() try: sock_info.send_message(data, max_doc_size) response_data = sock_info.receive_message(1, request_id) except Exception as exc: if publish: duration = (datetime.now() - start) + encoding_duration failure = _convert_exception(exc) listeners.publish_command_failure( duration, failure, next(iter(cmd)), request_id, sock_info.address) raise if publish: duration = (datetime.now() - start) + encoding_duration if exhaust: return ExhaustResponse( data=response_data, address=self._description.address, socket_info=sock_info, pool=self._pool, duration=duration, request_id=request_id, from_command=use_find_cmd) else: return Response( data=response_data, address=self._description.address, duration=duration, request_id=request_id, from_command=use_find_cmd) @contextlib.contextmanager def get_socket(self, all_credentials, checkout=False): with self.pool.get_socket(all_credentials, checkout) as sock_info: yield sock_info @property def description(self): return self._description @description.setter def description(self, server_description): assert server_description.address == self._description.address self._description = server_description @property def pool(self): return self._pool def _split_message(self, message): """Return request_id, data, max_doc_size. :Parameters: - `message`: (request_id, data, max_doc_size) or (request_id, data) """ if len(message) == 3: return message else: # get_more and kill_cursors messages don't include BSON documents. request_id, data = message return request_id, data, 0 def __str__(self): d = self._description return '<Server "%s:%s" %s>' % ( d.address[0], d.address[1], SERVER_TYPE._fields[d.server_type])
pdxwebdev/yadapy
yada/lib/python2.7/site-packages/pymongo/server.py
Python
gpl-3.0
6,957
# -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ name: su short_description: Substitute User description: - This become plugins allows your remote/login user to execute commands as another user via the su utility. author: ansible (@core) version_added: "2.8" options: become_user: description: User you 'become' to execute the task default: root ini: - section: privilege_escalation key: become_user - section: su_become_plugin key: user vars: - name: ansible_become_user - name: ansible_su_user env: - name: ANSIBLE_BECOME_USER - name: ANSIBLE_SU_USER become_exe: description: Su executable default: su ini: - section: privilege_escalation key: become_exe - section: su_become_plugin key: executable vars: - name: ansible_become_exe - name: ansible_su_exe env: - name: ANSIBLE_BECOME_EXE - name: ANSIBLE_SU_EXE become_flags: description: Options to pass to su default: '' ini: - section: privilege_escalation key: become_flags - section: su_become_plugin key: flags vars: - name: ansible_become_flags - name: ansible_su_flags env: - name: ANSIBLE_BECOME_FLAGS - name: ANSIBLE_SU_FLAGS become_pass: description: Password to pass to su required: False vars: - name: ansible_become_password - name: ansible_become_pass - name: ansible_su_pass env: - name: ANSIBLE_BECOME_PASS - name: ANSIBLE_SU_PASS ini: - section: su_become_plugin key: password prompt_l10n: description: - List of localized strings to match for prompt detection - If empty we'll use the built in one - Do NOT add a colon (:) to your custom entries. Ansible adds a colon at the end of each prompt; if you add another one in your string, your prompt will fail with a "Timeout" error. default: [] type: list ini: - section: su_become_plugin key: localized_prompts vars: - name: ansible_su_prompt_l10n env: - name: ANSIBLE_SU_PROMPT_L10N """ import re import shlex from ansible.module_utils._text import to_bytes from ansible.plugins.become import BecomeBase class BecomeModule(BecomeBase): name = 'su' # messages for detecting prompted password issues fail = ('Authentication failure',) SU_PROMPT_LOCALIZATIONS = [ 'Password', '암호', 'パスワード', 'Adgangskode', 'Contraseña', 'Contrasenya', 'Hasło', 'Heslo', 'Jelszó', 'Lösenord', 'Mật khẩu', 'Mot de passe', 'Parola', 'Parool', 'Pasahitza', 'Passord', 'Passwort', 'Salasana', 'Sandi', 'Senha', 'Wachtwoord', 'ססמה', 'Лозинка', 'Парола', 'Пароль', 'गुप्तशब्द', 'शब्दकूट', 'సంకేతపదము', 'හස්පදය', '密码', '密碼', '口令', ] def check_password_prompt(self, b_output): ''' checks if the expected password prompt exists in b_output ''' prompts = self.get_option('prompt_l10n') or self.SU_PROMPT_LOCALIZATIONS b_password_string = b"|".join((br'(\w+\'s )?' + to_bytes(p)) for p in prompts) # Colon or unicode fullwidth colon b_password_string = b_password_string + to_bytes(u' ?(:|:) ?') b_su_prompt_localizations_re = re.compile(b_password_string, flags=re.IGNORECASE) return bool(b_su_prompt_localizations_re.match(b_output)) def build_become_command(self, cmd, shell): super(BecomeModule, self).build_become_command(cmd, shell) # Prompt handling for ``su`` is more complicated, this # is used to satisfy the connection plugin self.prompt = True if not cmd: return cmd exe = self.get_option('become_exe') or self.name flags = self.get_option('become_flags') or '' user = self.get_option('become_user') or '' success_cmd = self._build_success_command(cmd, shell) return "%s %s %s -c %s" % (exe, flags, user, shlex.quote(success_cmd))
nitzmahone/ansible
lib/ansible/plugins/become/su.py
Python
gpl-3.0
5,169
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ce_interface version_added: "2.4" short_description: Manages physical attributes of interfaces on HUAWEI CloudEngine switches. description: - Manages physical attributes of interfaces on HUAWEI CloudEngine switches. author: QijunPan (@QijunPan) notes: - This module is also used to create logical interfaces such as vlanif and loopbacks. - This module requires the netconf system service be enabled on the remote device being managed. - Recommended connection is C(netconf). - This module also works with C(local) connections for legacy playbooks. options: interface: description: - Full name of interface, i.e. 40GE1/0/10, Tunnel1. interface_type: description: - Interface type to be configured from the device. choices: ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'vlanif', 'loopback', 'meth', 'eth-trunk', 'nve', 'tunnel', 'ethernet', 'fcoe-port', 'fabric-port', 'stack-port', 'null'] admin_state: description: - Specifies the interface management status. The value is an enumerated type. up, An interface is in the administrative Up state. down, An interface is in the administrative Down state. choices: ['up', 'down'] description: description: - Specifies an interface description. The value is a string of 1 to 242 case-sensitive characters, spaces supported but question marks (?) not supported. mode: description: - Manage Layer 2 or Layer 3 state of the interface. choices: ['layer2', 'layer3'] l2sub: description: - Specifies whether the interface is a Layer 2 sub-interface. type: bool default: 'no' state: description: - Specify desired state of the resource. default: present choices: ['present', 'absent', 'default'] ''' EXAMPLES = ''' - name: interface module test hosts: cloudengine connection: local gather_facts: no vars: cli: host: "{{ inventory_hostname }}" port: "{{ ansible_ssh_port }}" username: "{{ username }}" password: "{{ password }}" transport: cli tasks: - name: Ensure an interface is a Layer 3 port and that it has the proper description ce_interface: interface: 10GE1/0/22 description: 'Configured by Ansible' mode: layer3 provider: '{{ cli }}' - name: Admin down an interface ce_interface: interface: 10GE1/0/22 admin_state: down provider: '{{ cli }}' - name: Remove all tunnel interfaces ce_interface: interface_type: tunnel state: absent provider: '{{ cli }}' - name: Remove all logical interfaces ce_interface: interface_type: '{{ item }}' state: absent provider: '{{ cli }}' with_items: - loopback - eth-trunk - nve - name: Admin up all 10GE interfaces ce_interface: interface_type: 10GE admin_state: up provider: '{{ cli }}' ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"interface": "10GE1/0/10", "admin_state": "down"} existing: description: k/v pairs of existing switchport returned: always type: dict sample: {"admin_state": "up", "description": "None", "interface": "10GE1/0/10", "mode": "layer2"} end_state: description: k/v pairs of switchport after module execution returned: always type: dict sample: {"admin_state": "down", "description": "None", "interface": "10GE1/0/10", "mode": "layer2"} updates: description: command list sent to the device returned: always type: list sample: ["interface 10GE1/0/10", "shutdown"] changed: description: check to see if a change was made on the device returned: always type: bool sample: true ''' import re from xml.etree import ElementTree from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.cloudengine.ce import get_nc_config, set_nc_config, ce_argument_spec CE_NC_GET_INTFS = """ <filter type="subtree"> <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface> <ifName></ifName> <ifPhyType>%s</ifPhyType> <ifNumber></ifNumber> <ifDescr></ifDescr> <ifAdminStatus></ifAdminStatus> <isL2SwitchPort></isL2SwitchPort> <ifMtu></ifMtu> </interface> </interfaces> </ifm> </filter> """ CE_NC_GET_INTF = """ <filter type="subtree"> <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface> <ifName>%s</ifName> <ifPhyType></ifPhyType> <ifNumber></ifNumber> <ifDescr></ifDescr> <ifAdminStatus></ifAdminStatus> <isL2SwitchPort></isL2SwitchPort> <ifMtu></ifMtu> </interface> </interfaces> </ifm> </filter> """ CE_NC_XML_CREATE_INTF = """ <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface operation="merge"> <ifName>%s</ifName> <ifDescr>%s</ifDescr> </interface> </interfaces> </ifm> """ CE_NC_XML_CREATE_INTF_L2SUB = """ <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface operation="merge"> <ifName>%s</ifName> <ifDescr>%s</ifDescr> <l2SubIfFlag>true</l2SubIfFlag> </interface> </interfaces> </ifm> """ CE_NC_XML_DELETE_INTF = """ <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface operation="delete"> <ifName>%s</ifName> </interface> </interfaces> </ifm> """ CE_NC_XML_MERGE_INTF_DES = """ <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface operation="merge"> <ifName>%s</ifName> <ifDescr>%s</ifDescr> </interface> </interfaces> </ifm> """ CE_NC_XML_MERGE_INTF_STATUS = """ <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface operation="merge"> <ifName>%s</ifName> <ifAdminStatus>%s</ifAdminStatus> </interface> </interfaces> </ifm> """ CE_NC_XML_MERGE_INTF_L2ENABLE = """ <ethernet xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <ethernetIfs> <ethernetIf operation="merge"> <ifName>%s</ifName> <l2Enable>%s</l2Enable> </ethernetIf> </ethernetIfs> </ethernet> """ ADMIN_STATE_TYPE = ('ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'vlanif', 'meth', 'eth-trunk', 'vbdif', 'tunnel', 'ethernet', 'stack-port') SWITCH_PORT_TYPE = ('ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'eth-trunk') def get_interface_type(interface): """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF...""" if interface is None: return None iftype = None if interface.upper().startswith('GE'): iftype = 'ge' elif interface.upper().startswith('10GE'): iftype = '10ge' elif interface.upper().startswith('25GE'): iftype = '25ge' elif interface.upper().startswith('4X10GE'): iftype = '4x10ge' elif interface.upper().startswith('40GE'): iftype = '40ge' elif interface.upper().startswith('100GE'): iftype = '100ge' elif interface.upper().startswith('VLANIF'): iftype = 'vlanif' elif interface.upper().startswith('LOOPBACK'): iftype = 'loopback' elif interface.upper().startswith('METH'): iftype = 'meth' elif interface.upper().startswith('ETH-TRUNK'): iftype = 'eth-trunk' elif interface.upper().startswith('VBDIF'): iftype = 'vbdif' elif interface.upper().startswith('NVE'): iftype = 'nve' elif interface.upper().startswith('TUNNEL'): iftype = 'tunnel' elif interface.upper().startswith('ETHERNET'): iftype = 'ethernet' elif interface.upper().startswith('FCOE-PORT'): iftype = 'fcoe-port' elif interface.upper().startswith('FABRIC-PORT'): iftype = 'fabric-port' elif interface.upper().startswith('STACK-PORT'): iftype = 'stack-port' elif interface.upper().startswith('NULL'): iftype = 'null' else: return None return iftype.lower() def is_admin_state_enable(iftype): """admin state disable: loopback nve""" return bool(iftype in ADMIN_STATE_TYPE) def is_portswitch_enalbe(iftype): """"is portswitch? """ return bool(iftype in SWITCH_PORT_TYPE) class Interface(object): """Manages physical attributes of interfaces.""" def __init__(self, argument_spec): self.spec = argument_spec self.module = None self.init_module() # interface info self.interface = self.module.params['interface'] self.interface_type = self.module.params['interface_type'] self.admin_state = self.module.params['admin_state'] self.description = self.module.params['description'] self.mode = self.module.params['mode'] self.l2sub = self.module.params['l2sub'] self.state = self.module.params['state'] # state self.changed = False self.updates_cmd = list() self.results = dict() self.proposed = dict() self.existing = dict() self.end_state = dict() self.intfs_info = dict() # all type interface info self.intf_info = dict() # one interface info self.intf_type = None # loopback tunnel ... def init_module(self): """init_module""" self.module = AnsibleModule( argument_spec=self.spec, supports_check_mode=True) def check_response(self, xml_str, xml_name): """Check if response message is already succeed.""" if "<ok/>" not in xml_str: self.module.fail_json(msg='Error: %s failed.' % xml_name) def get_interfaces_dict(self): """ get interfaces attributes dict.""" intfs_info = dict() conf_str = CE_NC_GET_INTFS % self.interface_type recv_xml = get_nc_config(self.module, conf_str) if "<data/>" in recv_xml: return intfs_info xml_str = recv_xml.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") root = ElementTree.fromstring(xml_str) intfs = root.findall("ifm/interfaces/") if intfs: for intf in intfs: intf_type = intf.find("ifPhyType").text.lower() if intf_type: if not intfs_info.get(intf_type): intfs_info[intf_type] = list() intf_info = dict() for tmp in intf: intf_info[tmp.tag] = tmp.text intfs_info[intf_type].append(intf_info) return intfs_info def get_interface_dict(self, ifname): """ get one interface attributes dict.""" intf_info = dict() conf_str = CE_NC_GET_INTF % ifname recv_xml = get_nc_config(self.module, conf_str) if "<data/>" in recv_xml: return intf_info xml_str = recv_xml.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") root = ElementTree.fromstring(xml_str) intfs = root.findall("ifm/interfaces/interface/") if intfs: for intf in intfs: intf_info[intf.tag] = intf.text return intf_info def create_interface(self, ifname, description, admin_state, mode, l2sub): """Create interface.""" if l2sub: self.updates_cmd.append("interface %s mode l2" % ifname) else: self.updates_cmd.append("interface %s" % ifname) if not description: description = '' else: self.updates_cmd.append("description %s" % description) if l2sub: xmlstr = CE_NC_XML_CREATE_INTF_L2SUB % (ifname, description) else: xmlstr = CE_NC_XML_CREATE_INTF % (ifname, description) if admin_state and is_admin_state_enable(self.intf_type): xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, admin_state) if admin_state == 'up': self.updates_cmd.append("undo shutdown") else: self.updates_cmd.append("shutdown") if mode and is_portswitch_enalbe(self.intf_type): if mode == "layer2": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable') self.updates_cmd.append('portswitch') elif mode == "layer3": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'disable') self.updates_cmd.append('undo portswitch') conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "CREATE_INTF") self.changed = True def delete_interface(self, ifname): """ Delete interface.""" xmlstr = CE_NC_XML_DELETE_INTF % ifname conf_str = '<config> ' + xmlstr + ' </config>' self.updates_cmd.append('undo interface %s' % ifname) recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "DELETE_INTF") self.changed = True def delete_interfaces(self, iftype): """ Delete interfaces with type.""" xmlstr = '' intfs_list = self.intfs_info.get(iftype.lower()) if not intfs_list: return for intf in intfs_list: xmlstr += CE_NC_XML_DELETE_INTF % intf['ifName'] self.updates_cmd.append('undo interface %s' % intf['ifName']) conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "DELETE_INTFS") self.changed = True def merge_interface(self, ifname, description, admin_state, mode): """ Merge interface attributes.""" xmlstr = '' change = False self.updates_cmd.append("interface %s" % ifname) if description and self.intf_info["ifDescr"] != description: xmlstr += CE_NC_XML_MERGE_INTF_DES % (ifname, description) self.updates_cmd.append("description %s" % description) change = True if admin_state and is_admin_state_enable(self.intf_type) \ and self.intf_info["ifAdminStatus"] != admin_state: xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, admin_state) change = True if admin_state == "up": self.updates_cmd.append("undo shutdown") else: self.updates_cmd.append("shutdown") if is_portswitch_enalbe(self.intf_type): if mode == "layer2" and self.intf_info["isL2SwitchPort"] != "true": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable') self.updates_cmd.append("portswitch") change = True elif mode == "layer3" \ and self.intf_info["isL2SwitchPort"] != "false": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'disable') self.updates_cmd.append("undo portswitch") change = True if not change: return conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "MERGE_INTF_ATTR") self.changed = True def merge_interfaces(self, iftype, description, admin_state, mode): """ Merge interface attributes by type.""" xmlstr = '' change = False intfs_list = self.intfs_info.get(iftype.lower()) if not intfs_list: return for intf in intfs_list: if_change = False self.updates_cmd.append("interface %s" % intf['ifName']) if description and intf["ifDescr"] != description: xmlstr += CE_NC_XML_MERGE_INTF_DES % ( intf['ifName'], description) self.updates_cmd.append("description %s" % description) if_change = True if admin_state and is_admin_state_enable(self.intf_type)\ and intf["ifAdminStatus"] != admin_state: xmlstr += CE_NC_XML_MERGE_INTF_STATUS % ( intf['ifName'], admin_state) if_change = True if admin_state == "up": self.updates_cmd.append("undo shutdown") else: self.updates_cmd.append("shutdown") if is_portswitch_enalbe(self.intf_type): if mode == "layer2" \ and intf["isL2SwitchPort"] != "true": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % ( intf['ifName'], 'enable') self.updates_cmd.append("portswitch") if_change = True elif mode == "layer3" \ and intf["isL2SwitchPort"] != "false": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % ( intf['ifName'], 'disable') self.updates_cmd.append("undo portswitch") if_change = True if if_change: change = True else: self.updates_cmd.pop() if not change: return conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "MERGE_INTFS_ATTR") self.changed = True def default_interface(self, ifname): """default_interface""" change = False xmlstr = "" self.updates_cmd.append("interface %s" % ifname) # set description default if self.intf_info["ifDescr"]: xmlstr += CE_NC_XML_MERGE_INTF_DES % (ifname, '') self.updates_cmd.append("undo description") change = True # set admin_status default if is_admin_state_enable(self.intf_type) \ and self.intf_info["ifAdminStatus"] != 'up': xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, 'up') self.updates_cmd.append("undo shutdown") change = True # set portswitch default if is_portswitch_enalbe(self.intf_type) \ and self.intf_info["isL2SwitchPort"] != "true": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable') self.updates_cmd.append("portswitch") change = True if not change: return conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "SET_INTF_DEFAULT") self.changed = True def default_interfaces(self, iftype): """ Set interface config to default by type.""" change = False xmlstr = '' intfs_list = self.intfs_info.get(iftype.lower()) if not intfs_list: return for intf in intfs_list: if_change = False self.updates_cmd.append("interface %s" % intf['ifName']) # set description default if intf['ifDescr']: xmlstr += CE_NC_XML_MERGE_INTF_DES % (intf['ifName'], '') self.updates_cmd.append("undo description") if_change = True # set admin_status default if is_admin_state_enable(self.intf_type) and intf["ifAdminStatus"] != 'up': xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (intf['ifName'], 'up') self.updates_cmd.append("undo shutdown") if_change = True # set portswitch default if is_portswitch_enalbe(self.intf_type) and intf["isL2SwitchPort"] != "true": xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (intf['ifName'], 'enable') self.updates_cmd.append("portswitch") if_change = True if if_change: change = True else: self.updates_cmd.pop() if not change: return conf_str = '<config> ' + xmlstr + ' </config>' recv_xml = set_nc_config(self.module, conf_str) self.check_response(recv_xml, "SET_INTFS_DEFAULT") self.changed = True def check_params(self): """Check all input params""" if not self.interface and not self.interface_type: self.module.fail_json( msg='Error: Interface or interface_type must be set.') if self.interface and self.interface_type: self.module.fail_json( msg='Error: Interface or interface_type' ' can not be set at the same time.') # interface type check if self.interface: self.intf_type = get_interface_type(self.interface) if not self.intf_type: self.module.fail_json( msg='Error: interface name of %s' ' is error.' % self.interface) elif self.interface_type: self.intf_type = get_interface_type(self.interface_type) if not self.intf_type or self.intf_type != self.interface_type.replace(" ", "").lower(): self.module.fail_json( msg='Error: interface type of %s' ' is error.' % self.interface_type) if not self.intf_type: self.module.fail_json( msg='Error: interface or interface type %s is error.') # shutdown check if not is_admin_state_enable(self.intf_type) \ and self.state == "present" and self.admin_state == "down": self.module.fail_json( msg='Error: The %s interface can not' ' be shutdown.' % self.intf_type) # port switch mode check if not is_portswitch_enalbe(self.intf_type)\ and self.mode and self.state == "present": self.module.fail_json( msg='Error: The %s interface can not manage' ' Layer 2 or Layer 3 state.' % self.intf_type) # check description len if self.description: if len(self.description) > 242 \ or len(self.description.replace(' ', '')) < 1: self.module.fail_json( msg='Error: interface description ' 'is not in the range from 1 to 242.') # check l2sub flag if self.l2sub: if not self.interface: self.module.fail_json(msg='Error: L2sub flag can not be set when there no interface set with.') if self.interface.count(".") != 1: self.module.fail_json(msg='Error: Interface name is invalid, it is not sub-interface.') def get_proposed(self): """get_proposed""" self.proposed['state'] = self.state if self.interface: self.proposed["interface"] = self.interface if self.interface_type: self.proposed["interface_type"] = self.interface_type if self.state == 'present': if self.description: self.proposed["description"] = self.description if self.mode: self.proposed["mode"] = self.mode if self.admin_state: self.proposed["admin_state"] = self.admin_state self.proposed["l2sub"] = self.l2sub elif self.state == 'default': if self.description: self.proposed["description"] = "" if is_admin_state_enable(self.intf_type) and self.admin_state: self.proposed["admin_state"] = self.admin_state if is_portswitch_enalbe(self.intf_type) and self.mode: self.proposed["mode"] = self.mode def get_existing(self): """get_existing""" if self.intf_info: self.existing["interface"] = self.intf_info["ifName"] if is_admin_state_enable(self.intf_type): self.existing["admin_state"] = self.intf_info["ifAdminStatus"] self.existing["description"] = self.intf_info["ifDescr"] if is_portswitch_enalbe(self.intf_type): if self.intf_info["isL2SwitchPort"] == "true": self.existing["mode"] = "layer2" else: self.existing["mode"] = "layer3" if self.intfs_info: intfs = self.intfs_info.get(self.intf_type.lower()) for intf in intfs: intf_para = dict() if intf["ifAdminStatus"]: intf_para["admin_state"] = intf["ifAdminStatus"] intf_para["description"] = intf["ifDescr"] if intf["isL2SwitchPort"] == "true": intf_para["mode"] = "layer2" else: intf_para["mode"] = "layer3" self.existing[intf["ifName"]] = intf_para def get_end_state(self): """get_end_state""" if self.interface: end_info = self.get_interface_dict(self.interface) if end_info: self.end_state["interface"] = end_info["ifName"] if is_admin_state_enable(self.intf_type): self.end_state["admin_state"] = end_info["ifAdminStatus"] self.end_state["description"] = end_info["ifDescr"] if is_portswitch_enalbe(self.intf_type): if end_info["isL2SwitchPort"] == "true": self.end_state["mode"] = "layer2" else: self.end_state["mode"] = "layer3" if self.interface_type: end_info = self.get_interfaces_dict() intfs = end_info.get(self.intf_type.lower()) for intf in intfs: intf_para = dict() if intf["ifAdminStatus"]: intf_para["admin_state"] = intf["ifAdminStatus"] intf_para["description"] = intf["ifDescr"] if intf["isL2SwitchPort"] == "true": intf_para["mode"] = "layer2" else: intf_para["mode"] = "layer3" self.end_state[intf["ifName"]] = intf_para def work(self): """worker""" self.check_params() # single interface config if self.interface: self.intf_info = self.get_interface_dict(self.interface) self.get_existing() if self.state == 'present': if not self.intf_info: # create interface self.create_interface(self.interface, self.description, self.admin_state, self.mode, self.l2sub) else: # merge interface if self.description or self.admin_state or self.mode: self.merge_interface(self.interface, self.description, self.admin_state, self.mode) elif self.state == 'absent': if self.intf_info: # delete interface self.delete_interface(self.interface) else: # interface does not exist self.module.fail_json( msg='Error: interface does not exist.') else: # default if not self.intf_info: # error, interface does not exist self.module.fail_json( msg='Error: interface does not exist.') else: self.default_interface(self.interface) # interface type config else: self.intfs_info = self.get_interfaces_dict() self.get_existing() if self.state == 'present': if self.intfs_info.get(self.intf_type.lower()): if self.description or self.admin_state or self.mode: self.merge_interfaces(self.intf_type, self.description, self.admin_state, self.mode) elif self.state == 'absent': # delete all interface of this type if self.intfs_info.get(self.intf_type.lower()): self.delete_interfaces(self.intf_type) else: # set interfaces config to default if self.intfs_info.get(self.intf_type.lower()): self.default_interfaces(self.intf_type) else: self.module.fail_json( msg='Error: no interface in this type.') self.get_proposed() self.get_end_state() self.results['changed'] = self.changed self.results['proposed'] = self.proposed self.results['existing'] = self.existing self.results['end_state'] = self.end_state if self.changed: self.results['updates'] = self.updates_cmd else: self.results['updates'] = list() self.module.exit_json(**self.results) def main(): """main""" argument_spec = dict( interface=dict(required=False, type='str'), admin_state=dict(choices=['up', 'down'], required=False), description=dict(required=False, default=None), mode=dict(choices=['layer2', 'layer3'], required=False), interface_type=dict(required=False), l2sub=dict(required=False, default=False, type='bool'), state=dict(choices=['absent', 'present', 'default'], default='present', required=False), ) argument_spec.update(ce_argument_spec) interface = Interface(argument_spec) interface.work() if __name__ == '__main__': main()
kvar/ansible
lib/ansible/modules/network/cloudengine/ce_interface.py
Python
gpl-3.0
31,784
import json import datetime import HTMLParser import urllib import bleach import jinja2 import pytz from babel import localedata from babel.dates import format_date, format_datetime, format_time from babel.numbers import format_decimal from jingo import env, register from pytz import timezone from soapbox.models import Message from tower import ugettext_lazy as _lazy from tower import ungettext from urlobject import URLObject from django.conf import settings from django.contrib.messages.storage.base import LEVEL_TAGS from django.contrib.staticfiles.storage import staticfiles_storage from django.template import defaultfilters from django.utils.encoding import force_text from django.utils.html import strip_tags from django.utils.timezone import get_default_timezone from .jobs import StaticI18nJob from .exceptions import DateTimeFormatError from .urlresolvers import reverse, split_path htmlparser = HTMLParser.HTMLParser() # Yanking filters from Django. register.filter(strip_tags) register.filter(defaultfilters.timesince) register.filter(defaultfilters.truncatewords) @register.filter def paginator(pager): """Render list of pages.""" return Paginator(pager).render() @register.function def url(viewname, *args, **kwargs): """Helper for Django's ``reverse`` in templates.""" locale = kwargs.pop('locale', None) return reverse(viewname, args=args, kwargs=kwargs, locale=locale) class Paginator(object): def __init__(self, pager): self.pager = pager self.max = 10 self.span = (self.max - 1) / 2 self.page = pager.number self.num_pages = pager.paginator.num_pages self.count = pager.paginator.count pager.page_range = self.range() pager.dotted_upper = self.num_pages not in pager.page_range pager.dotted_lower = 1 not in pager.page_range def range(self): """Return a list of page numbers to show in the paginator.""" page, total, span = self.page, self.num_pages, self.span if total < self.max: lower, upper = 0, total elif page < span + 1: lower, upper = 0, span * 2 elif page > total - span: lower, upper = total - span * 2, total else: lower, upper = page - span, page + span - 1 return range(max(lower + 1, 1), min(total, upper) + 1) def render(self): c = {'pager': self.pager, 'num_pages': self.num_pages, 'count': self.count} t = env.get_template('includes/paginator.html').render(c) return jinja2.Markup(t) @register.filter def timesince(d, now=None): """Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d is None or occurs after now, return ''. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Just one unit is displayed. For example, "2 weeks" and "1 year" are possible outputs, but "2 weeks, 3 days" and "1 year, 5 months" are not. Adapted from django.utils.timesince to have better i18n (not assuming commas as list separators and including "ago" so order of words isn't assumed), show only one time unit, and include seconds. """ if d is None: return u'' chunks = [ (60 * 60 * 24 * 365, lambda n: ungettext('%(number)d year ago', '%(number)d years ago', n)), (60 * 60 * 24 * 30, lambda n: ungettext('%(number)d month ago', '%(number)d months ago', n)), (60 * 60 * 24 * 7, lambda n: ungettext('%(number)d week ago', '%(number)d weeks ago', n)), (60 * 60 * 24, lambda n: ungettext('%(number)d day ago', '%(number)d days ago', n)), (60 * 60, lambda n: ungettext('%(number)d hour ago', '%(number)d hours ago', n)), (60, lambda n: ungettext('%(number)d minute ago', '%(number)d minutes ago', n)), (1, lambda n: ungettext('%(number)d second ago', '%(number)d seconds ago', n))] if not now: if d.tzinfo: now = datetime.datetime.now(get_default_timezone()) else: now = datetime.datetime.now() # Ignore microsecond part of 'd' since we removed it from 'now' delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return u'' for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break return name(count) % {'number': count} @register.filter def yesno(boolean_value): return jinja2.Markup(_lazy(u'Yes') if boolean_value else _lazy(u'No')) @register.filter def entity_decode(str): """Turn HTML entities in a string into unicode.""" return htmlparser.unescape(str) @register.function def inlinei18n(locale): return StaticI18nJob().get(locale) @register.function def page_title(title): return u'%s | MDN' % title @register.filter def level_tag(message): return jinja2.Markup(force_text(LEVEL_TAGS.get(message.level, ''), strings_only=True)) @register.filter def isotime(t): """Date/Time format according to ISO 8601""" if not hasattr(t, 'tzinfo'): return return _append_tz(t).astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def _append_tz(t): tz = pytz.timezone(settings.TIME_ZONE) return tz.localize(t) @register.function def thisyear(): """The current year.""" return jinja2.Markup(datetime.date.today().year) @register.filter def cleank(txt): """Clean and link some user-supplied text.""" return jinja2.Markup(bleach.linkify(bleach.clean(txt))) @register.filter def urlencode(txt): """Url encode a path.""" return urllib.quote_plus(txt.encode('utf8')) @register.filter def jsonencode(data): return jinja2.Markup(json.dumps(data)) @register.function def get_soapbox_messages(url): _, path = split_path(url) return Message.objects.match(path) @register.function def get_webfont_attributes(request): """ Return data attributes based on assumptions about if user has them cached """ if not request: return '' assume_loaded = 'true' if request.META.get('HTTP_PRAGMA') == 'no-cache': assume_loaded = 'false' elif request.META.get('HTTP_CACHE_CONTROL') == 'no-cache': assume_loaded = 'false' elif request.COOKIES.get('ffo', 'false') == 'true': assume_loaded = 'true' else: assume_loaded = 'false' font_names = ['opensanslight', 'opensans'] font_attributes = '' for font_name in font_names: font_attributes += ' data-ffo-' + font_name + '=' + assume_loaded + '' return font_attributes @register.inclusion_tag('core/elements/soapbox_messages.html') def soapbox_messages(soapbox_messages): return {'soapbox_messages': soapbox_messages} @register.function def add_utm(url_, campaign, source='developer.mozilla.org', medium='email'): """Add the utm_* tracking parameters to a URL.""" url_obj = URLObject(url_).add_query_params({ 'utm_campaign': campaign, 'utm_source': source, 'utm_medium': medium}) return str(url_obj) def _babel_locale(locale): """Return the Babel locale code, given a normal one.""" # Babel uses underscore as separator. return locale.replace('-', '_') def _contextual_locale(context): """Return locale from the context, falling back to a default if invalid.""" locale = context['request'].locale if not localedata.exists(locale): locale = settings.LANGUAGE_CODE return locale @register.function @jinja2.contextfunction def datetimeformat(context, value, format='shortdatetime', output='html'): """ Returns date/time formatted using babel's locale settings. Uses the timezone from settings.py """ if not isinstance(value, datetime.datetime): if isinstance(value, datetime.date): # Turn a date into a datetime value = datetime.datetime.combine(value, datetime.datetime.min.time()) else: # Expecting datetime value raise ValueError default_tz = timezone(settings.TIME_ZONE) tzvalue = default_tz.localize(value) user = context['request'].user try: if user.is_authenticated() and user.timezone: user_tz = timezone(user.timezone) tzvalue = user_tz.normalize(tzvalue.astimezone(user_tz)) except AttributeError: pass locale = _babel_locale(_contextual_locale(context)) # If within a day, 24 * 60 * 60 = 86400s if format == 'shortdatetime': # Check if the date is today if value.toordinal() == datetime.date.today().toordinal(): formatted = _lazy(u'Today at %s') % format_time( tzvalue, format='short', locale=locale) else: formatted = format_datetime(tzvalue, format='short', locale=locale) elif format == 'longdatetime': formatted = format_datetime(tzvalue, format='long', locale=locale) elif format == 'date': formatted = format_date(tzvalue, locale=locale) elif format == 'time': formatted = format_time(tzvalue, locale=locale) elif format == 'datetime': formatted = format_datetime(tzvalue, locale=locale) else: # Unknown format raise DateTimeFormatError if output == 'json': return formatted return jinja2.Markup('<time datetime="%s">%s</time>' % (tzvalue.isoformat(), formatted)) @register.function @jinja2.contextfunction def number(context, n): """Return the localized representation of an integer or decimal. For None, print nothing. """ if n is None: return '' return format_decimal(n, locale=_babel_locale(_contextual_locale(context))) @register.function def static(path): return staticfiles_storage.url(path)
robhudson/kuma
kuma/core/helpers.py
Python
mpl-2.0
10,358
from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty from kivy.properties import StringProperty from UIElements.scrollableLabel import ScrollableLabel class ScrollableTextPopup(FloatLayout): ''' A Pop-up Dialog To Display Text If the text does not all fit on the display, the user can scroll it ''' cancel = ObjectProperty(None) text = StringProperty("")
abetusk/dev
projects/maslowcnc/software/GroundControl-master/UIElements/scrollableTextPopup.py
Python
agpl-3.0
494
# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest # test_records = frappe.get_test_records('Appraisal Template') class TestAppraisalTemplate(unittest.TestCase): pass
gangadhar-kadam/verve_test_erp
erpnext/hr/doctype/appraisal_template/test_appraisal_template.py
Python
agpl-3.0
297
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Netease Corporation # 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. """ Tests for availability zones """ from oslo.config import cfg from nova import availability_zones as az from nova import context from nova import db from nova import test CONF = cfg.CONF CONF.import_opt('internal_service_availability_zone', 'nova.availability_zones') CONF.import_opt('default_availability_zone', 'nova.availability_zones') class AvailabilityZoneTestCases(test.TestCase): """Test case for aggregate based availability zone.""" def setUp(self): super(AvailabilityZoneTestCases, self).setUp() self.host = 'me' self.availability_zone = 'nova-test' self.default_az = CONF.default_availability_zone self.default_in_az = CONF.internal_service_availability_zone self.context = context.get_admin_context() self.agg = self._create_az('az_agg', self.availability_zone) def tearDown(self): db.aggregate_delete(self.context, self.agg['id']) super(AvailabilityZoneTestCases, self).tearDown() def _create_az(self, agg_name, az_name): agg_meta = {'name': agg_name} agg = db.aggregate_create(self.context, agg_meta) metadata = {'availability_zone': az_name} db.aggregate_metadata_add(self.context, agg['id'], metadata) return agg def _create_service_with_topic(self, topic, host, disabled=False): values = { 'binary': 'bin', 'host': host, 'topic': topic, 'disabled': disabled, } return db.service_create(self.context, values) def _destroy_service(self, service): return db.service_destroy(self.context, service['id']) def _add_to_aggregate(self, service, aggregate): return db.aggregate_host_add(self.context, aggregate['id'], service['host']) def _delete_from_aggregate(self, service, aggregate): return db.aggregate_host_delete(self.context, self.aggregate['id'], service['host']) def test_set_availability_zone_compute_service(self): """Test for compute service get right availability zone.""" service = self._create_service_with_topic('compute', self.host) services = db.service_get_all(self.context) # The service is not add into aggregate, so confirm it is default # availability zone. new_service = az.set_availability_zones(self.context, services)[0] self.assertEquals(new_service['availability_zone'], self.default_az) # The service is added into aggregate, confirm return the aggregate # availability zone. self._add_to_aggregate(service, self.agg) new_service = az.set_availability_zones(self.context, services)[0] self.assertEquals(new_service['availability_zone'], self.availability_zone) self._destroy_service(service) def test_set_availability_zone_not_compute_service(self): """Test not compute service get right availability zone.""" service = self._create_service_with_topic('network', self.host) services = db.service_get_all(self.context) new_service = az.set_availability_zones(self.context, services)[0] self.assertEquals(new_service['availability_zone'], self.default_in_az) self._destroy_service(service) def test_get_host_availability_zone(self): """Test get right availability zone by given host.""" self.assertEquals(self.default_az, az.get_host_availability_zone(self.context, self.host)) service = self._create_service_with_topic('compute', self.host) self._add_to_aggregate(service, self.agg) self.assertEquals(self.availability_zone, az.get_host_availability_zone(self.context, self.host)) def test_get_availability_zones(self): """Test get_availability_zones.""" # get_availability_zones returns two lists, zones with at least one # enabled services, and zones with no enabled services. # Use the following test data: # # zone host enabled # nova-test host1 Yes # nova-test host2 No # nova-test2 host3 Yes # nova-test3 host4 No # <default> host5 No agg2 = self._create_az('agg-az2', 'nova-test2') agg3 = self._create_az('agg-az3', 'nova-test3') service1 = self._create_service_with_topic('compute', 'host1', disabled=False) service2 = self._create_service_with_topic('compute', 'host2', disabled=True) service3 = self._create_service_with_topic('compute', 'host3', disabled=False) service4 = self._create_service_with_topic('compute', 'host4', disabled=True) service5 = self._create_service_with_topic('compute', 'host5', disabled=True) self._add_to_aggregate(service1, self.agg) self._add_to_aggregate(service2, self.agg) self._add_to_aggregate(service3, agg2) self._add_to_aggregate(service4, agg3) zones, not_zones = az.get_availability_zones(self.context) self.assertEquals(zones, ['nova-test', 'nova-test2']) self.assertEquals(not_zones, ['nova-test3', 'nova'])
zestrada/nova-cs498cc
nova/tests/test_availability_zones.py
Python
apache-2.0
6,307
# -*- coding: utf-8 -*- ############################################################################### # # ProjectCounts # Retrieves a count of all projects sorted by project status. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class ProjectCounts(Choreography): def __init__(self, temboo_session): """ Create a new instance of the ProjectCounts Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(ProjectCounts, self).__init__(temboo_session, '/Library/Basecamp/ProjectCounts') def new_input_set(self): return ProjectCountsInputSet() def _make_result_set(self, result, path): return ProjectCountsResultSet(result, path) def _make_execution(self, session, exec_id, path): return ProjectCountsChoreographyExecution(session, exec_id, path) class ProjectCountsInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the ProjectCounts Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccountName(self, value): """ Set the value of the AccountName input for this Choreo. ((required, string) The Basecamp account name for you or your company. This is the first part of your account URL.) """ super(ProjectCountsInputSet, self)._set_input('AccountName', value) def set_Password(self, value): """ Set the value of the Password input for this Choreo. ((required, password) Your Basecamp password. You can use the value 'X' when specifying an API Key for the Username input.) """ super(ProjectCountsInputSet, self)._set_input('Password', value) def set_Username(self, value): """ Set the value of the Username input for this Choreo. ((required, string) Your Basecamp username or API Key.) """ super(ProjectCountsInputSet, self)._set_input('Username', value) class ProjectCountsResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the ProjectCounts Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Basecamp.) """ return self._output.get('Response', None) class ProjectCountsChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return ProjectCountsResultSet(response, path)
jordanemedlock/psychtruths
temboo/core/Library/Basecamp/ProjectCounts.py
Python
apache-2.0
3,555
"""Offer API to configure the Home Assistant auth provider.""" import voluptuous as vol from homeassistant.auth.providers import homeassistant as auth_ha from homeassistant.components import websocket_api from homeassistant.components.websocket_api import decorators from homeassistant.exceptions import Unauthorized async def async_setup(hass): """Enable the Home Assistant views.""" hass.components.websocket_api.async_register_command(websocket_create) hass.components.websocket_api.async_register_command(websocket_delete) hass.components.websocket_api.async_register_command(websocket_change_password) hass.components.websocket_api.async_register_command( websocket_admin_change_password ) return True @decorators.websocket_command( { vol.Required("type"): "config/auth_provider/homeassistant/create", vol.Required("user_id"): str, vol.Required("username"): str, vol.Required("password"): str, } ) @websocket_api.require_admin @websocket_api.async_response async def websocket_create(hass, connection, msg): """Create credentials and attach to a user.""" provider = auth_ha.async_get_provider(hass) user = await hass.auth.async_get_user(msg["user_id"]) if user is None: connection.send_error(msg["id"], "not_found", "User not found") return if user.system_generated: connection.send_error( msg["id"], "system_generated", "Cannot add credentials to a system generated user.", ) return try: await provider.async_add_auth(msg["username"], msg["password"]) except auth_ha.InvalidUser: connection.send_error(msg["id"], "username_exists", "Username already exists") return credentials = await provider.async_get_or_create_credentials( {"username": msg["username"]} ) await hass.auth.async_link_user(user, credentials) connection.send_result(msg["id"]) @decorators.websocket_command( { vol.Required("type"): "config/auth_provider/homeassistant/delete", vol.Required("username"): str, } ) @websocket_api.require_admin @websocket_api.async_response async def websocket_delete(hass, connection, msg): """Delete username and related credential.""" provider = auth_ha.async_get_provider(hass) credentials = await provider.async_get_or_create_credentials( {"username": msg["username"]} ) # if not new, an existing credential exists. # Removing the credential will also remove the auth. if not credentials.is_new: await hass.auth.async_remove_credentials(credentials) connection.send_result(msg["id"]) return try: await provider.async_remove_auth(msg["username"]) except auth_ha.InvalidUser: connection.send_error( msg["id"], "auth_not_found", "Given username was not found." ) return connection.send_result(msg["id"]) @decorators.websocket_command( { vol.Required("type"): "config/auth_provider/homeassistant/change_password", vol.Required("current_password"): str, vol.Required("new_password"): str, } ) @websocket_api.async_response async def websocket_change_password(hass, connection, msg): """Change current user password.""" user = connection.user if user is None: connection.send_error(msg["id"], "user_not_found", "User not found") return provider = auth_ha.async_get_provider(hass) username = None for credential in user.credentials: if credential.auth_provider_type == provider.type: username = credential.data["username"] break if username is None: connection.send_error( msg["id"], "credentials_not_found", "Credentials not found" ) return try: await provider.async_validate_login(username, msg["current_password"]) except auth_ha.InvalidAuth: connection.send_error(msg["id"], "invalid_password", "Invalid password") return await provider.async_change_password(username, msg["new_password"]) connection.send_result(msg["id"]) @decorators.websocket_command( { vol.Required( "type" ): "config/auth_provider/homeassistant/admin_change_password", vol.Required("user_id"): str, vol.Required("password"): str, } ) @decorators.require_admin @decorators.async_response async def websocket_admin_change_password(hass, connection, msg): """Change password of any user.""" if not connection.user.is_owner: raise Unauthorized(context=connection.context(msg)) user = await hass.auth.async_get_user(msg["user_id"]) if user is None: connection.send_error(msg["id"], "user_not_found", "User not found") return provider = auth_ha.async_get_provider(hass) username = None for credential in user.credentials: if credential.auth_provider_type == provider.type: username = credential.data["username"] break if username is None: connection.send_error( msg["id"], "credentials_not_found", "Credentials not found" ) return try: await provider.async_change_password(username, msg["password"]) connection.send_result(msg["id"]) except auth_ha.InvalidUser: connection.send_error( msg["id"], "credentials_not_found", "Credentials not found" ) return
sdague/home-assistant
homeassistant/components/config/auth_provider_homeassistant.py
Python
apache-2.0
5,545
#!/usr/bin/env python """Load all rdfvalues in this directory to populate the registry. """ # These need to register plugins so, pylint: disable=unused-import from grr.lib.rdfvalues import aff4_rdfvalues from grr.lib.rdfvalues import anomaly from grr.lib.rdfvalues import client from grr.lib.rdfvalues import config_file from grr.lib.rdfvalues import cronjobs from grr.lib.rdfvalues import crypto from grr.lib.rdfvalues import data_server from grr.lib.rdfvalues import data_store from grr.lib.rdfvalues import flows from grr.lib.rdfvalues import foreman from grr.lib.rdfvalues import grr_rdf from grr.lib.rdfvalues import hunts from grr.lib.rdfvalues import nsrl from grr.lib.rdfvalues import paths from grr.lib.rdfvalues import plist from grr.lib.rdfvalues import protodict from grr.lib.rdfvalues import rekall_types from grr.lib.rdfvalues import stats from grr.lib.rdfvalues import structs from grr.lib.rdfvalues import webhistory
darrenbilby/grr
lib/rdfvalues/registry_init.py
Python
apache-2.0
933
# Copyright 2014 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import os import stat import sys from multiprocessing import cpu_count from catkin_tools.runner import run_command from .color import clr # Due to portability issues, it uses only POSIX-compliant shell features. # This means that there is no support for BASH-like arrays, and special # care needs to be taken in order to preserve argument atomicity when # passing along to the `exec` instruction at the end. # # This involves forming a string called `_ARGS` which is composed of # tokens like `"$_Ai"` for i=0..N-1 for N arguments so that with N=3 # arguments, for example, `_ARGS` would look like `"$_A0" "$_A1" "$_A2"`. # The double-quotes are necessary because they define the argument # boundaries when the variables are expanded by calling `eval`. env_file_template = """\ #!/usr/bin/env sh # generated from within catkin_tools/verbs/catkin_build/common.py if [ $# -eq 0 ] ; then /bin/echo "Usage: build_env.sh COMMANDS" /bin/echo "Calling build_env.sh without arguments is not supported anymore." /bin/echo "Instead spawn a subshell and source a setup file manually." exit 1 fi # save original args for later _ARGS= _ARGI=0 for arg in "$@"; do # Define placeholder variable eval "_A$_ARGI=\$arg" # Add placeholder variable to arg list _ARGS="$_ARGS \\"\$_A$_ARGI\\"" # Increment arg index _ARGI=`expr $_ARGI + 1` ####################### ## Uncomment for debug: #_escaped="$(echo "$arg" | sed -e 's@ @ @g')" #echo "$_escaped" #eval "echo '$_ARGI \$_A$_ARGI'" ####################### done ####################### ## Uncomment for debug: #echo "exec args:" #echo "$_ARGS" #for arg in $_ARGS; do eval echo $arg; done #echo "-----------" ##################### # remove all passed in args, resetting $@, $*, $#, $n shift $# # set the args for the sourced scripts set -- $@ "--extend" # source setup.sh with implicit --extend argument for each direct build depend in the workspace {sources} # execute given args eval exec $_ARGS """ def generate_env_file(sources, env_file_path): env_file = env_file_template.format(sources='\n'.join(sources)) with open(env_file_path, 'w') as f: f.write(env_file) # Make this file executable os.chmod(env_file_path, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR) return env_file_path def create_build_space(buildspace, package_name): """Creates a build space, if it does not already exist, in the build space :param buildspace: folder in which packages are built :type buildspace: str :param package_name: name of the package this build space is for :type package_name: str :returns: package specific build directory :rtype: str """ package_build_dir = os.path.join(buildspace, package_name) if not os.path.exists(package_build_dir): os.makedirs(package_build_dir) return package_build_dir def get_build_type(package): """Returns the build type for a given package :param package: package object :type package: :py:class:`catkin_pkg.package.Package` :returns: build type of the package, e.g. 'catkin' or 'cmake' :rtype: str """ export_tags = [e.tagname for e in package.exports] if 'build_type' in export_tags: build_type_tag = [e.content for e in package.exports if e.tagname == 'build_type'][0] else: build_type_tag = 'catkin' return build_type_tag def get_python_install_dir(): """Returns the same value as the CMake variable PYTHON_INSTALL_DIR The PYTHON_INSTALL_DIR variable is normally set from the CMake file: catkin/cmake/python.cmake :returns: Python install directory for the system Python :rtype: str """ python_install_dir = 'lib' if os.name != 'nt': python_version_xdoty = str(sys.version_info[0]) + '.' + str(sys.version_info[1]) python_install_dir = os.path.join(python_install_dir, 'python' + python_version_xdoty) python_use_debian_layout = os.path.exists('/etc/debian_version') python_packages_dir = 'dist-packages' if python_use_debian_layout else 'site-packages' python_install_dir = os.path.join(python_install_dir, python_packages_dir) return python_install_dir
davetcoleman/catkin_tools
catkin_tools/verbs/catkin_build/common.py
Python
apache-2.0
4,816
# Copyright 2012 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api from neutron.api.v2 import attributes from neutron.common import constants as l3_constants from neutron.common import exceptions as n_exc from neutron.common import rpc as n_rpc from neutron.common import utils from neutron.db import model_base from neutron.db import models_v2 from neutron.extensions import external_net from neutron.extensions import l3 from neutron.i18n import _LI from neutron import manager from neutron.openstack.common import log as logging from neutron.openstack.common import uuidutils from neutron.plugins.common import constants LOG = logging.getLogger(__name__) DEVICE_OWNER_ROUTER_INTF = l3_constants.DEVICE_OWNER_ROUTER_INTF DEVICE_OWNER_ROUTER_GW = l3_constants.DEVICE_OWNER_ROUTER_GW DEVICE_OWNER_FLOATINGIP = l3_constants.DEVICE_OWNER_FLOATINGIP EXTERNAL_GW_INFO = l3.EXTERNAL_GW_INFO # Maps API field to DB column # API parameter name and Database column names may differ. # Useful to keep the filtering between API and Database. API_TO_DB_COLUMN_MAP = {'port_id': 'fixed_port_id'} CORE_ROUTER_ATTRS = ('id', 'name', 'tenant_id', 'admin_state_up', 'status') class RouterPort(model_base.BASEV2): router_id = sa.Column( sa.String(36), sa.ForeignKey('routers.id', ondelete="CASCADE"), primary_key=True) port_id = sa.Column( sa.String(36), sa.ForeignKey('ports.id', ondelete="CASCADE"), primary_key=True) # The port_type attribute is redundant as the port table already specifies # it in DEVICE_OWNER.However, this redundancy enables more efficient # queries on router ports, and also prevents potential error-prone # conditions which might originate from users altering the DEVICE_OWNER # property of router ports. port_type = sa.Column(sa.String(255)) port = orm.relationship( models_v2.Port, backref=orm.backref('routerport', uselist=False, cascade="all,delete")) class Router(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a v2 neutron router.""" name = sa.Column(sa.String(255)) status = sa.Column(sa.String(16)) admin_state_up = sa.Column(sa.Boolean) gw_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) gw_port = orm.relationship(models_v2.Port, lazy='joined') attached_ports = orm.relationship( RouterPort, backref='router', lazy='dynamic') class FloatingIP(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a floating IP address. This IP address may or may not be allocated to a tenant, and may or may not be associated with an internal port/ip address/router. """ floating_ip_address = sa.Column(sa.String(64), nullable=False) floating_network_id = sa.Column(sa.String(36), nullable=False) floating_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id'), nullable=False) fixed_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) fixed_ip_address = sa.Column(sa.String(64)) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id')) # Additional attribute for keeping track of the router where the floating # ip was associated in order to be able to ensure consistency even if an # aysnchronous backend is unavailable when the floating IP is disassociated last_known_router_id = sa.Column(sa.String(36)) status = sa.Column(sa.String(16)) router = orm.relationship(Router, backref='floating_ips') class L3_NAT_dbonly_mixin(l3.RouterPluginBase): """Mixin class to add L3/NAT router methods to db_base_plugin_v2.""" router_device_owners = ( DEVICE_OWNER_ROUTER_INTF, DEVICE_OWNER_ROUTER_GW, DEVICE_OWNER_FLOATINGIP ) @property def _core_plugin(self): return manager.NeutronManager.get_plugin() def _get_router(self, context, router_id): try: router = self._get_by_id(context, Router, router_id) except exc.NoResultFound: raise l3.RouterNotFound(router_id=router_id) return router def _make_router_dict(self, router, fields=None, process_extensions=True): res = dict((key, router[key]) for key in CORE_ROUTER_ATTRS) if router['gw_port_id']: ext_gw_info = { 'network_id': router.gw_port['network_id'], 'external_fixed_ips': [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in router.gw_port['fixed_ips']]} else: ext_gw_info = None res.update({ EXTERNAL_GW_INFO: ext_gw_info, 'gw_port_id': router['gw_port_id'], }) # NOTE(salv-orlando): The following assumes this mixin is used in a # class inheriting from CommonDbMixin, which is true for all existing # plugins. if process_extensions: self._apply_dict_extend_functions(l3.ROUTERS, res, router) return self._fields(res, fields) def _create_router_db(self, context, router, tenant_id): """Create the DB object.""" with context.session.begin(subtransactions=True): # pre-generate id so it will be available when # configuring external gw port router_db = Router(id=uuidutils.generate_uuid(), tenant_id=tenant_id, name=router['name'], admin_state_up=router['admin_state_up'], status="ACTIVE") context.session.add(router_db) return router_db def create_router(self, context, router): r = router['router'] gw_info = r.pop(EXTERNAL_GW_INFO, None) tenant_id = self._get_tenant_id_for_create(context, r) with context.session.begin(subtransactions=True): router_db = self._create_router_db(context, r, tenant_id) if gw_info: self._update_router_gw_info(context, router_db['id'], gw_info, router=router_db) return self._make_router_dict(router_db) def _update_router_db(self, context, router_id, data, gw_info): """Update the DB object.""" with context.session.begin(subtransactions=True): router_db = self._get_router(context, router_id) if data: router_db.update(data) return router_db def update_router(self, context, id, router): r = router['router'] gw_info = r.pop(EXTERNAL_GW_INFO, attributes.ATTR_NOT_SPECIFIED) # check whether router needs and can be rescheduled to the proper # l3 agent (associated with given external network); # do check before update in DB as an exception will be raised # in case no proper l3 agent found if gw_info != attributes.ATTR_NOT_SPECIFIED: candidates = self._check_router_needs_rescheduling( context, id, gw_info) # Update the gateway outside of the DB update since it involves L2 # calls that don't make sense to rollback and may cause deadlocks # in a transaction. self._update_router_gw_info(context, id, gw_info) else: candidates = None router_db = self._update_router_db(context, id, r, gw_info) if candidates: l3_plugin = manager.NeutronManager.get_service_plugins().get( constants.L3_ROUTER_NAT) l3_plugin.reschedule_router(context, id, candidates) return self._make_router_dict(router_db) def _check_router_needs_rescheduling(self, context, router_id, gw_info): """Checks whether router's l3 agent can handle the given network When external_network_bridge is set, each L3 agent can be associated with at most one external network. If router's new external gateway is on other network then the router needs to be rescheduled to the proper l3 agent. If external_network_bridge is not set then the agent can support multiple external networks and rescheduling is not needed :return: list of candidate agents if rescheduling needed, None otherwise; raises exception if there is no eligible l3 agent associated with target external network """ # TODO(obondarev): rethink placement of this func as l3 db manager is # not really a proper place for agent scheduling stuff network_id = gw_info.get('network_id') if gw_info else None if not network_id: return nets = self._core_plugin.get_networks( context, {external_net.EXTERNAL: [True]}) # nothing to do if there is only one external network if len(nets) <= 1: return # first get plugin supporting l3 agent scheduling # (either l3 service plugin or core_plugin) l3_plugin = manager.NeutronManager.get_service_plugins().get( constants.L3_ROUTER_NAT) if (not utils.is_extension_supported( l3_plugin, l3_constants.L3_AGENT_SCHEDULER_EXT_ALIAS) or l3_plugin.router_scheduler is None): # that might mean that we are dealing with non-agent-based # implementation of l3 services return cur_agents = l3_plugin.list_l3_agents_hosting_router( context, router_id)['agents'] for agent in cur_agents: ext_net_id = agent['configurations'].get( 'gateway_external_network_id') ext_bridge = agent['configurations'].get( 'external_network_bridge', 'br-ex') if (ext_net_id == network_id or (not ext_net_id and not ext_bridge)): return # otherwise find l3 agent with matching gateway_external_network_id active_agents = l3_plugin.get_l3_agents(context, active=True) router = { 'id': router_id, 'external_gateway_info': {'network_id': network_id} } candidates = l3_plugin.get_l3_agent_candidates(context, router, active_agents) if not candidates: msg = (_('No eligible l3 agent associated with external network ' '%s found') % network_id) raise n_exc.BadRequest(resource='router', msg=msg) return candidates def _create_router_gw_port(self, context, router, network_id): # Port has no 'tenant-id', as it is hidden from user gw_port = self._core_plugin.create_port(context.elevated(), { 'port': {'tenant_id': '', # intentionally not set 'network_id': network_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'device_id': router['id'], 'device_owner': DEVICE_OWNER_ROUTER_GW, 'admin_state_up': True, 'name': ''}}) if not gw_port['fixed_ips']: self._core_plugin.delete_port(context.elevated(), gw_port['id'], l3_port_check=False) msg = (_('No IPs available for external network %s') % network_id) raise n_exc.BadRequest(resource='router', msg=msg) with context.session.begin(subtransactions=True): router.gw_port = self._core_plugin._get_port(context.elevated(), gw_port['id']) router_port = RouterPort( router_id=router.id, port_id=gw_port['id'], port_type=DEVICE_OWNER_ROUTER_GW ) context.session.add(router) context.session.add(router_port) def _validate_gw_info(self, context, gw_port, info): network_id = info['network_id'] if info else None if network_id: network_db = self._core_plugin._get_network(context, network_id) if not network_db.external: msg = _("Network %s is not an external network") % network_id raise n_exc.BadRequest(resource='router', msg=msg) return network_id def _delete_current_gw_port(self, context, router_id, router, new_network): """Delete gw port, if it is attached to an old network.""" is_gw_port_attached_to_existing_network = ( router.gw_port and router.gw_port['network_id'] != new_network) admin_ctx = context.elevated() if is_gw_port_attached_to_existing_network: if self.get_floatingips_count( admin_ctx, {'router_id': [router_id]}): raise l3.RouterExternalGatewayInUseByFloatingIp( router_id=router_id, net_id=router.gw_port['network_id']) with context.session.begin(subtransactions=True): gw_port = router.gw_port router.gw_port = None context.session.add(router) context.session.expire(gw_port) vpnservice = manager.NeutronManager.get_service_plugins().get( constants.VPN) if vpnservice: vpnservice.check_router_in_use(context, router_id) self._core_plugin.delete_port( admin_ctx, gw_port['id'], l3_port_check=False) def _create_gw_port(self, context, router_id, router, new_network): new_valid_gw_port_attachment = ( new_network and (not router.gw_port or router.gw_port['network_id'] != new_network)) if new_valid_gw_port_attachment: subnets = self._core_plugin._get_subnets_by_network(context, new_network) for subnet in subnets: self._check_for_dup_router_subnet(context, router, new_network, subnet['id'], subnet['cidr']) self._create_router_gw_port(context, router, new_network) def _update_router_gw_info(self, context, router_id, info, router=None): # TODO(salvatore-orlando): guarantee atomic behavior also across # operations that span beyond the model classes handled by this # class (e.g.: delete_port) router = router or self._get_router(context, router_id) gw_port = router.gw_port network_id = self._validate_gw_info(context, gw_port, info) self._delete_current_gw_port(context, router_id, router, network_id) self._create_gw_port(context, router_id, router, network_id) def _ensure_router_not_in_use(self, context, router_id): admin_ctx = context.elevated() router = self._get_router(context, router_id) if self.get_floatingips_count( admin_ctx, filters={'router_id': [router_id]}): raise l3.RouterInUse(router_id=router_id) device_owner = self._get_device_owner(context, router) if any(rp.port_type == device_owner for rp in router.attached_ports.all()): raise l3.RouterInUse(router_id=router_id) return router def delete_router(self, context, id): with context.session.begin(subtransactions=True): router = self._ensure_router_not_in_use(context, id) #TODO(nati) Refactor here when we have router insertion model vpnservice = manager.NeutronManager.get_service_plugins().get( constants.VPN) if vpnservice: vpnservice.check_router_in_use(context, id) router_ports = router.attached_ports.all() # Set the router's gw_port to None to avoid a constraint violation. router.gw_port = None for rp in router_ports: self._core_plugin._delete_port(context.elevated(), rp.port.id) context.session.delete(router) def get_router(self, context, id, fields=None): router = self._get_router(context, id) return self._make_router_dict(router, fields) def get_routers(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'router', limit, marker) return self._get_collection(context, Router, self._make_router_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def get_routers_count(self, context, filters=None): return self._get_collection_count(context, Router, filters=filters) def _check_for_dup_router_subnet(self, context, router, network_id, subnet_id, subnet_cidr): try: # It's possible these ports are on the same network, but # different subnets. new_ipnet = netaddr.IPNetwork(subnet_cidr) for p in (rp.port for rp in router.attached_ports): for ip in p['fixed_ips']: if ip['subnet_id'] == subnet_id: msg = (_("Router already has a port on subnet %s") % subnet_id) raise n_exc.BadRequest(resource='router', msg=msg) sub_id = ip['subnet_id'] cidr = self._core_plugin._get_subnet(context.elevated(), sub_id)['cidr'] ipnet = netaddr.IPNetwork(cidr) match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr]) match2 = netaddr.all_matching_cidrs(ipnet, [subnet_cidr]) if match1 or match2: data = {'subnet_cidr': subnet_cidr, 'subnet_id': subnet_id, 'cidr': cidr, 'sub_id': sub_id} msg = (_("Cidr %(subnet_cidr)s of subnet " "%(subnet_id)s overlaps with cidr %(cidr)s " "of subnet %(sub_id)s") % data) raise n_exc.BadRequest(resource='router', msg=msg) except exc.NoResultFound: pass def _get_device_owner(self, context, router=None): """Get device_owner for the specified router.""" # NOTE(armando-migliaccio): in the base case this is invariant return DEVICE_OWNER_ROUTER_INTF def _validate_interface_info(self, interface_info): port_id_specified = interface_info and 'port_id' in interface_info subnet_id_specified = interface_info and 'subnet_id' in interface_info if not (port_id_specified or subnet_id_specified): msg = _("Either subnet_id or port_id must be specified") raise n_exc.BadRequest(resource='router', msg=msg) if port_id_specified and subnet_id_specified: msg = _("Cannot specify both subnet-id and port-id") raise n_exc.BadRequest(resource='router', msg=msg) return port_id_specified, subnet_id_specified def _add_interface_by_port(self, context, router, port_id, owner): with context.session.begin(subtransactions=True): port = self._core_plugin._get_port(context, port_id) if port['device_id']: raise n_exc.PortInUse(net_id=port['network_id'], port_id=port['id'], device_id=port['device_id']) fixed_ips = [ip for ip in port['fixed_ips']] if len(fixed_ips) != 1: msg = _('Router port must have exactly one fixed IP') raise n_exc.BadRequest(resource='router', msg=msg) subnet_id = fixed_ips[0]['subnet_id'] subnet = self._core_plugin._get_subnet(context, subnet_id) self._check_for_dup_router_subnet(context, router, port['network_id'], subnet['id'], subnet['cidr']) port.update({'device_id': router.id, 'device_owner': owner}) return port def _add_interface_by_subnet(self, context, router, subnet_id, owner): subnet = self._core_plugin._get_subnet(context, subnet_id) if not subnet['gateway_ip']: msg = _('Subnet for router interface must have a gateway IP') raise n_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router, subnet['network_id'], subnet_id, subnet['cidr']) fixed_ip = {'ip_address': subnet['gateway_ip'], 'subnet_id': subnet['id']} return self._core_plugin.create_port(context, { 'port': {'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'fixed_ips': [fixed_ip], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': router.id, 'device_owner': owner, 'name': ''}}) @staticmethod def _make_router_interface_info( router_id, tenant_id, port_id, subnet_id): return { 'id': router_id, 'tenant_id': tenant_id, 'port_id': port_id, 'subnet_id': subnet_id } def add_router_interface(self, context, router_id, interface_info): router = self._get_router(context, router_id) add_by_port, add_by_sub = self._validate_interface_info(interface_info) device_owner = self._get_device_owner(context, router_id) if add_by_port: port = self._add_interface_by_port( context, router, interface_info['port_id'], device_owner) elif add_by_sub: port = self._add_interface_by_subnet( context, router, interface_info['subnet_id'], device_owner) with context.session.begin(subtransactions=True): router_port = RouterPort( port_id=port['id'], router_id=router.id, port_type=device_owner ) context.session.add(router_port) return self._make_router_interface_info( router.id, port['tenant_id'], port['id'], port['fixed_ips'][0]['subnet_id']) def _confirm_router_interface_not_in_use(self, context, router_id, subnet_id): subnet_db = self._core_plugin._get_subnet(context, subnet_id) subnet_cidr = netaddr.IPNetwork(subnet_db['cidr']) fip_qry = context.session.query(FloatingIP) vpnservice = manager.NeutronManager.get_service_plugins().get( constants.VPN) if vpnservice: vpnservice.check_subnet_in_use(context, subnet_id) for fip_db in fip_qry.filter_by(router_id=router_id): if netaddr.IPAddress(fip_db['fixed_ip_address']) in subnet_cidr: raise l3.RouterInterfaceInUseByFloatingIP( router_id=router_id, subnet_id=subnet_id) def _remove_interface_by_port(self, context, router_id, port_id, subnet_id, owner): qry = context.session.query(RouterPort) qry = qry.filter_by( port_id=port_id, router_id=router_id, port_type=owner ) try: port_db = qry.one().port except exc.NoResultFound: raise l3.RouterInterfaceNotFound(router_id=router_id, port_id=port_id) port_subnet_id = port_db['fixed_ips'][0]['subnet_id'] if subnet_id and port_subnet_id != subnet_id: raise n_exc.SubnetMismatchForPort( port_id=port_id, subnet_id=subnet_id) subnet = self._core_plugin._get_subnet(context, port_subnet_id) self._confirm_router_interface_not_in_use( context, router_id, port_subnet_id) self._core_plugin.delete_port(context, port_db['id'], l3_port_check=False) return (port_db, subnet) def _remove_interface_by_subnet(self, context, router_id, subnet_id, owner): self._confirm_router_interface_not_in_use( context, router_id, subnet_id) subnet = self._core_plugin._get_subnet(context, subnet_id) try: rport_qry = context.session.query(models_v2.Port).join(RouterPort) ports = rport_qry.filter( RouterPort.router_id == router_id, RouterPort.port_type == owner, models_v2.Port.network_id == subnet['network_id'] ) for p in ports: if p['fixed_ips'][0]['subnet_id'] == subnet_id: self._core_plugin.delete_port(context, p['id'], l3_port_check=False) return (p, subnet) except exc.NoResultFound: pass raise l3.RouterInterfaceNotFoundForSubnet(router_id=router_id, subnet_id=subnet_id) def remove_router_interface(self, context, router_id, interface_info): if not interface_info: msg = _("Either subnet_id or port_id must be specified") raise n_exc.BadRequest(resource='router', msg=msg) port_id = interface_info.get('port_id') subnet_id = interface_info.get('subnet_id') device_owner = self._get_device_owner(context, router_id) if port_id: port, subnet = self._remove_interface_by_port(context, router_id, port_id, subnet_id, device_owner) elif subnet_id: port, subnet = self._remove_interface_by_subnet( context, router_id, subnet_id, device_owner) return self._make_router_interface_info(router_id, port['tenant_id'], port['id'], subnet['id']) def _get_floatingip(self, context, id): try: floatingip = self._get_by_id(context, FloatingIP, id) except exc.NoResultFound: raise l3.FloatingIPNotFound(floatingip_id=id) return floatingip def _make_floatingip_dict(self, floatingip, fields=None): res = {'id': floatingip['id'], 'tenant_id': floatingip['tenant_id'], 'floating_ip_address': floatingip['floating_ip_address'], 'floating_network_id': floatingip['floating_network_id'], 'router_id': floatingip['router_id'], 'port_id': floatingip['fixed_port_id'], 'fixed_ip_address': floatingip['fixed_ip_address'], 'status': floatingip['status']} return self._fields(res, fields) def _get_interface_ports_for_network(self, context, network_id): router_intf_qry = context.session.query(RouterPort) router_intf_qry = router_intf_qry.join(models_v2.Port) return router_intf_qry.filter( models_v2.Port.network_id == network_id, RouterPort.port_type == DEVICE_OWNER_ROUTER_INTF ) def _get_router_for_floatingip(self, context, internal_port, internal_subnet_id, external_network_id): subnet_db = self._core_plugin._get_subnet(context, internal_subnet_id) if not subnet_db['gateway_ip']: msg = (_('Cannot add floating IP to port on subnet %s ' 'which has no gateway_ip') % internal_subnet_id) raise n_exc.BadRequest(resource='floatingip', msg=msg) router_intf_ports = self._get_interface_ports_for_network( context, internal_port['network_id']) # This joins on port_id so is not a cross-join routerport_qry = router_intf_ports.join(models_v2.IPAllocation) routerport_qry = routerport_qry.filter( models_v2.IPAllocation.subnet_id == internal_subnet_id ) router_port = routerport_qry.first() if router_port and router_port.router.gw_port: return router_port.router.id raise l3.ExternalGatewayForFloatingIPNotFound( subnet_id=internal_subnet_id, external_network_id=external_network_id, port_id=internal_port['id']) def _internal_fip_assoc_data(self, context, fip): """Retrieve internal port data for floating IP. Retrieve information concerning the internal port where the floating IP should be associated to. """ internal_port = self._core_plugin._get_port(context, fip['port_id']) if not internal_port['tenant_id'] == fip['tenant_id']: port_id = fip['port_id'] if 'id' in fip: floatingip_id = fip['id'] data = {'port_id': port_id, 'floatingip_id': floatingip_id} msg = (_('Port %(port_id)s is associated with a different ' 'tenant than Floating IP %(floatingip_id)s and ' 'therefore cannot be bound.') % data) else: msg = (_('Cannot create floating IP and bind it to ' 'Port %s, since that port is owned by a ' 'different tenant.') % port_id) raise n_exc.BadRequest(resource='floatingip', msg=msg) internal_subnet_id = None if 'fixed_ip_address' in fip and fip['fixed_ip_address']: internal_ip_address = fip['fixed_ip_address'] for ip in internal_port['fixed_ips']: if ip['ip_address'] == internal_ip_address: internal_subnet_id = ip['subnet_id'] if not internal_subnet_id: msg = (_('Port %(id)s does not have fixed ip %(address)s') % {'id': internal_port['id'], 'address': internal_ip_address}) raise n_exc.BadRequest(resource='floatingip', msg=msg) else: ips = [ip['ip_address'] for ip in internal_port['fixed_ips']] if not ips: msg = (_('Cannot add floating IP to port %s that has' 'no fixed IP addresses') % internal_port['id']) raise n_exc.BadRequest(resource='floatingip', msg=msg) if len(ips) > 1: msg = (_('Port %s has multiple fixed IPs. Must provide' ' a specific IP when assigning a floating IP') % internal_port['id']) raise n_exc.BadRequest(resource='floatingip', msg=msg) internal_ip_address = internal_port['fixed_ips'][0]['ip_address'] internal_subnet_id = internal_port['fixed_ips'][0]['subnet_id'] return internal_port, internal_subnet_id, internal_ip_address def get_assoc_data(self, context, fip, floating_network_id): """Determine/extract data associated with the internal port. When a floating IP is associated with an internal port, we need to extract/determine some data associated with the internal port, including the internal_ip_address, and router_id. The confirmation of the internal port whether owned by the tenant who owns the floating IP will be confirmed by _get_router_for_floatingip. """ (internal_port, internal_subnet_id, internal_ip_address) = self._internal_fip_assoc_data(context, fip) router_id = self._get_router_for_floatingip(context, internal_port, internal_subnet_id, floating_network_id) return (fip['port_id'], internal_ip_address, router_id) def _check_and_get_fip_assoc(self, context, fip, floatingip_db): port_id = internal_ip_address = router_id = None if (('fixed_ip_address' in fip and fip['fixed_ip_address']) and not ('port_id' in fip and fip['port_id'])): msg = _("fixed_ip_address cannot be specified without a port_id") raise n_exc.BadRequest(resource='floatingip', msg=msg) if 'port_id' in fip and fip['port_id']: port_id, internal_ip_address, router_id = self.get_assoc_data( context, fip, floatingip_db['floating_network_id']) fip_qry = context.session.query(FloatingIP) try: fip_qry.filter_by( fixed_port_id=fip['port_id'], floating_network_id=floatingip_db['floating_network_id'], fixed_ip_address=internal_ip_address).one() raise l3.FloatingIPPortAlreadyAssociated( port_id=fip['port_id'], fip_id=floatingip_db['id'], floating_ip_address=floatingip_db['floating_ip_address'], fixed_ip=internal_ip_address, net_id=floatingip_db['floating_network_id']) except exc.NoResultFound: pass return port_id, internal_ip_address, router_id def _update_fip_assoc(self, context, fip, floatingip_db, external_port): previous_router_id = floatingip_db.router_id port_id, internal_ip_address, router_id = ( self._check_and_get_fip_assoc(context, fip, floatingip_db)) floatingip_db.update({'fixed_ip_address': internal_ip_address, 'fixed_port_id': port_id, 'router_id': router_id, 'last_known_router_id': previous_router_id}) def create_floatingip(self, context, floatingip, initial_status=l3_constants.FLOATINGIP_STATUS_ACTIVE): fip = floatingip['floatingip'] tenant_id = self._get_tenant_id_for_create(context, fip) fip_id = uuidutils.generate_uuid() f_net_id = fip['floating_network_id'] if not self._core_plugin._network_is_external(context, f_net_id): msg = _("Network %s is not a valid external network") % f_net_id raise n_exc.BadRequest(resource='floatingip', msg=msg) with context.session.begin(subtransactions=True): # This external port is never exposed to the tenant. # it is used purely for internal system and admin use when # managing floating IPs. external_port = self._core_plugin.create_port(context.elevated(), { 'port': {'tenant_id': '', # tenant intentionally not set 'network_id': f_net_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': fip_id, 'device_owner': DEVICE_OWNER_FLOATINGIP, 'name': ''}}) # Ensure IP addresses are allocated on external port if not external_port['fixed_ips']: raise n_exc.ExternalIpAddressExhausted(net_id=f_net_id) floating_fixed_ip = external_port['fixed_ips'][0] floating_ip_address = floating_fixed_ip['ip_address'] floatingip_db = FloatingIP( id=fip_id, tenant_id=tenant_id, status=initial_status, floating_network_id=fip['floating_network_id'], floating_ip_address=floating_ip_address, floating_port_id=external_port['id']) fip['tenant_id'] = tenant_id # Update association with internal port # and define external IP address self._update_fip_assoc(context, fip, floatingip_db, external_port) context.session.add(floatingip_db) return self._make_floatingip_dict(floatingip_db) def _update_floatingip(self, context, id, floatingip): fip = floatingip['floatingip'] with context.session.begin(subtransactions=True): floatingip_db = self._get_floatingip(context, id) old_floatingip = self._make_floatingip_dict(floatingip_db) fip['tenant_id'] = floatingip_db['tenant_id'] fip['id'] = id fip_port_id = floatingip_db['floating_port_id'] self._update_fip_assoc(context, fip, floatingip_db, self._core_plugin.get_port( context.elevated(), fip_port_id)) return old_floatingip, self._make_floatingip_dict(floatingip_db) def _floatingips_to_router_ids(self, floatingips): return list(set([floatingip['router_id'] for floatingip in floatingips if floatingip['router_id']])) def update_floatingip(self, context, id, floatingip): _old_floatingip, floatingip = self._update_floatingip( context, id, floatingip) return floatingip def update_floatingip_status(self, context, floatingip_id, status): """Update operational status for floating IP in neutron DB.""" fip_query = self._model_query(context, FloatingIP).filter( FloatingIP.id == floatingip_id) fip_query.update({'status': status}, synchronize_session=False) def _delete_floatingip(self, context, id): floatingip = self._get_floatingip(context, id) router_id = floatingip['router_id'] with context.session.begin(subtransactions=True): context.session.delete(floatingip) self._core_plugin.delete_port(context.elevated(), floatingip['floating_port_id'], l3_port_check=False) return router_id def delete_floatingip(self, context, id): self._delete_floatingip(context, id) def get_floatingip(self, context, id, fields=None): floatingip = self._get_floatingip(context, id) return self._make_floatingip_dict(floatingip, fields) def get_floatingips(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'floatingip', limit, marker) if filters is not None: for key, val in API_TO_DB_COLUMN_MAP.iteritems(): if key in filters: filters[val] = filters.pop(key) return self._get_collection(context, FloatingIP, self._make_floatingip_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def delete_disassociated_floatingips(self, context, network_id): query = self._model_query(context, FloatingIP) query = query.filter_by(floating_network_id=network_id, fixed_port_id=None, router_id=None) for fip in query: self.delete_floatingip(context, fip.id) def get_floatingips_count(self, context, filters=None): return self._get_collection_count(context, FloatingIP, filters=filters) def prevent_l3_port_deletion(self, context, port_id): """Checks to make sure a port is allowed to be deleted. Raises an exception if this is not the case. This should be called by any plugin when the API requests the deletion of a port, since some ports for L3 are not intended to be deleted directly via a DELETE to /ports, but rather via other API calls that perform the proper deletion checks. """ port_db = self._core_plugin._get_port(context, port_id) if port_db['device_owner'] in self.router_device_owners: # Raise port in use only if the port has IP addresses # Otherwise it's a stale port that can be removed fixed_ips = port_db['fixed_ips'] if fixed_ips: raise l3.L3PortInUse(port_id=port_id, device_owner=port_db['device_owner']) else: LOG.debug("Port %(port_id)s has owner %(port_owner)s, but " "no IP address, so it can be deleted", {'port_id': port_db['id'], 'port_owner': port_db['device_owner']}) def disassociate_floatingips(self, context, port_id): """Disassociate all floating IPs linked to specific port. @param port_id: ID of the port to disassociate floating IPs. @param do_notify: whether we should notify routers right away. @return: set of router-ids that require notification updates if do_notify is False, otherwise None. """ router_ids = set() with context.session.begin(subtransactions=True): fip_qry = context.session.query(FloatingIP) floating_ips = fip_qry.filter_by(fixed_port_id=port_id) for floating_ip in floating_ips: router_ids.add(floating_ip['router_id']) floating_ip.update({'fixed_port_id': None, 'fixed_ip_address': None, 'router_id': None}) return router_ids def _build_routers_list(self, context, routers, gw_ports): for router in routers: gw_port_id = router['gw_port_id'] # Collect gw ports only if available if gw_port_id and gw_ports.get(gw_port_id): router['gw_port'] = gw_ports[gw_port_id] return routers def _get_sync_routers(self, context, router_ids=None, active=None): """Query routers and their gw ports for l3 agent. Query routers with the router_ids. The gateway ports, if any, will be queried too. l3 agent has an option to deal with only one router id. In addition, when we need to notify the agent the data about only one router (when modification of router, its interfaces, gw_port and floatingips), we will have router_ids. @param router_ids: the list of router ids which we want to query. if it is None, all of routers will be queried. @return: a list of dicted routers with dicted gw_port populated if any """ filters = {'id': router_ids} if router_ids else {} if active is not None: filters['admin_state_up'] = [active] router_dicts = self.get_routers(context, filters=filters) gw_port_ids = [] if not router_dicts: return [] for router_dict in router_dicts: gw_port_id = router_dict['gw_port_id'] if gw_port_id: gw_port_ids.append(gw_port_id) gw_ports = [] if gw_port_ids: gw_ports = dict((gw_port['id'], gw_port) for gw_port in self.get_sync_gw_ports(context, gw_port_ids)) # NOTE(armando-migliaccio): between get_routers and get_sync_gw_ports # gw ports may get deleted, which means that router_dicts may contain # ports that gw_ports does not; we should rebuild router_dicts, but # letting the callee check for missing gw_ports sounds like a good # defensive approach regardless return self._build_routers_list(context, router_dicts, gw_ports) def _get_sync_floating_ips(self, context, router_ids): """Query floating_ips that relate to list of router_ids.""" if not router_ids: return [] return self.get_floatingips(context, {'router_id': router_ids}) def get_sync_gw_ports(self, context, gw_port_ids): if not gw_port_ids: return [] filters = {'id': gw_port_ids} gw_ports = self._core_plugin.get_ports(context, filters) if gw_ports: self._populate_subnet_for_ports(context, gw_ports) return gw_ports def get_sync_interfaces(self, context, router_ids, device_owners=None): """Query router interfaces that relate to list of router_ids.""" device_owners = device_owners or [DEVICE_OWNER_ROUTER_INTF] if not router_ids: return [] qry = context.session.query(RouterPort) qry = qry.filter( Router.id.in_(router_ids), RouterPort.port_type.in_(device_owners) ) # TODO(markmcclain): This is suboptimal but was left to reduce # changeset size since it is late in cycle ports = [rp.port.id for rp in qry] interfaces = self._core_plugin.get_ports(context, {'id': ports}) if interfaces: self._populate_subnet_for_ports(context, interfaces) return interfaces def _populate_subnet_for_ports(self, context, ports): """Populate ports with subnet. These ports already have fixed_ips populated. """ if not ports: return def each_port_with_ip(): for port in ports: fixed_ips = port.get('fixed_ips', []) if len(fixed_ips) > 1: LOG.info(_LI("Ignoring multiple IPs on router port %s"), port['id']) continue elif not fixed_ips: # Skip ports without IPs, which can occur if a subnet # attached to a router is deleted LOG.info(_LI("Skipping port %s as no IP is configure on " "it"), port['id']) continue yield (port, fixed_ips[0]) network_ids = set(p['network_id'] for p, _ in each_port_with_ip()) filters = {'network_id': [id for id in network_ids]} fields = ['id', 'cidr', 'gateway_ip', 'network_id', 'ipv6_ra_mode'] subnets_by_network = dict((id, []) for id in network_ids) for subnet in self._core_plugin.get_subnets(context, filters, fields): subnets_by_network[subnet['network_id']].append(subnet) for port, fixed_ip in each_port_with_ip(): port['extra_subnets'] = [] for subnet in subnets_by_network[port['network_id']]: subnet_info = {'id': subnet['id'], 'cidr': subnet['cidr'], 'gateway_ip': subnet['gateway_ip'], 'ipv6_ra_mode': subnet['ipv6_ra_mode']} if subnet['id'] == fixed_ip['subnet_id']: port['subnet'] = subnet_info else: port['extra_subnets'].append(subnet_info) def _process_floating_ips(self, context, routers_dict, floating_ips): for floating_ip in floating_ips: router = routers_dict.get(floating_ip['router_id']) if router: router_floatingips = router.get(l3_constants.FLOATINGIP_KEY, []) router_floatingips.append(floating_ip) router[l3_constants.FLOATINGIP_KEY] = router_floatingips def _process_interfaces(self, routers_dict, interfaces): for interface in interfaces: router = routers_dict.get(interface['device_id']) if router: router_interfaces = router.get(l3_constants.INTERFACE_KEY, []) router_interfaces.append(interface) router[l3_constants.INTERFACE_KEY] = router_interfaces def _get_router_info_list(self, context, router_ids=None, active=None, device_owners=None): """Query routers and their related floating_ips, interfaces.""" with context.session.begin(subtransactions=True): routers = self._get_sync_routers(context, router_ids=router_ids, active=active) router_ids = [router['id'] for router in routers] interfaces = self.get_sync_interfaces( context, router_ids, device_owners) floating_ips = self._get_sync_floating_ips(context, router_ids) return (routers, interfaces, floating_ips) def get_sync_data(self, context, router_ids=None, active=None): routers, interfaces, floating_ips = self._get_router_info_list( context, router_ids=router_ids, active=active) routers_dict = dict((router['id'], router) for router in routers) self._process_floating_ips(context, routers_dict, floating_ips) self._process_interfaces(routers_dict, interfaces) return routers_dict.values() class L3RpcNotifierMixin(object): """Mixin class to add rpc notifier attribute to db_base_plugin_v2.""" @property def l3_rpc_notifier(self): if not hasattr(self, '_l3_rpc_notifier'): self._l3_rpc_notifier = l3_rpc_agent_api.L3AgentNotifyAPI() return self._l3_rpc_notifier @l3_rpc_notifier.setter def l3_rpc_notifier(self, value): self._l3_rpc_notifier = value def notify_router_updated(self, context, router_id, operation=None): if router_id: self.l3_rpc_notifier.routers_updated( context, [router_id], operation) def notify_routers_updated(self, context, router_ids, operation=None, data=None): if router_ids: self.l3_rpc_notifier.routers_updated( context, router_ids, operation, data) def notify_router_deleted(self, context, router_id): self.l3_rpc_notifier.router_deleted(context, router_id) class L3_NAT_db_mixin(L3_NAT_dbonly_mixin, L3RpcNotifierMixin): """Mixin class to add rpc notifier methods to db_base_plugin_v2.""" def update_router(self, context, id, router): router_dict = super(L3_NAT_db_mixin, self).update_router(context, id, router) self.notify_router_updated(context, router_dict['id'], None) return router_dict def delete_router(self, context, id): super(L3_NAT_db_mixin, self).delete_router(context, id) self.notify_router_deleted(context, id) def notify_router_interface_action( self, context, router_interface_info, action): l3_method = '%s_router_interface' % action super(L3_NAT_db_mixin, self).notify_routers_updated( context, [router_interface_info['id']], l3_method, {'subnet_id': router_interface_info['subnet_id']}) mapping = {'add': 'create', 'remove': 'delete'} notifier = n_rpc.get_notifier('network') router_event = 'router.interface.%s' % mapping[action] notifier.info(context, router_event, {'router_interface': router_interface_info}) def add_router_interface(self, context, router_id, interface_info): router_interface_info = super( L3_NAT_db_mixin, self).add_router_interface( context, router_id, interface_info) self.notify_router_interface_action( context, router_interface_info, 'add') return router_interface_info def remove_router_interface(self, context, router_id, interface_info): router_interface_info = super( L3_NAT_db_mixin, self).remove_router_interface( context, router_id, interface_info) self.notify_router_interface_action( context, router_interface_info, 'remove') return router_interface_info def create_floatingip(self, context, floatingip, initial_status=l3_constants.FLOATINGIP_STATUS_ACTIVE): floatingip_dict = super(L3_NAT_db_mixin, self).create_floatingip( context, floatingip, initial_status) router_id = floatingip_dict['router_id'] self.notify_router_updated(context, router_id, 'create_floatingip') return floatingip_dict def update_floatingip(self, context, id, floatingip): old_floatingip, floatingip = self._update_floatingip( context, id, floatingip) router_ids = self._floatingips_to_router_ids( [old_floatingip, floatingip]) super(L3_NAT_db_mixin, self).notify_routers_updated( context, router_ids, 'update_floatingip', {}) return floatingip def delete_floatingip(self, context, id): router_id = self._delete_floatingip(context, id) self.notify_router_updated(context, router_id, 'delete_floatingip') def disassociate_floatingips(self, context, port_id, do_notify=True): """Disassociate all floating IPs linked to specific port. @param port_id: ID of the port to disassociate floating IPs. @param do_notify: whether we should notify routers right away. @return: set of router-ids that require notification updates if do_notify is False, otherwise None. """ router_ids = super(L3_NAT_db_mixin, self).disassociate_floatingips( context, port_id) if do_notify: self.notify_routers_updated(context, router_ids) # since caller assumes that we handled notifications on its # behalf, return nothing return return router_ids def notify_routers_updated(self, context, router_ids): super(L3_NAT_db_mixin, self).notify_routers_updated( context, list(router_ids), 'disassociate_floatingips', {})
leeseuljeong/leeseulstack_neutron
neutron/db/l3_db.py
Python
apache-2.0
55,905
"""Support for the AEMET OpenData service.""" from homeassistant.components.weather import WeatherEntity from homeassistant.const import TEMP_CELSIUS from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( ATTR_API_CONDITION, ATTR_API_HUMIDITY, ATTR_API_PRESSURE, ATTR_API_TEMPERATURE, ATTR_API_WIND_BEARING, ATTR_API_WIND_SPEED, ATTRIBUTION, DOMAIN, ENTRY_NAME, ENTRY_WEATHER_COORDINATOR, FORECAST_MODE_ATTR_API, FORECAST_MODE_DAILY, FORECAST_MODES, ) from .weather_update_coordinator import WeatherUpdateCoordinator async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AEMET OpenData weather entity based on a config entry.""" domain_data = hass.data[DOMAIN][config_entry.entry_id] weather_coordinator = domain_data[ENTRY_WEATHER_COORDINATOR] entities = [] for mode in FORECAST_MODES: name = f"{domain_data[ENTRY_NAME]} {mode}" unique_id = f"{config_entry.unique_id} {mode}" entities.append(AemetWeather(name, unique_id, weather_coordinator, mode)) if entities: async_add_entities(entities, False) class AemetWeather(CoordinatorEntity, WeatherEntity): """Implementation of an AEMET OpenData sensor.""" def __init__( self, name, unique_id, coordinator: WeatherUpdateCoordinator, forecast_mode, ): """Initialize the sensor.""" super().__init__(coordinator) self._name = name self._unique_id = unique_id self._forecast_mode = forecast_mode @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def condition(self): """Return the current condition.""" return self.coordinator.data[ATTR_API_CONDITION] @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self._forecast_mode == FORECAST_MODE_DAILY @property def forecast(self): """Return the forecast array.""" return self.coordinator.data[FORECAST_MODE_ATTR_API[self._forecast_mode]] @property def humidity(self): """Return the humidity.""" return self.coordinator.data[ATTR_API_HUMIDITY] @property def name(self): """Return the name of the sensor.""" return self._name @property def pressure(self): """Return the pressure.""" return self.coordinator.data[ATTR_API_PRESSURE] @property def temperature(self): """Return the temperature.""" return self.coordinator.data[ATTR_API_TEMPERATURE] @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def unique_id(self): """Return a unique_id for this entity.""" return self._unique_id @property def wind_bearing(self): """Return the temperature.""" return self.coordinator.data[ATTR_API_WIND_BEARING] @property def wind_speed(self): """Return the temperature.""" return self.coordinator.data[ATTR_API_WIND_SPEED]
kennedyshead/home-assistant
homeassistant/components/aemet/weather.py
Python
apache-2.0
3,266
from __future__ import print_function import sys import numpy as np from numba.compiler import compile_isolated, Flags from numba import jit, types from numba.tests.support import TestCase, MemoryLeakMixin import numba.unittest_support as unittest from numba import testing enable_pyobj_flags = Flags() enable_pyobj_flags.set("enable_pyobject") forceobj_flags = Flags() forceobj_flags.set("force_pyobject") no_pyobj_flags = Flags() def make_consumer(gen_func): def consumer(x): res = 0.0 for y in gen_func(x): res += y return res return consumer def gen1(x): for i in range(x): yield i def gen2(x): for i in range(x): yield i for j in range(1, 3): yield i + j def gen3(x): # Polymorphic yield types must be unified yield x yield x + 1.5 yield x + 1j def gen4(x, y, z): for i in range(3): yield z yield y + z return yield x def gen5(): # The bytecode for this generator doesn't contain any YIELD_VALUE # (it's optimized away). We fail typing it, since the yield type # is entirely undefined. if 0: yield 1 def gen6(a, b): # Infinite loop: exercise computation of state variables x = a + 1 while True: y = b + 2 yield x + y def gen7(arr): # Array variable in generator state for i in range(arr.size): yield arr[i] def genobj(x): object() yield x def return_generator_expr(x): return (i * 2 for i in x) def gen_ndindex(shape): for ind in np.ndindex(shape): yield ind def gen_flat(arr): for val in arr.flat: yield val def gen_ndenumerate(arr): for tup in np.ndenumerate(arr): yield tup class TestGenerators(MemoryLeakMixin, TestCase): def check_generator(self, pygen, cgen): self.assertEqual(next(cgen), next(pygen)) # Use list comprehensions to make sure we trash the generator's # former C stack. expected = [x for x in pygen] got = [x for x in cgen] self.assertEqual(expected, got) with self.assertRaises(StopIteration): next(cgen) def check_gen1(self, flags=no_pyobj_flags): pyfunc = gen1 cr = compile_isolated(pyfunc, (types.int32,), flags=flags) pygen = pyfunc(8) cgen = cr.entry_point(8) self.check_generator(pygen, cgen) def test_gen1(self): self.check_gen1() def test_gen1_objmode(self): self.check_gen1(flags=forceobj_flags) def check_gen2(self, flags=no_pyobj_flags): pyfunc = gen2 cr = compile_isolated(pyfunc, (types.int32,), flags=flags) pygen = pyfunc(8) cgen = cr.entry_point(8) self.check_generator(pygen, cgen) def test_gen2(self): self.check_gen2() def test_gen2_objmode(self): self.check_gen2(flags=forceobj_flags) def check_gen3(self, flags=no_pyobj_flags): pyfunc = gen3 cr = compile_isolated(pyfunc, (types.int32,), flags=flags) pygen = pyfunc(8) cgen = cr.entry_point(8) self.check_generator(pygen, cgen) def test_gen3(self): self.check_gen3() def test_gen3_objmode(self): self.check_gen3(flags=forceobj_flags) def check_gen4(self, flags=no_pyobj_flags): pyfunc = gen4 cr = compile_isolated(pyfunc, (types.int32,) * 3, flags=flags) pygen = pyfunc(5, 6, 7) cgen = cr.entry_point(5, 6, 7) self.check_generator(pygen, cgen) def test_gen4(self): self.check_gen4() def test_gen4_objmode(self): self.check_gen4(flags=forceobj_flags) def test_gen5(self): with self.assertTypingError() as cm: cr = compile_isolated(gen5, ()) self.assertIn("Cannot type generator: it does not yield any value", str(cm.exception)) def test_gen5_objmode(self): cr = compile_isolated(gen5, (), flags=forceobj_flags) cgen = cr.entry_point() self.assertEqual(list(cgen), []) with self.assertRaises(StopIteration): next(cgen) def check_gen6(self, flags=no_pyobj_flags): pyfunc = gen6 cr = compile_isolated(pyfunc, (types.int32,) * 2, flags=flags) cgen = cr.entry_point(5, 6) l = [] for i in range(3): l.append(next(cgen)) self.assertEqual(l, [14] * 3) def test_gen6(self): self.check_gen6() def test_gen6_objmode(self): self.check_gen6(flags=forceobj_flags) def check_gen7(self, flags=no_pyobj_flags): pyfunc = gen7 cr = compile_isolated(pyfunc, (types.Array(types.float64, 1, 'C'),), flags=flags) arr = np.linspace(1, 10, 7) pygen = pyfunc(arr.copy()) cgen = cr.entry_point(arr) self.check_generator(pygen, cgen) def test_gen7(self): self.check_gen7() def test_gen7_objmode(self): self.check_gen7(flags=forceobj_flags) def check_consume_generator(self, gen_func): cgen = jit(nopython=True)(gen_func) cfunc = jit(nopython=True)(make_consumer(cgen)) pyfunc = make_consumer(gen_func) expected = pyfunc(5) got = cfunc(5) self.assertPreciseEqual(got, expected) def test_consume_gen1(self): self.check_consume_generator(gen1) def test_consume_gen2(self): self.check_consume_generator(gen2) def test_consume_gen3(self): self.check_consume_generator(gen3) # Check generator storage of some types def check_ndindex(self, flags=no_pyobj_flags): pyfunc = gen_ndindex cr = compile_isolated(pyfunc, (types.UniTuple(types.intp, 2),), flags=flags) shape = (2, 3) pygen = pyfunc(shape) cgen = cr.entry_point(shape) self.check_generator(pygen, cgen) def test_ndindex(self): self.check_ndindex() def test_ndindex_objmode(self): self.check_ndindex(flags=forceobj_flags) def check_np_flat(self, pyfunc, flags=no_pyobj_flags): cr = compile_isolated(pyfunc, (types.Array(types.int32, 2, "C"),), flags=flags) arr = np.arange(6, dtype=np.int32).reshape((2, 3)) self.check_generator(pyfunc(arr), cr.entry_point(arr)) cr = compile_isolated(pyfunc, (types.Array(types.int32, 2, "A"),), flags=flags) arr = arr.T self.check_generator(pyfunc(arr), cr.entry_point(arr)) def test_np_flat(self): self.check_np_flat(gen_flat) def test_np_flat_objmode(self): self.check_np_flat(gen_flat, flags=forceobj_flags) def test_ndenumerate(self): self.check_np_flat(gen_ndenumerate) def test_ndenumerate_objmode(self): self.check_np_flat(gen_ndenumerate, flags=forceobj_flags) class TestGenExprs(MemoryLeakMixin, TestCase): @testing.allow_interpreter_mode def test_return_generator_expr(self): pyfunc = return_generator_expr cr = compile_isolated(pyfunc, ()) cfunc = cr.entry_point self.assertEqual(sum(cfunc([1, 2, 3])), sum(pyfunc([1, 2, 3]))) def nrt_gen0(ary): for elem in ary: yield elem def nrt_gen1(ary1, ary2): for e1, e2 in zip(ary1, ary2): yield e1 yield e2 class TestNrtArrayGen(MemoryLeakMixin, TestCase): def test_nrt_gen0(self): pygen = nrt_gen0 cgen = jit(nopython=True)(pygen) py_ary = np.arange(10) c_ary = py_ary.copy() py_res = list(pygen(py_ary)) c_res = list(cgen(c_ary)) np.testing.assert_equal(py_ary, c_ary) self.assertEqual(py_res, c_res) # Check reference count self.assertEqual(sys.getrefcount(py_ary), sys.getrefcount(c_ary)) def test_nrt_gen1(self): pygen = nrt_gen1 cgen = jit(nopython=True)(pygen) py_ary1 = np.arange(10) py_ary2 = py_ary1 + 100 c_ary1 = py_ary1.copy() c_ary2 = py_ary2.copy() py_res = list(pygen(py_ary1, py_ary2)) c_res = list(cgen(c_ary1, c_ary2)) np.testing.assert_equal(py_ary1, c_ary1) np.testing.assert_equal(py_ary2, c_ary2) self.assertEqual(py_res, c_res) # Check reference count self.assertEqual(sys.getrefcount(py_ary1), sys.getrefcount(c_ary1)) self.assertEqual(sys.getrefcount(py_ary2), sys.getrefcount(c_ary2)) def test_combine_gen0_gen1(self): """ Issue #1163 is observed when two generator with NRT object arguments is ran in sequence. The first one does a invalid free and corrupts the NRT memory subsystem. The second generator is likely to segfault due to corrupted NRT data structure (an invalid MemInfo). """ self.test_nrt_gen0() self.test_nrt_gen1() def test_nrt_gen0_stop_iteration(self): """ Test cleanup on StopIteration """ pygen = nrt_gen0 cgen = jit(nopython=True)(pygen) py_ary = np.arange(1) c_ary = py_ary.copy() py_iter = pygen(py_ary) c_iter = cgen(c_ary) py_res = next(py_iter) c_res = next(c_iter) with self.assertRaises(StopIteration): py_res = next(py_iter) with self.assertRaises(StopIteration): c_res = next(c_iter) del py_iter del c_iter np.testing.assert_equal(py_ary, c_ary) self.assertEqual(py_res, c_res) # Check reference count self.assertEqual(sys.getrefcount(py_ary), sys.getrefcount(c_ary)) def test_nrt_gen0_no_iter(self): """ Test cleanup for a initialized but never iterated (never call next()) generator. """ pygen = nrt_gen0 cgen = jit(nopython=True)(pygen) py_ary = np.arange(1) c_ary = py_ary.copy() py_iter = pygen(py_ary) c_iter = cgen(c_ary) del py_iter del c_iter np.testing.assert_equal(py_ary, c_ary) # Check reference count self.assertEqual(sys.getrefcount(py_ary), sys.getrefcount(c_ary)) # TODO: fix nested generator and MemoryLeakMixin class TestNrtNestedGen(TestCase): def test_nrt_nested_gen(self): def gen0(arr): for i in range(arr.size): yield arr def factory(gen0): def gen1(arr): out = np.zeros_like(arr) for x in gen0(arr): out = out + x return out, arr return gen1 py_arr = np.arange(10) c_arr = py_arr.copy() py_res, py_old = factory(gen0)(py_arr) c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0))) c_res, c_old = c_gen(c_arr) self.assertIsNot(py_arr, c_arr) self.assertIs(py_old, py_arr) self.assertIs(c_old, c_arr) np.testing.assert_equal(py_res, c_res) self.assertEqual(sys.getrefcount(py_res), sys.getrefcount(c_res)) # The below test will fail due to generator finalizer not invoked. # This kept a reference of the c_old. # # self.assertEqual(sys.getrefcount(py_old), # sys.getrefcount(c_old)) @unittest.expectedFailure def test_nrt_nested_gen_refct(self): def gen0(arr): yield arr def factory(gen0): def gen1(arr): for out in gen0(arr): return out return gen1 py_arr = np.arange(10) c_arr = py_arr.copy() py_old = factory(gen0)(py_arr) c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0))) c_old = c_gen(c_arr) self.assertIsNot(py_arr, c_arr) self.assertIs(py_old, py_arr) self.assertIs(c_old, c_arr) self.assertEqual(sys.getrefcount(py_old), sys.getrefcount(c_old)) def test_nrt_nested_nopython_gen(self): """ Test nesting three generators """ def factory(decor=lambda x: x): @decor def foo(a, n): for i in range(n): yield a[i] a[i] += i @decor def bar(n): a = np.arange(n) for i in foo(a, n): yield i * 2 for i in range(a.size): yield a[i] @decor def cat(n): for i in bar(n): yield i + i return cat py_gen = factory() c_gen = factory(jit(nopython=True)) py_res = list(py_gen(10)) c_res = list(c_gen(10)) self.assertEqual(py_res, c_res) class TestGeneratorWithNRT(MemoryLeakMixin, TestCase): def test_issue_1254(self): """ Missing environment for returning array """ @jit(nopython=True) def random_directions(n): for i in range(n): vec = np.empty(3) vec[:] = 12 yield vec outputs = list(random_directions(5)) self.assertEqual(len(outputs), 5) expect = np.empty(3) expect[:] = 12 for got in outputs: np.testing.assert_equal(expect, got) def test_issue_1265(self): """ Double-free for locally allocated, non escaping NRT objects """ def py_gen(rmin, rmax, nr): a = np.linspace(rmin, rmax, nr) yield a[0] yield a[1] c_gen = jit(nopython=True)(py_gen) py_res = list(py_gen(-2, 2, 100)) c_res = list(c_gen(-2, 2, 100)) self.assertEqual(py_res, c_res) def py_driver(args): rmin, rmax, nr = args points = np.empty(nr, dtype=np.complex128) for i, c in enumerate(py_gen(rmin, rmax, nr)): points[i] = c return points @jit(nopython=True) def c_driver(args): rmin, rmax, nr = args points = np.empty(nr, dtype=np.complex128) for i, c in enumerate(c_gen(rmin, rmax, nr)): points[i] = c return points n = 2 patches = (-2, -1, n) py_res = py_driver(patches) # The error will cause a segfault here c_res = c_driver(patches) np.testing.assert_equal(py_res, c_res) if __name__ == '__main__': unittest.main()
ssarangi/numba
numba/tests/test_generators.py
Python
bsd-2-clause
14,740
from streamlink.plugins.n13tv import N13TV from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlN13TV(PluginCanHandleUrl): __plugin__ = N13TV should_match = [ "http://13tv.co.il/live", "https://13tv.co.il/live", "http://www.13tv.co.il/live/", "https://www.13tv.co.il/live/", "http://13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", "https://13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", "http://www.13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", "https://www.13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/" "http://13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/", "https://13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/", "http://www.13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/" "https://www.13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/" ]
chhe/streamlink
tests/plugins/test_n13tv.py
Python
bsd-2-clause
1,113
"""" Dummy mocking module for pandas. When pandas is not avaialbe we will import this module as graphlab.deps.pandas, and set HAS_pandas to false. All methods that access pandas should check the HAS_pandas flag, therefore, attributes/class/methods in this module should never be actually used. """ ''' Copyright (C) 2016 Turi All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. '''
ylow/SFrame
oss_src/unity/python/sframe/deps/pandas_mock.py
Python
bsd-3-clause
469
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #-----------------------------------------------------------------------------
bokeh/bokeh
tests/integration/tools/__init__.py
Python
bsd-3-clause
347
import os import re from subprocess import Popen, PIPE from django.core.management.utils import find_command can_run_extraction_tests = False can_run_compilation_tests = False # checks if it can find xgettext on the PATH and # imports the extraction tests if yes xgettext_cmd = find_command('xgettext') if xgettext_cmd: p = Popen('%s --version' % xgettext_cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True) output = p.communicate()[0] match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output) if match: xversion = (int(match.group('major')), int(match.group('minor'))) if xversion >= (0, 15): can_run_extraction_tests = True del p if find_command('msgfmt'): can_run_compilation_tests = True
postrational/django
tests/i18n/commands/tests.py
Python
bsd-3-clause
794
import os from optparse import make_option from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.test.utils import setup_test_environment, teardown_test_environment from django.utils import unittest from django.utils.unittest import TestSuite, defaultTestLoader class DiscoverRunner(object): """ A Django test runner that uses unittest2 test discovery. """ test_loader = defaultTestLoader reorder_by = (TestCase, ) option_list = ( make_option('-t', '--top-level-directory', action='store', dest='top_level', default=None, help='Top level of project for unittest discovery.'), make_option('-p', '--pattern', action='store', dest='pattern', default="test*.py", help='The test matching pattern. Defaults to test*.py.'), ) def __init__(self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, **kwargs): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False unittest.installHandler() def build_suite(self, test_labels=None, extra_tests=None, **kwargs): suite = TestSuite() test_labels = test_labels or ['.'] extra_tests = extra_tests or [] discover_kwargs = {} if self.pattern is not None: discover_kwargs['pattern'] = self.pattern if self.top_level is not None: discover_kwargs['top_level_dir'] = self.top_level for label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a module, or "module.ClassName[.method_name]", just run those if not os.path.exists(label_as_path): tests = self.test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path) and not self.top_level: # Try to be a bit smarter than unittest about finding the # default top-level for a given directory path, to avoid # breaking relative imports. (Unittest's default is to set # top-level equal to the path, which means relative imports # will result in "Attempted relative import in non-package."). # We'd be happy to skip this and require dotted module paths # (which don't cause this problem) instead of file paths (which # do), but in the case of a directory in the cwd, which would # be equally valid if considered as a top-level module or as a # directory path, unittest unfortunately prefers the latter. top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()): # if no tests found, it's probably a package; try discovery tests = self.test_loader.discover(start_dir=label, **kwargs) # make unittest forget the top-level dir it calculated from this # run, to support running tests from two different top-levels. self.test_loader._top_level_dir = None suite.addTests(tests) for test in extra_tests: suite.addTest(test) return reorder_suite(suite, self.reorder_by) def setup_databases(self, **kwargs): return setup_databases(self.verbosity, self.interactive, **kwargs) def run_suite(self, suite, **kwargs): return unittest.TextTestRunner( verbosity=self.verbosity, failfast=self.failfast, ).run(suite) def teardown_databases(self, old_config, **kwargs): """ Destroys all the non-mirror databases. """ old_names, mirrors = old_config for connection, old_name, destroy in old_names: if destroy: connection.creation.destroy_test_db(old_name, self.verbosity) def teardown_test_environment(self, **kwargs): unittest.removeHandler() teardown_test_environment() def suite_result(self, suite, result, **kwargs): return len(result.failures) + len(result.errors) def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Test labels should be dotted Python paths to test modules, test classes, or test methods. A list of 'extra' tests may also be provided; these tests will be added to the test suite. Returns the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() return self.suite_result(suite, result) def dependency_ordered(test_databases, dependencies): """ Reorder test_databases into an order that honors the dependencies described in TEST_DEPENDENCIES. """ ordered_test_databases = [] resolved_databases = set() # Maps db signature to dependencies of all it's aliases dependencies_map = {} # sanity check - no DB can depend on it's own alias for sig, (_, aliases) in test_databases: all_deps = set() for alias in aliases: all_deps.update(dependencies.get(alias, [])) if not all_deps.isdisjoint(aliases): raise ImproperlyConfigured( "Circular dependency: databases %r depend on each other, " "but are aliases." % aliases) dependencies_map[sig] = all_deps while test_databases: changed = False deferred = [] # Try to find a DB that has all it's dependencies met for signature, (db_name, aliases) in test_databases: if dependencies_map[signature].issubset(resolved_databases): resolved_databases.update(aliases) ordered_test_databases.append((signature, (db_name, aliases))) changed = True else: deferred.append((signature, (db_name, aliases))) if not changed: raise ImproperlyConfigured( "Circular dependency in TEST_DEPENDENCIES") test_databases = deferred return ordered_test_databases def reorder_suite(suite, classes): """ Reorders a test suite by test type. `classes` is a sequence of types All tests of type classes[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. """ class_count = len(classes) bins = [unittest.TestSuite() for i in range(class_count+1)] partition_suite(suite, classes, bins) for i in range(class_count): bins[0].addTests(bins[i+1]) return bins[0] def partition_suite(suite, classes, bins): """ Partitions a test suite by test type. classes is a sequence of types bins is a sequence of TestSuites, one more than classes Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ for test in suite: if isinstance(test, unittest.TestSuite): partition_suite(test, classes, bins) else: for i in range(len(classes)): if isinstance(test, classes[i]): bins[i].addTest(test) break else: bins[-1].addTest(test) def setup_databases(verbosity, interactive, **kwargs): from django.db import connections, DEFAULT_DB_ALIAS # First pass -- work out which databases actually need to be created, # and which ones are test mirrors or duplicate entries in DATABASES mirrored_aliases = {} test_databases = {} dependencies = {} for alias in connections: connection = connections[alias] if connection.settings_dict['TEST_MIRROR']: # If the database is marked as a test mirror, save # the alias. mirrored_aliases[alias] = ( connection.settings_dict['TEST_MIRROR']) else: # Store a tuple with DB parameters that uniquely identify it. # If we have two aliases with the same values for that tuple, # we only need to create the test database once. item = test_databases.setdefault( connection.creation.test_db_signature(), (connection.settings_dict['NAME'], set()) ) item[1].add(alias) if 'TEST_DEPENDENCIES' in connection.settings_dict: dependencies[alias] = ( connection.settings_dict['TEST_DEPENDENCIES']) else: if alias != DEFAULT_DB_ALIAS: dependencies[alias] = connection.settings_dict.get( 'TEST_DEPENDENCIES', [DEFAULT_DB_ALIAS]) # Second pass -- actually create the databases. old_names = [] mirrors = [] for signature, (db_name, aliases) in dependency_ordered( test_databases.items(), dependencies): test_db_name = None # Actually create the database for the first connection for alias in aliases: connection = connections[alias] old_names.append((connection, db_name, True)) if test_db_name is None: test_db_name = connection.creation.create_test_db( verbosity, autoclobber=not interactive) else: connection.settings_dict['NAME'] = test_db_name for alias, mirror_alias in mirrored_aliases.items(): mirrors.append((alias, connections[alias].settings_dict['NAME'])) connections[alias].settings_dict['NAME'] = ( connections[mirror_alias].settings_dict['NAME']) return old_names, mirrors
postrational/django
django/test/runner.py
Python
bsd-3-clause
10,748
########################################################### # # Copyright (c) 2009, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # __all__ = ["FreeFormLayoutWdg"] from pyasm.common import Common, jsonloads from pyasm.search import Search, SearchKey from pyasm.web import DivWdg, Table, WebContainer from pyasm.widget import WidgetConfig from tactic.ui.common import BaseRefreshWdg from tactic.ui.widget import ActionButtonWdg import random class FreeFormLayoutWdg(BaseRefreshWdg): ARGS_KEYS = { 'search_type': { 'description': 'Search Type for Free Form layout', 'type': 'TextWdg', 'order': 1, 'category': 'Options' }, 'view': { 'description': 'Freeform view', 'type': 'TextWdg', 'order': 1, 'category': 'Options' }, 'css': { 'description': 'Top level style', 'type': 'TextAreaWdg', 'order': 2, 'category': 'Options' }, } def get_input_value(my, name): value = my.kwargs.get(name) if value == None: web = WebContainer.get_web() value = web.get_form_value(name) return value def get_default_background(my): return DivWdg().get_color("background") def get_display(my): category = "FreeformWdg" view = my.get_input_value("view") sobject = my.get_input_value("sobject") if not sobject and my.sobjects: sobject = my.sobjects[0] if not view: view = 'freeform' if sobject: search_key = sobject.get_search_key() search_type = sobject.get_base_search_type() else: search_key = my.get_input_value("search_key") search_type = my.get_input_value("search_type") if sobject: pass elif search_key: sobject = Search.get_by_search_key(search_key) elif search_type: search = Search(search_type) search.add_limit(1) sobject = search.get_sobject() else: sobject = None top = DivWdg() top.add_class("spt_freeform_top") search = Search("config/widget_config") search.add_filter("search_type", search_type) search.add_filter("view", view) config_sobj = search.get_sobject() if config_sobj: config_xml = config_sobj.get_value("config") else: config_xml = "" if not config_xml: top.add("No definition found") return top config = WidgetConfig.get(view=view, xml=config_xml) view_attrs = config.get_view_attributes() bgcolor = view_attrs.get("bgcolor") if not bgcolor: bgcolor = my.get_default_background() if bgcolor: top.add_style("background", bgcolor) # draw the layout freeform_layout = my.get_canvas_display(search_type, view, config, sobject) top.add(freeform_layout) return top def get_canvas_display(my, search_type, view, config, sobject): top = DivWdg() top.add_class("spt_freeform_layout_top") my.set_as_panel(top) #top.add_color("background", "background") #top.add_color("color", "color") #top.add_style("height: 100%") #top.add_style("width: 100%") #border_color = top.get_color("border") #top.add_border() css = my.kwargs.get("css") if css: css = jsonloads(css) for name, value in css.items(): top.add_style(name, value) # define canvas canvas = top canvas.add_class("spt_freeform_canvas") canvas.add_style("position: relative") canvas.add_style("overflow: hidden") my.kwargs['view'] = view element_names = config.get_element_names() view_attrs = config.get_view_attributes() canvas_height = view_attrs.get("height") if not canvas_height: canvas_height = '400px' canvas.add_style("height: %s" % canvas_height) canvas_width = view_attrs.get("width") if not canvas_width: canvas_width = '400px' canvas.add_style("width: %s" % canvas_width) for element_name in element_names: widget_div = DivWdg() canvas.add(widget_div) widget_div.add_style("position: absolute") widget_div.add_style("vertical-align: top") widget_div.add_class("SPT_ELEMENT_SELECT") el_attrs = config.get_element_attributes(element_name) height = el_attrs.get("height") if height: widget_div.add_style("height: %s" % height) width = el_attrs.get("width") if width: widget_div.add_style("width: %s" % width) display_handler = config.get_display_handler(element_name) display_options = config.get_display_options(element_name) widget_div.add_attr("spt_display_handler", display_handler) try: widget = config.get_display_widget(element_name) except: continue widget.set_sobject(sobject) widget_div.add_attr("spt_element_name", element_name) widget_div.add_class("spt_element") #widget_div.add(widget) try: widget_div.add(widget.get_buffer_display()) except: widget_div.add("Error") raise try: is_resizable = widget.is_resizable() except: is_resizable = False if is_resizable: widget.add_style("width: 100%") widget.add_style("height: 100%") widget.add_style("overflow: hidden") xpos = el_attrs.get("xpos") if not xpos: xpos = '100px' widget_div.add_style("left: %s" % xpos) ypos = el_attrs.get("ypos") if not ypos: ypos = '100px' widget_div.add_style("top: %s" % ypos) return top __all__.append("FreeFormElementWdg") from tactic.ui.common import BaseTableElementWdg class FreeFormElementWdg(BaseTableElementWdg): ARGS_KEYS = { 'view': { 'description': 'Freeform view', 'type': 'TextWdg', 'order': 1, 'category': 'Options' }, } def preprocess(my): my.layout = FreeFormLayoutWdg(**my.kwargs) def is_editable(my): return False def get_display(my): sobject = my.get_current_sobject() my.layout.set_sobject(sobject) top = my.top top.add(my.layout.get_buffer_display()) return top
sadanandb/pmt
src/tactic/ui/panel/freeform_layout_wdg.py
Python
epl-1.0
7,039
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2011, 2012, 2013, 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibRank database models.""" # General imports. from flask import g from invenio.ext.sqlalchemy import db # Create your models here. from invenio.modules.accounts.models import User from invenio.modules.editor.models import Bibdoc from invenio.modules.records.models import Record as Bibrec from invenio.modules.search.models import Collection class RnkMETHOD(db.Model): """Represent a RnkMETHOD record.""" __tablename__ = 'rnkMETHOD' id = db.Column(db.MediumInteger(9, unsigned=True), primary_key=True, nullable=False) name = db.Column(db.String(20), unique=True, nullable=False, server_default='') last_updated = db.Column(db.DateTime, nullable=False, server_default='1900-01-01 00:00:00') def get_name_ln(self, ln=None): """Return localized method name.""" try: if ln is None: ln = g.ln return self.names.filter_by(ln=g.ln, type='ln').one().value except: return self.name class RnkMETHODDATA(db.Model): """Represent a RnkMETHODDATA record.""" __tablename__ = 'rnkMETHODDATA' id_rnkMETHOD = db.Column(db.MediumInteger(9, unsigned=True), db.ForeignKey(RnkMETHOD.id), primary_key=True) relevance_data = db.Column(db.iLargeBinary, nullable=True) class RnkMETHODNAME(db.Model): """Represent a RnkMETHODNAME record.""" __tablename__ = 'rnkMETHODNAME' id_rnkMETHOD = db.Column(db.MediumInteger(9, unsigned=True), db.ForeignKey(RnkMETHOD.id), primary_key=True) ln = db.Column(db.Char(5), primary_key=True, server_default='') type = db.Column(db.Char(3), primary_key=True, server_default='sn') value = db.Column(db.String(255), nullable=False) method = db.relationship(RnkMETHOD, backref=db.backref('names', lazy='dynamic')) class RnkCITATIONDICT(db.Model): """Represent a RnkCITATIONDICT record.""" __tablename__ = 'rnkCITATIONDICT' citee = db.Column(db.Integer(10, unsigned=True), primary_key=True) citer = db.Column(db.Integer(10, unsigned=True), primary_key=True) last_updated = db.Column(db.DateTime, nullable=False) __table_args__ = (db.Index('rnkCITATIONDICT_reverse', citer, citee), db.Model.__table_args__) class RnkCITATIONDATAERR(db.Model): """Represent a RnkCITATIONDATAERR record.""" __tablename__ = 'rnkCITATIONDATAERR' type = db.Column(db.Enum('multiple-matches', 'not-well-formed', name='rnkcitattiondataerr_type'), primary_key=True) citinfo = db.Column(db.String(255), primary_key=True, server_default='') class RnkCITATIONLOG(db.Model): """Represents a RnkCITATIONLOG record.""" __tablename__ = 'rnkCITATIONLOG' id = db.Column(db.Integer(11, unsigned=True), primary_key=True, autoincrement=True, nullable=False) citee = db.Column(db.Integer(10, unsigned=True), nullable=False) citer = db.Column(db.Integer(10, unsigned=True), nullable=False) type = db.Column(db.Enum('added', 'removed', name='rnkcitationlog_type'), nullable=True) action_date = db.Column(db.DateTime, nullable=False) __table_args__ = (db.Index('citee', citee), db.Index('citer', citer), db.Model.__table_args__) class RnkCITATIONDATAEXT(db.Model): """Represent a RnkCITATIONDATAEXT record.""" __tablename__ = 'rnkCITATIONDATAEXT' id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), autoincrement=False, primary_key=True, nullable=False, server_default='0') extcitepubinfo = db.Column(db.String(255), primary_key=True, nullable=False, index=True) class RnkAUTHORDATA(db.Model): """Represent a RnkAUTHORDATA record.""" __tablename__ = 'rnkAUTHORDATA' aterm = db.Column(db.String(50), primary_key=True, nullable=True) hitlist = db.Column(db.iLargeBinary, nullable=True) class RnkDOWNLOADS(db.Model): """Represent a RnkDOWNLOADS record.""" __tablename__ = 'rnkDOWNLOADS' id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True) id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), nullable=True) download_time = db.Column(db.DateTime, nullable=True, server_default='1900-01-01 00:00:00') client_host = db.Column(db.Integer(10, unsigned=True), nullable=True) id_user = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), nullable=True) id_bibdoc = db.Column(db.MediumInteger(9, unsigned=True), db.ForeignKey(Bibdoc.id), nullable=True) file_version = db.Column(db.SmallInteger(2, unsigned=True), nullable=True) file_format = db.Column(db.String(50), nullable=True) bibrec = db.relationship(Bibrec, backref='downloads') bibdoc = db.relationship(Bibdoc, backref='downloads') user = db.relationship(User, backref='downloads') class RnkPAGEVIEWS(db.Model): """Represent a RnkPAGEVIEWS record.""" __tablename__ = 'rnkPAGEVIEWS' id = db.Column(db.MediumInteger, primary_key=True, nullable=False, autoincrement=True) id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), nullable=True, primary_key=True) id_user = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), server_default='0', primary_key=True) client_host = db.Column(db.Integer(10, unsigned=True), nullable=True) view_time = db.Column(db.DateTime, primary_key=True, server_default='1900-01-01 00:00:00') bibrec = db.relationship(Bibrec, backref='pageviews') user = db.relationship(User, backref='pageviews') class RnkWORD01F(db.Model): """Represent a RnkWORD01F record.""" __tablename__ = 'rnkWORD01F' id = db.Column(db.MediumInteger(9, unsigned=True), nullable=False, primary_key=True, autoincrement=True) term = db.Column(db.String(50), nullable=True, unique=True) hitlist = db.Column(db.iLargeBinary, nullable=True) class RnkWORD01R(db.Model): """Represent a RnkWORD01R record.""" __tablename__ = 'rnkWORD01R' id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), nullable=False, primary_key=True) termlist = db.Column(db.LargeBinary, nullable=True) type = db.Column(db.Enum('CURRENT', 'FUTURE', 'TEMPORARY', name='rnkword_type'), nullable=False, server_default='CURRENT', primary_key=True) bibrec = db.relationship(Bibrec, backref='word01rs') class RnkEXTENDEDAUTHORS(db.Model): """Represent a RnkEXTENDEDAUTHORS record.""" __tablename__ = 'rnkEXTENDEDAUTHORS' id = db.Column(db.Integer(10, unsigned=True), primary_key=True, nullable=False, autoincrement=False) authorid = db.Column(db.BigInteger(10), primary_key=True, nullable=False, autoincrement=False) class RnkRECORDSCACHE(db.Model): """Represent a RnkRECORDSCACHE record.""" __tablename__ = 'rnkRECORDSCACHE' id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), nullable=True, primary_key=True) authorid = db.Column(db.BigInteger(10), primary_key=True, nullable=False) class RnkSELFCITES(db.Model): """Represent a RnkSELFCITES record.""" __tablename__ = 'rnkSELFCITES' id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), nullable=True, primary_key=True) count = db.Column(db.Integer(10, unsigned=True), nullable=False) references = db.Column(db.Text, nullable=False) last_updated = db.Column(db.DateTime, nullable=False) class RnkSELFCITEDICT(db.Model): """Represents a RnkSELFCITEDICT record.""" __tablename__ = 'rnkSELFCITEDICT' citee = db.Column(db.Integer(10, unsigned=True), nullable=False, primary_key=True, autoincrement=False) citer = db.Column(db.Integer(10, unsigned=True), nullable=False, primary_key=True, autoincrement=False) last_updated = db.Column(db.DateTime, nullable=False) __table_args__ = (db.Index('rnkSELFCITEDICT_reverse', citer, citee), db.Model.__table_args__) class CollectionRnkMETHOD(db.Model): """Represent a CollectionRnkMETHOD record.""" __tablename__ = 'collection_rnkMETHOD' id_collection = db.Column(db.MediumInteger(9, unsigned=True), db.ForeignKey(Collection.id), primary_key=True, nullable=False) id_rnkMETHOD = db.Column(db.MediumInteger(9, unsigned=True), db.ForeignKey(RnkMETHOD.id), primary_key=True, nullable=False) score = db.Column(db.TinyInteger(4, unsigned=True), nullable=False, server_default='0') collection = db.relationship(Collection, backref='rnkMETHODs') rnkMETHOD = db.relationship(RnkMETHOD, backref='collections') __all__ = ('RnkMETHOD', 'RnkMETHODDATA', 'RnkMETHODNAME', 'RnkCITATIONDICT', 'RnkCITATIONDATAERR', 'RnkCITATIONDATAEXT', 'RnkCITATIONLOG', 'RnkAUTHORDATA', 'RnkDOWNLOADS', 'RnkPAGEVIEWS', 'RnkWORD01F', 'RnkWORD01R', 'RnkEXTENDEDAUTHORS', 'RnkRECORDSCACHE', 'RnkSELFCITES', 'RnkSELFCITEDICT', 'CollectionRnkMETHOD', )
zenodo/invenio
invenio/modules/ranker/models.py
Python
gpl-2.0
10,897
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Thierry Sallé (@seuf) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function ANSIBLE_METADATA = { 'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1' } DOCUMENTATION = ''' --- module: grafana_datasource author: - Thierry Sallé (@seuf) version_added: "2.5" short_description: Manage Grafana datasources description: - Create/update/delete Grafana datasources via API. options: grafana_url: description: - The Grafana URL. required: true name: description: - The name of the datasource. required: true ds_type: description: - The type of the datasource. required: true choices: [ elasticsearch, graphite, influxdb, mysql, opentsdb, postgres, prometheus ] url: description: - The URL of the datasource. required: true access: description: - The access mode for this datasource. choices: [ direct, proxy ] default: proxy grafana_user: description: - The Grafana API user. default: admin grafana_password: description: - The Grafana API password. default: admin grafana_api_key: description: - The Grafana API key. - If set, C(grafana_user) and C(grafana_password) will be ignored. database: description: - Name of the database for the datasource. - This options is required when the C(ds_type) is C(influxdb), C(elasticsearch) (index name), C(mysql) or C(postgres). required: false user: description: - The datasource login user for influxdb datasources. password: description: - The datasource password basic_auth_user: description: - The datasource basic auth user. - Setting this option with basic_auth_password will enable basic auth. basic_auth_password: description: - The datasource basic auth password, when C(basic auth) is C(yes). with_credentials: description: - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type: bool default: 'no' tls_client_cert: description: - The client TLS certificate. - If C(tls_client_cert) and C(tls_client_key) are set, this will enable TLS authentication. - Starts with ----- BEGIN CERTIFICATE ----- tls_client_key: description: - The client TLS private key - Starts with ----- BEGIN RSA PRIVATE KEY ----- tls_ca_cert: description: - The TLS CA certificate for self signed certificates. - Only used when C(tls_client_cert) and C(tls_client_key) are set. tls_skip_verify: description: - Skip the TLS datasource certificate verification. type: bool default: False version_added: 2.6 is_default: description: - Make this datasource the default one. type: bool default: 'no' org_id: description: - Grafana Organisation ID in which the datasource should be created. - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only belong to one organisation. default: 1 state: description: - Status of the datasource choices: [ absent, present ] default: present es_version: description: - Elasticsearch version (for C(ds_type = elasticsearch) only) - Version 56 is for elasticsearch 5.6+ where tou can specify the C(max_concurrent_shard_requests) option. choices: [ 2, 5, 56 ] default: 5 max_concurrent_shard_requests: description: - Starting with elasticsearch 5.6, you can specify the max concurrent shard per requests. default: 256 time_field: description: - Name of the time field in elasticsearch ds. - For example C(@timestamp) default: timestamp time_interval: description: - Minimum group by interval for C(influxdb) or C(elasticsearch) datasources. - for example C(>10s) interval: description: - For elasticsearch C(ds_type), this is the index pattern used. choices: ['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'] tsdb_version: description: - The opentsdb version. - Use C(1) for <=2.1, C(2) for ==2.2, C(3) for ==2.3. choices: [ 1, 2, 3 ] default: 1 tsdb_resolution: description: - The opentsdb time resolution. choices: [ millisecond, second ] default: second sslmode: description: - SSL mode for C(postgres) datasoure type. choices: [ disable, require, verify-ca, verify-full ] validate_certs: description: - Whether to validate the Grafana certificate. type: bool default: 'yes' ''' EXAMPLES = ''' --- - name: Create elasticsearch datasource grafana_datasource: name: "datasource-elastic" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "elasticisearch" url: "https://elastic.company.com:9200" database: "[logstash_]YYYY.MM.DD" basic_auth_user: "grafana" basic_auth_password: "******" time_field: "@timestamp" time_interval: "1m" interval: "Daily" es_version: 56 max_concurrent_shard_requests: 42 tls_ca_cert: "/etc/ssl/certs/ca.pem" - name: Create influxdb datasource grafana_datasource: name: "datasource-influxdb" grafana_url: "https://grafana.company.com" grafana_user: "admin" grafana_password: "xxxxxx" org_id: "1" ds_type: "influxdb" url: "https://influx.company.com:8086" database: "telegraf" time_interval: ">10s" tls_ca_cert: "/etc/ssl/certs/ca.pem" ''' RETURN = ''' --- name: description: name of the datasource created. returned: success type: string sample: test-ds id: description: Id of the datasource returned: success type: int sample: 42 before: description: datasource returned by grafana api returned: changed type: dict sample: { "access": "proxy", "basicAuth": false, "database": "test_*", "id": 1035, "isDefault": false, "jsonData": { "esVersion": 5, "timeField": "@timestamp", "timeInterval": "1m", }, "name": "grafana_datasource_test", "orgId": 1, "type": "elasticsearch", "url": "http://elastic.company.com:9200", "user": "", "password": "", "withCredentials": false } after: description: datasource updated by module returned: changed type: dict sample: { "access": "proxy", "basicAuth": false, "database": "test_*", "id": 1035, "isDefault": false, "jsonData": { "esVersion": 5, "timeField": "@timestamp", "timeInterval": "10s", }, "name": "grafana_datasource_test", "orgId": 1, "type": "elasticsearch", "url": "http://elastic.company.com:9200", "user": "", "password": "", "withCredentials": false } ''' import json import base64 from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url from ansible.module_utils._text import to_bytes __metaclass__ = type class GrafanaAPIException(Exception): pass def grafana_switch_organisation(module, grafana_url, org_id, headers): r, info = fetch_url(module, '%s/api/user/using/%d' % (grafana_url, org_id), headers=headers, method='POST') if info['status'] != 200: raise GrafanaAPIException('Unable to switch to organization %s : %s' % (org_id, info)) def grafana_datasource_exists(module, grafana_url, name, headers): datasource_exists = False ds = {} r, info = fetch_url(module, '%s/api/datasources/name/%s' % (grafana_url, name), headers=headers, method='GET') if info['status'] == 200: datasource_exists = True ds = json.loads(r.read()) elif info['status'] == 404: datasource_exists = False else: raise GrafanaAPIException('Unable to get datasource %s : %s' % (name, info)) return datasource_exists, ds def grafana_create_datasource(module, data): # define data payload for grafana API payload = {'orgId': data['org_id'], 'name': data['name'], 'type': data['ds_type'], 'access': data['access'], 'url': data['url'], 'database': data['database'], 'withCredentials': data['with_credentials'], 'isDefault': data['is_default'], 'user': data['user'], 'password': data['password']} # define basic auth if 'basic_auth_user' in data and data['basic_auth_user'] and 'basic_auth_password' in data and data['basic_auth_password']: payload['basicAuth'] = True payload['basicAuthUser'] = data['basic_auth_user'] payload['basicAuthPassword'] = data['basic_auth_password'] else: payload['basicAuth'] = False # define tls auth json_data = {} if data.get('tls_client_cert') and data.get('tls_client_key'): json_data['tlsAuth'] = True if data.get('tls_ca_cert'): payload['secureJsonData'] = { 'tlsCACert': data['tls_ca_cert'], 'tlsClientCert': data['tls_client_cert'], 'tlsClientKey': data['tls_client_key'] } json_data['tlsAuthWithCACert'] = True else: payload['secureJsonData'] = { 'tlsClientCert': data['tls_client_cert'], 'tlsClientKey': data['tls_client_key'] } else: json_data['tlsAuth'] = False json_data['tlsAuthWithCACert'] = False if data.get('tls_ca_cert'): payload['secureJsonData'] = { 'tlsCACert': data['tls_ca_cert'] } if data.get('tls_skip_verify'): json_data['tlsSkipVerify'] = True # datasource type related parameters if data['ds_type'] == 'elasticsearch': json_data['esVersion'] = data['es_version'] json_data['timeField'] = data['time_field'] if data.get('interval'): json_data['interval'] = data['interval'] if data['es_version'] >= 56: json_data['maxConcurrentShardRequests'] = data['max_concurrent_shard_requests'] if data['ds_type'] == 'elasticsearch' or data['ds_type'] == 'influxdb': if data.get('time_interval'): json_data['timeInterval'] = data['time_interval'] if data['ds_type'] == 'opentsdb': json_data['tsdbVersion'] = data['tsdb_version'] if data['tsdb_resolution'] == 'second': json_data['tsdbResolution'] = 1 else: json_data['tsdbResolution'] = 2 if data['ds_type'] == 'postgres': json_data['sslmode'] = data['sslmode'] payload['jsonData'] = json_data # define http header headers = {'content-type': 'application/json; charset=utf8'} if 'grafana_api_key' in data and data['grafana_api_key'] is not None: headers['Authorization'] = "Bearer %s" % data['grafana_api_key'] else: auth = base64.b64encode(to_bytes('%s:%s' % (data['grafana_user'], data['grafana_password'])).replace('\n', '')) headers['Authorization'] = 'Basic %s' % auth grafana_switch_organisation(module, data['grafana_url'], data['org_id'], headers) # test if datasource already exists datasource_exists, ds = grafana_datasource_exists(module, data['grafana_url'], data['name'], headers=headers) result = {} if datasource_exists is True: del ds['typeLogoUrl'] if ds['basicAuth'] is False: del ds['basicAuthUser'] del ds['basicAuthPassword'] if 'jsonData' in ds: if 'tlsAuth' in ds['jsonData'] and ds['jsonData']['tlsAuth'] is False: del ds['secureJsonFields'] if 'tlsAuth' not in ds['jsonData']: del ds['secureJsonFields'] payload['id'] = ds['id'] if ds == payload: # unchanged result['name'] = data['name'] result['id'] = ds['id'] result['msg'] = "Datasource %s unchanged." % data['name'] result['changed'] = False else: # update r, info = fetch_url(module, '%s/api/datasources/%d' % (data['grafana_url'], ds['id']), data=json.dumps(payload), headers=headers, method='PUT') if info['status'] == 200: res = json.loads(r.read()) result['name'] = data['name'] result['id'] = ds['id'] result['before'] = ds result['after'] = payload result['msg'] = "Datasource %s updated %s" % (data['name'], res['message']) result['changed'] = True else: raise GrafanaAPIException('Unable to update the datasource id %d : %s' % (ds['id'], info)) else: # create r, info = fetch_url(module, '%s/api/datasources' % data['grafana_url'], data=json.dumps(payload), headers=headers, method='POST') if info['status'] == 200: res = json.loads(r.read()) result['msg'] = "Datasource %s created : %s" % (data['name'], res['message']) result['changed'] = True result['name'] = data['name'] result['id'] = res['id'] else: raise GrafanaAPIException('Unable to create the new datasource %s : %s - %s.' % (data['name'], info['status'], info)) return result def grafana_delete_datasource(module, data): # define http headers headers = {'content-type': 'application/json'} if 'grafana_api_key' in data and data['grafana_api_key']: headers['Authorization'] = "Bearer %s" % data['grafana_api_key'] else: auth = base64.b64encode(to_bytes('%s:%s' % (data['grafana_user'], data['grafana_password'])).replace('\n', '')) headers['Authorization'] = 'Basic %s' % auth grafana_switch_organisation(module, data['grafana_url'], data['org_id'], headers) # test if datasource already exists datasource_exists, ds = grafana_datasource_exists(module, data['grafana_url'], data['name'], headers=headers) result = {} if datasource_exists is True: # delete r, info = fetch_url(module, '%s/api/datasources/name/%s' % (data['grafana_url'], data['name']), headers=headers, method='DELETE') if info['status'] == 200: res = json.loads(r.read()) result['msg'] = "Datasource %s deleted : %s" % (data['name'], res['message']) result['changed'] = True result['name'] = data['name'] result['id'] = 0 else: raise GrafanaAPIException('Unable to update the datasource id %s : %s' % (ds['id'], info)) else: # datasource does not exist, do nothing result = {'msg': "Datasource %s does not exist." % data['name'], 'changed': False, 'id': 0, 'name': data['name']} return result def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str'), state=dict(choices=['present', 'absent'], default='present'), grafana_url=dict(required=True, type='str'), ds_type=dict(choices=['graphite', 'prometheus', 'elasticsearch', 'influxdb', 'opentsdb', 'mysql', 'postgres']), url=dict(required=True, type='str'), access=dict(default='proxy', choices=['proxy', 'direct']), grafana_user=dict(default='admin'), grafana_password=dict(default='admin', no_log=True), grafana_api_key=dict(type='str', no_log=True), database=dict(type='str'), user=dict(default='', type='str'), password=dict(default='', no_log=True, type='str'), basic_auth_user=dict(type='str'), basic_auth_password=dict(type='str', no_log=True), with_credentials=dict(default=False, type='bool'), tls_client_cert=dict(type='str', no_log=True), tls_client_key=dict(type='str', no_log=True), tls_ca_cert=dict(type='str', no_log=True), tls_skip_verify=dict(type='bool', default=False), is_default=dict(default=False, type='bool'), org_id=dict(default=1, type='int'), es_version=dict(type='int', default=5, choices=[2, 5, 56]), max_concurrent_shard_requests=dict(type='int', default=256), time_field=dict(default='@timestamp', type='str'), time_interval=dict(type='str'), interval=dict(type='str', choices=['', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'], default=''), tsdb_version=dict(type='int', default=1, choices=[1, 2, 3]), tsdb_resolution=dict(type='str', default='second', choices=['second', 'millisecond']), sslmode=dict(default='disable', choices=['disable', 'require', 'verify-ca', 'verify-full']), validate_certs=dict(type='bool', default=True) ), supports_check_mode=False, required_together=[['grafana_user', 'grafana_password', 'org_id'], ['tls_client_cert', 'tls_client_key']], mutually_exclusive=[['grafana_user', 'grafana_api_key'], ['tls_ca_cert', 'tls_skip_verify']], required_if=[ ['ds_type', 'opentsdb', ['tsdb_version', 'tsdb_resolution']], ['ds_type', 'influxdb', ['database']], ['ds_type', 'elasticsearch', ['database', 'es_version', 'time_field', 'interval']], ['ds_type', 'mysql', ['database']], ['ds_type', 'postgres', ['database', 'sslmode']], ['es_version', 56, ['max_concurrent_shard_requests']] ], ) try: if module.params['state'] == 'present': result = grafana_create_datasource(module, module.params) else: result = grafana_delete_datasource(module, module.params) except GrafanaAPIException as e: module.fail_json( failed=True, msg="error %s : %s " % (type(e), e) ) return module.exit_json( failed=False, **result ) return if __name__ == '__main__': main()
KohlsTechnology/ansible
lib/ansible/modules/monitoring/grafana_datasource.py
Python
gpl-3.0
18,623
#!/usr/bin/python # encoding: utf-8 # Copyright: (c) 2012, Matt Wright <matt@nobien.net> # Copyright: (c) 2013, Alexander Saltanov <asd@mokote.com> # Copyright: (c) 2014, Rutger Spiertz <rutger@kumina.nl> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: apt_repository short_description: Add and remove APT repositories description: - Add or remove an APT repositories in Ubuntu and Debian. extends_documentation_fragment: action_common_attributes attributes: check_mode: support: full diff_mode: support: full platform: platforms: debian notes: - This module supports Debian Squeeze (version 6) as well as its successors and derivatives. options: repo: description: - A source string for the repository. type: str required: true state: description: - A source string state. type: str choices: [ absent, present ] default: "present" mode: description: - The octal mode for newly created files in sources.list.d. - Default is what system uses (probably 0644). type: raw version_added: "1.6" update_cache: description: - Run the equivalent of C(apt-get update) when a change occurs. Cache updates are run after making changes. type: bool default: "yes" aliases: [ update-cache ] update_cache_retries: description: - Amount of retries if the cache update fails. Also see I(update_cache_retry_max_delay). type: int default: 5 version_added: '2.10' update_cache_retry_max_delay: description: - Use an exponential backoff delay for each retry (see I(update_cache_retries)) up to this max delay in seconds. type: int default: 12 version_added: '2.10' validate_certs: description: - If C(no), SSL certificates for the target repo will not be validated. This should only be used on personally controlled sites using self-signed certificates. type: bool default: 'yes' version_added: '1.8' filename: description: - Sets the name of the source list file in sources.list.d. Defaults to a file name based on the repository source url. The .list extension will be automatically added. type: str version_added: '2.1' codename: description: - Override the distribution codename to use for PPA repositories. Should usually only be set when working with a PPA on a non-Ubuntu target (for example, Debian or Mint). type: str version_added: '2.3' install_python_apt: description: - Whether to automatically try to install the Python apt library or not, if it is not already installed. Without this library, the module does not work. - Runs C(apt-get install python-apt) for Python 2, and C(apt-get install python3-apt) for Python 3. - Only works with the system Python 2 or Python 3. If you are using a Python on the remote that is not the system Python, set I(install_python_apt=false) and ensure that the Python apt library for your Python version is installed some other way. type: bool default: true author: - Alexander Saltanov (@sashka) version_added: "0.7" requirements: - python-apt (python 2) - python3-apt (python 3) ''' EXAMPLES = ''' - name: Add specified repository into sources list ansible.builtin.apt_repository: repo: deb http://archive.canonical.com/ubuntu hardy partner state: present - name: Add specified repository into sources list using specified filename ansible.builtin.apt_repository: repo: deb http://dl.google.com/linux/chrome/deb/ stable main state: present filename: google-chrome - name: Add source repository into sources list ansible.builtin.apt_repository: repo: deb-src http://archive.canonical.com/ubuntu hardy partner state: present - name: Remove specified repository from sources list ansible.builtin.apt_repository: repo: deb http://archive.canonical.com/ubuntu hardy partner state: absent - name: Add nginx stable repository from PPA and install its signing key on Ubuntu target ansible.builtin.apt_repository: repo: ppa:nginx/stable - name: Add nginx stable repository from PPA and install its signing key on Debian target ansible.builtin.apt_repository: repo: 'ppa:nginx/stable' codename: trusty ''' RETURN = '''#''' import glob import json import os import re import sys import tempfile import copy import random import time from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.respawn import has_respawned, probe_interpreters_for_module, respawn_module from ansible.module_utils._text import to_native from ansible.module_utils.six import PY3 from ansible.module_utils.urls import fetch_url # init module names to keep pylint happy apt = apt_pkg = aptsources_distro = distro = None try: import apt import apt_pkg import aptsources.distro as aptsources_distro distro = aptsources_distro.get_distro() HAVE_PYTHON_APT = True except ImportError: HAVE_PYTHON_APT = False DEFAULT_SOURCES_PERM = 0o0644 VALID_SOURCE_TYPES = ('deb', 'deb-src') def install_python_apt(module, apt_pkg_name): if not module.check_mode: apt_get_path = module.get_bin_path('apt-get') if apt_get_path: rc, so, se = module.run_command([apt_get_path, 'update']) if rc != 0: module.fail_json(msg="Failed to auto-install %s. Error was: '%s'" % (apt_pkg_name, se.strip())) rc, so, se = module.run_command([apt_get_path, 'install', apt_pkg_name, '-y', '-q']) if rc != 0: module.fail_json(msg="Failed to auto-install %s. Error was: '%s'" % (apt_pkg_name, se.strip())) else: module.fail_json(msg="%s must be installed to use check mode" % apt_pkg_name) class InvalidSource(Exception): pass # Simple version of aptsources.sourceslist.SourcesList. # No advanced logic and no backups inside. class SourcesList(object): def __init__(self, module): self.module = module self.files = {} # group sources by file # Repositories that we're adding -- used to implement mode param self.new_repos = set() self.default_file = self._apt_cfg_file('Dir::Etc::sourcelist') # read sources.list if it exists if os.path.isfile(self.default_file): self.load(self.default_file) # read sources.list.d for file in glob.iglob('%s/*.list' % self._apt_cfg_dir('Dir::Etc::sourceparts')): self.load(file) def __iter__(self): '''Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped.''' for file, sources in self.files.items(): for n, valid, enabled, source, comment in sources: if valid: yield file, n, enabled, source, comment def _expand_path(self, filename): if '/' in filename: return filename else: return os.path.abspath(os.path.join(self._apt_cfg_dir('Dir::Etc::sourceparts'), filename)) def _suggest_filename(self, line): def _cleanup_filename(s): filename = self.module.params['filename'] if filename is not None: return filename return '_'.join(re.sub('[^a-zA-Z0-9]', ' ', s).split()) def _strip_username_password(s): if '@' in s: s = s.split('@', 1) s = s[-1] return s # Drop options and protocols. line = re.sub(r'\[[^\]]+\]', '', line) line = re.sub(r'\w+://', '', line) # split line into valid keywords parts = [part for part in line.split() if part not in VALID_SOURCE_TYPES] # Drop usernames and passwords parts[0] = _strip_username_password(parts[0]) return '%s.list' % _cleanup_filename(' '.join(parts[:1])) def _parse(self, line, raise_if_invalid_or_disabled=False): valid = False enabled = True source = '' comment = '' line = line.strip() if line.startswith('#'): enabled = False line = line[1:] # Check for another "#" in the line and treat a part after it as a comment. i = line.find('#') if i > 0: comment = line[i + 1:].strip() line = line[:i] # Split a source into substring to make sure that it is source spec. # Duplicated whitespaces in a valid source spec will be removed. source = line.strip() if source: chunks = source.split() if chunks[0] in VALID_SOURCE_TYPES: valid = True source = ' '.join(chunks) if raise_if_invalid_or_disabled and (not valid or not enabled): raise InvalidSource(line) return valid, enabled, source, comment @staticmethod def _apt_cfg_file(filespec): ''' Wrapper for `apt_pkg` module for running with Python 2.5 ''' try: result = apt_pkg.config.find_file(filespec) except AttributeError: result = apt_pkg.Config.FindFile(filespec) return result @staticmethod def _apt_cfg_dir(dirspec): ''' Wrapper for `apt_pkg` module for running with Python 2.5 ''' try: result = apt_pkg.config.find_dir(dirspec) except AttributeError: result = apt_pkg.Config.FindDir(dirspec) return result def load(self, file): group = [] f = open(file, 'r') for n, line in enumerate(f): valid, enabled, source, comment = self._parse(line) group.append((n, valid, enabled, source, comment)) self.files[file] = group def save(self): for filename, sources in list(self.files.items()): if sources: d, fn = os.path.split(filename) try: os.makedirs(d) except OSError as err: if not os.path.isdir(d): self.module.fail_json("Failed to create directory %s: %s" % (d, to_native(err))) fd, tmp_path = tempfile.mkstemp(prefix=".%s-" % fn, dir=d) f = os.fdopen(fd, 'w') for n, valid, enabled, source, comment in sources: chunks = [] if not enabled: chunks.append('# ') chunks.append(source) if comment: chunks.append(' # ') chunks.append(comment) chunks.append('\n') line = ''.join(chunks) try: f.write(line) except IOError as err: self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, to_native(err))) self.module.atomic_move(tmp_path, filename) # allow the user to override the default mode if filename in self.new_repos: this_mode = self.module.params.get('mode', DEFAULT_SOURCES_PERM) self.module.set_mode_if_different(filename, this_mode, False) else: del self.files[filename] if os.path.exists(filename): os.remove(filename) def dump(self): dumpstruct = {} for filename, sources in self.files.items(): if sources: lines = [] for n, valid, enabled, source, comment in sources: chunks = [] if not enabled: chunks.append('# ') chunks.append(source) if comment: chunks.append(' # ') chunks.append(comment) chunks.append('\n') lines.append(''.join(chunks)) dumpstruct[filename] = ''.join(lines) return dumpstruct def _choice(self, new, old): if new is None: return old return new def modify(self, file, n, enabled=None, source=None, comment=None): ''' This function to be used with iterator, so we don't care of invalid sources. If source, enabled, or comment is None, original value from line ``n`` will be preserved. ''' valid, enabled_old, source_old, comment_old = self.files[file][n][1:] self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old)) def _add_valid_source(self, source_new, comment_new, file): # We'll try to reuse disabled source if we have it. # If we have more than one entry, we will enable them all - no advanced logic, remember. found = False for filename, n, enabled, source, comment in self: if source == source_new: self.modify(filename, n, enabled=True) found = True if not found: if file is None: file = self.default_file else: file = self._expand_path(file) if file not in self.files: self.files[file] = [] files = self.files[file] files.append((len(files), True, True, source_new, comment_new)) self.new_repos.add(file) def add_source(self, line, comment='', file=None): source = self._parse(line, raise_if_invalid_or_disabled=True)[2] # Prefer separate files for new sources. self._add_valid_source(source, comment, file=file or self._suggest_filename(source)) def _remove_valid_source(self, source): # If we have more than one entry, we will remove them all (not comment, remove!) for filename, n, enabled, src, comment in self: if source == src and enabled: self.files[filename].pop(n) def remove_source(self, line): source = self._parse(line, raise_if_invalid_or_disabled=True)[2] self._remove_valid_source(source) class UbuntuSourcesList(SourcesList): LP_API = 'https://launchpad.net/api/1.0/~%s/+archive/%s' def __init__(self, module, add_ppa_signing_keys_callback=None): self.module = module self.add_ppa_signing_keys_callback = add_ppa_signing_keys_callback self.codename = module.params['codename'] or distro.codename super(UbuntuSourcesList, self).__init__(module) def __deepcopy__(self, memo=None): return UbuntuSourcesList( self.module, add_ppa_signing_keys_callback=self.add_ppa_signing_keys_callback ) def _get_ppa_info(self, owner_name, ppa_name): lp_api = self.LP_API % (owner_name, ppa_name) headers = dict(Accept='application/json') response, info = fetch_url(self.module, lp_api, headers=headers) if info['status'] != 200: self.module.fail_json(msg="failed to fetch PPA information, error was: %s" % info['msg']) return json.loads(to_native(response.read())) def _expand_ppa(self, path): ppa = path.split(':')[1] ppa_owner = ppa.split('/')[0] try: ppa_name = ppa.split('/')[1] except IndexError: ppa_name = 'ppa' line = 'deb http://ppa.launchpad.net/%s/%s/ubuntu %s main' % (ppa_owner, ppa_name, self.codename) return line, ppa_owner, ppa_name def _key_already_exists(self, key_fingerprint): rc, out, err = self.module.run_command('apt-key export %s' % key_fingerprint, check_rc=True) return len(err) == 0 def add_source(self, line, comment='', file=None): if line.startswith('ppa:'): source, ppa_owner, ppa_name = self._expand_ppa(line) if source in self.repos_urls: # repository already exists return if self.add_ppa_signing_keys_callback is not None: info = self._get_ppa_info(ppa_owner, ppa_name) if not self._key_already_exists(info['signing_key_fingerprint']): command = ['apt-key', 'adv', '--recv-keys', '--no-tty', '--keyserver', 'hkp://keyserver.ubuntu.com:80', info['signing_key_fingerprint']] self.add_ppa_signing_keys_callback(command) file = file or self._suggest_filename('%s_%s' % (line, self.codename)) else: source = self._parse(line, raise_if_invalid_or_disabled=True)[2] file = file or self._suggest_filename(source) self._add_valid_source(source, comment, file) def remove_source(self, line): if line.startswith('ppa:'): source = self._expand_ppa(line)[0] else: source = self._parse(line, raise_if_invalid_or_disabled=True)[2] self._remove_valid_source(source) @property def repos_urls(self): _repositories = [] for parsed_repos in self.files.values(): for parsed_repo in parsed_repos: valid = parsed_repo[1] enabled = parsed_repo[2] source_line = parsed_repo[3] if not valid or not enabled: continue if source_line.startswith('ppa:'): source, ppa_owner, ppa_name = self._expand_ppa(source_line) _repositories.append(source) else: _repositories.append(source_line) return _repositories def get_add_ppa_signing_key_callback(module): def _run_command(command): module.run_command(command, check_rc=True) if module.check_mode: return None else: return _run_command def revert_sources_list(sources_before, sources_after, sourceslist_before): '''Revert the sourcelist files to their previous state.''' # First remove any new files that were created: for filename in set(sources_after.keys()).difference(sources_before.keys()): if os.path.exists(filename): os.remove(filename) # Now revert the existing files to their former state: sourceslist_before.save() def main(): module = AnsibleModule( argument_spec=dict( repo=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), mode=dict(type='raw'), update_cache=dict(type='bool', default=True, aliases=['update-cache']), update_cache_retries=dict(type='int', default=5), update_cache_retry_max_delay=dict(type='int', default=12), filename=dict(type='str'), # This should not be needed, but exists as a failsafe install_python_apt=dict(type='bool', default=True), validate_certs=dict(type='bool', default=True), codename=dict(type='str'), ), supports_check_mode=True, ) params = module.params repo = module.params['repo'] state = module.params['state'] update_cache = module.params['update_cache'] # Note: mode is referenced in SourcesList class via the passed in module (self here) sourceslist = None if not HAVE_PYTHON_APT: # This interpreter can't see the apt Python library- we'll do the following to try and fix that: # 1) look in common locations for system-owned interpreters that can see it; if we find one, respawn under it # 2) finding none, try to install a matching python-apt package for the current interpreter version; # we limit to the current interpreter version to try and avoid installing a whole other Python just # for apt support # 3) if we installed a support package, try to respawn under what we think is the right interpreter (could be # the current interpreter again, but we'll let it respawn anyway for simplicity) # 4) if still not working, return an error and give up (some corner cases not covered, but this shouldn't be # made any more complex than it already is to try and cover more, eg, custom interpreters taking over # system locations) apt_pkg_name = 'python3-apt' if PY3 else 'python-apt' if has_respawned(): # this shouldn't be possible; short-circuit early if it happens... module.fail_json(msg="{0} must be installed and visible from {1}.".format(apt_pkg_name, sys.executable)) interpreters = ['/usr/bin/python3', '/usr/bin/python2', '/usr/bin/python'] interpreter = probe_interpreters_for_module(interpreters, 'apt') if interpreter: # found the Python bindings; respawn this module under the interpreter where we found them respawn_module(interpreter) # this is the end of the line for this process, it will exit here once the respawned module has completed # don't make changes if we're in check_mode if module.check_mode: module.fail_json(msg="%s must be installed to use check mode. " "If run normally this module can auto-install it." % apt_pkg_name) if params['install_python_apt']: install_python_apt(module, apt_pkg_name) else: module.fail_json(msg='%s is not installed, and install_python_apt is False' % apt_pkg_name) # try again to find the bindings in common places interpreter = probe_interpreters_for_module(interpreters, 'apt') if interpreter: # found the Python bindings; respawn this module under the interpreter where we found them # NB: respawn is somewhat wasteful if it's this interpreter, but simplifies the code respawn_module(interpreter) # this is the end of the line for this process, it will exit here once the respawned module has completed else: # we've done all we can do; just tell the user it's busted and get out module.fail_json(msg="{0} must be installed and visible from {1}.".format(apt_pkg_name, sys.executable)) if not repo: module.fail_json(msg='Please set argument \'repo\' to a non-empty value') if isinstance(distro, aptsources_distro.Distribution): sourceslist = UbuntuSourcesList(module, add_ppa_signing_keys_callback=get_add_ppa_signing_key_callback(module)) else: module.fail_json(msg='Module apt_repository is not supported on target.') sourceslist_before = copy.deepcopy(sourceslist) sources_before = sourceslist.dump() try: if state == 'present': sourceslist.add_source(repo) elif state == 'absent': sourceslist.remove_source(repo) except InvalidSource as err: module.fail_json(msg='Invalid repository string: %s' % to_native(err)) sources_after = sourceslist.dump() changed = sources_before != sources_after if changed and module._diff: diff = [] for filename in set(sources_before.keys()).union(sources_after.keys()): diff.append({'before': sources_before.get(filename, ''), 'after': sources_after.get(filename, ''), 'before_header': (filename, '/dev/null')[filename not in sources_before], 'after_header': (filename, '/dev/null')[filename not in sources_after]}) else: diff = {} if changed and not module.check_mode: try: sourceslist.save() if update_cache: err = '' update_cache_retries = module.params.get('update_cache_retries') update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay') randomize = random.randint(0, 1000) / 1000.0 for retry in range(update_cache_retries): try: cache = apt.Cache() cache.update() break except apt.cache.FetchFailedException as e: err = to_native(e) # Use exponential backoff with a max fail count, plus a little bit of randomness delay = 2 ** retry + randomize if delay > update_cache_retry_max_delay: delay = update_cache_retry_max_delay + randomize time.sleep(delay) else: revert_sources_list(sources_before, sources_after, sourceslist_before) module.fail_json(msg='Failed to update apt cache: %s' % (err if err else 'unknown reason')) except (OSError, IOError) as err: revert_sources_list(sources_before, sources_after, sourceslist_before) module.fail_json(msg=to_native(err)) module.exit_json(changed=changed, repo=repo, state=state, diff=diff) if __name__ == '__main__': main()
srvg/ansible
lib/ansible/modules/apt_repository.py
Python
gpl-3.0
25,568
import agoclient client = agoclient.AgoConnection("test") def messageHandler(internalid, content): if "command" in content: if content["command"] == "test": retval = {} retval["hallo"] = "blah" return retval return {} client.addHandler(messageHandler) client.addDevice("123", "test") client.run()
JoakimLindbom/agocontrol
test/test-device.py
Python
gpl-3.0
311
from __future__ import unicode_literals def execute(): import webnotes from webnotes.modules import reload_doc reload_doc('stock', 'doctype', 'serial_no') webnotes.conn.sql("update `tabSerial No` set sle_exists = 1")
gangadhar-kadam/mtn-erpnext
patches/april_2012/serial_no_fixes.py
Python
agpl-3.0
222
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('xblock_django.models', 'common.djangoapps.xblock_django.models') from common.djangoapps.xblock_django.models import *
eduNEXT/edunext-platform
import_shims/studio/xblock_django/models.py
Python
agpl-3.0
389
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PySphinxcontribTrio(PythonPackage): """This sphinx extension helps you document Python code that uses async/await, or abstract methods, or context managers, or generators, or ... you get the idea.""" homepage = "https://github.com/python-trio/sphinxcontrib-trio" pypi = "sphinxcontrib-trio/sphinxcontrib-trio-1.1.2.tar.gz" version('1.1.2', sha256='9f1ba9c1d5965b534e85258d8b677dd94e9b1a9a2e918b85ccd42590596b47c0') version('1.1.0', sha256='d90f46d239ba0556e53d9a110989f98c9eb2cea76ab47937a1f39b62f63fe654') depends_on('py-sphinx@1.7:') patch('sphinxcontrib-trio.patch', when='@1.1.0')
LLNL/spack
var/spack/repos/builtin/packages/py-sphinxcontrib-trio/package.py
Python
lgpl-2.1
851
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLES2 import _types as _cs # End users want this... from OpenGL.raw.GLES2._types import * from OpenGL.raw.GLES2 import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GLES2_NV_shadow_samplers_array' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_NV_shadow_samplers_array',error_checker=_errors._error_checker) GL_SAMPLER_2D_ARRAY_SHADOW_NV=_C('GL_SAMPLER_2D_ARRAY_SHADOW_NV',0x8DC4)
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/raw/GLES2/NV/shadow_samplers_array.py
Python
lgpl-3.0
601
# -*- coding: utf-8 -*- from cms.management.commands.subcommands.base import SubcommandsCommand from cms.models.pluginmodel import CMSPlugin from cms.models.titlemodels import Title from cms.plugin_pool import plugin_pool from django.core.management.base import NoArgsCommand from django.db.utils import DatabaseError class ListApphooksCommand(NoArgsCommand): help = 'Lists all apphooks in pages' def handle_noargs(self, **options): urls = Title.objects.filter(application_urls__gt='').values_list("application_urls", flat=True) for url in urls: self.stdout.write('%s\n' % url) def plugin_report(): # structure of report: # [ # { # 'type': CMSPlugin class, # 'model': plugin_type.model, # 'instances': instances in the CMSPlugin table, # 'unsaved_instances': those with no corresponding model instance, # }, # ] plugin_report = [] all_plugins = CMSPlugin.objects.order_by("plugin_type") plugin_types = list(set(all_plugins.values_list("plugin_type", flat=True))) plugin_types.sort() for plugin_type in plugin_types: plugin = {} plugin["type"] = plugin_type try: # get all plugins of this type plugins = CMSPlugin.objects.filter(plugin_type=plugin_type) plugin["instances"] = plugins # does this plugin have a model? report unsaved instances plugin["model"] = plugin_pool.get_plugin(name=plugin_type).model unsaved_instances = [p for p in plugins if not p.get_plugin_instance()[0]] plugin["unsaved_instances"] = unsaved_instances # catch uninstalled plugins except KeyError: plugin["model"] = None plugin["instances"] = plugins plugin["unsaved_instances"] = [] plugin_report.append(plugin) return plugin_report class ListPluginsCommand(NoArgsCommand): help = 'Lists all plugins in CMSPlugin' def handle_noargs(self, **options): self.stdout.write("==== Plugin report ==== \n\n") self.stdout.write("There are %s plugin types in your database \n" % len(plugin_report())) for plugin in plugin_report(): self.stdout.write("\n%s \n" % plugin["type"]) plugin_model = plugin["model"] instances = len(plugin["instances"]) unsaved_instances = len(plugin["unsaved_instances"]) if not plugin_model: self.stdout.write(self.style.ERROR(" ERROR : not installed \n")) elif plugin_model == CMSPlugin: self.stdout.write(" model-less plugin \n") self.stdout.write(" unsaved instance(s) : %s \n" % unsaved_instances) else: self.stdout.write(" model : %s.%s \n" % (plugin_model.__module__, plugin_model.__name__)) if unsaved_instances: self.stdout.write(self.style.ERROR(" ERROR : %s unsaved instance(s) \n" % unsaved_instances)) self.stdout.write(" instance(s): %s \n" % instances) class ListCommand(SubcommandsCommand): help = 'List commands' subcommands = { 'apphooks': ListApphooksCommand, 'plugins': ListPluginsCommand }
mpetyx/palmdrop
venv/lib/python2.7/site-packages/cms/management/commands/subcommands/list.py
Python
apache-2.0
3,426
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for exporting utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from official.utils.export import export class ExportUtilsTest(tf.test.TestCase): """Tests for the ExportUtils.""" def test_build_tensor_serving_input_receiver_fn(self): receiver_fn = export.build_tensor_serving_input_receiver_fn(shape=[4, 5]) with tf.Graph().as_default(): receiver = receiver_fn() self.assertIsInstance( receiver, tf.estimator.export.TensorServingInputReceiver) self.assertIsInstance(receiver.features, tf.Tensor) self.assertEqual(receiver.features.shape, tf.TensorShape([1, 4, 5])) self.assertEqual(receiver.features.dtype, tf.float32) self.assertIsInstance(receiver.receiver_tensors, dict) # Note that Python 3 can no longer index .values() directly; cast to list. self.assertEqual(list(receiver.receiver_tensors.values())[0].shape, tf.TensorShape([1, 4, 5])) def test_build_tensor_serving_input_receiver_fn_batch_dtype(self): receiver_fn = export.build_tensor_serving_input_receiver_fn( shape=[4, 5], dtype=tf.int8, batch_size=10) with tf.Graph().as_default(): receiver = receiver_fn() self.assertIsInstance( receiver, tf.estimator.export.TensorServingInputReceiver) self.assertIsInstance(receiver.features, tf.Tensor) self.assertEqual(receiver.features.shape, tf.TensorShape([10, 4, 5])) self.assertEqual(receiver.features.dtype, tf.int8) self.assertIsInstance(receiver.receiver_tensors, dict) # Note that Python 3 can no longer index .values() directly; cast to list. self.assertEqual(list(receiver.receiver_tensors.values())[0].shape, tf.TensorShape([10, 4, 5])) if __name__ == "__main__": tf.test.main()
mlperf/training_results_v0.5
v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/models/official/utils/export/export_test.py
Python
apache-2.0
2,628
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for integer division by zero.""" from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import test_util from tensorflow.python.platform import test class ZeroDivisionTest(test.TestCase): def testZeros(self): with test_util.use_gpu(): for dtype in dtypes.uint8, dtypes.int16, dtypes.int32, dtypes.int64: zero = constant_op.constant(0, dtype=dtype) one = constant_op.constant(1, dtype=dtype) bads = [lambda x, y: x // y] if dtype in (dtypes.int32, dtypes.int64): bads.append(lambda x, y: x % y) for bad in bads: try: result = self.evaluate(bad(one, zero)) except (errors.OpError, errors.InvalidArgumentError) as e: # Ideally, we'd get a nice exception. In theory, this should only # happen on CPU, but 32 bit integer GPU division is actually on # CPU due to a placer bug. # TODO(irving): Make stricter once the placer bug is fixed. self.assertIn('Integer division by zero', str(e)) else: # On the GPU, integer division by zero produces all bits set. # But apparently on some GPUs "all bits set" for 64 bit division # means 32 bits set, so we allow 0xffffffff as well. This isn't # very portable, so we may need to expand this list if other GPUs # do different things. # # XLA constant folds integer division by zero to 1. self.assertTrue(test.is_gpu_available()) self.assertIn(result, (-1, 1, 2, 0xff, 0xffffffff)) if __name__ == '__main__': test.main()
tensorflow/tensorflow
tensorflow/python/kernel_tests/math_ops/zero_division_test.py
Python
apache-2.0
2,457
#!/usr/bin/env python # Copyright 2016 The Kubernetes Authors. # # 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 os import logging from logging.handlers import RotatingFileHandler # pylint: disable=import-error import numpy as np from flask import Flask, request from sklearn.feature_extraction import FeatureHasher from sklearn.externals import joblib from sklearn.linear_model import SGDClassifier from nltk.tokenize import RegexpTokenizer from nltk.stem.porter import PorterStemmer # pylint: enable=import-error APP = Flask(__name__) # parameters TEAM_FN = './models/trained_teams_model.pkl' COMPONENT_FN = './models/trained_components_model.pkl' LOG_FILE = '/tmp/issue-labeler.log' LOG_SIZE = 1024*1024*100 NUM_FEATURES = 262144 MY_LOSS = 'hinge' MY_ALPHA = .1 MY_PENALTY = 'l2' MY_HASHER = FeatureHasher(input_type='string', n_features=NUM_FEATURES, non_negative=True) MY_STEMMER = PorterStemmer() TOKENIZER = RegexpTokenizer(r'\w+') STOPWORDS = [] try: if not STOPWORDS: STOPWORDS_FILENAME = './stopwords.txt' with open(STOPWORDS_FILENAME, 'r') as fp: STOPWORDS = list([word.strip() for word in fp]) except: # pylint:disable=bare-except # don't remove any stopwords STOPWORDS = [] @APP.errorhandler(500) def internal_error(exception): return str(exception), 500 @APP.route("/", methods=['POST']) def get_labels(): """ The request should contain 2 form-urlencoded parameters 1) title : title of the issue 2) body: body of the issue It returns a team/<label> and a component/<label> """ title = request.form.get('title', '') body = request.form.get('body', '') tokens = tokenize_stem_stop(" ".join([title, body])) team_mod = joblib.load(TEAM_FN) comp_mod = joblib.load(COMPONENT_FN) vec = MY_HASHER.transform([tokens]) tlabel = team_mod.predict(vec)[0] clabel = comp_mod.predict(vec)[0] return ",".join([tlabel, clabel]) def tokenize_stem_stop(input_string): input_string = input_string.encode('utf-8') cur_title_body = TOKENIZER.tokenize(input_string.decode('utf-8').lower()) return [MY_STEMMER.stem(x) for x in cur_title_body if x not in STOPWORDS] @APP.route("/update_models", methods=['PUT']) def update_model(): # pylint: disable=too-many-locals """ data should contain three fields titles: list of titles bodies: list of bodies labels: list of list of labels """ data = request.json titles = data.get('titles') bodies = data.get('bodies') labels = data.get('labels') t_tokens = [] c_tokens = [] team_labels = [] component_labels = [] for (title, body, label_list) in zip(titles, bodies, labels): t_label = [x for x in label_list if x.startswith('team')] c_label = [x for x in label_list if x.startswith('component')] tokens = tokenize_stem_stop(" ".join([title, body])) if t_label: team_labels += t_label t_tokens += [tokens] if c_label: component_labels += c_label c_tokens += [tokens] t_vec = MY_HASHER.transform(t_tokens) c_vec = MY_HASHER.transform(c_tokens) if team_labels: if os.path.isfile(TEAM_FN): team_model = joblib.load(TEAM_FN) team_model.partial_fit(t_vec, np.array(team_labels)) else: # no team model stored so build a new one team_model = SGDClassifier(loss=MY_LOSS, penalty=MY_PENALTY, alpha=MY_ALPHA) team_model.fit(t_vec, np.array(team_labels)) if component_labels: if os.path.isfile(COMPONENT_FN): component_model = joblib.load(COMPONENT_FN) component_model.partial_fit(c_vec, np.array(component_labels)) else: # no comp model stored so build a new one component_model = SGDClassifier(loss=MY_LOSS, penalty=MY_PENALTY, alpha=MY_ALPHA) component_model.fit(c_vec, np.array(component_labels)) joblib.dump(team_model, TEAM_FN) joblib.dump(component_model, COMPONENT_FN) return "" def configure_logger(): log_format = '%(asctime)-20s %(levelname)-10s %(message)s' file_handler = RotatingFileHandler(LOG_FILE, maxBytes=LOG_SIZE, backupCount=3) formatter = logging.Formatter(log_format) file_handler.setFormatter(formatter) APP.logger.addHandler(file_handler) if __name__ == "__main__": configure_logger() APP.run(host="0.0.0.0")
foxish/test-infra
mungegithub/issue_labeler/simple_app.py
Python
apache-2.0
4,947
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import logging import os from modellers.MalletLDA import BuildLDA def TrainMallet( corpus_path, model_path, token_regex, num_topics, num_iters, is_quiet, force_overwrite ): logger = logging.getLogger( 'termite' ) logger.addHandler( logging.StreamHandler() ) logger.setLevel( logging.INFO if is_quiet else logging.DEBUG ) corpus_filename = '{}/corpus.txt'.format(corpus_path) logger.info( '--------------------------------------------------------------------------------' ) logger.info( 'Training an LDA topic model using MALLET...' ) logger.info( ' corpus = %s', corpus_filename ) logger.info( ' model = %s', model_path ) logger.info( ' token_regex = %s', token_regex ) logger.info( ' topics = %s', num_topics ) logger.info( ' iters = %s', num_iters ) logger.info( '--------------------------------------------------------------------------------' ) if force_overwrite or not os.path.exists( model_path ): BuildLDA( corpus_filename, model_path, tokenRegex = token_regex, numTopics = num_topics, numIters = num_iters ) else: logger.info( ' Already exists: %s', model_path ) def main(): parser = argparse.ArgumentParser( description = 'Train an LDA topic model using MALLET.' ) parser.add_argument( 'corpus_path' , type = str , help = 'Input folder containing the text corpus as "corpus.txt"' ) parser.add_argument( 'model_path' , type = str , help = 'Output model folder' ) parser.add_argument( '--token-regex', type = str , default = r'\w{3,}' , help = 'Tokenization', dest = 'token_regex' ) parser.add_argument( '--topics' , type = int , default = 20 , help = 'Number of topics' ) parser.add_argument( '--iters' , type = int , default = 1000 , help = 'Number of iterations' ) parser.add_argument( '--quiet' , const = True , default = False , help = 'Show fewer debugging messages', action = 'store_const' ) parser.add_argument( '--overwrite' , const = True , default = False , help = 'Overwrite any existing model', action = 'store_const' ) args = parser.parse_args() TrainMallet( args.corpus_path, args.model_path, args.token_regex, args.topics, args.iters, args.quiet, args.overwrite ) if __name__ == '__main__': main()
maoxuxiang/termite_mallet_project
bin/train_mallet.py
Python
bsd-3-clause
2,344
# -*- coding: utf-8 -*- from cms.models import CMSPlugin from cms.models.fields import PlaceholderField from cms.utils.copy_plugins import copy_plugins_to from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class PlaceholderReference(CMSPlugin): cmsplugin_ptr = models.OneToOneField(CMSPlugin, related_name='cms_placeholderreference', parent_link=True) name = models.CharField(max_length=255) placeholder_ref = PlaceholderField(slotname='clipboard') class Meta: app_label = 'cms' def __str__(self): return self.name def copy_to(self, placeholder, language): copy_plugins_to(self.placeholder_ref.get_plugins(), placeholder, to_language=language) def copy_from(self, placeholder, language): plugins = placeholder.get_plugins(language) return copy_plugins_to(plugins, self.placeholder_ref, to_language=self.language) def move_to(self, placeholder, language): for plugin in self.placeholder_ref.get_plugins(): plugin.placeholder = placeholder plugin.language = language plugin.save() def move_from(self, placeholder, language): for plugin in placeholder.get_plugins(): plugin.placeholder = self.placeholder_ref plugin.language = language plugin.save()
jproffitt/django-cms
cms/models/placeholderpluginmodel.py
Python
bsd-3-clause
1,387
"""Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.""" from __future__ import absolute_import import json import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import PIL.Image import skfmm import digits from digits.utils import subclass, override from digits.utils.constants import COLOR_PALETTE_ATTRIBUTE from .forms import ConfigForm from ..interface import VisualizationInterface CONFIG_TEMPLATE = "config_template.html" HEADER_TEMPLATE = "header_template.html" APP_BEGIN_TEMPLATE = "app_begin_template.html" APP_END_TEMPLATE = "app_end_template.html" VIEW_TEMPLATE = "view_template.html" @subclass class Visualization(VisualizationInterface): """A visualization extension to display the network output as an image.""" def __init__(self, dataset, **kwargs): """Constructor for Visualization class. :param dataset: :type dataset: :param kwargs: :type kwargs: """ # memorize view template for later use extension_dir = os.path.dirname(os.path.abspath(__file__)) self.view_template = open( os.path.join(extension_dir, VIEW_TEMPLATE), "r").read() # view options if kwargs['colormap'] == 'dataset': if COLOR_PALETTE_ATTRIBUTE not in dataset.extension_userdata or \ not dataset.extension_userdata[COLOR_PALETTE_ATTRIBUTE]: raise ValueError("No palette found in dataset - choose other colormap") palette = dataset.extension_userdata[COLOR_PALETTE_ATTRIBUTE] # assume 8-bit RGB palette and convert to N*3 numpy array palette = np.array(palette).reshape((len(palette) / 3, 3)) / 255. # normalize input pixels to [0,1] norm = mpl.colors.Normalize(vmin=0, vmax=255) # create map cmap = mpl.colors.ListedColormap(palette) self.map = plt.cm.ScalarMappable(norm=norm, cmap=cmap) elif kwargs['colormap'] == 'paired': cmap = plt.cm.get_cmap('Paired') self.map = plt.cm.ScalarMappable(norm=None, cmap=cmap) elif kwargs['colormap'] == 'none': self.map = None else: raise ValueError("Unknown color map option: %s" % kwargs['colormap']) # memorize class labels if 'class_labels' in dataset.extension_userdata: self.class_labels = dataset.extension_userdata['class_labels'] else: self.class_labels = None @staticmethod def get_config_form(): """Utility function. returns: ConfigForm(). """ return ConfigForm() @staticmethod def get_config_template(form): """Get the template and context. parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, CONFIG_TEMPLATE), "r").read() return (template, {'form': form}) def get_legend_for(self, found_classes, skip_classes=[]): """Return the legend color image squares and text for each class. :param found_classes: list of class indices :param skip_classes: list of class indices to skip :return: list of dicts of text hex_color for each class """ legend = [] for c in (x for x in found_classes if x not in skip_classes): # create hex color associated with the category ID if self.map: rgb_color = self.map.to_rgba([c])[0, :3] hex_color = mpl.colors.rgb2hex(rgb_color) else: # make a grey scale hex color h = hex(int(c)).split('x')[1].zfill(2) hex_color = '#%s%s%s' % (h, h, h) if self.class_labels: text = self.class_labels[int(c)] else: text = "Class #%d" % c legend.append({'index': c, 'text': text, 'hex_color': hex_color}) return legend @override def get_header_template(self): """Implement get_header_template method from view extension interface.""" extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, HEADER_TEMPLATE), "r").read() return template, {} @override def get_ng_templates(self): """Implement get_ng_templates method from view extension interface.""" extension_dir = os.path.dirname(os.path.abspath(__file__)) header = open(os.path.join(extension_dir, APP_BEGIN_TEMPLATE), "r").read() footer = open(os.path.join(extension_dir, APP_END_TEMPLATE), "r").read() return header, footer @staticmethod def get_id(): """returns: id string that identifies the extension.""" return 'image-segmentation' @staticmethod def get_title(): """returns: name string to display in html.""" return 'Image Segmentation' @staticmethod def get_dirname(): """returns: extension dir name to locate static dir.""" return 'imageSegmentation' @override def get_view_template(self, data): """Get the view template. returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ return self.view_template, { 'input_id': data['input_id'], 'input_image': digits.utils.image.embed_image_html(data['input_image']), 'fill_image': digits.utils.image.embed_image_html(data['fill_image']), 'line_image': digits.utils.image.embed_image_html(data['line_image']), 'seg_image': digits.utils.image.embed_image_html(data['seg_image']), 'mask_image': digits.utils.image.embed_image_html(data['mask_image']), 'legend': data['legend'], 'is_binary': data['is_binary'], 'class_data': json.dumps(data['class_data'].tolist()), } @override def process_data(self, input_id, input_data, output_data): """Process one inference and return data to visualize.""" # assume the only output is a CHW image where C is the number # of classes, H and W are the height and width of the image class_data = output_data[output_data.keys()[0]].astype('float32') # Is this binary segmentation? is_binary = class_data.shape[0] == 2 # retain only the top class for each pixel class_data = np.argmax(class_data, axis=0).astype('uint8') # remember the classes we found found_classes = np.unique(class_data) # convert using color map (assume 8-bit output) if self.map: fill_data = (self.map.to_rgba(class_data) * 255).astype('uint8') else: fill_data = np.ndarray((class_data.shape[0], class_data.shape[1], 4), dtype='uint8') for x in xrange(3): fill_data[:, :, x] = class_data.copy() # Assuming that class 0 is the background mask = np.greater(class_data, 0) fill_data[:, :, 3] = mask * 255 line_data = fill_data.copy() seg_data = fill_data.copy() # Black mask of non-segmented pixels mask_data = np.zeros(fill_data.shape, dtype='uint8') mask_data[:, :, 3] = (1 - mask) * 255 def normalize(array): mn = array.min() mx = array.max() return (array - mn) * 255 / (mx - mn) if (mx - mn) > 0 else array * 255 try: PIL.Image.fromarray(input_data) except TypeError: # If input_data can not be converted to an image, # normalize and convert to uint8 input_data = normalize(input_data).astype('uint8') # Generate outlines around segmented classes if len(found_classes) > 1: # Assuming that class 0 is the background. line_mask = np.zeros(class_data.shape, dtype=bool) max_distance = np.zeros(class_data.shape, dtype=float) + 1 for c in (x for x in found_classes if x != 0): c_mask = np.equal(class_data, c) # Find the signed distance from the zero contour distance = skfmm.distance(c_mask.astype('float32') - 0.5) # Accumulate the mask for all classes line_width = 3 line_mask |= c_mask & np.less(distance, line_width) max_distance = np.maximum(max_distance, distance + 128) line_data[:, :, 3] = line_mask * 255 max_distance = np.maximum(max_distance, np.zeros(max_distance.shape, dtype=float)) max_distance = np.minimum(max_distance, np.zeros(max_distance.shape, dtype=float) + 255) seg_data[:, :, 3] = max_distance # Input image with outlines input_max = input_data.max() input_min = input_data.min() input_range = input_max - input_min if input_range > 255: input_data = (input_data - input_min) * 255.0 / input_range elif input_min < 0: input_data -= input_min input_image = PIL.Image.fromarray(input_data.astype('uint8')) input_image.format = 'png' # Fill image fill_image = PIL.Image.fromarray(fill_data) fill_image.format = 'png' # Fill image line_image = PIL.Image.fromarray(line_data) line_image.format = 'png' # Seg image seg_image = PIL.Image.fromarray(seg_data) seg_image.format = 'png' seg_image.save('seg.png') # Mask image mask_image = PIL.Image.fromarray(mask_data) mask_image.format = 'png' # legend for this instance legend = self.get_legend_for(found_classes, skip_classes=[0]) return { 'input_id': input_id, 'input_image': input_image, 'fill_image': fill_image, 'line_image': line_image, 'seg_image': seg_image, 'mask_image': mask_image, 'legend': legend, 'is_binary': is_binary, 'class_data': class_data, }
ethantang95/DIGITS
digits/extensions/view/imageSegmentation/view.py
Python
bsd-3-clause
10,647
import re from django.conf import settings from django.utils.encoding import smart_bytes from pipeline.compilers import CompilerBase from pipeline.exceptions import CompilerError class BrowserifyCompiler(CompilerBase): output_extension = 'browserified.js' def match_file(self, path): # Allow for cache busting hashes between ".browserify" and ".js" return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None def compile_file(self, infile, outfile, outdated=False, force=False): pipeline_settings = getattr(settings, 'PIPELINE', {}) command = "%s %s %s > %s" % ( pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'), pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''), infile, outfile ) return self.execute_command(command) def execute_command(self, command, content=None, cwd=None): """This is like the one in SubProcessCompiler, except it checks the exit code.""" import subprocess pipe = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if content: content = smart_bytes(content) stdout, stderr = pipe.communicate(content) if self.verbose: print(stderr) if pipe.returncode != 0: raise CompilerError(stderr) return stdout
mythmon/kitsune
kitsune/lib/pipeline_compilers.py
Python
bsd-3-clause
1,506
import os from django.conf import settings from django.http import HttpResponse from django.views.generic import View from knox.auth import TokenAuthentication from rest_framework import status from rest_framework.generics import GenericAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response class IndexView(View): """Render main page.""" def get(self, request): """Return html for main application page.""" abspath = open(os.path.join(settings.BASE_DIR, 'static_dist/index.html'), 'r') return HttpResponse(content=abspath.read()) class ProtectedDataView(GenericAPIView): """Return protected data main page.""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): """Process GET request and return protected data.""" data = { 'data': 'THIS IS THE PROTECTED STRING FROM SERVER', } return Response(data, status=status.HTTP_200_OK)
lroyland/SalaSIS
src/base/views.py
Python
mit
1,044
# coding: utf-8 import re SLUG_REMOVE = re.compile(r'[,\s\.\(\)/\\;:]*') class DatasetException(Exception): pass class FreezeException(DatasetException): pass
Backflipz/plugin.video.excubed
resources/lib/dataset/util.py
Python
gpl-2.0
172
#!/usr/bin/env python # # System.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA import logging log = logging.getLogger("Thug") class System: def __init__(self): pass def getProperty(self, property): if property == "java.version": javaplugin = log.ThugVulnModules._javaplugin.split('.') last = javaplugin.pop() return '%s_%s' % ('.'.join(javaplugin), last) if property == "java.vendor": return 'Sun Microsystems Inc.'
palaniyappanBala/thug
src/Java/System.py
Python
gpl-2.0
1,103
# -*- coding: utf-8 -*- """ Created on Mon Dec 28 02:31:03 2015 @author: winpython """ import os import sys, getopt import time import numpy as np from cnn_training_computation import fit, predict import pickle, cPickle from matplotlib.pyplot import imshow import matplotlib.pyplot as plt from PIL import Image def run(): print '... loading data' test_set = np.zeros((200,147456),dtype=np.float32) pil_im = Image.open( "P_20160109_190757.jpg" ).convert('L') pil_im = pil_im.resize((512, 288), Image.BILINEAR ) pil_im = np.array(pil_im) fig = plt.figure() plotwindow = fig.add_subplot() plt.imshow(pil_im, cmap='gray') plt.show() note = 0 for j in range(288): for k in range(512): test_set[0][note]= ((255 - pil_im[j][k])/225.) note += 1 """ # read the data, labels data = np.genfromtxt("data/mnist_train.data") print ". .", test_data = np.genfromtxt("data/mnist_test.data") print ". .", valid_data = np.genfromtxt("data/mnist_valid.data") labels = np.genfromtxt("data/mnist_train.solution") """ print ". . finished reading" """ # DO argmax labels = np.argmax(labels, axis=1) print labels # normalization amean = np.mean(data) data = data - amean astd = np.std(data) data = data / astd # normalise using coefficients from training data test_data = (test_data - amean) / astd valid_data = (valid_data - amean) / astd """ #fit(data, labels) print "開始預測..." rv = predict(test_set) # UNDO argmax and save results x 2 r = rv N = len(r) res = np.zeros((N, 20)) for i in range(N): res[i][r[i]] = 1 print "==================================================================" print " " print " " print "predict Tag : [ 0 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 19 ]" print " " print " ---------------------------------------------------- " print " " print "predict Value:", print res[0] print res[1] print " " print " " print "==================================================================" #np.savetxt("test.predict", res, fmt='%i') print "finished predicting." if __name__ == '__main__': run()
artmusic0/theano-learning.part02
Myfile_run-py_releasev5_SFMAKE/run_v5.0_predict.py
Python
gpl-3.0
2,332
# Copyright (C) 2007-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Interface for a roster of members.""" __all__ = [ 'IRoster', ] from zope.interface import Interface, Attribute class IRoster(Interface): """A roster is a collection of `IMembers`.""" name = Attribute( """The name for this roster. Rosters are considered equal if they have the same name.""") members = Attribute( """An iterator over all the IMembers managed by this roster.""") member_count = Attribute( """The number of members managed by this roster.""") users = Attribute( """An iterator over all the IUsers reachable by this roster. This returns all the users for all the members managed by this roster. """) addresses = Attribute( """An iterator over all the IAddresses reachable by this roster. This returns all the addresses for all the users for all the members managed by this roster. """) def get_member(email): """Get the member for the given address. *Note* that it is possible for an email to be subscribed to a mailing list twice, once through its explicit address and once indirectly through a user's preferred address. In this case, this API always returns the explicit address. Use ``get_memberships()`` to return them all. :param email: The email address to search for. :type email: string :return: The member if found, otherwise None :rtype: `IMember` or None """ def get_memberships(email): """Get the memberships for the given address. :param email: The email address to search for. :type email: string :return: All the memberships associated with this email address. :rtype: sequence of length 0, 1, or 2 of ``IMember`` """
khushboo9293/mailman
src/mailman/interfaces/roster.py
Python
gpl-3.0
2,570
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\updateCheckDialog.ui' # # Created: Fri Jan 31 15:29:49 2014 # by: PyQt4 UI code generator 4.9.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_UpdateCheckDialog(object): def setupUi(self, UpdateCheckDialog): UpdateCheckDialog.setObjectName(_fromUtf8("UpdateCheckDialog")) UpdateCheckDialog.resize(473, 300) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/creepy/creepy")), QtGui.QIcon.Normal, QtGui.QIcon.Off) UpdateCheckDialog.setWindowIcon(icon) self.buttonBox = QtGui.QDialogButtonBox(UpdateCheckDialog) self.buttonBox.setGeometry(QtCore.QRect(110, 250, 341, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Close) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.verticalLayoutWidget = QtGui.QWidget(UpdateCheckDialog) self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 451, 221)) self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget")) self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.label = QtGui.QLabel(self.verticalLayoutWidget) self.label.setOpenExternalLinks(False) self.label.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse) self.label.setObjectName(_fromUtf8("label")) self.verticalLayout.addWidget(self.label) self.versionsTableWidget = QtGui.QTableWidget(self.verticalLayoutWidget) self.versionsTableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.versionsTableWidget.setTabKeyNavigation(False) self.versionsTableWidget.setProperty("showDropIndicator", False) self.versionsTableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.versionsTableWidget.setTextElideMode(QtCore.Qt.ElideNone) self.versionsTableWidget.setRowCount(1) self.versionsTableWidget.setColumnCount(5) self.versionsTableWidget.setObjectName(_fromUtf8("versionsTableWidget")) item = QtGui.QTableWidgetItem() self.versionsTableWidget.setItem(0, 0, item) item = QtGui.QTableWidgetItem() self.versionsTableWidget.setItem(0, 1, item) item = QtGui.QTableWidgetItem() self.versionsTableWidget.setItem(0, 2, item) item = QtGui.QTableWidgetItem() item.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled) self.versionsTableWidget.setItem(0, 3, item) self.versionsTableWidget.horizontalHeader().setCascadingSectionResizes(True) self.versionsTableWidget.horizontalHeader().setDefaultSectionSize(80) self.versionsTableWidget.horizontalHeader().setStretchLastSection(True) self.versionsTableWidget.verticalHeader().setVisible(False) self.verticalLayout.addWidget(self.versionsTableWidget) self.dlNewVersionLabel = QtGui.QLabel(self.verticalLayoutWidget) self.dlNewVersionLabel.setText(_fromUtf8("")) self.dlNewVersionLabel.setOpenExternalLinks(True) self.dlNewVersionLabel.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse) self.dlNewVersionLabel.setObjectName(_fromUtf8("dlNewVersionLabel")) self.verticalLayout.addWidget(self.dlNewVersionLabel) self.retranslateUi(UpdateCheckDialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), UpdateCheckDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), UpdateCheckDialog.reject) QtCore.QMetaObject.connectSlotsByName(UpdateCheckDialog) def retranslateUi(self, UpdateCheckDialog): UpdateCheckDialog.setWindowTitle(QtGui.QApplication.translate("UpdateCheckDialog", "Update Check", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("UpdateCheckDialog", "<html><head/><body><p><span style=\" font-weight:600;\">Results of Update Check</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) __sortingEnabled = self.versionsTableWidget.isSortingEnabled() self.versionsTableWidget.setSortingEnabled(False) self.versionsTableWidget.setSortingEnabled(__sortingEnabled) import creepy_resources_rc if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) UpdateCheckDialog = QtGui.QDialog() ui = Ui_UpdateCheckDialog() ui.setupUi(UpdateCheckDialog) UpdateCheckDialog.show() sys.exit(app.exec_())
ilektrojohn/creepy
creepy/ui/UpdateCheckDialog.py
Python
gpl-3.0
4,920
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import urllib from PyQt4.QtGui import QFrame, QImage, QPixmap, QApplication from PyQt4.QtCore import Qt, SIGNAL from weboob.applications.qcineoob.ui.minimovie_ui import Ui_MiniMovie from weboob.capabilities.base import empty, NotAvailable class MiniMovie(QFrame): def __init__(self, weboob, backend, movie, parent=None): QFrame.__init__(self, parent) self.parent = parent self.ui = Ui_MiniMovie() self.ui.setupUi(self) self.weboob = weboob self.backend = backend self.movie = movie self.ui.titleLabel.setText(movie.original_title) self.ui.shortDescLabel.setText(movie.short_description) self.ui.backendLabel.setText(backend.name) self.connect(self.ui.newTabButton, SIGNAL("clicked()"), self.newTabPressed) self.connect(self.ui.viewButton, SIGNAL("clicked()"), self.viewPressed) self.connect(self.ui.viewThumbnailButton, SIGNAL("clicked()"), self.gotThumbnail) if self.parent.parent.ui.showTCheck.isChecked(): self.gotThumbnail() def gotThumbnail(self): if empty(self.movie.thumbnail_url) and self.movie.thumbnail_url != NotAvailable: self.backend.fill_movie(self.movie, ('thumbnail_url')) if not empty(self.movie.thumbnail_url): data = urllib.urlopen(self.movie.thumbnail_url).read() img = QImage.fromData(data) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToHeight(100,Qt.SmoothTransformation)) def viewPressed(self): QApplication.setOverrideCursor(Qt.WaitCursor) movie = self.backend.get_movie(self.movie.id) if movie: self.parent.doAction('Details of movie "%s"' % movie.original_title, self.parent.displayMovie, [movie, self.backend]) def newTabPressed(self): movie = self.backend.get_movie(self.movie.id) self.parent.parent.newTab(u'Details of movie "%s"' % movie.original_title, self.backend, movie=movie) def enterEvent(self, event): self.setFrameShadow(self.Sunken) QFrame.enterEvent(self, event) def leaveEvent(self, event): self.setFrameShadow(self.Raised) QFrame.leaveEvent(self, event) def mousePressEvent(self, event): QFrame.mousePressEvent(self, event) if event.button() == 2: self.gotThumbnail() elif event.button() == 4: self.newTabPressed() else: self.viewPressed()
sputnick-dev/weboob
weboob/applications/qcineoob/minimovie.py
Python
agpl-3.0
3,257
from django.test import TestCase from django.contrib.auth.models import User from userena import forms from userena import settings as userena_settings class SignupFormTests(TestCase): """ Test the signup form. """ fixtures = ['users'] def test_signup_form(self): """ Test that the ``SignupForm`` checks for unique usernames and unique e-mail addresses. """ invalid_data_dicts = [ # Non-alphanumeric username. {'data': {'username': 'foo@bar', 'email': 'foo@example.com', 'password': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('username', [u'Username must contain only letters, numbers, dots and underscores.'])}, # Password is not the same {'data': {'username': 'katy', 'email': 'katy@newexample.com', 'password1': 'foo', 'password2': 'foo2', 'tos': 'on'}, 'error': ('__all__', [u'The two password fields didn\'t match.'])}, # Already taken username {'data': {'username': 'john', 'email': 'john@newexample.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('username', [u'This username is already taken.'])}, # Forbidden username {'data': {'username': 'SignUp', 'email': 'foo@example.com', 'password': 'foo', 'password2': 'foo2', 'tos': 'on'}, 'error': ('username', [u'This username is not allowed.'])}, # Already taken email {'data': {'username': 'alice', 'email': 'john@example.com', 'password': 'foo', 'password2': 'foo', 'tos': 'on'}, 'error': ('email', [u'This email is already in use. Please supply a different email.'])}, ] for invalid_dict in invalid_data_dicts: form = forms.SignupForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) # And finally, a valid form. form = forms.SignupForm(data={'username': 'foo.bla', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on'}) self.failUnless(form.is_valid()) class AuthenticationFormTests(TestCase): """ Test the ``AuthenticationForm`` """ fixtures = ['users',] def test_signin_form(self): """ Check that the ``SigninForm`` requires both identification and password """ invalid_data_dicts = [ {'data': {'identification': '', 'password': 'inhalefish'}, 'error': ('identification', [u'Either supply us with your email or username.'])}, {'data': {'identification': 'john', 'password': 'inhalefish'}, 'error': ('__all__', [u'Please enter a correct username or email and password. Note that both fields are case-sensitive.'])} ] for invalid_dict in invalid_data_dicts: form = forms.AuthenticationForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) valid_data_dicts = [ {'identification': 'john', 'password': 'blowfish'}, {'identification': 'john@example.com', 'password': 'blowfish'} ] for valid_dict in valid_data_dicts: form = forms.AuthenticationForm(valid_dict) self.failUnless(form.is_valid()) def test_signin_form_email(self): """ Test that the signin form has a different label is ``USERENA_WITHOUT_USERNAME`` is set to ``True`` """ userena_settings.USERENA_WITHOUT_USERNAMES = True form = forms.AuthenticationForm(data={'identification': "john", 'password': "blowfish"}) correct_label = "Email" self.assertEqual(form.fields['identification'].label, correct_label) # Restore default settings userena_settings.USERENA_WITHOUT_USERNAMES = False class SignupFormOnlyEmailTests(TestCase): """ Test the :class:`SignupFormOnlyEmail`. This is the same form as :class:`SignupForm` but doesn't require an username for a successfull signup. """ fixtures = ['users'] def test_signup_form_only_email(self): """ Test that the form has no username field. And that the username is generated in the save method """ valid_data = {'email': 'hans@gretel.com', 'password1': 'blowfish', 'password2': 'blowfish'} form = forms.SignupFormOnlyEmail(data=valid_data) # Should have no username field self.failIf(form.fields.get('username', False)) # Form should be valid. self.failUnless(form.is_valid()) # Creates an unique username user = form.save() self.failUnless(len(user.username), 5) class ChangeEmailFormTests(TestCase): """ Test the ``ChangeEmailForm`` """ fixtures = ['users'] def test_change_email_form(self): user = User.objects.get(pk=1) invalid_data_dicts = [ # No change in e-mail address {'data': {'email': 'john@example.com'}, 'error': ('email', [u'You\'re already known under this email.'])}, # An e-mail address used by another {'data': {'email': 'jane@example.com'}, 'error': ('email', [u'This email is already in use. Please supply a different email.'])}, ] for invalid_dict in invalid_data_dicts: form = forms.ChangeEmailForm(user, data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) # Test a valid post form = forms.ChangeEmailForm(user, data={'email': 'john@newexample.com'}) self.failUnless(form.is_valid()) def test_form_init(self): """ The form must be initialized with a ``User`` instance. """ self.assertRaises(TypeError, forms.ChangeEmailForm, None) class EditAccountFormTest(TestCase): """ Test the ``EditAccountForm`` """ pass
MareAtlantica/agora-ciudadana
userena/tests/forms.py
Python
agpl-3.0
7,002
""" Tests for discussion pages """ import datetime from pytz import UTC from uuid import uuid4 from nose.plugins.attrib import attr from .helpers import BaseDiscussionTestCase from ..helpers import UniqueCourseTest from ...pages.lms.auto_auth import AutoAuthPage from ...pages.lms.courseware import CoursewarePage from ...pages.lms.discussion import ( DiscussionTabSingleThreadPage, InlineDiscussionPage, InlineDiscussionThreadPage, DiscussionUserProfilePage, DiscussionTabHomePage, DiscussionSortPreferencePage, ) from ...pages.lms.learner_profile import LearnerProfilePage from ...fixtures.course import CourseFixture, XBlockFixtureDesc from ...fixtures.discussion import ( SingleThreadViewFixture, UserProfileViewFixture, SearchResultFixture, Thread, Response, Comment, SearchResult, MultipleThreadFixture) from .helpers import BaseDiscussionMixin THREAD_CONTENT_WITH_LATEX = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n----------\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. (b).\n\n **(a)** $H_1(e^{j\\omega}) = \\sum_{n=-\\infty}^{\\infty}h_1[n]e^{-j\\omega n} = \\sum_{n=-\\infty} ^{\\infty}h[n]e^{-j\\omega n}+\\delta_2e^{-j\\omega n_0}$ $= H(e^{j\\omega})+\\delta_2e^{-j\\omega n_0}=A_e (e^{j\\omega}) e^{-j\\omega n_0} +\\delta_2e^{-j\\omega n_0}=e^{-j\\omega n_0} (A_e(e^{j\\omega})+\\delta_2) $H_3(e^{j\\omega})=A_e(e^{j\\omega})+\\delta_2$. Dummy $A_e(e^{j\\omega})$ dummy post $. $A_e(e^{j\\omega}) \\ge -\\delta_2$, it follows that $H_3(e^{j\\omega})$ is real and $H_3(e^{j\\omega})\\ge 0$.\n\n**(b)** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur.\n\n **Case 1:** If $re^{j\\theta}$ is a Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n**Case 3:** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem $H_3(e^{j\\omega}) = P(cos\\omega)(cos\\omega - cos\\theta)^k$, Lorem Lorem Lorem Lorem Lorem Lorem $P(cos\\omega)$ has no $(cos\\omega - cos\\theta)$ factor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. $P(cos\\theta) \\neq 0$. Since $P(cos\\omega)$ this is a dummy data post $\\omega$, dummy $\\delta > 0$ such that for all $\\omega$ dummy $|\\omega - \\theta| < \\delta$, $P(cos\\omega)$ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. """ class DiscussionResponsePaginationTestMixin(BaseDiscussionMixin): """ A mixin containing tests for response pagination for use by both inline discussion and the discussion tab """ def assert_response_display_correct(self, response_total, displayed_responses): """ Assert that various aspects of the display of responses are all correct: * Text indicating total number of responses * Presence of "Add a response" button * Number of responses actually displayed * Presence and text of indicator of how many responses are shown * Presence and text of button to load more responses """ self.assertEqual( self.thread_page.get_response_total_text(), str(response_total) + " responses" ) self.assertEqual(self.thread_page.has_add_response_button(), response_total != 0) self.assertEqual(self.thread_page.get_num_displayed_responses(), displayed_responses) self.assertEqual( self.thread_page.get_shown_responses_text(), ( None if response_total == 0 else "Showing all responses" if response_total == displayed_responses else "Showing first {} responses".format(displayed_responses) ) ) self.assertEqual( self.thread_page.get_load_responses_button_text(), ( None if response_total == displayed_responses else "Load all responses" if response_total - displayed_responses < 100 else "Load next 100 responses" ) ) def test_pagination_no_responses(self): self.setup_thread(0) self.assert_response_display_correct(0, 0) def test_pagination_few_responses(self): self.setup_thread(5) self.assert_response_display_correct(5, 5) def test_pagination_two_response_pages(self): self.setup_thread(50) self.assert_response_display_correct(50, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(50, 50) def test_pagination_exactly_two_response_pages(self): self.setup_thread(125) self.assert_response_display_correct(125, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(125, 125) def test_pagination_three_response_pages(self): self.setup_thread(150) self.assert_response_display_correct(150, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 125) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 150) def test_add_response_button(self): self.setup_thread(5) self.assertTrue(self.thread_page.has_add_response_button()) self.thread_page.click_add_response_button() def test_add_response_button_closed_thread(self): self.setup_thread(5, closed=True) self.assertFalse(self.thread_page.has_add_response_button()) @attr('shard_1') class DiscussionHomePageTest(UniqueCourseTest): """ Tests for the discussion home page. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionHomePageTest, self).setUp() CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() def test_new_post_button(self): """ Scenario: I can create new posts from the Discussion home page. Given that I am on the Discussion home page When I click on the 'New Post' button Then I should be shown the new post form """ self.assertIsNotNone(self.page.new_post_button) self.page.click_new_post_button() self.assertIsNotNone(self.page.new_post_form) @attr('shard_1') class DiscussionTabSingleThreadTest(BaseDiscussionTestCase, DiscussionResponsePaginationTestMixin): """ Tests for the discussion page displaying a single thread """ def setUp(self): super(DiscussionTabSingleThreadTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() def setup_thread_page(self, thread_id): self.thread_page = self.create_single_thread_page(thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.visit() def test_mathjax_rendering(self): thread_id = "test_thread_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread( id=thread_id, body=THREAD_CONTENT_WITH_LATEX, commentable_id=self.discussion_id, thread_type="discussion" ) ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertTrue(self.thread_page.is_discussion_body_visible()) self.assertTrue(self.thread_page.is_mathjax_preview_available()) self.assertTrue(self.thread_page.is_mathjax_rendered()) def test_marked_answer_comments(self): thread_id = "test_thread_{}".format(uuid4().hex) response_id = "test_response_{}".format(uuid4().hex) comment_id = "test_comment_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread(id=thread_id, commentable_id=self.discussion_id, thread_type="question") ) thread_fixture.addResponse( Response(id=response_id, endorsed=True), [Comment(id=comment_id)] ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertFalse(self.thread_page.is_comment_visible(comment_id)) self.assertFalse(self.thread_page.is_add_comment_visible(response_id)) self.assertTrue(self.thread_page.is_show_comments_visible(response_id)) self.thread_page.show_comments(response_id) self.assertTrue(self.thread_page.is_comment_visible(comment_id)) self.assertTrue(self.thread_page.is_add_comment_visible(response_id)) self.assertFalse(self.thread_page.is_show_comments_visible(response_id)) @attr('shard_1') class DiscussionTabMultipleThreadTest(BaseDiscussionTestCase): """ Tests for the discussion page with multiple threads """ def setUp(self): super(DiscussionTabMultipleThreadTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.thread_count = 2 self.thread_ids = [] self.setup_multiple_threads(thread_count=self.thread_count) self.thread_page_1 = DiscussionTabSingleThreadPage( self.browser, self.course_id, self.discussion_id, self.thread_ids[0] ) self.thread_page_2 = DiscussionTabSingleThreadPage( self.browser, self.course_id, self.discussion_id, self.thread_ids[1] ) self.thread_page_1.visit() def setup_multiple_threads(self, thread_count): threads = [] for i in range(thread_count): thread_id = "test_thread_{}_{}".format(i, uuid4().hex) thread_body = "Dummy Long text body." * 50 threads.append( Thread(id=thread_id, commentable_id=self.discussion_id, body=thread_body), ) self.thread_ids.append(thread_id) view = MultipleThreadFixture(threads) view.push() def test_page_scroll_on_thread_change_view(self): """ Check switching between threads changes the page to scroll to bottom """ # verify threads are rendered on the page self.assertTrue( self.thread_page_1.check_threads_rendered_successfully(thread_count=self.thread_count) ) # From the thread_page_1 open & verify next thread self.thread_page_1.click_and_open_thread(thread_id=self.thread_ids[1]) self.assertTrue(self.thread_page_2.is_browser_on_page()) # Verify that window is on top of page. self.thread_page_2.check_window_is_on_top() @attr('shard_1') class DiscussionOpenClosedThreadTest(BaseDiscussionTestCase): """ Tests for checking the display of attributes on open and closed threads """ def setUp(self): super(DiscussionOpenClosedThreadTest, self).setUp() self.thread_id = "test_thread_{}".format(uuid4().hex) def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self, **thread_kwargs): thread_kwargs.update({'commentable_id': self.discussion_id}) view = SingleThreadViewFixture( Thread(id=self.thread_id, **thread_kwargs) ) view.addResponse(Response(id="response1")) view.push() def setup_openclosed_thread_page(self, closed=False): self.setup_user(roles=['Moderator']) if closed: self.setup_view(closed=True) else: self.setup_view() page = self.create_single_thread_page(self.thread_id) page.visit() page.close_open_thread() return page def test_originally_open_thread_vote_display(self): page = self.setup_openclosed_thread_page() self.assertFalse(page._is_element_visible('.forum-thread-main-wrapper .action-vote')) self.assertTrue(page._is_element_visible('.forum-thread-main-wrapper .display-vote')) self.assertFalse(page._is_element_visible('.response_response1 .action-vote')) self.assertTrue(page._is_element_visible('.response_response1 .display-vote')) def test_originally_closed_thread_vote_display(self): page = self.setup_openclosed_thread_page(True) self.assertTrue(page._is_element_visible('.forum-thread-main-wrapper .action-vote')) self.assertFalse(page._is_element_visible('.forum-thread-main-wrapper .display-vote')) self.assertTrue(page._is_element_visible('.response_response1 .action-vote')) self.assertFalse(page._is_element_visible('.response_response1 .display-vote')) @attr('shard_1') class DiscussionCommentDeletionTest(BaseDiscussionTestCase): """ Tests for deleting comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_deletion_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [Comment(id="comment_other_author", user_id="other"), Comment(id="comment_self_author", user_id=self.user_id)]) view.push() def test_comment_deletion_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") def test_comment_deletion_as_moderator(self): self.setup_user(roles=['Moderator']) self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") page.delete_comment("comment_other_author") @attr('shard_1') class DiscussionResponseEditTest(BaseDiscussionTestCase): """ Tests for editing responses displayed beneath thread in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="response_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response_other_author", user_id="other", thread_id="response_edit_test_thread"), ) view.addResponse( Response(id="response_self_author", user_id=self.user_id, thread_id="response_edit_test_thread"), ) view.push() def edit_response(self, page, response_id): self.assertTrue(page.is_response_editable(response_id)) page.start_response_edit(response_id) new_response = "edited body" page.set_response_editor_value(response_id, new_response) page.submit_response_edit(response_id, new_response) def test_edit_response_as_student(self): """ Scenario: Students should be able to edit the response they created not responses of other users Given that I am on discussion page with student logged in When I try to edit the response created by student Then the response should be edited and rendered successfully And responses from other users should be shown over there And the student should be able to edit the response of other people """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.assertTrue(page.is_response_visible("response_other_author")) self.assertFalse(page.is_response_editable("response_other_author")) self.edit_response(page, "response_self_author") def test_edit_response_as_moderator(self): """ Scenario: Moderator should be able to edit the response they created and responses of other users Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") def test_vote_report_endorse_after_edit(self): """ Scenario: Moderator should be able to vote, report or endorse after editing the response. Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully And I try to vote the response created by moderator Then the response should be voted successfully And I try to vote the response created by other users Then the response should be voted successfully And I try to report the response created by moderator Then the response should be reported successfully And I try to report the response created by other users Then the response should be reported successfully And I try to endorse the response created by moderator Then the response should be endorsed successfully And I try to endorse the response created by other users Then the response should be endorsed successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") page.vote_response('response_self_author') page.vote_response('response_other_author') page.report_response('response_self_author') page.report_response('response_other_author') page.endorse_response('response_self_author') page.endorse_response('response_other_author') @attr('shard_1') class DiscussionCommentEditTest(BaseDiscussionTestCase): """ Tests for editing comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [Comment(id="comment_other_author", user_id="other"), Comment(id="comment_self_author", user_id=self.user_id)]) view.push() def edit_comment(self, page, comment_id): page.start_comment_edit(comment_id) new_comment = "edited body" page.set_comment_editor_value(comment_id, new_comment) page.submit_comment_edit(comment_id, new_comment) def test_edit_comment_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") def test_edit_comment_as_moderator(self): self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") self.edit_comment(page, "comment_other_author") def test_cancel_comment_edit(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") page.set_comment_editor_value("comment_self_author", "edited body") page.cancel_comment_edit("comment_self_author", original_body) def test_editor_visibility(self): """Only one editor should be visible at a time within a single response""" self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.assertTrue(page.is_add_comment_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_add_comment_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.set_comment_editor_value("comment_self_author", "edited body") page.start_comment_edit("comment_other_author") self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_comment_editor_visible("comment_other_author")) self.assertEqual(page.get_comment_body("comment_self_author"), original_body) page.start_response_edit("response1") self.assertFalse(page.is_comment_editor_visible("comment_other_author")) self.assertTrue(page.is_response_editor_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_response_editor_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.cancel_comment_edit("comment_self_author", original_body) self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_add_comment_visible("response1")) @attr('shard_1') class InlineDiscussionTest(UniqueCourseTest, DiscussionResponsePaginationTestMixin): """ Tests for inline discussions """ def setUp(self): super(InlineDiscussionTest, self).setUp() self.discussion_id = "test_discussion_{}".format(uuid4().hex) self.additional_discussion_id = "test_discussion_{}".format(uuid4().hex) self.course_fix = CourseFixture(**self.course_info).add_children( XBlockFixtureDesc("chapter", "Test Section").add_children( XBlockFixtureDesc("sequential", "Test Subsection").add_children( XBlockFixtureDesc("vertical", "Test Unit").add_children( XBlockFixtureDesc( "discussion", "Test Discussion", metadata={"discussion_id": self.discussion_id} ), XBlockFixtureDesc( "discussion", "Test Discussion 1", metadata={"discussion_id": self.additional_discussion_id} ) ) ) ) ).install() self.user_id = AutoAuthPage(self.browser, course_id=self.course_id).visit().get_user_id() self.courseware_page = CoursewarePage(self.browser, self.course_id) self.courseware_page.visit() self.discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) self.additional_discussion_page = InlineDiscussionPage(self.browser, self.additional_discussion_id) def setup_thread_page(self, thread_id): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 1) self.thread_page = InlineDiscussionThreadPage(self.browser, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.expand() def test_initial_render(self): self.assertFalse(self.discussion_page.is_discussion_expanded()) def test_expand_discussion_empty(self): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 0) def check_anonymous_to_peers(self, is_staff): thread = Thread(id=uuid4().hex, anonymous_to_peers=True, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertEqual(self.thread_page.is_thread_anonymous(), not is_staff) def test_anonymous_to_peers_threads_as_staff(self): AutoAuthPage(self.browser, course_id=self.course_id, roles="Administrator").visit() self.courseware_page.visit() self.check_anonymous_to_peers(True) def test_anonymous_to_peers_threads_as_peer(self): self.check_anonymous_to_peers(False) def test_discussion_blackout_period(self): now = datetime.datetime.now(UTC) self.course_fix.add_advanced_settings( { u"discussion_blackouts": { "value": [ [ (now - datetime.timedelta(days=14)).isoformat(), (now + datetime.timedelta(days=2)).isoformat() ] ] } } ) self.course_fix._add_advanced_settings() self.browser.refresh() thread = Thread(id=uuid4().hex, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.addResponse( Response(id="response1"), [Comment(id="comment1", user_id="other"), Comment(id="comment2", user_id=self.user_id)]) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertFalse(self.discussion_page.element_exists(".new-post-btn")) self.assertFalse(self.thread_page.has_add_response_button()) self.assertFalse(self.thread_page.is_response_editable("response1")) self.assertFalse(self.thread_page.is_add_comment_visible("response1")) self.assertFalse(self.thread_page.is_comment_editable("comment1")) self.assertFalse(self.thread_page.is_comment_editable("comment2")) self.assertFalse(self.thread_page.is_comment_deletable("comment1")) self.assertFalse(self.thread_page.is_comment_deletable("comment2")) def test_dual_discussion_module(self): """ Scenario: Two discussion module in one unit shouldn't override their actions Given that I'm on courseware page where there are two inline discussion When I click on one discussion module new post button Then it should add new post form of that module in DOM And I should be shown new post form of that module And I shouldn't be shown second discussion module new post form And I click on second discussion module new post button Then it should add new post form of second module in DOM And I should be shown second discussion new post form And I shouldn't be shown first discussion module new post form And I have two new post form in the DOM When I click back on first module new post button And I should be shown new post form of that module And I shouldn't be shown second discussion module new post form """ self.discussion_page.wait_for_page() self.additional_discussion_page.wait_for_page() self.discussion_page.click_new_post_button() with self.discussion_page.handle_alert(): self.discussion_page.click_cancel_new_post() self.additional_discussion_page.click_new_post_button() self.assertFalse(self.discussion_page._is_element_visible(".new-post-article")) with self.additional_discussion_page.handle_alert(): self.additional_discussion_page.click_cancel_new_post() self.discussion_page.click_new_post_button() self.assertFalse(self.additional_discussion_page._is_element_visible(".new-post-article")) @attr('shard_1') class DiscussionUserProfileTest(UniqueCourseTest): """ Tests for user profile page in discussion tab. """ PAGE_SIZE = 20 # django_comment_client.forum.views.THREADS_PER_PAGE PROFILED_USERNAME = "profiled-user" def setUp(self): super(DiscussionUserProfileTest, self).setUp() CourseFixture(**self.course_info).install() # The following line creates a user enrolled in our course, whose # threads will be viewed, but not the one who will view the page. # It isn't necessary to log them in, but using the AutoAuthPage # saves a lot of code. self.profiled_user_id = AutoAuthPage( self.browser, username=self.PROFILED_USERNAME, course_id=self.course_id ).visit().get_user_id() # now create a second user who will view the profile. self.user_id = AutoAuthPage( self.browser, course_id=self.course_id ).visit().get_user_id() def check_pages(self, num_threads): # set up the stub server to return the desired amount of thread results threads = [Thread(id=uuid4().hex) for _ in range(num_threads)] UserProfileViewFixture(threads).push() # navigate to default view (page 1) page = DiscussionUserProfilePage( self.browser, self.course_id, self.profiled_user_id, self.PROFILED_USERNAME ) page.visit() current_page = 1 total_pages = max(num_threads - 1, 1) / self.PAGE_SIZE + 1 all_pages = range(1, total_pages + 1) return page def _check_page(): # ensure the page being displayed as "current" is the expected one self.assertEqual(page.get_current_page(), current_page) # ensure the expected threads are being shown in the right order threads_expected = threads[(current_page - 1) * self.PAGE_SIZE:current_page * self.PAGE_SIZE] self.assertEqual(page.get_shown_thread_ids(), [t["id"] for t in threads_expected]) # ensure the clickable page numbers are the expected ones self.assertEqual(page.get_clickable_pages(), [ p for p in all_pages if p != current_page and p - 2 <= current_page <= p + 2 or (current_page > 2 and p == 1) or (current_page < total_pages and p == total_pages) ]) # ensure the previous button is shown, but only if it should be. # when it is shown, make sure it works. if current_page > 1: self.assertTrue(page.is_prev_button_shown(current_page - 1)) page.click_prev_page() self.assertEqual(page.get_current_page(), current_page - 1) page.click_next_page() self.assertEqual(page.get_current_page(), current_page) else: self.assertFalse(page.is_prev_button_shown()) # ensure the next button is shown, but only if it should be. if current_page < total_pages: self.assertTrue(page.is_next_button_shown(current_page + 1)) else: self.assertFalse(page.is_next_button_shown()) # click all the way up through each page for i in range(current_page, total_pages): _check_page() if current_page < total_pages: page.click_on_page(current_page + 1) current_page += 1 # click all the way back down for i in range(current_page, 0, -1): _check_page() if current_page > 1: page.click_on_page(current_page - 1) current_page -= 1 def test_0_threads(self): self.check_pages(0) def test_1_thread(self): self.check_pages(1) def test_20_threads(self): self.check_pages(20) def test_21_threads(self): self.check_pages(21) def test_151_threads(self): self.check_pages(151) def test_pagination_window_reposition(self): page = self.check_pages(50) page.click_next_page() page.wait_for_ajax() self.assertTrue(page.is_window_on_top()) def test_redirects_to_learner_profile(self): """ Scenario: Verify that learner-profile link is present on forum discussions page and we can navigate to it. Given that I am on discussion forum user's profile page. And I can see a username on left sidebar When I click on my username. Then I will be navigated to Learner Profile page. And I can my username on Learner Profile page """ learner_profile_page = LearnerProfilePage(self.browser, self.PROFILED_USERNAME) page = self.check_pages(1) page.click_on_sidebar_username() learner_profile_page.wait_for_page() self.assertTrue(learner_profile_page.field_is_visible('username')) @attr('shard_1') class DiscussionSearchAlertTest(UniqueCourseTest): """ Tests for spawning and dismissing alerts related to user search actions and their results. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionSearchAlertTest, self).setUp() CourseFixture(**self.course_info).install() # first auto auth call sets up a user that we will search for in some tests self.searched_user_id = AutoAuthPage( self.browser, username=self.SEARCHED_USERNAME, course_id=self.course_id ).visit().get_user_id() # this auto auth call creates the actual session user AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() def setup_corrected_text(self, text): SearchResultFixture(SearchResult(corrected_text=text)).push() def check_search_alert_messages(self, expected): actual = self.page.get_search_alert_messages() self.assertTrue(all(map(lambda msg, sub: msg.lower().find(sub.lower()) >= 0, actual, expected))) def test_no_rewrite(self): self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) def test_rewrite_dismiss(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.page.dismiss_alert_message("foo") self.check_search_alert_messages([]) def test_new_search(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.setup_corrected_text("bar") self.page.perform_search() self.check_search_alert_messages(["bar"]) self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) def test_rewrite_and_user(self): self.setup_corrected_text("foo") self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["foo", self.SEARCHED_USERNAME]) def test_user_only(self): self.setup_corrected_text(None) self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["no threads", self.SEARCHED_USERNAME]) # make sure clicking the link leads to the user profile page UserProfileViewFixture([]).push() self.page.get_search_alert_links().first.click() DiscussionUserProfilePage( self.browser, self.course_id, self.searched_user_id, self.SEARCHED_USERNAME ).wait_for_page() @attr('shard_1') class DiscussionSortPreferenceTest(UniqueCourseTest): """ Tests for the discussion page displaying a single thread. """ def setUp(self): super(DiscussionSortPreferenceTest, self).setUp() # Create a course to register for. CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.sort_page = DiscussionSortPreferencePage(self.browser, self.course_id) self.sort_page.visit() def test_default_sort_preference(self): """ Test to check the default sorting preference of user. (Default = date ) """ selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, "date") def test_change_sort_preference(self): """ Test that if user sorting preference is changing properly. """ selected_sort = "" for sort_type in ["votes", "comments", "date"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) def test_last_preference_saved(self): """ Test that user last preference is saved. """ selected_sort = "" for sort_type in ["votes", "comments", "date"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) self.sort_page.refresh_page() selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type)
dkarakats/edx-platform
common/test/acceptance/tests/discussion/test_discussion.py
Python
agpl-3.0
44,559
# 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 os import sys import ssl import copy import binascii import time import xml.dom.minidom try: from lxml import etree as ET except ImportError: from xml.etree import ElementTree as ET from pipes import quote as pquote try: import simplejson as json except: import json import libcloud from libcloud.utils.py3 import PY3, PY25 from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlparse from libcloud.utils.py3 import urlencode from libcloud.utils.py3 import StringIO from libcloud.utils.py3 import u from libcloud.utils.py3 import b from libcloud.utils.misc import lowercase_keys, retry from libcloud.utils.compression import decompress_data from libcloud.common.exceptions import exception_from_message from libcloud.common.types import LibcloudError, MalformedResponseError from libcloud.httplib_ssl import LibcloudHTTPConnection from libcloud.httplib_ssl import LibcloudHTTPSConnection __all__ = [ 'RETRY_FAILED_HTTP_REQUESTS', 'BaseDriver', 'Connection', 'PollingConnection', 'ConnectionKey', 'ConnectionUserAndKey', 'CertificateConnection', 'LoggingHTTPConnection', 'LoggingHTTPSConnection', 'Response', 'HTTPResponse', 'JsonResponse', 'XmlResponse', 'RawResponse' ] # Module level variable indicates if the failed HTTP requests should be retried RETRY_FAILED_HTTP_REQUESTS = False class HTTPResponse(httplib.HTTPResponse): # On python 2.6 some calls can hang because HEAD isn't quite properly # supported. # In particular this happens on S3 when calls are made to get_object to # objects that don't exist. # This applies the behaviour from 2.7, fixing the hangs. def read(self, amt=None): if self.fp is None: return '' if self._method == 'HEAD': self.close() return '' return httplib.HTTPResponse.read(self, amt) class Response(object): """ A base Response class to derive from. """ status = httplib.OK # Response status code headers = {} # Response headers body = None # Raw response body object = None # Parsed response body error = None # Reason returned by the server. connection = None # Parent connection class parse_zero_length_body = False def __init__(self, response, connection): """ :param response: HTTP response object. (optional) :type response: :class:`httplib.HTTPResponse` :param connection: Parent connection object. :type connection: :class:`.Connection` """ self.connection = connection # http.client In Python 3 doesn't automatically lowercase the header # names self.headers = lowercase_keys(dict(response.getheaders())) self.error = response.reason self.status = response.status # This attribute is set when using LoggingConnection. original_data = getattr(response, '_original_data', None) if original_data: # LoggingConnection already decompresses data so it can log it # which means we don't need to decompress it here. self.body = response._original_data else: self.body = self._decompress_response(body=response.read(), headers=self.headers) if PY3: self.body = b(self.body).decode('utf-8') if not self.success(): raise exception_from_message(code=self.status, message=self.parse_error(), headers=self.headers) self.object = self.parse_body() def parse_body(self): """ Parse response body. Override in a provider's subclass. :return: Parsed body. :rtype: ``str`` """ return self.body def parse_error(self): """ Parse the error messages. Override in a provider's subclass. :return: Parsed error. :rtype: ``str`` """ return self.body def success(self): """ Determine if our request was successful. The meaning of this can be arbitrary; did we receive OK status? Did the node get created? Were we authenticated? :rtype: ``bool`` :return: ``True`` or ``False`` """ return self.status in [httplib.OK, httplib.CREATED] def _decompress_response(self, body, headers): """ Decompress a response body if it is using deflate or gzip encoding. :param body: Response body. :type body: ``str`` :param headers: Response headers. :type headers: ``dict`` :return: Decompressed response :rtype: ``str`` """ encoding = headers.get('content-encoding', None) if encoding in ['zlib', 'deflate']: body = decompress_data('zlib', body) elif encoding in ['gzip', 'x-gzip']: body = decompress_data('gzip', body) else: body = body.strip() return body class JsonResponse(Response): """ A Base JSON Response class to derive from. """ def parse_body(self): if len(self.body) == 0 and not self.parse_zero_length_body: return self.body try: body = json.loads(self.body) except: raise MalformedResponseError( 'Failed to parse JSON', body=self.body, driver=self.connection.driver) return body parse_error = parse_body class XmlResponse(Response): """ A Base XML Response class to derive from. """ def parse_body(self): if len(self.body) == 0 and not self.parse_zero_length_body: return self.body try: body = ET.XML(self.body) except: raise MalformedResponseError('Failed to parse XML', body=self.body, driver=self.connection.driver) return body parse_error = parse_body class RawResponse(Response): def __init__(self, connection): """ :param connection: Parent connection object. :type connection: :class:`.Connection` """ self._status = None self._response = None self._headers = {} self._error = None self._reason = None self.connection = connection @property def response(self): if not self._response: response = self.connection.connection.getresponse() self._response, self.body = response, response if not self.success(): self.parse_error() return self._response @property def status(self): if not self._status: self._status = self.response.status return self._status @property def headers(self): if not self._headers: self._headers = lowercase_keys(dict(self.response.getheaders())) return self._headers @property def reason(self): if not self._reason: self._reason = self.response.reason return self._reason # TODO: Move this to a better location/package class LoggingConnection(): """ Debug class to log all HTTP(s) requests as they could be made with the curl command. :cvar log: file-like object that logs entries are written to. """ log = None http_proxy_used = False def _log_response(self, r): rv = "# -------- begin %d:%d response ----------\n" % (id(self), id(r)) ht = "" v = r.version if r.version == 10: v = "HTTP/1.0" if r.version == 11: v = "HTTP/1.1" ht += "%s %s %s\r\n" % (v, r.status, r.reason) body = r.read() for h in r.getheaders(): ht += "%s: %s\r\n" % (h[0].title(), h[1]) ht += "\r\n" # this is evil. laugh with me. ha arharhrhahahaha class fakesock: def __init__(self, s): self.s = s def makefile(self, *args, **kwargs): if PY3: from io import BytesIO cls = BytesIO else: cls = StringIO return cls(self.s) rr = r headers = lowercase_keys(dict(r.getheaders())) encoding = headers.get('content-encoding', None) content_type = headers.get('content-type', None) if encoding in ['zlib', 'deflate']: body = decompress_data('zlib', body) elif encoding in ['gzip', 'x-gzip']: body = decompress_data('gzip', body) pretty_print = os.environ.get('LIBCLOUD_DEBUG_PRETTY_PRINT_RESPONSE', False) if r.chunked: ht += "%x\r\n" % (len(body)) ht += body.decode('utf-8') ht += "\r\n0\r\n" else: if pretty_print and content_type == 'application/json': try: body = json.loads(body.decode('utf-8')) body = json.dumps(body, sort_keys=True, indent=4) except: # Invalid JSON or server is lying about content-type pass elif pretty_print and content_type == 'text/xml': try: elem = xml.dom.minidom.parseString(body.decode('utf-8')) body = elem.toprettyxml() except Exception: # Invalid XML pass ht += u(body) if sys.version_info >= (2, 6) and sys.version_info < (2, 7): cls = HTTPResponse else: cls = httplib.HTTPResponse rr = cls(sock=fakesock(ht), method=r._method, debuglevel=r.debuglevel) rr.begin() rv += ht rv += ("\n# -------- end %d:%d response ----------\n" % (id(self), id(r))) rr._original_data = body return (rr, rv) def _log_curl(self, method, url, body, headers): cmd = ["curl"] if self.http_proxy_used: if self.proxy_username and self.proxy_password: proxy_url = 'http://%s:%s@%s:%s' % (self.proxy_username, self.proxy_password, self.proxy_host, self.proxy_port) else: proxy_url = 'http://%s:%s' % (self.proxy_host, self.proxy_port) proxy_url = pquote(proxy_url) cmd.extend(['--proxy', proxy_url]) cmd.extend(['-i']) if method.lower() == 'head': # HEAD method need special handling cmd.extend(["--head"]) else: cmd.extend(["-X", pquote(method)]) for h in headers: cmd.extend(["-H", pquote("%s: %s" % (h, headers[h]))]) cert_file = getattr(self, 'cert_file', None) if cert_file: cmd.extend(["--cert", pquote(cert_file)]) # TODO: in python 2.6, body can be a file-like object. if body is not None and len(body) > 0: cmd.extend(["--data-binary", pquote(body)]) cmd.extend(["--compress"]) cmd.extend([pquote("%s://%s:%d%s" % (self.protocol, self.host, self.port, url))]) return " ".join(cmd) class LoggingHTTPSConnection(LoggingConnection, LibcloudHTTPSConnection): """ Utility Class for logging HTTPS connections """ protocol = 'https' def getresponse(self): r = LibcloudHTTPSConnection.getresponse(self) if self.log is not None: r, rv = self._log_response(r) self.log.write(rv + "\n") self.log.flush() return r def request(self, method, url, body=None, headers=None): headers.update({'X-LC-Request-ID': str(id(self))}) if self.log is not None: pre = "# -------- begin %d request ----------\n" % id(self) self.log.write(pre + self._log_curl(method, url, body, headers) + "\n") self.log.flush() return LibcloudHTTPSConnection.request(self, method, url, body, headers) class LoggingHTTPConnection(LoggingConnection, LibcloudHTTPConnection): """ Utility Class for logging HTTP connections """ protocol = 'http' def getresponse(self): r = LibcloudHTTPConnection.getresponse(self) if self.log is not None: r, rv = self._log_response(r) self.log.write(rv + "\n") self.log.flush() return r def request(self, method, url, body=None, headers=None): headers.update({'X-LC-Request-ID': str(id(self))}) if self.log is not None: pre = '# -------- begin %d request ----------\n' % id(self) self.log.write(pre + self._log_curl(method, url, body, headers) + "\n") self.log.flush() return LibcloudHTTPConnection.request(self, method, url, body, headers) class Connection(object): """ A Base Connection class to derive from. """ # conn_classes = (LoggingHTTPSConnection) conn_classes = (LibcloudHTTPConnection, LibcloudHTTPSConnection) responseCls = Response rawResponseCls = RawResponse connection = None host = '127.0.0.1' port = 443 timeout = None secure = 1 driver = None action = None cache_busting = False backoff = None retry_delay = None allow_insecure = True def __init__(self, secure=True, host=None, port=None, url=None, timeout=None, proxy_url=None, retry_delay=None, backoff=None): self.secure = secure and 1 or 0 self.ua = [] self.context = {} if not self.allow_insecure and not secure: # TODO: We should eventually switch to whitelist instead of # blacklist approach raise ValueError('Non https connections are not allowed (use ' 'secure=True)') self.request_path = '' if host: self.host = host if port is not None: self.port = port else: if self.secure == 1: self.port = 443 else: self.port = 80 if url: (self.host, self.port, self.secure, self.request_path) = self._tuple_from_url(url) if timeout is None: timeout = self.__class__.timeout self.timeout = timeout self.retry_delay = retry_delay self.backoff = backoff self.proxy_url = proxy_url def set_http_proxy(self, proxy_url): """ Set a HTTP proxy which will be used with this connection. :param proxy_url: Proxy URL (e.g. http://<hostname>:<port> without authentication and http://<username>:<password>@<hostname>:<port> for basic auth authentication information. :type proxy_url: ``str`` """ self.proxy_url = proxy_url def set_context(self, context): if not isinstance(context, dict): raise TypeError('context needs to be a dictionary') self.context = context def reset_context(self): self.context = {} def _tuple_from_url(self, url): secure = 1 port = None (scheme, netloc, request_path, param, query, fragment) = urlparse.urlparse(url) if scheme not in ['http', 'https']: raise LibcloudError('Invalid scheme: %s in url %s' % (scheme, url)) if scheme == "http": secure = 0 if ":" in netloc: netloc, port = netloc.rsplit(":") port = int(port) if not port: if scheme == "http": port = 80 else: port = 443 host = netloc port = int(port) return (host, port, secure, request_path) def connect(self, host=None, port=None, base_url=None, **kwargs): """ Establish a connection with the API server. :type host: ``str`` :param host: Optional host to override our default :type port: ``int`` :param port: Optional port to override our default :returns: A connection """ # prefer the attribute base_url if its set or sent connection = None secure = self.secure if getattr(self, 'base_url', None) and base_url is None: (host, port, secure, request_path) = self._tuple_from_url(self.base_url) elif base_url is not None: (host, port, secure, request_path) = self._tuple_from_url(base_url) else: host = host or self.host port = port or self.port # Make sure port is an int port = int(port) if not hasattr(kwargs, 'host'): kwargs.update({'host': host}) if not hasattr(kwargs, 'port'): kwargs.update({'port': port}) if not hasattr(kwargs, 'key_file') and hasattr(self, 'key_file'): kwargs.update({'key_file': self.key_file}) if not hasattr(kwargs, 'cert_file') and hasattr(self, 'cert_file'): kwargs.update({'cert_file': self.cert_file}) # kwargs = {'host': host, 'port': int(port)} # Timeout is only supported in Python 2.6 and later # http://docs.python.org/library/httplib.html#httplib.HTTPConnection if self.timeout and not PY25: kwargs.update({'timeout': self.timeout}) if self.proxy_url: kwargs.update({'proxy_url': self.proxy_url}) connection = self.conn_classes[secure](**kwargs) # You can uncoment this line, if you setup a reverse proxy server # which proxies to your endpoint, and lets you easily capture # connections in cleartext when you setup the proxy to do SSL # for you # connection = self.conn_classes[False]("127.0.0.1", 8080) self.connection = connection def _user_agent(self): user_agent_suffix = ' '.join(['(%s)' % x for x in self.ua]) if self.driver: user_agent = 'libcloud/%s (%s) %s' % ( libcloud.__version__, self.driver.name, user_agent_suffix) else: user_agent = 'libcloud/%s %s' % ( libcloud.__version__, user_agent_suffix) return user_agent def user_agent_append(self, token): """ Append a token to a user agent string. Users of the library should call this to uniquely identify their requests to a provider. :type token: ``str`` :param token: Token to add to the user agent. """ self.ua.append(token) def request(self, action, params=None, data=None, headers=None, method='GET', raw=False): """ Request a given `action`. Basically a wrapper around the connection object's `request` that does some helpful pre-processing. :type action: ``str`` :param action: A path. This can include arguments. If included, any extra parameters are appended to the existing ones. :type params: ``dict`` :param params: Optional mapping of additional parameters to send. If None, leave as an empty ``dict``. :type data: ``unicode`` :param data: A body of data to send with the request. :type headers: ``dict`` :param headers: Extra headers to add to the request None, leave as an empty ``dict``. :type method: ``str`` :param method: An HTTP method such as "GET" or "POST". :type raw: ``bool`` :param raw: True to perform a "raw" request aka only send the headers and use the rawResponseCls class. This is used with storage API when uploading a file. :return: An :class:`Response` instance. :rtype: :class:`Response` instance """ if params is None: params = {} else: params = copy.copy(params) if headers is None: headers = {} else: headers = copy.copy(headers) retry_enabled = os.environ.get('LIBCLOUD_RETRY_FAILED_HTTP_REQUESTS', False) or RETRY_FAILED_HTTP_REQUESTS action = self.morph_action_hook(action) self.action = action self.method = method # Extend default parameters params = self.add_default_params(params) # Add cache busting parameters (if enabled) if self.cache_busting and method == 'GET': params = self._add_cache_busting_to_params(params=params) # Extend default headers headers = self.add_default_headers(headers) # We always send a user-agent header headers.update({'User-Agent': self._user_agent()}) # Indicate that we support gzip and deflate compression headers.update({'Accept-Encoding': 'gzip,deflate'}) port = int(self.port) if port not in (80, 443): headers.update({'Host': "%s:%d" % (self.host, port)}) else: headers.update({'Host': self.host}) if data: data = self.encode_data(data) headers['Content-Length'] = str(len(data)) elif method.upper() in ['POST', 'PUT'] and not raw: # Only send Content-Length 0 with POST and PUT request. # # Note: Content-Length is not added when using "raw" mode means # means that headers are upfront and the body is sent at some point # later on. With raw mode user can specify Content-Length with # "data" not being set. headers['Content-Length'] = '0' params, headers = self.pre_connect_hook(params, headers) if params: if '?' in action: url = '&'.join((action, urlencode(params, doseq=True))) else: url = '?'.join((action, urlencode(params, doseq=True))) else: url = action # Removed terrible hack...this a less-bad hack that doesn't execute a # request twice, but it's still a hack. self.connect() try: # @TODO: Should we just pass File object as body to request method # instead of dealing with splitting and sending the file ourselves? if raw: self.connection.putrequest(method, url) for key, value in list(headers.items()): self.connection.putheader(key, str(value)) self.connection.endheaders() else: if retry_enabled: retry_request = retry(timeout=self.timeout, retry_delay=self.retry_delay, backoff=self.backoff) retry_request(self.connection.request)(method=method, url=url, body=data, headers=headers) else: self.connection.request(method=method, url=url, body=data, headers=headers) except ssl.SSLError: e = sys.exc_info()[1] self.reset_context() raise ssl.SSLError(str(e)) if raw: responseCls = self.rawResponseCls kwargs = {'connection': self} else: responseCls = self.responseCls kwargs = {'connection': self, 'response': self.connection.getresponse()} try: response = responseCls(**kwargs) finally: # Always reset the context after the request has completed self.reset_context() return response def morph_action_hook(self, action): return self.request_path + action def add_default_params(self, params): """ Adds default parameters (such as API key, version, etc.) to the passed `params` Should return a dictionary. """ return params def add_default_headers(self, headers): """ Adds default headers (such as Authorization, X-Foo-Bar) to the passed `headers` Should return a dictionary. """ return headers def pre_connect_hook(self, params, headers): """ A hook which is called before connecting to the remote server. This hook can perform a final manipulation on the params, headers and url parameters. :type params: ``dict`` :param params: Request parameters. :type headers: ``dict`` :param headers: Request headers. """ return params, headers def encode_data(self, data): """ Encode body data. Override in a provider's subclass. """ return data def _add_cache_busting_to_params(self, params): """ Add cache busting parameter to the query parameters of a GET request. Parameters are only added if "cache_busting" class attribute is set to True. Note: This should only be used with *naughty* providers which use excessive caching of responses. """ cache_busting_value = binascii.hexlify(os.urandom(8)).decode('ascii') if isinstance(params, dict): params['cache-busting'] = cache_busting_value else: params.append(('cache-busting', cache_busting_value)) return params class PollingConnection(Connection): """ Connection class which can also work with the async APIs. After initial requests, this class periodically polls for jobs status and waits until the job has finished. If job doesn't finish in timeout seconds, an Exception thrown. """ poll_interval = 0.5 timeout = 200 request_method = 'request' def async_request(self, action, params=None, data=None, headers=None, method='GET', context=None): """ Perform an 'async' request to the specified path. Keep in mind that this function is *blocking* and 'async' in this case means that the hit URL only returns a job ID which is the periodically polled until the job has completed. This function works like this: - Perform a request to the specified path. Response should contain a 'job_id'. - Returned 'job_id' is then used to construct a URL which is used for retrieving job status. Constructed URL is then periodically polled until the response indicates that the job has completed or the timeout of 'self.timeout' seconds has been reached. :type action: ``str`` :param action: A path :type params: ``dict`` :param params: Optional mapping of additional parameters to send. If None, leave as an empty ``dict``. :type data: ``unicode`` :param data: A body of data to send with the request. :type headers: ``dict`` :param headers: Extra headers to add to the request None, leave as an empty ``dict``. :type method: ``str`` :param method: An HTTP method such as "GET" or "POST". :type context: ``dict`` :param context: Context dictionary which is passed to the functions which construct initial and poll URL. :return: An :class:`Response` instance. :rtype: :class:`Response` instance """ request = getattr(self, self.request_method) kwargs = self.get_request_kwargs(action=action, params=params, data=data, headers=headers, method=method, context=context) response = request(**kwargs) kwargs = self.get_poll_request_kwargs(response=response, context=context, request_kwargs=kwargs) end = time.time() + self.timeout completed = False while time.time() < end and not completed: response = request(**kwargs) completed = self.has_completed(response=response) if not completed: time.sleep(self.poll_interval) if not completed: raise LibcloudError('Job did not complete in %s seconds' % (self.timeout)) return response def get_request_kwargs(self, action, params=None, data=None, headers=None, method='GET', context=None): """ Arguments which are passed to the initial request() call inside async_request. """ kwargs = {'action': action, 'params': params, 'data': data, 'headers': headers, 'method': method} return kwargs def get_poll_request_kwargs(self, response, context, request_kwargs): """ Return keyword arguments which are passed to the request() method when polling for the job status. :param response: Response object returned by poll request. :type response: :class:`HTTPResponse` :param request_kwargs: Kwargs previously used to initiate the poll request. :type response: ``dict`` :return ``dict`` Keyword arguments """ raise NotImplementedError('get_poll_request_kwargs not implemented') def has_completed(self, response): """ Return job completion status. :param response: Response object returned by poll request. :type response: :class:`HTTPResponse` :return ``bool`` True if the job has completed, False otherwise. """ raise NotImplementedError('has_completed not implemented') class ConnectionKey(Connection): """ Base connection class which accepts a single ``key`` argument. """ def __init__(self, key, secure=True, host=None, port=None, url=None, timeout=None, proxy_url=None, backoff=None, retry_delay=None): """ Initialize `user_id` and `key`; set `secure` to an ``int`` based on passed value. """ super(ConnectionKey, self).__init__(secure=secure, host=host, port=port, url=url, timeout=timeout, proxy_url=proxy_url, backoff=backoff, retry_delay=retry_delay) self.key = key class CertificateConnection(Connection): """ Base connection class which accepts a single ``cert_file`` argument. """ def __init__(self, cert_file, secure=True, host=None, port=None, url=None, timeout=None, backoff=None, retry_delay=None): """ Initialize `cert_file`; set `secure` to an ``int`` based on passed value. """ super(CertificateConnection, self).__init__(secure=secure, host=host, port=port, url=url, timeout=timeout, backoff=backoff, retry_delay=retry_delay) self.cert_file = cert_file class ConnectionUserAndKey(ConnectionKey): """ Base connection class which accepts a ``user_id`` and ``key`` argument. """ user_id = None def __init__(self, user_id, key, secure=True, host=None, port=None, url=None, timeout=None, proxy_url=None, backoff=None, retry_delay=None): super(ConnectionUserAndKey, self).__init__(key, secure=secure, host=host, port=port, url=url, timeout=timeout, backoff=backoff, retry_delay=retry_delay, proxy_url=proxy_url) self.user_id = user_id class BaseDriver(object): """ Base driver class from which other classes can inherit from. """ connectionCls = ConnectionKey def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=None, region=None, **kwargs): """ :param key: API key or username to be used (required) :type key: ``str`` :param secret: Secret password to be used (required) :type secret: ``str`` :param secure: Weither to use HTTPS or HTTP. Note: Some providers only support HTTPS, and it is on by default. :type secure: ``bool`` :param host: Override hostname used for connections. :type host: ``str`` :param port: Override port used for connections. :type port: ``int`` :param api_version: Optional API version. Only used by drivers which support multiple API versions. :type api_version: ``str`` :param region: Optional driver region. Only used by drivers which support multiple regions. :type region: ``str`` :rtype: ``None`` """ self.key = key self.secret = secret self.secure = secure args = [self.key] if self.secret is not None: args.append(self.secret) args.append(secure) if host is not None: args.append(host) if port is not None: args.append(port) self.api_version = api_version self.region = region conn_kwargs = self._ex_connection_class_kwargs() conn_kwargs.update({'timeout': kwargs.pop('timeout', None), 'retry_delay': kwargs.pop('retry_delay', None), 'backoff': kwargs.pop('backoff', None)}) self.connection = self.connectionCls(*args, **conn_kwargs) self.connection.driver = self self.connection.connect() def _ex_connection_class_kwargs(self): """ Return extra connection keyword arguments which are passed to the Connection class constructor. """ return {}
dcorbacho/libcloud
libcloud/common/base.py
Python
apache-2.0
36,111
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import unittest from extensions_paths import CHROME_EXTENSIONS from server_instance import ServerInstance from test_file_system import TestFileSystem _TEST_FILESYSTEM = { 'api': { '_api_features.json': json.dumps({ 'audioCapture': { 'channel': 'stable', 'extension_types': ['platform_app'] }, 'background': [ { 'channel': 'stable', 'extension_types': ['extension'] }, { 'channel': 'stable', 'extension_types': ['platform_app'], 'whitelist': ['im not here'] } ], 'inheritsFromDifferentDependencyName': { 'dependencies': ['manifest:inheritsPlatformAndChannelFromDependency'] }, 'inheritsPlatformAndChannelFromDependency': { 'dependencies': ['manifest:inheritsPlatformAndChannelFromDependency'] }, 'omnibox': { 'dependencies': ['manifest:omnibox'], 'contexts': ['blessed_extension'] }, 'syncFileSystem': { 'dependencies': ['permission:syncFileSystem'], 'contexts': ['blessed_extension'] }, 'tabs': { 'channel': 'stable', 'extension_types': ['extension', 'legacy_packaged_app'], 'contexts': ['blessed_extension'] }, 'test': { 'channel': 'stable', 'extension_types': 'all', 'contexts': [ 'blessed_extension', 'unblessed_extension', 'content_script'] }, 'overridesPlatformAndChannelFromDependency': { 'channel': 'beta', 'dependencies': [ 'permission:overridesPlatformAndChannelFromDependency' ], 'extension_types': ['platform_app'] }, 'windows': { 'dependencies': ['api:tabs'], 'contexts': ['blessed_extension'] } }), '_manifest_features.json': json.dumps({ 'app.content_security_policy': { 'channel': 'stable', 'extension_types': ['platform_app'], 'min_manifest_version': 2, 'whitelist': ['this isnt happening'] }, 'background': { 'channel': 'stable', 'extension_types': ['extension', 'legacy_packaged_app', 'hosted_app'] }, 'inheritsPlatformAndChannelFromDependency': { 'channel': 'dev', 'extension_types': ['extension'] }, 'manifest_version': { 'channel': 'stable', 'extension_types': 'all' }, 'omnibox': { 'channel': 'stable', 'extension_types': ['extension'], 'platforms': ['win'] }, 'page_action': { 'channel': 'stable', 'extension_types': ['extension'] }, 'sockets': { 'channel': 'dev', 'extension_types': ['platform_app'] } }), '_permission_features.json': json.dumps({ 'bluetooth': { 'channel': 'dev', 'extension_types': ['platform_app'] }, 'overridesPlatformAndChannelFromDependency': { 'channel': 'stable', 'extension_types': ['extension'] }, 'power': { 'channel': 'stable', 'extension_types': [ 'extension', 'legacy_packaged_app', 'platform_app' ] }, 'syncFileSystem': { 'channel': 'beta', 'extension_types': ['platform_app'] }, 'tabs': { 'channel': 'stable', 'extension_types': ['extension'] } }) }, 'docs': { 'templates': { 'json': { 'manifest.json': json.dumps({ 'background': { 'documentation': 'background_pages.html' }, 'manifest_version': { 'documentation': 'manifest/manifest_version.html', 'example': 2, 'level': 'required' }, 'page_action': { 'documentation': 'pageAction.html', 'example': {}, 'level': 'only_one' } }), 'permissions.json': json.dumps({ 'fakeUnsupportedFeature': {}, 'syncFileSystem': { 'partial': 'permissions/sync_file_system.html' }, 'tabs': { 'partial': 'permissions/tabs.html' }, }) } } } } class FeaturesBundleTest(unittest.TestCase): def setUp(self): self._server = ServerInstance.ForTest( TestFileSystem(_TEST_FILESYSTEM, relative_to=CHROME_EXTENSIONS)) def testManifestFeatures(self): expected_features = { 'background': { 'name': 'background', 'channel': 'stable', 'platforms': ['extensions'], 'documentation': 'background_pages.html' }, 'inheritsPlatformAndChannelFromDependency': { 'channel': 'dev', 'name': 'inheritsPlatformAndChannelFromDependency', 'platforms': ['extensions'] }, 'manifest_version': { 'name': 'manifest_version', 'channel': 'stable', 'platforms': ['apps', 'extensions'], 'documentation': 'manifest/manifest_version.html', 'level': 'required', 'example': 2 }, 'omnibox': { 'name': 'omnibox', 'channel': 'stable', 'platforms': ['extensions'] }, 'page_action': { 'name': 'page_action', 'channel': 'stable', 'platforms': ['extensions'], 'documentation': 'pageAction.html', 'level': 'only_one', 'example': {} }, 'sockets': { 'name': 'sockets', 'channel': 'dev', 'platforms': ['apps'] } } self.assertEqual( expected_features, self._server.features_bundle.GetManifestFeatures().Get()) def testPermissionFeatures(self): expected_features = { 'bluetooth': { 'name': 'bluetooth', 'channel': 'dev', 'platforms': ['apps'], }, 'fakeUnsupportedFeature': { 'name': 'fakeUnsupportedFeature', 'platforms': [] }, 'overridesPlatformAndChannelFromDependency': { 'name': 'overridesPlatformAndChannelFromDependency', 'channel': 'stable', 'platforms': ['extensions'] }, 'power': { 'name': 'power', 'channel': 'stable', 'platforms': ['apps', 'extensions'], }, 'syncFileSystem': { 'name': 'syncFileSystem', 'channel': 'beta', 'platforms': ['apps'], 'partial': 'permissions/sync_file_system.html' }, 'tabs': { 'name': 'tabs', 'channel': 'stable', 'platforms': ['extensions'], 'partial': 'permissions/tabs.html' } } self.assertEqual( expected_features, self._server.features_bundle.GetPermissionFeatures().Get()) def testAPIFeatures(self): expected_features = { 'audioCapture': { 'name': 'audioCapture', 'channel': 'stable', 'platforms': ['apps'] }, 'background': { 'name': 'background', 'channel': 'stable', 'platforms': ['extensions'] }, 'inheritsFromDifferentDependencyName': { 'channel': 'dev', 'name': 'inheritsFromDifferentDependencyName', 'dependencies': ['manifest:inheritsPlatformAndChannelFromDependency'], 'platforms': ['extensions'] }, 'inheritsPlatformAndChannelFromDependency': { 'channel': 'dev', 'name': 'inheritsPlatformAndChannelFromDependency', 'dependencies': ['manifest:inheritsPlatformAndChannelFromDependency'], 'platforms': ['extensions'] }, 'omnibox': { 'channel': 'stable', 'name': 'omnibox', 'platforms': ['extensions'], 'contexts': ['blessed_extension'], 'dependencies': ['manifest:omnibox'] }, 'overridesPlatformAndChannelFromDependency': { 'channel': 'beta', 'name': 'overridesPlatformAndChannelFromDependency', 'dependencies': [ 'permission:overridesPlatformAndChannelFromDependency' ], 'platforms': ['apps'] }, 'syncFileSystem': { 'channel': 'beta', 'name': 'syncFileSystem', 'platforms': ['apps'], 'contexts': ['blessed_extension'], 'dependencies': ['permission:syncFileSystem'] }, 'tabs': { 'channel': 'stable', 'name': 'tabs', 'channel': 'stable', 'platforms': ['extensions'], 'contexts': ['blessed_extension'], }, 'test': { 'channel': 'stable', 'name': 'test', 'channel': 'stable', 'platforms': ['apps', 'extensions'], 'contexts': [ 'blessed_extension', 'unblessed_extension', 'content_script'], }, 'windows': { 'channel': 'stable', 'name': 'windows', 'platforms': ['extensions'], 'contexts': ['blessed_extension'], 'dependencies': ['api:tabs'] } } self.assertEqual( expected_features, self._server.features_bundle.GetAPIFeatures().Get()) if __name__ == '__main__': unittest.main()
AndroidOpenDevelopment/android_external_chromium_org
chrome/common/extensions/docs/server2/features_bundle_test.py
Python
bsd-3-clause
9,222
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Regression tests for the units package.""" import pickle from fractions import Fraction import pytest import numpy as np from numpy.testing import assert_allclose from astropy import units as u from astropy import constants as c from astropy.units import utils def test_initialisation(): assert u.Unit(u.m) is u.m ten_meter = u.Unit(10.*u.m) assert ten_meter == u.CompositeUnit(10., [u.m], [1]) assert u.Unit(ten_meter) is ten_meter assert u.Unit(10.*ten_meter) == u.CompositeUnit(100., [u.m], [1]) foo = u.Unit('foo', (10. * ten_meter)**2, namespace=locals()) assert foo == u.CompositeUnit(10000., [u.m], [2]) assert u.Unit('m') == u.m assert u.Unit('') == u.dimensionless_unscaled assert u.one == u.dimensionless_unscaled assert u.Unit('10 m') == ten_meter assert u.Unit(10.) == u.CompositeUnit(10., [], []) assert u.Unit() == u.dimensionless_unscaled def test_invalid_power(): x = u.m ** Fraction(1, 3) assert isinstance(x.powers[0], Fraction) x = u.m ** Fraction(1, 2) assert isinstance(x.powers[0], float) # Test the automatic conversion to a fraction x = u.m ** (1. / 3.) assert isinstance(x.powers[0], Fraction) def test_invalid_compare(): assert not (u.m == u.s) def test_convert(): assert u.h._get_converter(u.s)(1) == 3600 def test_convert_fail(): with pytest.raises(u.UnitsError): u.cm.to(u.s, 1) with pytest.raises(u.UnitsError): (u.cm / u.s).to(u.m, 1) def test_composite(): assert (u.cm / u.s * u.h)._get_converter(u.m)(1) == 36 assert u.cm * u.cm == u.cm ** 2 assert u.cm * u.cm * u.cm == u.cm ** 3 assert u.Hz.to(1000 * u.Hz, 1) == 0.001 def test_str(): assert str(u.cm) == "cm" def test_repr(): assert repr(u.cm) == 'Unit("cm")' def test_represents(): assert u.m.represents is u.m assert u.km.represents.scale == 1000. assert u.km.represents.bases == [u.m] assert u.Ry.scale == 1.0 and u.Ry.bases == [u.Ry] assert_allclose(u.Ry.represents.scale, 13.605692518464949) assert u.Ry.represents.bases == [u.eV] bla = u.def_unit('bla', namespace=locals()) assert bla.represents is bla blabla = u.def_unit('blabla', 10 * u.hr, namespace=locals()) assert blabla.represents.scale == 10. assert blabla.represents.bases == [u.hr] assert blabla.decompose().scale == 10 * 3600 assert blabla.decompose().bases == [u.s] def test_units_conversion(): assert_allclose(u.kpc.to(u.Mpc), 0.001) assert_allclose(u.Mpc.to(u.kpc), 1000) assert_allclose(u.yr.to(u.Myr), 1.e-6) assert_allclose(u.AU.to(u.pc), 4.84813681e-6) assert_allclose(u.cycle.to(u.rad), 6.283185307179586) assert_allclose(u.spat.to(u.sr), 12.56637061435917) def test_units_manipulation(): # Just do some manipulation and check it's happy (u.kpc * u.yr) ** Fraction(1, 3) / u.Myr (u.AA * u.erg) ** 9 def test_decompose(): assert u.Ry == u.Ry.decompose() def test_dimensionless_to_si(): """ Issue #1150: Test for conversion of dimensionless quantities to the SI system """ testunit = ((1.0 * u.kpc) / (1.0 * u.Mpc)) assert testunit.unit.physical_type == 'dimensionless' assert_allclose(testunit.si, 0.001) def test_dimensionless_to_cgs(): """ Issue #1150: Test for conversion of dimensionless quantities to the CGS system """ testunit = ((1.0 * u.m) / (1.0 * u.km)) assert testunit.unit.physical_type == 'dimensionless' assert_allclose(testunit.cgs, 0.001) def test_unknown_unit(): with pytest.warns(u.UnitsWarning, match='FOO'): u.Unit("FOO", parse_strict='warn') def test_multiple_solidus(): with pytest.warns(u.UnitsWarning, match="'m/s/kg' contains multiple " "slashes, which is discouraged"): assert u.Unit("m/s/kg").to_string() == 'm / (kg s)' with pytest.raises(ValueError): u.Unit("m/s/kg", format="vounit") # Regression test for #9000: solidi in exponents do not count towards this. x = u.Unit("kg(3/10) * m(5/2) / s", format="vounit") assert x.to_string() == 'kg(3/10) m(5/2) / s' def test_unknown_unit3(): unit = u.Unit("FOO", parse_strict='silent') assert isinstance(unit, u.UnrecognizedUnit) assert unit.name == "FOO" unit2 = u.Unit("FOO", parse_strict='silent') assert unit == unit2 assert unit.is_equivalent(unit2) unit3 = u.Unit("BAR", parse_strict='silent') assert unit != unit3 assert not unit.is_equivalent(unit3) # Also test basic (in)equalities. assert unit == "FOO" assert unit != u.m # next two from gh-7603. assert unit != None # noqa assert unit not in (None, u.m) with pytest.raises(ValueError): unit._get_converter(unit3) _ = unit.to_string('latex') _ = unit2.to_string('cgs') with pytest.raises(ValueError): u.Unit("BAR", parse_strict='strict') with pytest.raises(TypeError): u.Unit(None) def test_invalid_scale(): with pytest.raises(TypeError): ['a', 'b', 'c'] * u.m def test_cds_power(): unit = u.Unit("10+22/cm2", format="cds", parse_strict='silent') assert unit.scale == 1e22 def test_register(): foo = u.def_unit("foo", u.m ** 3, namespace=locals()) assert 'foo' in locals() with u.add_enabled_units(foo): assert 'foo' in u.get_current_unit_registry().registry assert 'foo' not in u.get_current_unit_registry().registry def test_in_units(): speed_unit = u.cm / u.s _ = speed_unit.in_units(u.pc / u.hour, 1) def test_null_unit(): assert (u.m / u.m) == u.Unit(1) def test_unrecognized_equivalency(): assert u.m.is_equivalent('foo') is False assert u.m.is_equivalent('pc') is True def test_convertible_exception(): with pytest.raises(u.UnitsError, match=r'length.+ are not convertible'): u.AA.to(u.h * u.s ** 2) def test_convertible_exception2(): with pytest.raises(u.UnitsError, match=r'length. and .+time.+ are not convertible'): u.m.to(u.s) def test_invalid_type(): class A: pass with pytest.raises(TypeError): u.Unit(A()) def test_steradian(): """ Issue #599 """ assert u.sr.is_equivalent(u.rad * u.rad) results = u.sr.compose(units=u.cgs.bases) assert results[0].bases[0] is u.rad results = u.sr.compose(units=u.cgs.__dict__) assert results[0].bases[0] is u.sr def test_decompose_bases(): """ From issue #576 """ from astropy.units import cgs from astropy.constants import e d = e.esu.unit.decompose(bases=cgs.bases) assert d._bases == [u.cm, u.g, u.s] assert d._powers == [Fraction(3, 2), 0.5, -1] assert d._scale == 1.0 def test_complex_compose(): complex = u.cd * u.sr * u.Wb composed = complex.compose() assert set(composed[0]._bases) == set([u.lm, u.Wb]) def test_equiv_compose(): composed = u.m.compose(equivalencies=u.spectral()) assert any([u.Hz] == x.bases for x in composed) def test_empty_compose(): with pytest.raises(u.UnitsError): u.m.compose(units=[]) def _unit_as_str(unit): # This function serves two purposes - it is used to sort the units to # test alphabetically, and it is also use to allow pytest to show the unit # in the [] when running the parametrized tests. return str(unit) # We use a set to make sure we don't have any duplicates. COMPOSE_ROUNDTRIP = set() for val in u.__dict__.values(): if (isinstance(val, u.UnitBase) and not isinstance(val, u.PrefixUnit)): COMPOSE_ROUNDTRIP.add(val) @pytest.mark.parametrize('unit', sorted(COMPOSE_ROUNDTRIP, key=_unit_as_str), ids=_unit_as_str) def test_compose_roundtrip(unit): composed_list = unit.decompose().compose() found = False for composed in composed_list: if len(composed.bases): if composed.bases[0] is unit: found = True break elif len(unit.bases) == 0: found = True break assert found # We use a set to make sure we don't have any duplicates. COMPOSE_CGS_TO_SI = set() for val in u.cgs.__dict__.values(): # Can't decompose Celsius if (isinstance(val, u.UnitBase) and not isinstance(val, u.PrefixUnit) and val != u.cgs.deg_C): COMPOSE_CGS_TO_SI.add(val) @pytest.mark.parametrize('unit', sorted(COMPOSE_CGS_TO_SI, key=_unit_as_str), ids=_unit_as_str) def test_compose_cgs_to_si(unit): si = unit.to_system(u.si) assert [x.is_equivalent(unit) for x in si] assert si[0] == unit.si # We use a set to make sure we don't have any duplicates. COMPOSE_SI_TO_CGS = set() for val in u.si.__dict__.values(): # Can't decompose Celsius if (isinstance(val, u.UnitBase) and not isinstance(val, u.PrefixUnit) and val != u.si.deg_C): COMPOSE_SI_TO_CGS.add(val) @pytest.mark.parametrize('unit', sorted(COMPOSE_SI_TO_CGS, key=_unit_as_str), ids=_unit_as_str) def test_compose_si_to_cgs(unit): # Can't convert things with Ampere to CGS without more context try: cgs = unit.to_system(u.cgs) except u.UnitsError: if u.A in unit.decompose().bases: pass else: raise else: assert [x.is_equivalent(unit) for x in cgs] assert cgs[0] == unit.cgs def test_to_si(): """Check units that are not official derived units. Should not appear on its own or as part of a composite unit. """ # TODO: extend to all units not listed in Tables 1--6 of # https://physics.nist.gov/cuu/Units/units.html # See gh-10585. # This was always the case assert u.bar.si is not u.bar # But this used to fail. assert u.bar not in (u.kg/(u.s**2*u.sr*u.nm)).si._bases def test_to_cgs(): assert u.Pa.to_system(u.cgs)[1]._bases[0] is u.Ba assert u.Pa.to_system(u.cgs)[1]._scale == 10.0 def test_decompose_to_cgs(): from astropy.units import cgs assert u.m.decompose(bases=cgs.bases)._bases[0] is cgs.cm def test_compose_issue_579(): unit = u.kg * u.s ** 2 / u.m result = unit.compose(units=[u.N, u.s, u.m]) assert len(result) == 1 assert result[0]._bases == [u.s, u.N, u.m] assert result[0]._powers == [4, 1, -2] def test_compose_prefix_unit(): x = u.m.compose(units=(u.m,)) assert x[0].bases[0] is u.m assert x[0].scale == 1.0 x = u.m.compose(units=[u.km], include_prefix_units=True) assert x[0].bases[0] is u.km assert x[0].scale == 0.001 x = u.m.compose(units=[u.km]) assert x[0].bases[0] is u.km assert x[0].scale == 0.001 x = (u.km/u.s).compose(units=(u.pc, u.Myr)) assert x[0].bases == [u.pc, u.Myr] assert_allclose(x[0].scale, 1.0227121650537077) with pytest.raises(u.UnitsError): (u.km/u.s).compose(units=(u.pc, u.Myr), include_prefix_units=False) def test_self_compose(): unit = u.kg * u.s assert len(unit.compose(units=[u.g, u.s])) == 1 def test_compose_failed(): unit = u.kg with pytest.raises(u.UnitsError): unit.compose(units=[u.N]) def test_compose_fractional_powers(): # Warning: with a complicated unit, this test becomes very slow; # e.g., x = (u.kg / u.s ** 3 * u.au ** 2.5 / u.yr ** 0.5 / u.sr ** 2) # takes 3 s x = u.m ** 0.5 / u.yr ** 1.5 factored = x.compose() for unit in factored: assert x.decompose() == unit.decompose() factored = x.compose(units=u.cgs) for unit in factored: assert x.decompose() == unit.decompose() factored = x.compose(units=u.si) for unit in factored: assert x.decompose() == unit.decompose() def test_compose_best_unit_first(): results = u.l.compose() assert len(results[0].bases) == 1 assert results[0].bases[0] is u.l results = (u.s ** -1).compose() assert results[0].bases[0] in (u.Hz, u.Bq) results = (u.Ry.decompose()).compose() assert results[0].bases[0] is u.Ry def test_compose_no_duplicates(): new = u.kg / u.s ** 3 * u.au ** 2.5 / u.yr ** 0.5 / u.sr ** 2 composed = new.compose(units=u.cgs.bases) assert len(composed) == 1 def test_long_int(): """ Issue #672 """ sigma = 10 ** 21 * u.M_p / u.cm ** 2 sigma.to(u.M_sun / u.pc ** 2) def test_endian_independence(): """ Regression test for #744 A logic issue in the units code meant that big endian arrays could not be converted because the dtype is '>f4', not 'float32', and the code was looking for the strings 'float' or 'int'. """ for endian in ['<', '>']: for ntype in ['i', 'f']: for byte in ['4', '8']: x = np.array([1, 2, 3], dtype=(endian + ntype + byte)) u.m.to(u.cm, x) def test_radian_base(): """ Issue #863 """ assert (1 * u.degree).si.unit == u.rad def test_no_as(): # We don't define 'as', since it is a keyword, but we # do want to define the long form (`attosecond`). assert not hasattr(u, 'as') assert hasattr(u, 'attosecond') def test_no_duplicates_in_names(): # Regression test for #5036 assert u.ct.names == ['ct', 'count'] assert u.ct.short_names == ['ct', 'count'] assert u.ct.long_names == ['count'] assert set(u.ph.names) == set(u.ph.short_names) | set(u.ph.long_names) def test_pickling(): p = pickle.dumps(u.m) other = pickle.loads(p) assert other is u.m new_unit = u.IrreducibleUnit(['foo'], format={'baz': 'bar'}) # This is local, so the unit should not be registered. assert 'foo' not in u.get_current_unit_registry().registry # Test pickling of this unregistered unit. p = pickle.dumps(new_unit) new_unit_copy = pickle.loads(p) assert new_unit_copy is not new_unit assert new_unit_copy.names == ['foo'] assert new_unit_copy.get_format_name('baz') == 'bar' # It should still not be registered. assert 'foo' not in u.get_current_unit_registry().registry # Now try the same with a registered unit. with u.add_enabled_units([new_unit]): p = pickle.dumps(new_unit) assert 'foo' in u.get_current_unit_registry().registry new_unit_copy = pickle.loads(p) assert new_unit_copy is new_unit # Check that a registered unit can be loaded and that it gets re-enabled. with u.add_enabled_units([]): assert 'foo' not in u.get_current_unit_registry().registry new_unit_copy = pickle.loads(p) assert new_unit_copy is not new_unit assert new_unit_copy.names == ['foo'] assert new_unit_copy.get_format_name('baz') == 'bar' assert 'foo' in u.get_current_unit_registry().registry # And just to be sure, that it gets removed outside of the context. assert 'foo' not in u.get_current_unit_registry().registry def test_pickle_between_sessions(): """We cannot really test between sessions easily, so fake it. This test can be changed if the pickle protocol or the code changes enough that it no longer works. """ hash_m = hash(u.m) unit = pickle.loads( b'\x80\x04\x95\xd6\x00\x00\x00\x00\x00\x00\x00\x8c\x12' b'astropy.units.core\x94\x8c\x1a_recreate_irreducible_unit' b'\x94\x93\x94h\x00\x8c\x0fIrreducibleUnit\x94\x93\x94]\x94' b'(\x8c\x01m\x94\x8c\x05meter\x94e\x88\x87\x94R\x94}\x94(\x8c\x06' b'_names\x94]\x94(h\x06h\x07e\x8c\x0c_short_names' b'\x94]\x94h\x06a\x8c\x0b_long_names\x94]\x94h\x07a\x8c\x07' b'_format\x94}\x94\x8c\x07__doc__\x94\x8c ' b'meter: base unit of length in SI\x94ub.') assert unit is u.m assert hash(u.m) == hash_m @pytest.mark.parametrize('unit', [ u.IrreducibleUnit(['foo'], format={'baz': 'bar'}), u.Unit('m_per_s', u.m/u.s)]) def test_pickle_does_not_keep_memoized_hash(unit): """ Tests private attribute since the problem with _hash being pickled and restored only appeared if the unpickling was done in another session, for which the hash no longer was valid, and it is difficult to mimic separate sessions in a simple test. See gh-11872. """ unit_hash = hash(unit) assert unit._hash is not None unit_copy = pickle.loads(pickle.dumps(unit)) # unit is not registered so we get a copy. assert unit_copy is not unit assert unit_copy._hash is None assert hash(unit_copy) == unit_hash with u.add_enabled_units([unit]): # unit is registered, so we get a reference. unit_ref = pickle.loads(pickle.dumps(unit)) if isinstance(unit, u.IrreducibleUnit): assert unit_ref is unit else: assert unit_ref is not unit # pickle.load used to override the hash, although in this case # it would be the same anyway, so not clear this tests much. assert hash(unit) == unit_hash def test_pickle_unrecognized_unit(): """ Issue #2047 """ a = u.Unit('asdf', parse_strict='silent') pickle.loads(pickle.dumps(a)) def test_duplicate_define(): with pytest.raises(ValueError): u.def_unit('m', namespace=u.__dict__) def test_all_units(): from astropy.units.core import get_current_unit_registry registry = get_current_unit_registry() assert len(registry.all_units) > len(registry.non_prefix_units) def test_repr_latex(): assert u.m._repr_latex_() == u.m.to_string('latex') def test_operations_with_strings(): assert u.m / '5s' == (u.m / (5.0 * u.s)) assert u.m * '5s' == (5.0 * u.m * u.s) def test_comparison(): assert u.m > u.cm assert u.m >= u.cm assert u.cm < u.m assert u.cm <= u.m with pytest.raises(u.UnitsError): u.m > u.kg def test_compose_into_arbitrary_units(): # Issue #1438 from astropy.constants import G G.decompose([u.kg, u.km, u.Unit("15 s")]) def test_unit_multiplication_with_string(): """Check that multiplication with strings produces the correct unit.""" u1 = u.cm us = 'kg' assert us * u1 == u.Unit(us) * u1 assert u1 * us == u1 * u.Unit(us) def test_unit_division_by_string(): """Check that multiplication with strings produces the correct unit.""" u1 = u.cm us = 'kg' assert us / u1 == u.Unit(us) / u1 assert u1 / us == u1 / u.Unit(us) def test_sorted_bases(): """See #1616.""" assert (u.m * u.Jy).bases == (u.Jy * u.m).bases def test_megabit(): """See #1543""" assert u.Mbit is u.Mb assert u.megabit is u.Mb assert u.Mbyte is u.MB assert u.megabyte is u.MB def test_composite_unit_get_format_name(): """See #1576""" unit1 = u.Unit('nrad/s') unit2 = u.Unit('Hz(1/2)') assert (str(u.CompositeUnit(1, [unit1, unit2], [1, -1])) == 'nrad / (Hz(1/2) s)') def test_unicode_policy(): from astropy.tests.helper import assert_follows_unicode_guidelines assert_follows_unicode_guidelines( u.degree, roundtrip=u.__dict__) def test_suggestions(): for search, matches in [ ('microns', 'micron'), ('s/microns', 'micron'), ('M', 'm'), ('metre', 'meter'), ('angstroms', 'Angstrom or angstrom'), ('milimeter', 'millimeter'), ('ångström', 'Angstrom, angstrom, mAngstrom or mangstrom'), ('kev', 'EV, eV, kV or keV')]: with pytest.raises(ValueError, match=f'Did you mean {matches}'): u.Unit(search) def test_fits_hst_unit(): """See #1911.""" with pytest.warns(u.UnitsWarning, match='multiple slashes') as w: x = u.Unit("erg /s /cm**2 /angstrom") assert x == u.erg * u.s ** -1 * u.cm ** -2 * u.angstrom ** -1 assert len(w) == 1 def test_barn_prefixes(): """Regression test for https://github.com/astropy/astropy/issues/3753""" assert u.fbarn is u.femtobarn assert u.pbarn is u.picobarn def test_fractional_powers(): """See #2069""" m = 1e9 * u.Msun tH = 1. / (70. * u.km / u.s / u.Mpc) vc = 200 * u.km/u.s x = (c.G ** 2 * m ** 2 * tH.cgs) ** Fraction(1, 3) / vc v1 = x.to('pc') x = (c.G ** 2 * m ** 2 * tH) ** Fraction(1, 3) / vc v2 = x.to('pc') x = (c.G ** 2 * m ** 2 * tH.cgs) ** (1.0 / 3.0) / vc v3 = x.to('pc') x = (c.G ** 2 * m ** 2 * tH) ** (1.0 / 3.0) / vc v4 = x.to('pc') assert_allclose(v1, v2) assert_allclose(v2, v3) assert_allclose(v3, v4) x = u.m ** (1.0 / 101.0) assert isinstance(x.powers[0], float) x = u.m ** (3.0 / 7.0) assert isinstance(x.powers[0], Fraction) assert x.powers[0].numerator == 3 assert x.powers[0].denominator == 7 x = u.cm ** Fraction(1, 2) * u.cm ** Fraction(2, 3) assert isinstance(x.powers[0], Fraction) assert x.powers[0] == Fraction(7, 6) # Regression test for #9258. x = (u.TeV ** (-2.2)) ** (1/-2.2) assert isinstance(x.powers[0], Fraction) assert x.powers[0] == Fraction(1, 1) def test_sqrt_mag(): sqrt_mag = u.mag ** 0.5 assert hasattr(sqrt_mag.decompose().scale, 'imag') assert (sqrt_mag.decompose())**2 == u.mag def test_composite_compose(): # Issue #2382 composite_unit = u.s.compose(units=[u.Unit("s")])[0] u.s.compose(units=[composite_unit]) def test_data_quantities(): assert u.byte.is_equivalent(u.bit) def test_compare_with_none(): # Ensure that equality comparisons with `None` work, and don't # raise exceptions. We are deliberately not using `is None` here # because that doesn't trigger the bug. See #3108. assert not (u.m == None) # noqa assert u.m != None # noqa def test_validate_power_detect_fraction(): frac = utils.validate_power(1.1666666666666665) assert isinstance(frac, Fraction) assert frac.numerator == 7 assert frac.denominator == 6 def test_complex_fractional_rounding_errors(): # See #3788 kappa = 0.34 * u.cm**2 / u.g r_0 = 886221439924.7849 * u.cm q = 1.75 rho_0 = 5e-10 * u.solMass / u.solRad**3 y = 0.5 beta = 0.19047619047619049 a = 0.47619047619047628 m_h = 1e6*u.solMass t1 = 2 * c.c / (kappa * np.sqrt(np.pi)) t2 = (r_0**-q) / (rho_0 * y * beta * (a * c.G * m_h)**0.5) result = ((t1 * t2)**-0.8) assert result.unit.physical_type == 'length' result.to(u.solRad) def test_fractional_rounding_errors_simple(): x = (u.m ** 1.5) ** Fraction(4, 5) assert isinstance(x.powers[0], Fraction) assert x.powers[0].numerator == 6 assert x.powers[0].denominator == 5 def test_enable_unit_groupings(): from astropy.units import cds with cds.enable(): assert cds.geoMass in u.kg.find_equivalent_units() from astropy.units import imperial with imperial.enable(): assert imperial.inch in u.m.find_equivalent_units() def test_unit_summary_prefixes(): """ Test for a few units that the unit summary table correctly reports whether or not that unit supports prefixes. Regression test for https://github.com/astropy/astropy/issues/3835 """ from astropy.units import astrophys for summary in utils._iter_unit_summary(astrophys.__dict__): unit, _, _, _, prefixes = summary if unit.name == 'lyr': assert prefixes elif unit.name == 'pc': assert prefixes elif unit.name == 'barn': assert prefixes elif unit.name == 'cycle': assert prefixes == 'No' elif unit.name == 'spat': assert prefixes == 'No' elif unit.name == 'vox': assert prefixes == 'Yes' def test_raise_to_negative_power(): """Test that order of bases is changed when raising to negative power. Regression test for https://github.com/astropy/astropy/issues/8260 """ m2s2 = u.m ** 2 / u.s ** 2 spm = m2s2 ** (-1 / 2) assert spm.bases == [u.s, u.m] assert spm.powers == [1, -1] assert spm == u.s / u.m
aleksandr-bakanov/astropy
astropy/units/tests/test_units.py
Python
bsd-3-clause
24,065
from __future__ import unicode_literals from django.apps.registry import Apps from django.db import models from django.db.models import signals from django.dispatch import receiver from django.test import TestCase, mock from django.test.utils import isolate_apps from django.utils import six from .models import Author, Book, Car, Person class BaseSignalTest(TestCase): def setUp(self): # Save up the number of connected signals so that we can check at the # end that all the signals we register get properly unregistered (#9989) self.pre_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) def tearDown(self): # Check that all our signals got disconnected properly. post_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) self.assertEqual(self.pre_signals, post_signals) class SignalTests(BaseSignalTest): def test_model_pre_init_and_post_init(self): data = [] def pre_init_callback(sender, args, **kwargs): data.append(kwargs['kwargs']) signals.pre_init.connect(pre_init_callback) def post_init_callback(sender, instance, **kwargs): data.append(instance) signals.post_init.connect(post_init_callback) p1 = Person(first_name="John", last_name="Doe") self.assertEqual(data, [{}, p1]) def test_save_signals(self): data = [] def pre_save_handler(signal, sender, instance, **kwargs): data.append( (instance, sender, kwargs.get("raw", False)) ) def post_save_handler(signal, sender, instance, **kwargs): data.append( (instance, sender, kwargs.get("created"), kwargs.get("raw", False)) ) signals.pre_save.connect(pre_save_handler, weak=False) signals.post_save.connect(post_save_handler, weak=False) try: p1 = Person.objects.create(first_name="John", last_name="Smith") self.assertEqual(data, [ (p1, Person, False), (p1, Person, True, False), ]) data[:] = [] p1.first_name = "Tom" p1.save() self.assertEqual(data, [ (p1, Person, False), (p1, Person, False, False), ]) data[:] = [] # Calling an internal method purely so that we can trigger a "raw" save. p1.save_base(raw=True) self.assertEqual(data, [ (p1, Person, True), (p1, Person, False, True), ]) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() self.assertEqual(data, [ (p2, Person, False), (p2, Person, True, False), ]) data[:] = [] p2.id = 99998 p2.save() self.assertEqual(data, [ (p2, Person, False), (p2, Person, True, False), ]) # The sender should stay the same when using defer(). data[:] = [] p3 = Person.objects.defer('first_name').get(pk=p1.pk) p3.last_name = 'Reese' p3.save() self.assertEqual(data, [ (p3, Person, False), (p3, Person, False, False), ]) finally: signals.pre_save.disconnect(pre_save_handler) signals.post_save.disconnect(post_save_handler) def test_delete_signals(self): data = [] def pre_delete_handler(signal, sender, instance, **kwargs): data.append( (instance, sender, instance.id is None) ) # #8285: signals can be any callable class PostDeleteHandler(object): def __init__(self, data): self.data = data def __call__(self, signal, sender, instance, **kwargs): self.data.append( (instance, sender, instance.id is None) ) post_delete_handler = PostDeleteHandler(data) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: p1 = Person.objects.create(first_name="John", last_name="Smith") p1.delete() self.assertEqual(data, [ (p1, Person, False), (p1, Person, False), ]) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() p2.id = 99998 p2.save() p2.delete() self.assertEqual(data, [ (p2, Person, False), (p2, Person, False), ]) data[:] = [] self.assertQuerysetEqual( Person.objects.all(), [ "James Jones", ], six.text_type ) finally: signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_decorators(self): data = [] @receiver(signals.pre_save, weak=False) def decorated_handler(signal, sender, instance, **kwargs): data.append(instance) @receiver(signals.pre_save, sender=Car, weak=False) def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs): data.append(instance) try: c1 = Car.objects.create(make="Volkswagen", model="Passat") self.assertEqual(data, [c1, c1]) finally: signals.pre_save.disconnect(decorated_handler) signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) def test_save_and_delete_signals_with_m2m(self): data = [] def pre_save_handler(signal, sender, instance, **kwargs): data.append('pre_save signal, %s' % instance) if kwargs.get('raw'): data.append('Is raw') def post_save_handler(signal, sender, instance, **kwargs): data.append('post_save signal, %s' % instance) if 'created' in kwargs: if kwargs['created']: data.append('Is created') else: data.append('Is updated') if kwargs.get('raw'): data.append('Is raw') def pre_delete_handler(signal, sender, instance, **kwargs): data.append('pre_delete signal, %s' % instance) data.append('instance.id is not None: %s' % (instance.id is not None)) def post_delete_handler(signal, sender, instance, **kwargs): data.append('post_delete signal, %s' % instance) data.append('instance.id is not None: %s' % (instance.id is not None)) signals.pre_save.connect(pre_save_handler, weak=False) signals.post_save.connect(post_save_handler, weak=False) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: a1 = Author.objects.create(name='Neal Stephenson') self.assertEqual(data, [ "pre_save signal, Neal Stephenson", "post_save signal, Neal Stephenson", "Is created" ]) data[:] = [] b1 = Book.objects.create(name='Snow Crash') self.assertEqual(data, [ "pre_save signal, Snow Crash", "post_save signal, Snow Crash", "Is created" ]) data[:] = [] # Assigning and removing to/from m2m shouldn't generate an m2m signal. b1.authors.set([a1]) self.assertEqual(data, []) b1.authors.set([]) self.assertEqual(data, []) finally: signals.pre_save.disconnect(pre_save_handler) signals.post_save.disconnect(post_save_handler) signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_disconnect_in_dispatch(self): """ Test that signals that disconnect when being called don't mess future dispatching. """ class Handler(object): def __init__(self, param): self.param = param self._run = False def __call__(self, signal, sender, **kwargs): self._run = True signal.disconnect(receiver=self, sender=sender) a, b = Handler(1), Handler(2) signals.post_save.connect(a, sender=Person, weak=False) signals.post_save.connect(b, sender=Person, weak=False) Person.objects.create(first_name='John', last_name='Smith') self.assertTrue(a._run) self.assertTrue(b._run) self.assertEqual(signals.post_save.receivers, []) @mock.patch('weakref.ref') def test_lazy_model_signal(self, ref): def callback(sender, args, **kwargs): pass signals.pre_init.connect(callback) signals.pre_init.disconnect(callback) self.assertTrue(ref.called) ref.reset_mock() signals.pre_init.connect(callback, weak=False) signals.pre_init.disconnect(callback) ref.assert_not_called() class LazyModelRefTest(BaseSignalTest): def setUp(self): super(LazyModelRefTest, self).setUp() self.received = [] def receiver(self, **kwargs): self.received.append(kwargs) def test_invalid_sender_model_name(self): msg = "Invalid model reference 'invalid'. String model references must be of the form 'app_label.ModelName'." with self.assertRaisesMessage(ValueError, msg): signals.post_init.connect(self.receiver, sender='invalid') def test_already_loaded_model(self): signals.post_init.connect( self.receiver, sender='signals.Book', weak=False ) try: instance = Book() self.assertEqual(self.received, [{ 'signal': signals.post_init, 'sender': Book, 'instance': instance }]) finally: signals.post_init.disconnect(self.receiver, sender=Book) @isolate_apps('signals', kwarg_name='apps') def test_not_loaded_model(self, apps): signals.post_init.connect( self.receiver, sender='signals.Created', weak=False, apps=apps ) try: class Created(models.Model): pass instance = Created() self.assertEqual(self.received, [{ 'signal': signals.post_init, 'sender': Created, 'instance': instance }]) finally: signals.post_init.disconnect(self.receiver, sender=Created) @isolate_apps('signals', kwarg_name='apps') def test_disconnect(self, apps): received = [] def receiver(**kwargs): received.append(kwargs) signals.post_init.connect(receiver, sender='signals.Created', apps=apps) signals.post_init.disconnect(receiver, sender='signals.Created', apps=apps) class Created(models.Model): pass Created() self.assertEqual(received, []) def test_register_model_class_senders_immediately(self): """ Model signals registered with model classes as senders don't use the Apps.lazy_model_operation() mechanism. """ # Book isn't registered with apps2, so it will linger in # apps2._pending_operations if ModelSignal does the wrong thing. apps2 = Apps() signals.post_init.connect(self.receiver, sender=Book, apps=apps2) self.assertEqual(list(apps2._pending_operations), [])
guettli/django
tests/signals/tests.py
Python
bsd-3-clause
12,295
#!/usr/bin/env python # -*- encoding: utf-8 -*- from . import Request from pygithub3.resources.repos import Repo class List(Request): uri = 'repos/{user}/{repo}/forks' resource = Repo class Create(Request): uri = '/repos/{user}/{repo}/forks' resource = Repo
dongguangming/python-github3
pygithub3/requests/repos/forks.py
Python
isc
282
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Generic Internet address helper functions.""" import socket import dns.ipv4 import dns.ipv6 # We assume that AF_INET is always defined. AF_INET = socket.AF_INET # AF_INET6 might not be defined in the socket module, but we need it. # We'll try to use the socket module's value, and if it doesn't work, # we'll use our own value. try: AF_INET6 = socket.AF_INET6 except AttributeError: AF_INET6 = 9999 def inet_pton(family, text): """Convert the textual form of a network address into its binary form. @param family: the address family @type family: int @param text: the textual address @type text: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ if family == AF_INET: return dns.ipv4.inet_aton(text) elif family == AF_INET6: return dns.ipv6.inet_aton(text) else: raise NotImplementedError def inet_ntop(family, address): """Convert the binary form of a network address into its textual form. @param family: the address family @type family: int @param address: the binary address @type address: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ if family == AF_INET: return dns.ipv4.inet_ntoa(address) elif family == AF_INET6: return dns.ipv6.inet_ntoa(address) else: raise NotImplementedError def af_for_address(text): """Determine the address family of a textual-form network address. @param text: the textual address @type text: string @raises ValueError: the address family cannot be determined from the input. @rtype: int """ try: dns.ipv4.inet_aton(text) return AF_INET except Exception: try: dns.ipv6.inet_aton(text) return AF_INET6 except: raise ValueError def is_multicast(text): """Is the textual-form network address a multicast address? @param text: the textual address @raises ValueError: the address family cannot be determined from the input. @rtype: bool """ try: first = ord(dns.ipv4.inet_aton(text)[0]) return first >= 224 and first <= 239 except Exception: try: first = ord(dns.ipv6.inet_aton(text)[0]) return first == 255 except Exception: raise ValueError
burzillibus/RobHome
venv/lib/python2.7/site-packages/dns/inet.py
Python
mit
3,242
class A(object): def __init__(self, attribute): self.attribute = attribute print "Initializing A" attribute = "hello" def my_method(self): print self.attribute a = A() a.my_method() ##c <config> <classSelection>0</classSelection> <attributeSelection> <int>0</int> </attributeSelection> <methodOffsetStrategy>1</methodOffsetStrategy> <propertyOffsetStrategy>4</propertyOffsetStrategy> <methodSelection> <int>0</int> <int>2</int> </methodSelection> <accessModifier>1</accessModifier> </config> ##r class A(object): def __init__(self, attribute): self.attribute = attribute def get_attribute(self): return self.__attribute def del_attribute(self): del self.__attribute print "Initializing A" attribute = "hello" def my_method(self): print self.attribute attribute = property(get_attribute, None, del_attribute, None) a = A() a.my_method()
aptana/Pydev
tests/org.python.pydev.refactoring.tests/src/python/codegenerator/generateproperties/testGenerateProperties3.py
Python
epl-1.0
995
# # -*- coding: utf-8 -*- # Copyright 2019 Cisco and/or its affiliates. # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # Telemetry Command Reference File from __future__ import absolute_import, division, print_function __metaclass__ = type TMS_GLOBAL = ''' # The cmd_ref is a yaml formatted list of module commands. # A leading underscore denotes a non-command variable; e.g. _template. # TMS does not have convenient global json data so this cmd_ref uses raw cli configs. --- _template: # _template holds common settings for all commands # Enable feature telemetry if disabled feature: telemetry # Common get syntax for TMS commands get_command: show run telemetry all # Parent configuration for TMS commands context: - telemetry certificate: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] kind: dict getval: certificate (?P<key>\\S+) (?P<hostname>\\S+)$ setval: certificate {key} {hostname} default: key: ~ hostname: ~ compression: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] kind: str getval: use-compression (\\S+)$ setval: 'use-compression {0}' default: ~ context: &dpcontext - telemetry - destination-profile source_interface: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] kind: str getval: source-interface (\\S+)$ setval: 'source-interface {0}' default: ~ context: *dpcontext vrf: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] kind: str getval: use-vrf (\\S+)$ setval: 'use-vrf {0}' default: ~ context: *dpcontext ''' TMS_DESTGROUP = ''' # The cmd_ref is a yaml formatted list of module commands. # A leading underscore denotes a non-command variable; e.g. _template. # TBD: Use Structured Where Possible --- _template: # _template holds common settings for all commands # Enable feature telemetry if disabled feature: telemetry # Common get syntax for TMS commands get_command: show run telemetry all # Parent configuration for TMS commands context: - telemetry destination: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] multiple: true kind: dict getval: ip address (?P<ip>\\S+) port (?P<port>\\S+) protocol (?P<protocol>\\S+) encoding (?P<encoding>\\S+) setval: ip address {ip} port {port} protocol {protocol} encoding {encoding} default: ip: ~ port: ~ protocol: ~ encoding: ~ ''' TMS_SENSORGROUP = ''' # The cmd_ref is a yaml formatted list of module commands. # A leading underscore denotes a non-command variable; e.g. _template. # TBD: Use Structured Where Possible --- _template: # _template holds common settings for all commands # Enable feature telemetry if disabled feature: telemetry # Common get syntax for TMS commands get_command: show run telemetry all # Parent configuration for TMS commands context: - telemetry data_source: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] kind: str getval: data-source (\\S+)$ setval: 'data-source {0}' default: ~ path: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] multiple: true kind: dict getval: path (?P<name>(\\S+|".*"))( depth (?P<depth>\\S+))?( query-condition (?P<query_condition>\\S+))?( filter-condition (?P<filter_condition>\\S+))?$ setval: path {name} depth {depth} query-condition {query_condition} filter-condition {filter_condition} default: name: ~ depth: ~ query_condition: ~ filter_condition: ~ ''' TMS_SUBSCRIPTION = ''' # The cmd_ref is a yaml formatted list of module commands. # A leading underscore denotes a non-command variable; e.g. _template. # TBD: Use Structured Where Possible --- _template: # _template holds common settings for all commands # Enable feature telemetry if disabled feature: telemetry # Common get syntax for TMS commands get_command: show run telemetry all # Parent configuration for TMS commands context: - telemetry destination_group: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] multiple: true kind: int getval: dst-grp (\\S+)$ setval: 'dst-grp {0}' default: ~ sensor_group: _exclude: ['N3K', 'N5K', 'N6k', 'N7k'] multiple: true kind: dict getval: snsr-grp (?P<id>\\S+) sample-interval (?P<sample_interval>\\S+)$ setval: snsr-grp {id} sample-interval {sample_interval} default: id: ~ sample_interval: ~ '''
shsingh/ansible
lib/ansible/module_utils/network/nxos/cmdref/telemetry/telemetry.py
Python
gpl-3.0
4,241
# Copyright 2013 Brocade Communications System, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Authors: # Varma Bhupatiraju (vbhupati@#brocade.com) # Shiv Haris (sharis@brocade.com) """FAKE DRIVER, for unit tests purposes. Brocade NOS Driver implements NETCONF over SSHv2 for Neutron network life-cycle management. """ class NOSdriver(): """NOS NETCONF interface driver for Neutron network. Fake: Handles life-cycle management of Neutron network, leverages AMPP on NOS (for use by unit tests, avoids touching any hardware) """ def __init__(self): pass def connect(self, host, username, password): """Connect via SSH and initialize the NETCONF session.""" pass def create_network(self, host, username, password, net_id): """Creates a new virtual network.""" pass def delete_network(self, host, username, password, net_id): """Deletes a virtual network.""" pass def associate_mac_to_network(self, host, username, password, net_id, mac): """Associates a MAC address to virtual network.""" pass def dissociate_mac_from_network(self, host, username, password, net_id, mac): """Dissociates a MAC address from virtual network.""" pass def create_vlan_interface(self, mgr, vlan_id): """Configures a VLAN interface.""" pass def delete_vlan_interface(self, mgr, vlan_id): """Deletes a VLAN interface.""" pass def get_port_profiles(self, mgr): """Retrieves all port profiles.""" pass def get_port_profile(self, mgr, name): """Retrieves a port profile.""" pass def create_port_profile(self, mgr, name): """Creates a port profile.""" pass def delete_port_profile(self, mgr, name): """Deletes a port profile.""" pass def activate_port_profile(self, mgr, name): """Activates a port profile.""" pass def deactivate_port_profile(self, mgr, name): """Deactivates a port profile.""" pass def associate_mac_to_port_profile(self, mgr, name, mac_address): """Associates a MAC address to a port profile.""" pass def dissociate_mac_from_port_profile(self, mgr, name, mac_address): """Dissociates a MAC address from a port profile.""" pass def create_vlan_profile_for_port_profile(self, mgr, name): """Creates VLAN sub-profile for port profile.""" pass def configure_l2_mode_for_vlan_profile(self, mgr, name): """Configures L2 mode for VLAN sub-profile.""" pass def configure_trunk_mode_for_vlan_profile(self, mgr, name): """Configures trunk mode for VLAN sub-profile.""" pass def configure_allowed_vlans_for_vlan_profile(self, mgr, name, vlan_id): """Configures allowed VLANs for VLAN sub-profile.""" pass
virtualopensystems/neutron
neutron/plugins/brocade/nos/fake_nosdriver.py
Python
apache-2.0
3,548
# -*- coding: utf-8 -*- from typing import Text from zerver.lib.test_classes import WebhookTestCase class PagerDutyHookTests(WebhookTestCase): STREAM_NAME = 'pagerduty' URL_TEMPLATE = u"/api/v1/external/pagerduty?api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = 'pagerduty' def test_trigger(self) -> None: expected_message = ':imp: Incident [3](https://zulip-test.pagerduty.com/incidents/P140S4Y) triggered by [Test service](https://zulip-test.pagerduty.com/services/PIL5CUQ) and assigned to [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>foo' self.send_and_test_stream_message('trigger', u"incident 3", expected_message) def test_unacknowledge(self) -> None: expected_message = ':imp: Incident [3](https://zulip-test.pagerduty.com/incidents/P140S4Y) unacknowledged by [Test service](https://zulip-test.pagerduty.com/services/PIL5CUQ) and assigned to [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>foo' self.send_and_test_stream_message('unacknowledge', u"incident 3", expected_message) def test_resolved(self) -> None: expected_message = ':grinning: Incident [1](https://zulip-test.pagerduty.com/incidents/PO1XIJ5) resolved by [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>It is on fire' self.send_and_test_stream_message('resolved', u"incident 1", expected_message) def test_auto_resolved(self) -> None: expected_message = ':grinning: Incident [2](https://zulip-test.pagerduty.com/incidents/PX7K9J2) resolved\n\n>new' self.send_and_test_stream_message('auto_resolved', u"incident 2", expected_message) def test_acknowledge(self) -> None: expected_message = ':no_good: Incident [1](https://zulip-test.pagerduty.com/incidents/PO1XIJ5) acknowledged by [armooo@](https://zulip-test.pagerduty.com/users/POBCFRJ)\n\n>It is on fire' self.send_and_test_stream_message('acknowledge', u"incident 1", expected_message) def test_no_subject(self) -> None: expected_message = u':grinning: Incident [48219](https://dropbox.pagerduty.com/incidents/PJKGZF9) resolved\n\n>mp_error_block_down_critical\u2119\u01b4' self.send_and_test_stream_message('mp_fail', u"incident 48219", expected_message) def test_bad_message(self) -> None: expected_message = 'Unknown pagerduty message\n```\n{\n "type":"incident.triggered"\n}\n```' self.send_and_test_stream_message('bad_message_type', u"pagerduty", expected_message) def test_unknown_message_type(self) -> None: expected_message = 'Unknown pagerduty message\n```\n{\n "type":"foo"\n}\n```' self.send_and_test_stream_message('unknown_message_type', u"pagerduty", expected_message)
mahim97/zulip
zerver/webhooks/pagerduty/tests.py
Python
apache-2.0
2,743
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for ``flocker.provision._install``. """ import yaml from twisted.trial.unittest import SynchronousTestCase from pyrsistent import freeze, thaw from textwrap import dedent from .._install import ( task_configure_flocker_agent, task_enable_flocker_agent, run, put, run_from_args, get_repository_url, UnsupportedDistribution, get_installable_version, get_repo_options, _remove_dataset_fields, _remove_private_key, ) from .._ssh import Put from .._effect import sequence from ...acceptance.testtools import DatasetBackend from ... import __version__ as flocker_version THE_AGENT_YML_PATH = b"/etc/flocker/agent.yml" BASIC_AGENT_YML = freeze({ "version": 1, "control-service": { "hostname": "192.0.2.42", "port": 4524, }, "dataset": { "backend": "zfs", }, }) class ConfigureFlockerAgentTests(SynchronousTestCase): """ Tests for ``task_configure_flocker_agent``. """ def test_agent_yml(self): """ ```task_configure_flocker_agent`` writes a ``/etc/flocker/agent.yml`` file which contains the backend configuration passed to it. """ control_address = BASIC_AGENT_YML["control-service"]["hostname"] expected_pool = u"some-test-pool" expected_backend_configuration = dict(pool=expected_pool) commands = task_configure_flocker_agent( control_node=control_address, dataset_backend=DatasetBackend.lookupByName( BASIC_AGENT_YML["dataset"]["backend"] ), dataset_backend_configuration=expected_backend_configuration, ) [put_agent_yml] = list( effect.intent for effect in commands.intent.effects if isinstance(effect.intent, Put) ) # Seems like transform should be usable here but I don't know how. expected_agent_config = BASIC_AGENT_YML.set( "dataset", BASIC_AGENT_YML["dataset"].update(expected_backend_configuration) ) self.assertEqual( put( content=yaml.safe_dump(thaw(expected_agent_config)), path=THE_AGENT_YML_PATH, log_content_filter=_remove_dataset_fields, ).intent, put_agent_yml, ) class EnableFlockerAgentTests(SynchronousTestCase): """ Tests for ``task_enable_flocker_agent``. """ def test_centos_sequence(self): """ ``task_enable_flocker_agent`` for the 'centos-7' distribution returns a sequence of systemctl enable and restart commands for each agent. """ distribution = u"centos-7" commands = task_enable_flocker_agent( distribution=distribution, ) expected_sequence = sequence([ run(command="systemctl enable flocker-dataset-agent"), run(command="systemctl restart flocker-dataset-agent"), run(command="systemctl enable flocker-container-agent"), run(command="systemctl restart flocker-container-agent"), ]) self.assertEqual(commands, expected_sequence) def test_ubuntu_sequence(self): """ ``task_enable_flocker_agent`` for the 'ubuntu-14.04' distribution returns a sequence of 'service start' commands for each agent. """ distribution = u"ubuntu-14.04" commands = task_enable_flocker_agent( distribution=distribution, ) expected_sequence = sequence([ run(command="service flocker-dataset-agent start"), run(command="service flocker-container-agent start"), ]) self.assertEqual(commands, expected_sequence) def _centos7_install_commands(version): """ Construct the command sequence expected for installing Flocker on CentOS 7. :param str version: A Flocker native OS package version (a package name suffix) like ``"-1.2.3-1"``. :return: The sequence of commands expected for installing Flocker on CentOS7. """ installable_version = get_installable_version(flocker_version) return sequence([ run(command="yum clean all"), run(command="yum install -y {}".format(get_repository_url( distribution='centos-7', flocker_version=installable_version, ))), run_from_args( ['yum', 'install'] + get_repo_options(installable_version) + ['-y', 'clusterhq-flocker-node' + version]) ]) class GetRepoOptionsTests(SynchronousTestCase): """ Tests for ``get_repo_options``. """ def test_marketing_release(self): """ No extra repositories are enabled if the latest installable version is a marketing release. """ self.assertEqual(get_repo_options(flocker_version='0.3.0'), []) def test_development_release(self): """ Enabling a testing repository is enabled if the latest installable version is not a marketing release. """ self.assertEqual( get_repo_options(flocker_version='0.3.0.dev1'), ['--enablerepo=clusterhq-testing']) class GetRepositoryURLTests(SynchronousTestCase): """ Tests for ``get_repository_url``. """ def test_centos_7(self): """ It is possible to get a repository URL for CentOS 7 packages. """ expected = ("https://clusterhq-archive.s3.amazonaws.com/centos/" "clusterhq-release$(rpm -E %dist).noarch.rpm") self.assertEqual( get_repository_url( distribution='centos-7', flocker_version='0.3.0'), expected ) def test_ubuntu_14_04(self): """ It is possible to get a repository URL for Ubuntu 14.04 packages. """ expected = ("https://clusterhq-archive.s3.amazonaws.com/ubuntu/" "$(lsb_release --release --short)/\\$(ARCH)") self.assertEqual( get_repository_url( distribution='ubuntu-14.04', flocker_version='0.3.0'), expected ) def test_ubuntu_15_04(self): """ It is possible to get a repository URL for Ubuntu 15.04 packages. """ expected = ("https://clusterhq-archive.s3.amazonaws.com/ubuntu/" "$(lsb_release --release --short)/\\$(ARCH)") self.assertEqual( get_repository_url( distribution='ubuntu-15.04', flocker_version='0.3.0'), expected ) def test_unsupported_distribution(self): """ An ``UnsupportedDistribution`` error is thrown if a repository for the desired distribution cannot be found. """ self.assertRaises( UnsupportedDistribution, get_repository_url, 'unsupported-os', '0.3.0', ) def test_non_release_ubuntu(self): """ The operating system key for ubuntu has the suffix ``-testing`` for non-marketing releases. """ expected = ("https://clusterhq-archive.s3.amazonaws.com/" "ubuntu-testing/" "$(lsb_release --release --short)/\\$(ARCH)") self.assertEqual( get_repository_url( distribution='ubuntu-14.04', flocker_version='0.3.0.dev1'), expected ) def test_non_release_centos(self): """ The operating system key for centos stays the same non-marketing releases. """ expected = ("https://clusterhq-archive.s3.amazonaws.com/centos/" "clusterhq-release$(rpm -E %dist).noarch.rpm") self.assertEqual( get_repository_url( distribution='centos-7', flocker_version='0.3.0.dev1'), expected ) class PrivateKeyLoggingTest(SynchronousTestCase): """ Test removal of private keys from logs. """ def test_private_key_removed(self): """ A private key is removed for logging. """ key = dedent(''' -----BEGIN PRIVATE KEY----- MFDkDKSLDDSf MFSENSITIVED MDKODSFJOEWe -----END PRIVATE KEY----- ''') self.assertEqual( dedent(''' -----BEGIN PRIVATE KEY----- MFDk...REMOVED...OEWe -----END PRIVATE KEY----- '''), _remove_private_key(key)) def test_non_key_kept(self): """ Non-key data is kept for logging. """ key = 'some random data, not a key' self.assertEqual(key, _remove_private_key(key)) def test_short_key_kept(self): """ A key that is suspiciously short is kept for logging. """ key = dedent(''' -----BEGIN PRIVATE KEY----- short -----END PRIVATE KEY----- ''') self.assertEqual(key, _remove_private_key(key)) def test_no_end_key_removed(self): """ A missing end tag does not prevent removal working. """ key = dedent(''' -----BEGIN PRIVATE KEY----- MFDkDKSLDDSf MFSENSITIVED MDKODSFJOEWe ''') self.assertEqual( '\n-----BEGIN PRIVATE KEY-----\nMFDk...REMOVED...OEWe\n', _remove_private_key(key)) class DatasetLoggingTest(SynchronousTestCase): """ Test removal of sensitive information from logged configuration files. """ def test_dataset_logged_safely(self): """ Values are either the same or replaced by 'REMOVED'. """ config = { 'dataset': { 'secret': 'SENSITIVE', 'zone': 'keep' } } content = yaml.safe_dump(config) logged = _remove_dataset_fields(content) self.assertEqual( yaml.safe_load(logged), {'dataset': {'secret': 'REMOVED', 'zone': 'keep'}})
AndyHuu/flocker
flocker/provision/test/test_install.py
Python
apache-2.0
10,236
#!/usr/bin/env python # -*- coding: utf-8 -*- import os head = os.path.dirname(__file__) pygtkweb = os.path.join(head, '..', '..', '..', 'pygtkweb') TARGETS = { 'AutoGtk.py': dict( options=[ '--library_dir', os.path.join(pygtkweb, 'library'), ], ) } PACKAGE = { 'title': 'pywebgtkbuilder', 'desc': 'Python Web-Gtk "GtkBuilder" example', } def setup(targets): '''Setup example for translation, MUST call util.setup(targets).''' util.setup(targets) def translate(): '''Translate example, MUST call util.translate().''' util.translate() def install(package): '''Install and cleanup example module. MUST call util.install(package)''' util.install(package) ##---------------------------------------## # --------- (-: DO NOT EDIT :-) --------- # ##---------------------------------------## import sys import os examples = head = os.path.abspath(os.path.dirname(__file__)) while os.path.split(examples)[1].lower() != 'examples': examples = os.path.split(examples)[0] if not examples: raise ValueError("Cannot determine examples directory") sys.path.insert(0, os.path.join(examples)) from _examples import util sys.path.pop(0) util.init(head) setup(TARGETS) translate() install(PACKAGE)
spaceone/pyjs
examples/deprecated/pywebgtkbuilder/__main__.py
Python
apache-2.0
1,294
# Tracing in Jython works somewhat similarly to CPython, with the following exceptions: # # - No support for jump. Can't do that without dynamic bytecode # rewriting OR at least until we support a Python bytecode # interpreter # # - Some differences in how we compile, which results in different # trace orders. This is of course an implementation detail. For # example, we do not bother to dead-code while 0: loops because the # JVM does a good job of that (and more aggressively than CPython # for example, it should be to see comparable things like while # False). # # - Related to this, we record f.setlineno in too many places in our # code and not at all in the try, since this doesn't correspond to a # bytecode on the JVM. The latter records events separately. # # Testing the line trace facility. from test import test_support import unittest import sys import difflib # A very basic example. If this fails, we're in deep trouble. def basic(): return 1 basic.events = [(0, 'call'), (1, 'line'), (1, 'return')] # Many of the tests below are tricky because they involve pass statements. # If there is implicit control flow around a pass statement (in an except # clause or else caluse) under what conditions do you set a line number # following that clause? # The entire "while 0:" statement is optimized away. No code # exists for it, so the line numbers skip directly from "del x" # to "x = 1". def arigo_example(): x = 1 del x while 0: pass x = 1 arigo_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (5, 'line'), (5, 'return')] # check that lines consisting of just one instruction get traced: def one_instr_line(): x = 1 del x x = 1 one_instr_line.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (3, 'return')] def no_pop_tops(): # 0 x = 1 # 1 for a in range(2): # 2 if a: # 3 x = 1 # 4 else: # 5 x = 1 # 6 no_pop_tops.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (6, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (2, 'line'), (2, 'return')] def no_pop_blocks(): y = 1 while not y: bla x = 1 no_pop_blocks.events = [(0, 'call'), (1, 'line'), (2, 'line'), (4, 'line'), (4, 'return')] def called(): # line -3 x = 1 def call(): # line 0 called() call.events = [(0, 'call'), (1, 'line'), (-3, 'call'), (-2, 'line'), (-2, 'return'), (1, 'return')] def raises(): raise Exception def test_raise(): try: raises() except Exception, exc: x = 1 test_raise.events = [(0, 'call'), (1, 'line'), (2, 'line'), (-3, 'call'), (-2, 'line'), (-2, 'exception'), (-2, 'return'), (2, 'exception'), (3, 'line'), (4, 'line'), (4, 'return')] def _settrace_and_return(tracefunc): sys.settrace(tracefunc) sys._getframe().f_back.f_trace = tracefunc def settrace_and_return(tracefunc): _settrace_and_return(tracefunc) settrace_and_return.events = [(1, 'return')] def _settrace_and_raise(tracefunc): sys.settrace(tracefunc) sys._getframe().f_back.f_trace = tracefunc raise RuntimeError def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) except RuntimeError, exc: pass settrace_and_raise.events = [(2, 'exception'), (3, 'line'), (4, 'line'), (4, 'return')] # implicit return example # This test is interesting because of the else: pass # part of the code. The code generate for the true # part of the if contains a jump past the else branch. # The compiler then generates an implicit "return None" # Internally, the compiler visits the pass statement # and stores its line number for use on the next instruction. # The next instruction is the implicit return None. def ireturn_example(): a = 5 b = 5 if a == b: b = a+1 else: pass ireturn_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (6, 'line'), (6, 'return')] # Tight loop with while(1) example (SF #765624) def tightloop_example(): items = range(0, 3) try: i = 0 while 1: b = items[i]; i+=1 except IndexError: pass tightloop_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (5, 'line'), (5, 'line'), (5, 'line'), (5, 'line'), (5, 'exception'), (6, 'line'), (7, 'line'), (7, 'return')] def tighterloop_example(): items = range(1, 4) try: i = 0 while 1: i = items[i] except IndexError: pass tighterloop_example.events = [(0, 'call'), (1, 'line'), (2, 'line'), (3, 'line'), (4, 'line'), (4, 'line'), (4, 'line'), (4, 'line'), (4, 'exception'), (5, 'line'), (6, 'line'), (6, 'return')] def generator_function(): try: yield True "continued" finally: "finally" def generator_example(): # any() will leave the generator before its end x = any(generator_function()) # the following lines were not traced for x in range(10): y = x generator_example.events = ([(0, 'call'), (2, 'line'), (-6, 'call'), (-5, 'line'), (-4, 'line'), (-4, 'return'), (-4, 'call'), (-4, 'exception'), (-1, 'line'), (-1, 'return')] + [(5, 'line'), (6, 'line')] * 10 + [(5, 'line'), (5, 'return')]) class Tracer: def __init__(self): self.events = [] def trace(self, frame, event, arg): self.events.append((frame.f_lineno, event)) return self.trace def traceWithGenexp(self, frame, event, arg): (o for o in [1]) self.events.append((frame.f_lineno, event)) return self.trace class TraceTestCase(unittest.TestCase): def compare_events(self, line_offset, events, expected_events): events = [(l - line_offset, e) for (l, e) in events] if events != expected_events: self.fail( "events did not match expectation:\n" + "\n".join(difflib.ndiff([str(x) for x in expected_events], [str(x) for x in events]))) def run_and_compare(self, func, events): tracer = Tracer() sys.settrace(tracer.trace) func() sys.settrace(None) self.compare_events(func.func_code.co_firstlineno, tracer.events, events) def run_test(self, func): self.run_and_compare(func, func.events) def run_test2(self, func): tracer = Tracer() func(tracer.trace) sys.settrace(None) self.compare_events(func.func_code.co_firstlineno, tracer.events, func.events) def test_01_basic(self): self.run_test(basic) def test_02_arigo(self): self.run_test(arigo_example) def test_03_one_instr(self): self.run_test(one_instr_line) def test_04_no_pop_blocks(self): self.run_test(no_pop_blocks) def test_05_no_pop_tops(self): self.run_test(no_pop_tops) def test_06_call(self): self.run_test(call) def test_07_raise(self): self.run_test(test_raise) def test_08_settrace_and_return(self): self.run_test2(settrace_and_return) def test_09_settrace_and_raise(self): self.run_test2(settrace_and_raise) def test_10_ireturn(self): self.run_test(ireturn_example) def test_11_tightloop(self): self.run_test(tightloop_example) def test_12_tighterloop(self): self.run_test(tighterloop_example) def test_13_genexp(self): self.run_test(generator_example) # issue1265: if the trace function contains a generator, # and if the traced function contains another generator # that is not completely exhausted, the trace stopped. # Worse: the 'finally' clause was not invoked. tracer = Tracer() sys.settrace(tracer.traceWithGenexp) generator_example() sys.settrace(None) self.compare_events(generator_example.func_code.co_firstlineno, tracer.events, generator_example.events) def test_14_onliner_if(self): def onliners(): if True: False else: True return 0 self.run_and_compare( onliners, [(0, 'call'), (1, 'line'), (3, 'line'), (3, 'return')]) def test_15_loops(self): # issue1750076: "while" expression is skipped by debugger def for_example(): for x in range(2): pass self.run_and_compare( for_example, [(0, 'call'), (1, 'line'), (2, 'line'), (1, 'line'), (2, 'line'), (1, 'line'), (1, 'return')]) def while_example(): # While expression should be traced on every loop x = 2 while x > 0: x -= 1 self.run_and_compare( while_example, [(0, 'call'), (2, 'line'), (3, 'line'), (4, 'line'), (3, 'line'), (4, 'line'), (3, 'line'), (3, 'return')]) def test_16_blank_lines(self): exec("def f():\n" + "\n" * 256 + " pass") self.run_and_compare( f, [(0, 'call'), (257, 'line'), (257, 'return')]) class RaisingTraceFuncTestCase(unittest.TestCase): def trace(self, frame, event, arg): """A trace function that raises an exception in response to a specific trace event.""" if event == self.raiseOnEvent: raise ValueError # just something that isn't RuntimeError else: return self.trace def f(self): """The function to trace; raises an exception if that's the case we're testing, so that the 'exception' trace event fires.""" if self.raiseOnEvent == 'exception': x = 0 y = 1/x else: return 1 def run_test_for_event(self, event): """Tests that an exception raised in response to the given event is handled OK.""" self.raiseOnEvent = event try: for i in xrange(sys.getrecursionlimit() + 1): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail("exception not thrown!") except RuntimeError: self.fail("recursion counter not reset") # Test the handling of exceptions raised by each kind of trace event. def test_call(self): self.run_test_for_event('call') def test_line(self): self.run_test_for_event('line') def test_return(self): self.run_test_for_event('return') def test_exception(self): self.run_test_for_event('exception') def test_trash_stack(self): def f(): for i in range(5): print i # line tracing will raise an exception at this line def g(frame, why, extra): if (why == 'line' and frame.f_lineno == f.func_code.co_firstlineno + 2): raise RuntimeError, "i am crashing" return g sys.settrace(g) try: f() except RuntimeError: # the test is really that this doesn't segfault: import gc gc.collect() else: self.fail("exception not propagated") # 'Jump' tests: assigning to frame.f_lineno within a trace function # moves the execution position - it's how debuggers implement a Jump # command (aka. "Set next statement"). class JumpTracer: """Defines a trace function that jumps from one place to another, with the source and destination lines of the jump being defined by the 'jump' property of the function under test.""" def __init__(self, function): self.function = function self.jumpFrom = function.jump[0] self.jumpTo = function.jump[1] self.done = False def trace(self, frame, event, arg): if not self.done and frame.f_code == self.function.func_code: firstLine = frame.f_code.co_firstlineno if frame.f_lineno == firstLine + self.jumpFrom: # Cope with non-integer self.jumpTo (because of # no_jump_to_non_integers below). try: frame.f_lineno = firstLine + self.jumpTo except TypeError: frame.f_lineno = self.jumpTo self.done = True return self.trace # The first set of 'jump' tests are for things that are allowed: def jump_simple_forwards(output): output.append(1) output.append(2) output.append(3) jump_simple_forwards.jump = (1, 3) jump_simple_forwards.output = [3] def jump_simple_backwards(output): output.append(1) output.append(2) jump_simple_backwards.jump = (2, 1) jump_simple_backwards.output = [1, 1, 2] def jump_out_of_block_forwards(output): for i in 1, 2: output.append(2) for j in [3]: # Also tests jumping over a block output.append(4) output.append(5) jump_out_of_block_forwards.jump = (3, 5) jump_out_of_block_forwards.output = [2, 5] def jump_out_of_block_backwards(output): output.append(1) for i in [1]: output.append(3) for j in [2]: # Also tests jumping over a block output.append(5) output.append(6) output.append(7) jump_out_of_block_backwards.jump = (6, 1) jump_out_of_block_backwards.output = [1, 3, 5, 1, 3, 5, 6, 7] def jump_to_codeless_line(output): output.append(1) # Jumping to this line should skip to the next one. output.append(3) jump_to_codeless_line.jump = (1, 2) jump_to_codeless_line.output = [3] def jump_to_same_line(output): output.append(1) output.append(2) output.append(3) jump_to_same_line.jump = (2, 2) jump_to_same_line.output = [1, 2, 3] # Tests jumping within a finally block, and over one. def jump_in_nested_finally(output): try: output.append(2) finally: output.append(4) try: output.append(6) finally: output.append(8) output.append(9) jump_in_nested_finally.jump = (4, 9) jump_in_nested_finally.output = [2, 9] # The second set of 'jump' tests are for things that are not allowed: def no_jump_too_far_forwards(output): try: output.append(2) output.append(3) except ValueError, e: output.append('after' in str(e)) no_jump_too_far_forwards.jump = (3, 6) no_jump_too_far_forwards.output = [2, True] def no_jump_too_far_backwards(output): try: output.append(2) output.append(3) except ValueError, e: output.append('before' in str(e)) no_jump_too_far_backwards.jump = (3, -1) no_jump_too_far_backwards.output = [2, True] # Test each kind of 'except' line. def no_jump_to_except_1(output): try: output.append(2) except: e = sys.exc_info()[1] output.append('except' in str(e)) no_jump_to_except_1.jump = (2, 3) no_jump_to_except_1.output = [True] def no_jump_to_except_2(output): try: output.append(2) except ValueError: e = sys.exc_info()[1] output.append('except' in str(e)) no_jump_to_except_2.jump = (2, 3) no_jump_to_except_2.output = [True] def no_jump_to_except_3(output): try: output.append(2) except ValueError, e: output.append('except' in str(e)) no_jump_to_except_3.jump = (2, 3) no_jump_to_except_3.output = [True] def no_jump_to_except_4(output): try: output.append(2) except (ValueError, RuntimeError), e: output.append('except' in str(e)) no_jump_to_except_4.jump = (2, 3) no_jump_to_except_4.output = [True] def no_jump_forwards_into_block(output): try: output.append(2) for i in 1, 2: output.append(4) except ValueError, e: output.append('into' in str(e)) no_jump_forwards_into_block.jump = (2, 4) no_jump_forwards_into_block.output = [True] def no_jump_backwards_into_block(output): try: for i in 1, 2: output.append(3) output.append(4) except ValueError, e: output.append('into' in str(e)) no_jump_backwards_into_block.jump = (4, 3) no_jump_backwards_into_block.output = [3, 3, True] def no_jump_into_finally_block(output): try: try: output.append(3) x = 1 finally: output.append(6) except ValueError, e: output.append('finally' in str(e)) no_jump_into_finally_block.jump = (4, 6) no_jump_into_finally_block.output = [3, 6, True] # The 'finally' still runs def no_jump_out_of_finally_block(output): try: try: output.append(3) finally: output.append(5) output.append(6) except ValueError, e: output.append('finally' in str(e)) no_jump_out_of_finally_block.jump = (5, 1) no_jump_out_of_finally_block.output = [3, True] # This verifies the line-numbers-must-be-integers rule. def no_jump_to_non_integers(output): try: output.append(2) except ValueError, e: output.append('integer' in str(e)) no_jump_to_non_integers.jump = (2, "Spam") no_jump_to_non_integers.output = [True] # This verifies that you can't set f_lineno via _getframe or similar # trickery. def no_jump_without_trace_function(): try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno except ValueError, e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e): raise else: # Something's wrong - the expected exception wasn't raised. raise RuntimeError, "Trace-function-less jump failed to fail" class JumpTestCase(unittest.TestCase): def compare_jump_output(self, expected, received): if received != expected: self.fail( "Outputs don't match:\n" + "Expected: " + repr(expected) + "\n" + "Received: " + repr(received)) def run_test(self, func): tracer = JumpTracer(func) sys.settrace(tracer.trace) output = [] func(output) sys.settrace(None) self.compare_jump_output(func.output, output) def test_01_jump_simple_forwards(self): self.run_test(jump_simple_forwards) def test_02_jump_simple_backwards(self): self.run_test(jump_simple_backwards) def test_03_jump_out_of_block_forwards(self): self.run_test(jump_out_of_block_forwards) def test_04_jump_out_of_block_backwards(self): self.run_test(jump_out_of_block_backwards) def test_05_jump_to_codeless_line(self): self.run_test(jump_to_codeless_line) def test_06_jump_to_same_line(self): self.run_test(jump_to_same_line) def test_07_jump_in_nested_finally(self): self.run_test(jump_in_nested_finally) def test_08_no_jump_too_far_forwards(self): self.run_test(no_jump_too_far_forwards) def test_09_no_jump_too_far_backwards(self): self.run_test(no_jump_too_far_backwards) def test_10_no_jump_to_except_1(self): self.run_test(no_jump_to_except_1) def test_11_no_jump_to_except_2(self): self.run_test(no_jump_to_except_2) def test_12_no_jump_to_except_3(self): self.run_test(no_jump_to_except_3) def test_13_no_jump_to_except_4(self): self.run_test(no_jump_to_except_4) def test_14_no_jump_forwards_into_block(self): self.run_test(no_jump_forwards_into_block) def test_15_no_jump_backwards_into_block(self): self.run_test(no_jump_backwards_into_block) def test_16_no_jump_into_finally_block(self): self.run_test(no_jump_into_finally_block) def test_17_no_jump_out_of_finally_block(self): self.run_test(no_jump_out_of_finally_block) def test_18_no_jump_to_non_integers(self): self.run_test(no_jump_to_non_integers) def test_19_no_jump_without_trace_function(self): no_jump_without_trace_function() def test_main(): tests = [TraceTestCase, RaisingTraceFuncTestCase] if not test_support.is_jython: tests.append(JumpTestCase) else: del TraceTestCase.test_02_arigo del TraceTestCase.test_05_no_pop_tops del TraceTestCase.test_07_raise del TraceTestCase.test_09_settrace_and_raise del TraceTestCase.test_10_ireturn del TraceTestCase.test_11_tightloop del TraceTestCase.test_12_tighterloop del TraceTestCase.test_13_genexp del TraceTestCase.test_14_onliner_if del TraceTestCase.test_15_loops test_support.run_unittest(*tests) if __name__ == "__main__": test_main()
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_trace.py
Python
epl-1.0
23,027
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Douglas S. Blank <doug.blank@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard python modules # #------------------------------------------------------------------------- from abc import ABCMeta, abstractmethod import time from collections import deque class DbUndo(metaclass=ABCMeta): """ Base class for the Gramps undo/redo manager. Needs to be subclassed for use with a real backend. """ __slots__ = ('undodb', 'db', 'undo_history_timestamp', 'undoq', 'redoq') def __init__(self, db): """ Class constructor. Set up main instance variables """ self.db = db self.undoq = deque() self.redoq = deque() self.undo_history_timestamp = time.time() def clear(self): """ Clear the undo/redo list (but not the backing storage) """ self.undoq.clear() self.redoq.clear() self.undo_history_timestamp = time.time() def __enter__(self, value): """ Context manager method to establish the context """ self.open(value) return self def __exit__(self, exc_type, exc_val, exc_tb): """ Context manager method to finish the context """ if exc_type is None: self.close() return exc_type is None @abstractmethod def open(self, value): """ Open the backing storage. Needs to be overridden in the derived class. """ @abstractmethod def close(self): """ Close the backing storage. Needs to be overridden in the derived class. """ @abstractmethod def append(self, value): """ Add a new entry on the end. Needs to be overridden in the derived class. """ @abstractmethod def __getitem__(self, index): """ Returns an entry by index number. Needs to be overridden in the derived class. """ @abstractmethod def __setitem__(self, index, value): """ Set an entry to a value. Needs to be overridden in the derived class. """ @abstractmethod def __len__(self): """ Returns the number of entries. Needs to be overridden in the derived class. """ @abstractmethod def _redo(self, update_history): """ """ @abstractmethod def _undo(self, update_history): """ """ def commit(self, txn, msg): """ Commit the transaction to the undo/redo database. "txn" should be an instance of Gramps transaction class """ txn.set_description(msg) txn.timestamp = time.time() self.undoq.append(txn) def undo(self, update_history=True): """ Undo a previously committed transaction """ if self.db.readonly or self.undo_count == 0: return False return self._undo(update_history) def redo(self, update_history=True): """ Redo a previously committed, then undone, transaction """ if self.db.readonly or self.redo_count == 0: return False return self._redo(update_history) undo_count = property(lambda self:len(self.undoq)) redo_count = property(lambda self:len(self.redoq))
sam-m888/gramps
gramps/gen/db/undoredo.py
Python
gpl-2.0
4,160
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import fields, osv class product_product(osv.osv): _inherit = 'product.product' _columns = { 'manufacturer' : fields.many2one('res.partner', 'Manufacturer'), 'manufacturer_pname' : fields.char('Manufacturer Product Name', size=64), 'manufacturer_pref' : fields.char('Manufacturer Product Code', size=64), 'attribute_ids': fields.one2many('product.manufacturer.attribute', 'product_id', 'Attributes'), } product_product() class product_attribute(osv.osv): _name = "product.manufacturer.attribute" _description = "Product attributes" _columns = { 'name' : fields.char('Attribute', size=64, required=True), 'value' : fields.char('Value', size=64), 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade'), } product_attribute() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Johnzero/erp
openerp/addons/product_manufacturer/product_manufacturer.py
Python
agpl-3.0
1,864
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from osv import osv, fields class hr_attendance_byweek(osv.osv_memory): _name = 'hr.attendance.week' _description = 'Print Week Attendance Report' _columns = { 'init_date': fields.date('Starting Date', required=True), 'end_date': fields.date('Ending Date', required=True) } _defaults = { 'init_date': lambda *a: time.strftime('%Y-%m-%d'), 'end_date': lambda *a: time.strftime('%Y-%m-%d'), } def print_report(self, cr, uid, ids, context=None): datas = { 'ids': [], 'model': 'hr.employee', 'form': self.read(cr, uid, ids)[0] } return { 'type': 'ir.actions.report.xml', 'report_name': 'hr.attendance.allweeks', 'datas': datas, } hr_attendance_byweek() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
crmccreary/openerp_server
openerp/addons/hr_attendance/wizard/hr_attendance_byweek.py
Python
agpl-3.0
1,878
# Copyright (C) Research In Motion Limited 2011. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS “AS IS” AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL # APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import time from mod_pywebsocket import stream from mod_pywebsocket.handshake.hybi import compute_accept def web_socket_do_extra_handshake(request): # This simulates a broken server that sends a WebSocket frame before the # handshake, and more frames afterwards. It is important that if this # happens the client does not buffer all the frames as the server continues # to send more data - it should abort after reading a reasonable number of # bytes (set arbitrarily to 1024). frame = stream.create_text_frame('\0Frame-contains-thirty-two-bytes') msg = frame msg += 'HTTP/1.1 101 Switching Protocols\r\n' msg += 'Upgrade: websocket\r\n' msg += 'Connection: Upgrade\r\n' msg += 'Sec-WebSocket-Accept: %s\r\n' % compute_accept(request.headers_in['Sec-WebSocket-Key'])[0] msg += '\r\n' request.connection.write(msg) # continue writing data until the client disconnects while True: time.sleep(1) numFrames = 1024 / len(frame) # write over 1024 bytes including the above handshake for i in range(0, numFrames): request.connection.write(frame) def web_socket_transfer_data(request): pass
Xperia-Nicki/android_platform_sony_nicki
external/webkit/LayoutTests/http/tests/websocket/tests/hybi/handshake-fail-by-prepended-null_wsh.py
Python
apache-2.0
2,523
"""This test suite test general Pen stuff, it should not contain FontLab-specific code. """ import unittest from robofab.pens.digestPen import DigestPointPen from robofab.pens.adapterPens import SegmentToPointPen, PointToSegmentPen from robofab.pens.adapterPens import GuessSmoothPointPen from robofab.pens.reverseContourPointPen import ReverseContourPointPen from robofab.test.testSupport import getDemoFontGlyphSetPath from robofab.glifLib import GlyphSet class TestShapes: # Collection of test shapes. It's probably better to add these as # glyphs to the demo font. def square(pen): # a simple square as a closed path (100, 100, 600, 600) pen.beginPath() pen.addPoint((100, 100), "line") pen.addPoint((100, 600), "line") pen.addPoint((600, 600), "line") pen.addPoint((600, 100), "line") pen.endPath() square = staticmethod(square) def onCurveLessQuadShape(pen): pen.beginPath() pen.addPoint((100, 100)) pen.addPoint((100, 600)) pen.addPoint((600, 600)) pen.addPoint((600, 100)) pen.endPath() onCurveLessQuadShape = staticmethod(onCurveLessQuadShape) def openPath(pen): # a simple square as a closed path (100, 100, 600, 600) pen.beginPath() pen.addPoint((100, 100), "move") pen.addPoint((100, 600), "line") pen.addPoint((600, 600), "line") pen.addPoint((600, 100), "line") pen.endPath() openPath = staticmethod(openPath) def circle(pen): pen.beginPath() pen.addPoint((0, 500), "curve") pen.addPoint((0, 800)) pen.addPoint((200, 1000)) pen.addPoint((500, 1000), "curve") pen.addPoint((800, 1000)) pen.addPoint((1000, 800)) pen.addPoint((1000, 500), "curve") pen.addPoint((1000, 200)) pen.addPoint((800, 0)) pen.addPoint((500, 0), "curve") pen.addPoint((200, 0)) pen.addPoint((0, 200)) pen.endPath() circle = staticmethod(circle) class RoundTripTestCase(unittest.TestCase): def _doTest(self, shapeFunc, shapeName): pen = DigestPointPen(ignoreSmoothAndName=True) shapeFunc(pen) digest1 = pen.getDigest() digestPen = DigestPointPen(ignoreSmoothAndName=True) pen = PointToSegmentPen(SegmentToPointPen(digestPen)) shapeFunc(pen) digest2 = digestPen.getDigest() self.assertEqual(digest1, digest2, "%r failed round tripping" % shapeName) def testShapes(self): for name in dir(TestShapes): if name[0] != "_": self._doTest(getattr(TestShapes, name), name) def testShapesFromGlyphSet(self): glyphSet = GlyphSet(getDemoFontGlyphSetPath()) for name in glyphSet.keys(): self._doTest(glyphSet[name].drawPoints, name) def testGuessSmoothPen(self): glyphSet = GlyphSet(getDemoFontGlyphSetPath()) for name in glyphSet.keys(): digestPen = DigestPointPen() glyphSet[name].drawPoints(digestPen) digest1 = digestPen.getDigest() digestPen = DigestPointPen() pen = GuessSmoothPointPen(digestPen) glyphSet[name].drawPoints(pen) digest2 = digestPen.getDigest() self.assertEqual(digest1, digest2) class ReverseContourTestCase(unittest.TestCase): def testReverseContourClosedPath(self): digestPen = DigestPointPen() TestShapes.square(digestPen) d1 = digestPen.getDigest() digestPen = DigestPointPen() pen = ReverseContourPointPen(digestPen) pen.beginPath() pen.addPoint((100, 100), "line") pen.addPoint((600, 100), "line") pen.addPoint((600, 600), "line") pen.addPoint((100, 600), "line") pen.endPath() d2 = digestPen.getDigest() self.assertEqual(d1, d2) def testReverseContourOpenPath(self): digestPen = DigestPointPen() TestShapes.openPath(digestPen) d1 = digestPen.getDigest() digestPen = DigestPointPen() pen = ReverseContourPointPen(digestPen) pen.beginPath() pen.addPoint((600, 100), "move") pen.addPoint((600, 600), "line") pen.addPoint((100, 600), "line") pen.addPoint((100, 100), "line") pen.endPath() d2 = digestPen.getDigest() self.assertEqual(d1, d2) def testReversContourFromGlyphSet(self): glyphSet = GlyphSet(getDemoFontGlyphSetPath()) digestPen = DigestPointPen() glyphSet["testglyph1"].drawPoints(digestPen) digest1 = digestPen.getDigest() digestPen = DigestPointPen() pen = ReverseContourPointPen(digestPen) glyphSet["testglyph1.reversed"].drawPoints(pen) digest2 = digestPen.getDigest() self.assertEqual(digest1, digest2) if __name__ == "__main__": from robofab.test.testSupport import runTests runTests()
schriftgestalt/robofab
Lib/robofab/test/test_pens.py
Python
bsd-3-clause
4,340
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: POGOProtos/Networking/Responses/DiskEncounterResponse.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from POGOProtos.Data import PokemonData_pb2 as POGOProtos_dot_Data_dot_PokemonData__pb2 from POGOProtos.Data.Capture import CaptureProbability_pb2 as POGOProtos_dot_Data_dot_Capture_dot_CaptureProbability__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='POGOProtos/Networking/Responses/DiskEncounterResponse.proto', package='POGOProtos.Networking.Responses', syntax='proto3', serialized_pb=_b('\n;POGOProtos/Networking/Responses/DiskEncounterResponse.proto\x12\x1fPOGOProtos.Networking.Responses\x1a!POGOProtos/Data/PokemonData.proto\x1a\x30POGOProtos/Data/Capture/CaptureProbability.proto\"\xea\x02\n\x15\x44iskEncounterResponse\x12M\n\x06result\x18\x01 \x01(\x0e\x32=.POGOProtos.Networking.Responses.DiskEncounterResponse.Result\x12\x32\n\x0cpokemon_data\x18\x02 \x01(\x0b\x32\x1c.POGOProtos.Data.PokemonData\x12H\n\x13\x63\x61pture_probability\x18\x03 \x01(\x0b\x32+.POGOProtos.Data.Capture.CaptureProbability\"\x83\x01\n\x06Result\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0b\n\x07SUCCESS\x10\x01\x12\x11\n\rNOT_AVAILABLE\x10\x02\x12\x10\n\x0cNOT_IN_RANGE\x10\x03\x12\x1e\n\x1a\x45NCOUNTER_ALREADY_FINISHED\x10\x04\x12\x1a\n\x16POKEMON_INVENTORY_FULL\x10\x05\x62\x06proto3') , dependencies=[POGOProtos_dot_Data_dot_PokemonData__pb2.DESCRIPTOR,POGOProtos_dot_Data_dot_Capture_dot_CaptureProbability__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _DISKENCOUNTERRESPONSE_RESULT = _descriptor.EnumDescriptor( name='Result', full_name='POGOProtos.Networking.Responses.DiskEncounterResponse.Result', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNKNOWN', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='SUCCESS', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='NOT_AVAILABLE', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='NOT_IN_RANGE', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='ENCOUNTER_ALREADY_FINISHED', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='POKEMON_INVENTORY_FULL', index=5, number=5, options=None, type=None), ], containing_type=None, options=None, serialized_start=413, serialized_end=544, ) _sym_db.RegisterEnumDescriptor(_DISKENCOUNTERRESPONSE_RESULT) _DISKENCOUNTERRESPONSE = _descriptor.Descriptor( name='DiskEncounterResponse', full_name='POGOProtos.Networking.Responses.DiskEncounterResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='result', full_name='POGOProtos.Networking.Responses.DiskEncounterResponse.result', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokemon_data', full_name='POGOProtos.Networking.Responses.DiskEncounterResponse.pokemon_data', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='capture_probability', full_name='POGOProtos.Networking.Responses.DiskEncounterResponse.capture_probability', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _DISKENCOUNTERRESPONSE_RESULT, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=182, serialized_end=544, ) _DISKENCOUNTERRESPONSE.fields_by_name['result'].enum_type = _DISKENCOUNTERRESPONSE_RESULT _DISKENCOUNTERRESPONSE.fields_by_name['pokemon_data'].message_type = POGOProtos_dot_Data_dot_PokemonData__pb2._POKEMONDATA _DISKENCOUNTERRESPONSE.fields_by_name['capture_probability'].message_type = POGOProtos_dot_Data_dot_Capture_dot_CaptureProbability__pb2._CAPTUREPROBABILITY _DISKENCOUNTERRESPONSE_RESULT.containing_type = _DISKENCOUNTERRESPONSE DESCRIPTOR.message_types_by_name['DiskEncounterResponse'] = _DISKENCOUNTERRESPONSE DiskEncounterResponse = _reflection.GeneratedProtocolMessageType('DiskEncounterResponse', (_message.Message,), dict( DESCRIPTOR = _DISKENCOUNTERRESPONSE, __module__ = 'POGOProtos.Networking.Responses.DiskEncounterResponse_pb2' # @@protoc_insertion_point(class_scope:POGOProtos.Networking.Responses.DiskEncounterResponse) )) _sym_db.RegisterMessage(DiskEncounterResponse) # @@protoc_insertion_point(module_scope)
Mickey32111/pogom
pogom/pgoapi/protos/POGOProtos/Networking/Responses/DiskEncounterResponse_pb2.py
Python
mit
5,576
# XXX TO DO: # - popup menu # - support partial or total redisplay # - more doc strings # - tooltips # object browser # XXX TO DO: # - for classes/modules, add "open source" to object browser from reprlib import Repr from idlelib.tree import TreeItem, TreeNode, ScrolledCanvas myrepr = Repr() myrepr.maxstring = 100 myrepr.maxother = 100 class ObjectTreeItem(TreeItem): def __init__(self, labeltext, object, setfunction=None): self.labeltext = labeltext self.object = object self.setfunction = setfunction def GetLabelText(self): return self.labeltext def GetText(self): return myrepr.repr(self.object) def GetIconName(self): if not self.IsExpandable(): return "python" def IsEditable(self): return self.setfunction is not None def SetText(self, text): try: value = eval(text) self.setfunction(value) except: pass else: self.object = value def IsExpandable(self): return not not dir(self.object) def GetSubList(self): keys = dir(self.object) sublist = [] for key in keys: try: value = getattr(self.object, key) except AttributeError: continue item = make_objecttreeitem( str(key) + " =", value, lambda value, key=key, object=self.object: setattr(object, key, value)) sublist.append(item) return sublist class ClassTreeItem(ObjectTreeItem): def IsExpandable(self): return True def GetSubList(self): sublist = ObjectTreeItem.GetSubList(self) if len(self.object.__bases__) == 1: item = make_objecttreeitem("__bases__[0] =", self.object.__bases__[0]) else: item = make_objecttreeitem("__bases__ =", self.object.__bases__) sublist.insert(0, item) return sublist class AtomicObjectTreeItem(ObjectTreeItem): def IsExpandable(self): return False class SequenceTreeItem(ObjectTreeItem): def IsExpandable(self): return len(self.object) > 0 def keys(self): return range(len(self.object)) def GetSubList(self): sublist = [] for key in self.keys(): try: value = self.object[key] except KeyError: continue def setfunction(value, key=key, object=self.object): object[key] = value item = make_objecttreeitem("%r:" % (key,), value, setfunction) sublist.append(item) return sublist class DictTreeItem(SequenceTreeItem): def keys(self): keys = list(self.object.keys()) try: keys.sort() except: pass return keys dispatch = { int: AtomicObjectTreeItem, float: AtomicObjectTreeItem, str: AtomicObjectTreeItem, tuple: SequenceTreeItem, list: SequenceTreeItem, dict: DictTreeItem, type: ClassTreeItem, } def make_objecttreeitem(labeltext, object, setfunction=None): t = type(object) if t in dispatch: c = dispatch[t] else: c = ObjectTreeItem return c(labeltext, object, setfunction) def _object_browser(parent): # htest # import sys from tkinter import Toplevel top = Toplevel(parent) top.title("Test debug object browser") x, y = map(int, parent.geometry().split('+')[1:]) top.geometry("+%d+%d" % (x + 100, y + 175)) top.configure(bd=0, bg="yellow") top.focus_set() sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1) sc.frame.pack(expand=1, fill="both") item = make_objecttreeitem("sys", sys) node = TreeNode(sc.canvas, None, item) node.update() if __name__ == '__main__': from unittest import main main('idlelib.idle_test.test_debugobj', verbosity=2, exit=False) from idlelib.idle_test.htest import run run(_object_browser)
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/idlelib/debugobj.py
Python
gpl-2.0
4,055
# -*- coding: utf-8 -*- # This file is part of IRIS: Infrastructure and Release Information System # # Copyright (C) 2013 Intel Corporation # # IRIS is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2.0 as published by the Free Software Foundation. """ This is the views directory for the iris-core project. """
sunshine027/iris-panel
iris/core/views/__init__.py
Python
gpl-2.0
385
import mmap import string, os, re, sys PAGESIZE = mmap.PAGESIZE def test_both(): "Test mmap module on Unix systems and Windows" # Create an mmap'ed file f = open('foo', 'w+') # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages' assert string.find(m, 'foo') == PAGESIZE print ' Length of file:', len(m) / float(PAGESIZE), 'pages' assert len(m) == 2*PAGESIZE print ' Contents of byte 0:', repr(m[0]) assert m[0] == '\0' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '\0\0\0' # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3]='bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) assert m[0] == '3' print ' Contents of first 3 bytes:', repr(m[0:3]) assert m[0:3] == '3\0\0' print ' Contents of second page:', repr(m[PAGESIZE-1 : PAGESIZE + 7]) assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0' m.flush() # Test doing a regular expression match in an mmap'ed file match=re.search('[A-Za-z]+', m) if match == None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length assert start == PAGESIZE assert end == PAGESIZE + 6 # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' assert m.tell() == 0 m.seek(42,1) print ' Seek to 42nd byte' assert m.tell() == 42 m.seek(0,2) print ' Seek to last byte' assert m.tell() == len(m) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: assert 0, 'expected a ValueError but did not get it' # Try resizing map print ' Attempting resize()' try: m.resize( 512 ) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported assert len(m) == 512, "len(m) is %d, but expecting 512" % (len(m),) # Check that we can no longer seek beyond the new size. try: m.seek(513,0) except ValueError: pass else: assert 0, 'Could seek beyond the new size' m.close() os.unlink("foo") print ' Test passed' test_both()
kidmaple/CoolWall
user/python/Lib/test/test_mmap.py
Python
gpl-2.0
3,304
"""Tests for Multireddit class.""" from __future__ import print_function, unicode_literals from praw import errors, objects from .helper import PRAWTest, betamax class MultiredditTest(PRAWTest): def betamax_init(self): self.r.login(self.un, self.un_pswd, disable_warning=True) def test_multireddit_representations(self): multi = objects.Multireddit(self.r, author='Foo', name='Bar') self.assertEqual("Multireddit(author='Foo', name='Bar')", repr(multi)) self.assertEqual('Bar', str(multi)) @betamax() def test_add_and_remove_subreddit(self): multi = self.r.user.get_multireddits()[0] self.assertTrue(self.sr in (x.display_name for x in multi.subreddits)) multi.remove_subreddit(self.sr) multi.refresh() self.assertFalse(self.sr in (x.display_name for x in multi.subreddits)) multi.add_subreddit(self.sr) multi.refresh() self.assertTrue(self.sr in (x.display_name for x in multi.subreddits)) @betamax() def test_create_and_delete_multireddit(self): name = 'PRAW_{0}'.format(self.r.modhash)[:15] multi = self.r.create_multireddit(name) self.assertEqual(name.lower(), multi.name.lower()) self.assertEqual([], multi.subreddits) multi.delete() self.assertRaises(errors.NotFound, multi.refresh) @betamax() def test_copy_multireddit(self): name = 'praw_{0}'.format(self.r.modhash)[:15] multi = self.r.user.get_multireddits()[0] new_multi = multi.copy(name) self.assertNotEqual(multi.name, new_multi.name) self.assertEqual(multi.path, new_multi.copied_from) self.assertEqual(name, new_multi.name) self.assertEqual(multi.subreddits, new_multi.subreddits) @betamax() def test_edit_multireddit(self): name = 'PRAW_{0}'.format(self.r.modhash)[:15] multi = self.r.user.get_multireddits()[0] self.assertNotEqual(name, multi.description_md) self.assertEqual(name, multi.edit(description_md=name).description_md) self.assertEqual(name, multi.refresh().description_md) @betamax() def test_get_my_multis(self): multi = self.r.get_my_multireddits()[0] self.assertEqual('publicempty', multi.display_name) self.assertEqual([], multi.subreddits) @betamax() def test_get_multireddit(self): multi = self.r.user.get_multireddit('publicempty') self.assertEqual('/user/{0}/m/{1}'.format(self.un, 'publicempty'), multi.path) @betamax() def test_multireddit_get_new(self): multi = self.r.user.get_multireddit('publicempty') self.assertEqual([], list(multi.get_new())) @betamax() def test_rename_multireddit(self): name = 'renamed_{0}'.format(self.r.modhash)[:15] multi = self.r.user.get_multireddits()[0] self.assertNotEqual(name, multi.name) self.assertEqual(name, multi.rename(name).name) self.assertEqual(name, multi.refresh().name)
julianwachholz/praw
tests/test_multireddit.py
Python
gpl-3.0
3,055
from PyQt4.QtTest import *
M4rtinK/pyside-android
tests/util/module_wrapper/PySide/QtTest.py
Python
lgpl-2.1
28
# # Autogenerated by Thrift Compiler # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py:new_style # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class Iface(object): def getSyncState(self, authenticationToken): """ Asks the NoteStore to provide information about the status of the user account corresponding to the provided authentication token. Parameters: - authenticationToken """ pass def getSyncStateWithMetrics(self, authenticationToken, clientMetrics): """ Asks the NoteStore to provide information about the status of the user account corresponding to the provided authentication token. This version of 'getSyncState' allows the client to upload coarse- grained usage metrics to the service. @param clientMetrics see the documentation of the ClientUsageMetrics structure for an explanation of the fields that clients can pass to the service. Parameters: - authenticationToken - clientMetrics """ pass def getSyncChunk(self, authenticationToken, afterUSN, maxEntries, fullSyncOnly): """ DEPRECATED - use getFilteredSyncChunk. Parameters: - authenticationToken - afterUSN - maxEntries - fullSyncOnly """ pass def getFilteredSyncChunk(self, authenticationToken, afterUSN, maxEntries, filter): """ Asks the NoteStore to provide the state of the account in order of last modification. This request retrieves one block of the server's state so that a client can make several small requests against a large account rather than getting the entire state in one big message. This call gives fine-grained control of the data that will be received by a client by omitting data elements that a client doesn't need. This may reduce network traffic and sync times. @param afterUSN The client can pass this value to ask only for objects that have been updated after a certain point. This allows the client to receive updates after its last checkpoint rather than doing a full synchronization on every pass. The default value of "0" indicates that the client wants to get objects from the start of the account. @param maxEntries The maximum number of modified objects that should be returned in the result SyncChunk. This can be used to limit the size of each individual message to be friendly for network transfer. @param filter The caller must set some of the flags in this structure to specify which data types should be returned during the synchronization. See the SyncChunkFilter structure for information on each flag. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "afterUSN" - if negative </li> <li> BAD_DATA_FORMAT "maxEntries" - if less than 1 </li> </ul> Parameters: - authenticationToken - afterUSN - maxEntries - filter """ pass def getLinkedNotebookSyncState(self, authenticationToken, linkedNotebook): """ Asks the NoteStore to provide information about the status of a linked notebook that has been shared with the caller, or that is public to the world. This will return a result that is similar to getSyncState, but may omit SyncState.uploaded if the caller doesn't have permission to write to the linked notebook. This function must be called on the shard that owns the referenced notebook. (I.e. the shardId in /shard/shardId/edam/note must be the same as LinkedNotebook.shardId.) @param authenticationToken This should be an authenticationToken for the guest who has received the invitation to the share. (I.e. this should not be the result of NoteStore.authenticateToSharedNotebook) @param linkedNotebook This structure should contain identifying information and permissions to access the notebook in question. Parameters: - authenticationToken - linkedNotebook """ pass def getLinkedNotebookSyncChunk(self, authenticationToken, linkedNotebook, afterUSN, maxEntries, fullSyncOnly): """ Asks the NoteStore to provide information about the contents of a linked notebook that has been shared with the caller, or that is public to the world. This will return a result that is similar to getSyncChunk, but will only contain entries that are visible to the caller. I.e. only that particular Notebook will be visible, along with its Notes, and Tags on those Notes. This function must be called on the shard that owns the referenced notebook. (I.e. the shardId in /shard/shardId/edam/note must be the same as LinkedNotebook.shardId.) @param authenticationToken This should be an authenticationToken for the guest who has received the invitation to the share. (I.e. this should not be the result of NoteStore.authenticateToSharedNotebook) @param linkedNotebook This structure should contain identifying information and permissions to access the notebook in question. This must contain the valid fields for either a shared notebook (e.g. shareKey) or a public notebook (e.g. username, uri) @param afterUSN The client can pass this value to ask only for objects that have been updated after a certain point. This allows the client to receive updates after its last checkpoint rather than doing a full synchronization on every pass. The default value of "0" indicates that the client wants to get objects from the start of the account. @param maxEntries The maximum number of modified objects that should be returned in the result SyncChunk. This can be used to limit the size of each individual message to be friendly for network transfer. Applications should not request more than 256 objects at a time, and must handle the case where the service returns less than the requested number of objects in a given request even though more objects are available on the service. @param fullSyncOnly If true, then the client only wants initial data for a full sync. In this case, the service will not return any expunged objects, and will not return any Resources, since these are also provided in their corresponding Notes. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "afterUSN" - if negative </li> <li> BAD_DATA_FORMAT "maxEntries" - if less than 1 </li> </ul> @throws EDAMNotFoundException <ul> <li> "LinkedNotebook" - if the provided information doesn't match any valid notebook </li> <li> "LinkedNotebook.uri" - if the provided public URI doesn't match any valid notebook </li> <li> "SharedNotebook.id" - if the provided information indicates a shared notebook that no longer exists </li> </ul> Parameters: - authenticationToken - linkedNotebook - afterUSN - maxEntries - fullSyncOnly """ pass def listNotebooks(self, authenticationToken): """ Returns a list of all of the notebooks in the account. Parameters: - authenticationToken """ pass def getNotebook(self, authenticationToken, guid): """ Returns the current state of the notebook with the provided GUID. The notebook may be active or deleted (but not expunged). @param guid The GUID of the notebook to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Notebook" - private notebook, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def getDefaultNotebook(self, authenticationToken): """ Returns the notebook that should be used to store new notes in the user's account when no other notebooks are specified. Parameters: - authenticationToken """ pass def createNotebook(self, authenticationToken, notebook): """ Asks the service to make a notebook with the provided name. @param notebook The desired fields for the notebook must be provided on this object. The name of the notebook must be set, and either the 'active' or 'defaultNotebook' fields may be set by the client at creation. If a notebook exists in the account with the same name (via case-insensitive compare), this will throw an EDAMUserException. @return The newly created Notebook. The server-side GUID will be saved in this object's 'guid' field. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri </li> <li> BAD_DATA_FORMAT "Publishing.publicDescription" - if too long </li> <li> DATA_CONFLICT "Notebook.name" - name already in use </li> <li> DATA_CONFLICT "Publishing.uri" - if URI already in use </li> <li> DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing </li> <li> LIMIT_REACHED "Notebook" - at max number of notebooks </li> </ul> Parameters: - authenticationToken - notebook """ pass def updateNotebook(self, authenticationToken, notebook): """ Submits notebook changes to the service. The provided data must include the notebook's guid field for identification. @param notebook The notebook object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri </li> <li> BAD_DATA_FORMAT "Publishing.publicDescription" - if too long </li> <li> DATA_CONFLICT "Notebook.name" - name already in use </li> <li> DATA_CONFLICT "Publishing.uri" - if URI already in use </li> <li> DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - notebook """ pass def expungeNotebook(self, authenticationToken, guid): """ Permanently removes the notebook from the user's account. After this action, the notebook is no longer available for undeletion, etc. If the notebook contains any Notes, they will be moved to the current default notebook and moved into the trash (i.e. Note.active=false). <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the notebook to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing </li> <li> LIMIT_REACHED "Notebook" - trying to expunge the last Notebook </li> <li> PERMISSION_DENIED "Notebook" - private notebook, user doesn't own </li> </ul> Parameters: - authenticationToken - guid """ pass def listTags(self, authenticationToken): """ Returns a list of the tags in the account. Evernote does not support the undeletion of tags, so this will only include active tags. Parameters: - authenticationToken """ pass def listTagsByNotebook(self, authenticationToken, notebookGuid): """ Returns a list of the tags that are applied to at least one note within the provided notebook. If the notebook is public, the authenticationToken may be ignored. @param notebookGuid the GUID of the notebook to use to find tags @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - notebook not found by GUID </li> </ul> Parameters: - authenticationToken - notebookGuid """ pass def getTag(self, authenticationToken, guid): """ Returns the current state of the Tag with the provided GUID. @param guid The GUID of the tag to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Tag" - private Tag, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def createTag(self, authenticationToken, tag): """ Asks the service to make a tag with a set of information. @param tag The desired list of fields for the tag are specified in this object. The caller must specify the tag name, and may provide the parentGUID. @return The newly created Tag. The server-side GUID will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID </li> <li> DATA_CONFLICT "Tag.name" - name already in use </li> <li> LIMIT_REACHED "Tag" - at max number of tags </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.parentGuid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - tag """ pass def updateTag(self, authenticationToken, tag): """ Submits tag changes to the service. The provided data must include the tag's guid field for identification. The service will apply updates to the following tag fields: name, parentGuid @param tag The tag object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID </li> <li> DATA_CONFLICT "Tag.name" - name already in use </li> <li> DATA_CONFLICT "Tag.parentGuid" - can't set parent: circular </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> <li> "Tag.parentGuid" - parent not found, by GUID </li> </ul> Parameters: - authenticationToken - tag """ pass def untagAll(self, authenticationToken, guid): """ Removes the provided tag from every note that is currently tagged with this tag. If this operation is successful, the tag will still be in the account, but it will not be tagged on any notes. This function is not indended for use by full synchronizing clients, since it does not provide enough result information to the client to reconcile the local state without performing a follow-up sync from the service. This is intended for "thin clients" that need to efficiently support this as a UI operation. @param guid The GUID of the tag to remove from all notes. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def expungeTag(self, authenticationToken, guid): """ Permanently deletes the tag with the provided GUID, if present. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the tag to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def listSearches(self, authenticationToken): """ Returns a list of the searches in the account. Evernote does not support the undeletion of searches, so this will only include active searches. Parameters: - authenticationToken """ pass def getSearch(self, authenticationToken, guid): """ Returns the current state of the search with the provided GUID. @param guid The GUID of the search to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "SavedSearch" - private Tag, user doesn't own </li> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def createSearch(self, authenticationToken, search): """ Asks the service to make a saved search with a set of information. @param search The desired list of fields for the search are specified in this object. The caller must specify the name and query for the search, and may optionally specify a search scope. The SavedSearch.format field is ignored by the service. @return The newly created SavedSearch. The server-side GUID will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "SavedSearch.query" - invalid length </li> <li> DATA_CONFLICT "SavedSearch.name" - name already in use </li> <li> LIMIT_REACHED "SavedSearch" - at max number of searches </li> </ul> Parameters: - authenticationToken - search """ pass def updateSearch(self, authenticationToken, search): """ Submits search changes to the service. The provided data must include the search's guid field for identification. The service will apply updates to the following search fields: name, query, and scope. @param search The search object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "SavedSearch.query" - invalid length </li> <li> DATA_CONFLICT "SavedSearch.name" - name already in use </li> <li> PERMISSION_DENIED "SavedSearch" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - search """ pass def expungeSearch(self, authenticationToken, guid): """ Permanently deletes the saved search with the provided GUID, if present. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the search to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.guid" - if the guid parameter is empty </li> <li> PERMISSION_DENIED "SavedSearch" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def findNotes(self, authenticationToken, filter, offset, maxNotes): """ DEPRECATED. Use findNotesMetadata. Parameters: - authenticationToken - filter - offset - maxNotes """ pass def findNoteOffset(self, authenticationToken, filter, guid): """ Finds the position of a note within a sorted subset of all of the user's notes. This may be useful for thin clients that are displaying a paginated listing of a large account, which need to know where a particular note sits in the list without retrieving all notes first. @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The list of criteria that will constrain the notes to be returned. @param guid The GUID of the note to be retrieved. @return If the note with the provided GUID is found within the matching note list, this will return the offset of that note within that list (where the first offset is 0). If the note is not found within the set of notes, this will return -1. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - guid """ pass def findNotesMetadata(self, authenticationToken, filter, offset, maxNotes, resultSpec): """ Used to find the high-level information about a set of the notes from a user's account based on various criteria specified via a NoteFilter object. <p/> Web applications that wish to periodically check for new content in a user's Evernote account should consider using webhooks instead of polling this API. See http://dev.evernote.com/documentation/cloud/chapters/polling_notification.php for more information. @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The list of criteria that will constrain the notes to be returned. @param offset The numeric index of the first note to show within the sorted results. The numbering scheme starts with "0". This can be used for pagination. @param maxNotes The mximum notes to return in this query. The service will return a set of notes that is no larger than this number, but may return fewer notes if needed. The NoteList.totalNotes field in the return value will indicate whether there are more values available after the returned set. @param resultSpec This specifies which information should be returned for each matching Note. The fields on this structure can be used to eliminate data that the client doesn't need, which will reduce the time and bandwidth to receive and process the reply. @return The list of notes that match the criteria. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - offset - maxNotes - resultSpec """ pass def findNoteCounts(self, authenticationToken, filter, withTrash): """ This function is used to determine how many notes are found for each notebook and tag in the user's account, given a current set of filter parameters that determine the current selection. This function will return a structure that gives the note count for each notebook and tag that has at least one note under the requested filter. Any notebook or tag that has zero notes in the filtered set will not be listed in the reply to this function (so they can be assumed to be 0). @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The note selection filter that is currently being applied. The note counts are to be calculated with this filter applied to the total set of notes in the user's account. @param withTrash If true, then the NoteCollectionCounts.trashCount will be calculated and supplied in the reply. Otherwise, the trash value will be omitted. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - withTrash """ pass def getNote(self, authenticationToken, guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData): """ Returns the current state of the note in the service with the provided GUID. The ENML contents of the note will only be provided if the 'withContent' parameter is true. The service will include the meta-data for each resource in the note, but the binary contents of the resources and their recognition data will be omitted. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). The applicationData fields are returned as keysOnly. @param guid The GUID of the note to be retrieved. @param withContent If true, the note will include the ENML contents of its 'content' field. @param withResourcesData If true, any Resource elements in this Note will include the binary contents of their 'data' field's body. @param withResourcesRecognition If true, any Resource elements will include the binary contents of the 'recognition' field's body if recognition data is present. @param withResourcesAlternateData If true, any Resource elements in this Note will include the binary contents of their 'alternateData' fields' body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - withContent - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ pass def getNoteApplicationData(self, authenticationToken, guid): """ Get all of the application data for the note identified by GUID, with values returned within the LazyMap fullMap field. If there are no applicationData entries, then a LazyMap with an empty fullMap will be returned. If your application only needs to fetch its own applicationData entry, use getNoteApplicationDataEntry instead. Parameters: - authenticationToken - guid """ pass def getNoteApplicationDataEntry(self, authenticationToken, guid, key): """ Get the value of a single entry in the applicationData map for the note identified by GUID. @throws EDAMNotFoundException <ul> <li> "Note.guid" - note not found, by GUID</li> <li> "NoteAttributes.applicationData.key" - note not found, by key</li> </ul> Parameters: - authenticationToken - guid - key """ pass def setNoteApplicationDataEntry(self, authenticationToken, guid, key, value): """ Update, or create, an entry in the applicationData map for the note identified by guid. Parameters: - authenticationToken - guid - key - value """ pass def unsetNoteApplicationDataEntry(self, authenticationToken, guid, key): """ Remove an entry identified by 'key' from the applicationData map for the note identified by 'guid'. Silently ignores an unset of a non-existing key. Parameters: - authenticationToken - guid - key """ pass def getNoteContent(self, authenticationToken, guid): """ Returns XHTML contents of the note with the provided GUID. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the note to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def getNoteSearchText(self, authenticationToken, guid, noteOnly, tokenizeForIndexing): """ Returns a block of the extracted plain text contents of the note with the provided GUID. This text can be indexed for search purposes by a light client that doesn't have capabilities to extract all of the searchable text content from the note and its resources. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the note to be retrieved. @param noteOnly If true, this will only return the text extracted from the ENML contents of the note itself. If false, this will also include the extracted text from any text-bearing resources (PDF, recognized images) @param tokenizeForIndexing If true, this will break the text into cleanly separated and sanitized tokens. If false, this will return the more raw text extraction, with its original punctuation, capitalization, spacing, etc. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - noteOnly - tokenizeForIndexing """ pass def getResourceSearchText(self, authenticationToken, guid): """ Returns a block of the extracted plain text contents of the resource with the provided GUID. This text can be indexed for search purposes by a light client that doesn't have capability to extract all of the searchable text content from a resource. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def getNoteTagNames(self, authenticationToken, guid): """ Returns a list of the names of the tags for the note with the provided guid. This can be used with authentication to get the tags for a user's own note, or can be used without valid authentication to retrieve the names of the tags for a note in a public notebook. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def createNote(self, authenticationToken, note): """ Asks the service to make a note with the provided set of information. @param note A Note object containing the desired fields to be populated on the service. @return The newly created Note from the service. The server-side GUIDs for the Note and any Resources will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.title" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Note.content" - invalid length for ENML content </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> DATA_CONFLICT "Note.deleted" - deleted time set on active note </li> <li> DATA_REQUIRED "Resource.data" - resource data body missing </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> LIMIT_REACHED "Note" - at max number per account </li> <li> LIMIT_REACHED "Note.size" - total note size too large </li> <li> LIMIT_REACHED "Note.resources" - too many resources on Note </li> <li> LIMIT_REACHED "Note.tagGuids" - too many Tags on Note </li> <li> LIMIT_REACHED "Resource.data.size" - resource too large </li> <li> LIMIT_REACHED "NoteAttribute.*" - attribute string too long </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Note.notebookGuid" - NB not owned by user </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> <li> BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one of the specified tags had an invalid length or pattern </li> <li> LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required new tags would exceed the maximum number per account </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.notebookGuid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - note """ pass def updateNote(self, authenticationToken, note): """ Submit a set of changes to a note to the service. The provided data must include the note's guid field for identification. The note's title must also be set. @param note A Note object containing the desired fields to be populated on the service. With the exception of the note's title and guid, fields that are not being changed do not need to be set. If the content is not being modified, note.content should be left unset. If the list of resources is not being modified, note.resources should be left unset. @return The metadata (no contents) for the Note on the server after the update @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.title" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Note.content" - invalid length for ENML body </li> <li> BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> DATA_CONFLICT "Note.deleted" - deleted time set on active note </li> <li> DATA_REQUIRED "Resource.data" - resource data body missing </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> LIMIT_REACHED "Note.tagGuids" - too many Tags on Note </li> <li> LIMIT_REACHED "Note.resources" - too many resources on Note </li> <li> LIMIT_REACHED "Note.size" - total note size too large </li> <li> LIMIT_REACHED "Resource.data.size" - resource too large </li> <li> LIMIT_REACHED "NoteAttribute.*" - attribute string too long </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Note" - user doesn't own </li> <li> PERMISSION_DENIED "Note.notebookGuid" - user doesn't own destination </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> <li> BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one of the specified tags had an invalid length or pattern </li> <li> LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required new tags would exceed the maximum number per account </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - note not found, by GUID </li> <li> "Note.notebookGuid" - if notebookGuid provided, but not found </li> </ul> Parameters: - authenticationToken - note """ pass def deleteNote(self, authenticationToken, guid): """ Moves the note into the trash. The note may still be undeleted, unless it is expunged. This is equivalent to calling updateNote() after setting Note.active = false @param guid The GUID of the note to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't have permission to update the note. </li> </ul> @throws EDAMUserException <ul> <li> DATA_CONFLICT "Note.guid" - the note is already deleted </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def expungeNote(self, authenticationToken, guid): """ Permanently removes a Note, and all of its Resources, from the service. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the note to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def expungeNotes(self, authenticationToken, noteGuids): """ Permanently removes a list of Notes, and all of their Resources, from the service. This should be invoked with a small number of Note GUIDs (e.g. 100 or less) on each call. To expunge a larger number of notes, call this method multiple times. This should also be used to reduce the number of Notes in a notebook before calling expungeNotebook() or in the trash before calling expungeInactiveNotes(), since these calls may be prohibitively slow if there are more than a few hundred notes. If an exception is thrown for any of the GUIDs, then none of the notes will be deleted. I.e. this call can be treated as an atomic transaction. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param noteGuids The list of GUIDs for the Notes to remove. @return The account's updateCount at the end of this operation @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuids """ pass def expungeInactiveNotes(self, authenticationToken): """ Permanently removes all of the Notes that are currently marked as inactive. This is equivalent to "emptying the trash", and these Notes will be gone permanently. <p/> This operation may be relatively slow if the account contains a large number of inactive Notes. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @return The number of notes that were expunged. Parameters: - authenticationToken """ pass def copyNote(self, authenticationToken, noteGuid, toNotebookGuid): """ Performs a deep copy of the Note with the provided GUID 'noteGuid' into the Notebook with the provided GUID 'toNotebookGuid'. The caller must be the owner of both the Note and the Notebook. This creates a new Note in the destination Notebook with new content and Resources that match all of the content and Resources from the original Note, but with new GUID identifiers. The original Note is not modified by this operation. The copied note is considered as an "upload" for the purpose of upload transfer limit calculation, so its size is added to the upload count for the owner. @param noteGuid The GUID of the Note to copy. @param toNotebookGuid The GUID of the Notebook that should receive the new Note. @return The metadata for the new Note that was created. This will include the new GUID for this Note (and any copied Resources), but will not include the content body or the binary bodies of any Resources. @throws EDAMUserException <ul> <li> LIMIT_REACHED "Note" - at max number per account </li> <li> PERMISSION_DENIED "Notebook.guid" - destination not owned by user </li> <li> PERMISSION_DENIED "Note" - user doesn't own </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuid - toNotebookGuid """ pass def listNoteVersions(self, authenticationToken, noteGuid): """ Returns a list of the prior versions of a particular note that are saved within the service. These prior versions are stored to provide a recovery from unintentional removal of content from a note. The identifiers that are returned by this call can be used with getNoteVersion to retrieve the previous note. The identifiers will be listed from the most recent versions to the oldest. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuid """ pass def getNoteVersion(self, authenticationToken, noteGuid, updateSequenceNum, withResourcesData, withResourcesRecognition, withResourcesAlternateData): """ This can be used to retrieve a previous version of a Note after it has been updated within the service. The caller must identify the note (via its guid) and the version (via the updateSequenceNumber of that version). to find a listing of the stored version USNs for a note, call listNoteVersions. This call is only available for notes in Premium accounts. (I.e. access to past versions of Notes is a Premium-only feature.) @param noteGuid The GUID of the note to be retrieved. @param updateSequenceNum The USN of the version of the note that is being retrieved @param withResourcesData If true, any Resource elements in this Note will include the binary contents of their 'data' field's body. @param withResourcesRecognition If true, any Resource elements will include the binary contents of the 'recognition' field's body if recognition data is present. @param withResourcesAlternateData If true, any Resource elements in this Note will include the binary contents of their 'alternateData' fields' body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> <li> PERMISSION_DENIED "updateSequenceNum" - The account isn't permitted to access previous versions of notes. (i.e. this is a Free account.) </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> <li> "Note.updateSequenceNumber" - the Note doesn't have a version with the corresponding USN. </li> </ul> Parameters: - authenticationToken - noteGuid - updateSequenceNum - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ pass def getResource(self, authenticationToken, guid, withData, withRecognition, withAttributes, withAlternateData): """ Returns the current state of the resource in the service with the provided GUID. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). Only the keys for the applicationData will be returned. @param guid The GUID of the resource to be retrieved. @param withData If true, the Resource will include the binary contents of the 'data' field's body. @param withRecognition If true, the Resource will include the binary contents of the 'recognition' field's body if recognition data is present. @param withAttributes If true, the Resource will include the attributes @param withAlternateData If true, the Resource will include the binary contents of the 'alternateData' field's body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - withData - withRecognition - withAttributes - withAlternateData """ pass def getResourceApplicationData(self, authenticationToken, guid): """ Get all of the application data for the Resource identified by GUID, with values returned within the LazyMap fullMap field. If there are no applicationData entries, then a LazyMap with an empty fullMap will be returned. If your application only needs to fetch its own applicationData entry, use getResourceApplicationDataEntry instead. Parameters: - authenticationToken - guid """ pass def getResourceApplicationDataEntry(self, authenticationToken, guid, key): """ Get the value of a single entry in the applicationData map for the Resource identified by GUID. @throws EDAMNotFoundException <ul> <li> "Resource.guid" - Resource not found, by GUID</li> <li> "ResourceAttributes.applicationData.key" - Resource not found, by key</li> </ul> Parameters: - authenticationToken - guid - key """ pass def setResourceApplicationDataEntry(self, authenticationToken, guid, key, value): """ Update, or create, an entry in the applicationData map for the Resource identified by guid. Parameters: - authenticationToken - guid - key - value """ pass def unsetResourceApplicationDataEntry(self, authenticationToken, guid, key): """ Remove an entry identified by 'key' from the applicationData map for the Resource identified by 'guid'. Parameters: - authenticationToken - guid - key """ pass def updateResource(self, authenticationToken, resource): """ Submit a set of changes to a resource to the service. This can be used to update the meta-data about the resource, but cannot be used to change the binary contents of the resource (including the length and hash). These cannot be changed directly without creating a new resource and removing the old one via updateNote. @param resource A Resource object containing the desired fields to be populated on the service. The service will attempt to update the resource with the following fields from the client: <ul> <li>guid: must be provided to identify the resource </li> <li>mime </li> <li>width </li> <li>height </li> <li>duration </li> <li>attributes: optional. if present, the set of attributes will be replaced. </li> </ul> @return The Update Sequence Number of the resource after the changes have been applied. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - resource """ pass def getResourceData(self, authenticationToken, guid): """ Returns binary data of the resource with the provided GUID. For example, if this were an image resource, this would contain the raw bits of the image. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def getResourceByHash(self, authenticationToken, noteGuid, contentHash, withData, withRecognition, withAlternateData): """ Returns the current state of a resource, referenced by containing note GUID and resource content hash. @param noteGuid The GUID of the note that holds the resource to be retrieved. @param contentHash The MD5 checksum of the resource within that note. Note that this is the binary checksum, for example from Resource.data.bodyHash, and not the hex-encoded checksum that is used within an en-media tag in a note body. @param withData If true, the Resource will include the binary contents of the 'data' field's body. @param withRecognition If true, the Resource will include the binary contents of the 'recognition' field's body. @param withAlternateData If true, the Resource will include the binary contents of the 'alternateData' field's body, if an alternate form is present. @throws EDAMUserException <ul> <li> DATA_REQUIRED "Note.guid" - noteGuid param missing </li> <li> DATA_REQUIRED "Note.contentHash" - contentHash param missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note" - not found, by guid </li> <li> "Resource" - not found, by hash </li> </ul> Parameters: - authenticationToken - noteGuid - contentHash - withData - withRecognition - withAlternateData """ pass def getResourceRecognition(self, authenticationToken, guid): """ Returns the binary contents of the recognition index for the resource with the provided GUID. If the caller asks about a resource that has no recognition data, this will throw EDAMNotFoundException. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource whose recognition data should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> <li> "Resource.recognition" - resource has no recognition </li> </ul> Parameters: - authenticationToken - guid """ pass def getResourceAlternateData(self, authenticationToken, guid): """ If the Resource with the provided GUID has an alternate data representation (indicated via the Resource.alternateData field), then this request can be used to retrieve the binary contents of that alternate data file. If the caller asks about a resource that has no alternate data form, this will throw EDAMNotFoundException. @param guid The GUID of the resource whose recognition data should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> <li> "Resource.alternateData" - resource has no recognition </li> </ul> Parameters: - authenticationToken - guid """ pass def getResourceAttributes(self, authenticationToken, guid): """ Returns the set of attributes for the Resource with the provided GUID. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource whose attributes should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def getPublicNotebook(self, userId, publicUri): """ <p> Looks for a user account with the provided userId on this NoteStore shard and determines whether that account contains a public notebook with the given URI. If the account is not found, or no public notebook exists with this URI, this will throw an EDAMNotFoundException, otherwise this will return the information for that Notebook. </p> <p> If a notebook is visible on the web with a full URL like http://www.evernote.com/pub/sethdemo/api Then 'sethdemo' is the username that can be used to look up the userId, and 'api' is the publicUri. </p> @param userId The numeric identifier for the user who owns the public notebook. To find this value based on a username string, you can invoke UserStore.getPublicUserInfo @param publicUri The uri string for the public notebook, from Notebook.publishing.uri. @throws EDAMNotFoundException <ul> <li>"Publishing.uri" - not found, by URI</li> </ul> @throws EDAMSystemException <ul> <li> TAKEN_DOWN "PublicNotebook" - The specified public notebook is taken down (for all requesters).</li> <li> TAKEN_DOWN "Country" - The specified public notebook is taken down for the requester because of an IP-based country lookup.</li> </ul> Parameters: - userId - publicUri """ pass def createSharedNotebook(self, authenticationToken, sharedNotebook): """ Used to construct a shared notebook object. The constructed notebook will contain a "share key" which serve as a unique identifer and access token for a user to access the notebook of the shared notebook owner. @param sharedNotebook A shared notebook object populated with the email address of the share recipient, the notebook guid and the access permissions. All other attributes of the shared object are ignored. The SharedNotebook.allowPreview field must be explicitly set with either a true or false value. @return The fully populated SharedNotebook object including the server assigned share id and shareKey which can both be used to uniquely identify the SharedNotebook. @throws EDAMUserException <ul> <li>BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid</li> <li>BAD_DATA_FORMAT "requireLogin" - if the SharedNotebook.allowPreview field was not set, and the SharedNotebook.requireLogin was also not set or was set to false.</li> <li>PERMISSION_DENIED "SharedNotebook.recipientSettings" - if recipientSettings is set in the sharedNotebook. Only the recipient can set these values via the setSharedNotebookRecipientSettings method. </li> </ul> @throws EDAMNotFoundException <ul> <li>Notebook.guid - if the notebookGuid is not a valid GUID for the user. </li> </ul> Parameters: - authenticationToken - sharedNotebook """ pass def updateSharedNotebook(self, authenticationToken, sharedNotebook): """ Update a SharedNotebook object. @param authenticationToken Must be an authentication token from the owner or a shared notebook authentication token or business authentication token with sufficient permissions to change invitations for a notebook. @param sharedNotebook The SharedNotebook object containing the requested changes. The "id" of the shared notebook must be set to allow the service to identify the SharedNotebook to be updated. In addition, you MUST set the email, permission, and allowPreview fields to the desired values. All other fields will be ignored if set. @return The Update Serial Number for this change within the account. @throws EDAMUserException <ul> <li>UNSUPPORTED_OPERATION "updateSharedNotebook" - if this service instance does not support shared notebooks.</li> <li>BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid.</li> <li>DATA_REQUIRED "SharedNotebook.id" - if the id field was not set.</li> <li>DATA_REQUIRED "SharedNotebook.privilege" - if the privilege field was not set.</li> <li>DATA_REQUIRED "SharedNotebook.allowPreview" - if the allowPreview field was not set.</li> </ul> @throws EDAMNotFoundException <ul> <li>SharedNotebook.id - if no shared notebook with the specified ID was found. </ul> Parameters: - authenticationToken - sharedNotebook """ pass def setSharedNotebookRecipientSettings(self, authenticationToken, sharedNotebookId, recipientSettings): """ Set values for the recipient settings associated with a shared notebook. Having update rights to the shared notebook record itself has no effect on this call; only the recipient of the shared notebook can can the recipient settings. If you do <i>not</i> wish to, or cannot, change one of the reminderNotifyEmail or reminderNotifyInApp fields, you must leave that field unset in recipientSettings. This method will skip that field for updates and leave the existing state as it is. @return The update sequence number of the account to which the shared notebook belongs, which is the account from which we are sharing a notebook. @throws EDAMNotFoundException "sharedNotebookId" - Thrown if the service does not have a shared notebook record for the sharedNotebookId on the given shard. If you receive this exception, it is probable that the shared notebook record has been revoked or expired, or that you accessed the wrong shard. @throws EDAMUserException <ul> <li>PEMISSION_DENIED "authenticationToken" - If you do not have permission to set the recipient settings for the shared notebook. Only the recipient has permission to do this. <li>DATA_CONFLICT "recipientSettings.reminderNotifyEmail" - Setting whether or not you want to receive reminder e-mail notifications is possible on a business notebook in the business to which the user belongs. All others can safely unset the reminderNotifyEmail field from the recipientSettings parameter. </ul> Parameters: - authenticationToken - sharedNotebookId - recipientSettings """ pass def sendMessageToSharedNotebookMembers(self, authenticationToken, notebookGuid, messageText, recipients): """ Send a reminder message to some or all of the email addresses that a notebook has been shared with. The message includes the current link to view the notebook. @param authenticationToken The auth token of the user with permissions to share the notebook @param notebookGuid The guid of the shared notebook @param messageText User provided text to include in the email @param recipients The email addresses of the recipients. If this list is empty then all of the users that the notebook has been shared with are emailed. If an email address doesn't correspond to share invite members then that address is ignored. @return The number of messages sent @throws EDAMUserException <ul> <li> LIMIT_REACHED "(recipients)" - The email can't be sent because this would exceed the user's daily email limit. </li> <li> PERMISSION_DENIED "Notebook.guid" - The user doesn't have permission to send a message for the specified notebook. </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - notebookGuid - messageText - recipients """ pass def listSharedNotebooks(self, authenticationToken): """ Lists the collection of shared notebooks for all notebooks in the users account. @return The list of all SharedNotebooks for the user Parameters: - authenticationToken """ pass def expungeSharedNotebooks(self, authenticationToken, sharedNotebookIds): """ Expunges the SharedNotebooks in the user's account using the SharedNotebook.id as the identifier. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param sharedNotebookIds - a list of ShardNotebook.id longs identifying the objects to delete permanently. @return The account's update sequence number. Parameters: - authenticationToken - sharedNotebookIds """ pass def createLinkedNotebook(self, authenticationToken, linkedNotebook): """ Asks the service to make a linked notebook with the provided name, username of the owner and identifiers provided. A linked notebook can be either a link to a public notebook or to a private shared notebook. @param linkedNotebook The desired fields for the linked notebook must be provided on this object. The name of the linked notebook must be set. Either a username uri or a shard id and share key must be provided otherwise a EDAMUserException is thrown. @return The newly created LinkedNotebook. The server-side id will be saved in this object's 'id' field. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "LinkedNotebook.username" - bad username format </li> <li> BAD_DATA_FORMAT "LinkedNotebook.uri" - if public notebook set but bad uri </li> <li> BAD_DATA_FORMAT "LinkedNotebook.shareKey" - if private notebook set but bad shareKey </li> <li> DATA_REQUIRED "LinkedNotebook.shardId" - if private notebook but shard id not provided </li> </ul> Parameters: - authenticationToken - linkedNotebook """ pass def updateLinkedNotebook(self, authenticationToken, linkedNotebook): """ @param linkedNotebook Updates the name of a linked notebook. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern </li> </ul> Parameters: - authenticationToken - linkedNotebook """ pass def listLinkedNotebooks(self, authenticationToken): """ Returns a list of linked notebooks Parameters: - authenticationToken """ pass def expungeLinkedNotebook(self, authenticationToken, guid): """ Permanently expunges the linked notebook from the account. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The LinkedNotebook.guid field of the LinkedNotebook to permanently remove from the account. Parameters: - authenticationToken - guid """ pass def authenticateToSharedNotebook(self, shareKey, authenticationToken): """ Asks the service to produce an authentication token that can be used to access the contents of a shared notebook from someone else's account. This authenticationToken can be used with the various other NoteStore calls to find and retrieve notes, and if the permissions in the shared notebook are sufficient, to make changes to the contents of the notebook. @param shareKey The 'shareKey' identifier from the SharedNotebook that was granted to some recipient. This string internally encodes the notebook identifier and a security signature. @param authenticationToken If a non-empty string is provided, this is the full user-based authentication token that identifies the user who is currently logged in and trying to access the shared notebook. This may be required if the notebook was created with 'requireLogin'. If this string is empty, the service will attempt to authenticate to the shared notebook without any logged in user. @throws EDAMSystemException <ul> <li> BAD_DATA_FORMAT "shareKey" - invalid shareKey string </li> <li> INVALID_AUTH "shareKey" - bad signature on shareKey string </li> </ul> @throws EDAMNotFoundException <ul> <li> "SharedNotebook.id" - the shared notebook no longer exists </li> </ul> @throws EDAMUserException <ul> <li> DATA_REQUIRED "authenticationToken" - the share requires login, and no valid authentication token was provided. </li> <li> PERMISSION_DENIED "SharedNotebook.username" - share requires login, and another username has already been bound to this notebook. </li> </ul> Parameters: - shareKey - authenticationToken """ pass def getSharedNotebookByAuth(self, authenticationToken): """ This function is used to retrieve extended information about a shared notebook by a guest who has already authenticated to access that notebook. This requires an 'authenticationToken' parameter which should be the resut of a call to authenticateToSharedNotebook(...). I.e. this is the token that gives access to the particular shared notebook in someone else's account -- it's not the authenticationToken for the owner of the notebook itself. @param authenticationToken Should be the authentication token retrieved from the reply of authenticateToSharedNotebook(), proving access to a particular shared notebook. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "authenticationToken" - authentication token doesn't correspond to a valid shared notebook </li> </ul> @throws EDAMNotFoundException <ul> <li> "SharedNotebook.id" - the shared notebook no longer exists </li> </ul> Parameters: - authenticationToken """ pass def emailNote(self, authenticationToken, parameters): """ Attempts to send a single note to one or more email recipients. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param authenticationToken The note will be sent as the user logged in via this token, using that user's registered email address. If the authenticated user doesn't have permission to read that note, the emailing will fail. @param parameters The note must be specified either by GUID (in which case it will be sent using the existing data in the service), or else the full Note must be passed to this call. This also specifies the additional email fields that will be used in the email. @throws EDAMUserException <ul> <li> LIMIT_REACHED "NoteEmailParameters.toAddresses" - The email can't be sent because this would exceed the user's daily email limit. </li> <li> BAD_DATA_FORMAT "(email address)" - email address malformed </li> <li> DATA_REQUIRED "NoteEmailParameters.toAddresses" - if there are no To: or Cc: addresses provided. </li> <li> DATA_REQUIRED "Note.title" - if the caller provides a Note parameter with no title </li> <li> DATA_REQUIRED "Note.content" - if the caller provides a Note parameter with no content </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> DATA_REQUIRED "NoteEmailParameters.note" - if no guid or note provided </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - parameters """ pass def shareNote(self, authenticationToken, guid): """ If this note is not already shared (via its own direct URL), then this will start sharing that note. This will return the secret "Note Key" for this note that can currently be used in conjunction with the Note's GUID to gain direct read-only access to the Note. If the note is already shared, then this won't make any changes to the note, and the existing "Note Key" will be returned. The only way to change the Note Key for an existing note is to stopSharingNote first, and then call this function. @param guid The GUID of the note to be shared. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def stopSharingNote(self, authenticationToken, guid): """ If this note is not already shared then this will stop sharing that note and invalidate its "Note Key", so any existing URLs to access that Note will stop working. If the Note is not shared, then this function will do nothing. @param guid The GUID of the note to be un-shared. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ pass def authenticateToSharedNote(self, guid, noteKey, authenticationToken): """ Asks the service to produce an authentication token that can be used to access the contents of a single Note which was individually shared from someone's account. This authenticationToken can be used with the various other NoteStore calls to find and retrieve the Note and its directly-referenced children. @param guid The GUID identifying this Note on this shard. @param noteKey The 'noteKey' identifier from the Note that was originally created via a call to shareNote() and then given to a recipient to access. @param authenticationToken An optional authenticationToken that identifies the user accessing the shared note. This parameter may be required to access some shared notes. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - the Note with that GUID is either not shared, or the noteKey doesn't match the current key for this note </li> <li> PERMISSION_DENIED "authenticationToken" - an authentication token is required to access this Note, but either no authentication token or a "non-owner" authentication token was provided. </li> </ul> @throws EDAMNotFoundException <ul> <li> "guid" - the note with that GUID is not found </li> </ul> @throws EDAMSystemException <ul> <li> TAKEN_DOWN "Note" - The specified shared note is taken down (for all requesters). </li> <li> TAKEN_DOWN "Country" - The specified shared note is taken down for the requester because of an IP-based country lookup. </ul> </ul> Parameters: - guid - noteKey - authenticationToken """ pass def findRelated(self, authenticationToken, query, resultSpec): """ Identify related entities on the service, such as notes, notebooks, and tags related to notes or content. @param query The information about which we are finding related entities. @param resultSpec Allows the client to indicate the type and quantity of information to be returned, allowing a saving of time and bandwidth. @return The result of the query, with information considered to likely be relevantly related to the information described by the query. @throws EDAMUserException <ul> <li>BAD_DATA_FORMAT "RelatedQuery.plainText" - If you provided a a zero-length plain text value. </li> <li>BAD_DATA_FORMAT "RelatedQuery.noteGuid" - If you provided an invalid Note GUID, that is, one that does not match the constraints defined by EDAM_GUID_LEN_MIN, EDAM_GUID_LEN_MAX, EDAM_GUID_REGEX. </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> <li>PERMISSION_DENIED "Note" - If the caller does not have access to the note identified by RelatedQuery.noteGuid. </li> <li>DATA_REQUIRED "RelatedResultSpec" - If you did not not set any values in the result spec. </li> </ul> @throws EDAMNotFoundException <ul> <li>"RelatedQuery.noteGuid" - the note with that GUID is not found, if that field has been set in the query. </li> </ul> Parameters: - authenticationToken - query - resultSpec """ pass class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot = self._oprot = iprot if oprot is not None: self._oprot = oprot self._seqid = 0 def getSyncState(self, authenticationToken): """ Asks the NoteStore to provide information about the status of the user account corresponding to the provided authentication token. Parameters: - authenticationToken """ self.send_getSyncState(authenticationToken) return self.recv_getSyncState() def send_getSyncState(self, authenticationToken): self._oprot.writeMessageBegin('getSyncState', TMessageType.CALL, self._seqid) args = getSyncState_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getSyncState(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getSyncState_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getSyncState failed: unknown result"); def getSyncStateWithMetrics(self, authenticationToken, clientMetrics): """ Asks the NoteStore to provide information about the status of the user account corresponding to the provided authentication token. This version of 'getSyncState' allows the client to upload coarse- grained usage metrics to the service. @param clientMetrics see the documentation of the ClientUsageMetrics structure for an explanation of the fields that clients can pass to the service. Parameters: - authenticationToken - clientMetrics """ self.send_getSyncStateWithMetrics(authenticationToken, clientMetrics) return self.recv_getSyncStateWithMetrics() def send_getSyncStateWithMetrics(self, authenticationToken, clientMetrics): self._oprot.writeMessageBegin('getSyncStateWithMetrics', TMessageType.CALL, self._seqid) args = getSyncStateWithMetrics_args() args.authenticationToken = authenticationToken args.clientMetrics = clientMetrics args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getSyncStateWithMetrics(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getSyncStateWithMetrics_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getSyncStateWithMetrics failed: unknown result"); def getSyncChunk(self, authenticationToken, afterUSN, maxEntries, fullSyncOnly): """ DEPRECATED - use getFilteredSyncChunk. Parameters: - authenticationToken - afterUSN - maxEntries - fullSyncOnly """ self.send_getSyncChunk(authenticationToken, afterUSN, maxEntries, fullSyncOnly) return self.recv_getSyncChunk() def send_getSyncChunk(self, authenticationToken, afterUSN, maxEntries, fullSyncOnly): self._oprot.writeMessageBegin('getSyncChunk', TMessageType.CALL, self._seqid) args = getSyncChunk_args() args.authenticationToken = authenticationToken args.afterUSN = afterUSN args.maxEntries = maxEntries args.fullSyncOnly = fullSyncOnly args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getSyncChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getSyncChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getSyncChunk failed: unknown result"); def getFilteredSyncChunk(self, authenticationToken, afterUSN, maxEntries, filter): """ Asks the NoteStore to provide the state of the account in order of last modification. This request retrieves one block of the server's state so that a client can make several small requests against a large account rather than getting the entire state in one big message. This call gives fine-grained control of the data that will be received by a client by omitting data elements that a client doesn't need. This may reduce network traffic and sync times. @param afterUSN The client can pass this value to ask only for objects that have been updated after a certain point. This allows the client to receive updates after its last checkpoint rather than doing a full synchronization on every pass. The default value of "0" indicates that the client wants to get objects from the start of the account. @param maxEntries The maximum number of modified objects that should be returned in the result SyncChunk. This can be used to limit the size of each individual message to be friendly for network transfer. @param filter The caller must set some of the flags in this structure to specify which data types should be returned during the synchronization. See the SyncChunkFilter structure for information on each flag. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "afterUSN" - if negative </li> <li> BAD_DATA_FORMAT "maxEntries" - if less than 1 </li> </ul> Parameters: - authenticationToken - afterUSN - maxEntries - filter """ self.send_getFilteredSyncChunk(authenticationToken, afterUSN, maxEntries, filter) return self.recv_getFilteredSyncChunk() def send_getFilteredSyncChunk(self, authenticationToken, afterUSN, maxEntries, filter): self._oprot.writeMessageBegin('getFilteredSyncChunk', TMessageType.CALL, self._seqid) args = getFilteredSyncChunk_args() args.authenticationToken = authenticationToken args.afterUSN = afterUSN args.maxEntries = maxEntries args.filter = filter args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getFilteredSyncChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getFilteredSyncChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getFilteredSyncChunk failed: unknown result"); def getLinkedNotebookSyncState(self, authenticationToken, linkedNotebook): """ Asks the NoteStore to provide information about the status of a linked notebook that has been shared with the caller, or that is public to the world. This will return a result that is similar to getSyncState, but may omit SyncState.uploaded if the caller doesn't have permission to write to the linked notebook. This function must be called on the shard that owns the referenced notebook. (I.e. the shardId in /shard/shardId/edam/note must be the same as LinkedNotebook.shardId.) @param authenticationToken This should be an authenticationToken for the guest who has received the invitation to the share. (I.e. this should not be the result of NoteStore.authenticateToSharedNotebook) @param linkedNotebook This structure should contain identifying information and permissions to access the notebook in question. Parameters: - authenticationToken - linkedNotebook """ self.send_getLinkedNotebookSyncState(authenticationToken, linkedNotebook) return self.recv_getLinkedNotebookSyncState() def send_getLinkedNotebookSyncState(self, authenticationToken, linkedNotebook): self._oprot.writeMessageBegin('getLinkedNotebookSyncState', TMessageType.CALL, self._seqid) args = getLinkedNotebookSyncState_args() args.authenticationToken = authenticationToken args.linkedNotebook = linkedNotebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getLinkedNotebookSyncState(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getLinkedNotebookSyncState_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getLinkedNotebookSyncState failed: unknown result"); def getLinkedNotebookSyncChunk(self, authenticationToken, linkedNotebook, afterUSN, maxEntries, fullSyncOnly): """ Asks the NoteStore to provide information about the contents of a linked notebook that has been shared with the caller, or that is public to the world. This will return a result that is similar to getSyncChunk, but will only contain entries that are visible to the caller. I.e. only that particular Notebook will be visible, along with its Notes, and Tags on those Notes. This function must be called on the shard that owns the referenced notebook. (I.e. the shardId in /shard/shardId/edam/note must be the same as LinkedNotebook.shardId.) @param authenticationToken This should be an authenticationToken for the guest who has received the invitation to the share. (I.e. this should not be the result of NoteStore.authenticateToSharedNotebook) @param linkedNotebook This structure should contain identifying information and permissions to access the notebook in question. This must contain the valid fields for either a shared notebook (e.g. shareKey) or a public notebook (e.g. username, uri) @param afterUSN The client can pass this value to ask only for objects that have been updated after a certain point. This allows the client to receive updates after its last checkpoint rather than doing a full synchronization on every pass. The default value of "0" indicates that the client wants to get objects from the start of the account. @param maxEntries The maximum number of modified objects that should be returned in the result SyncChunk. This can be used to limit the size of each individual message to be friendly for network transfer. Applications should not request more than 256 objects at a time, and must handle the case where the service returns less than the requested number of objects in a given request even though more objects are available on the service. @param fullSyncOnly If true, then the client only wants initial data for a full sync. In this case, the service will not return any expunged objects, and will not return any Resources, since these are also provided in their corresponding Notes. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "afterUSN" - if negative </li> <li> BAD_DATA_FORMAT "maxEntries" - if less than 1 </li> </ul> @throws EDAMNotFoundException <ul> <li> "LinkedNotebook" - if the provided information doesn't match any valid notebook </li> <li> "LinkedNotebook.uri" - if the provided public URI doesn't match any valid notebook </li> <li> "SharedNotebook.id" - if the provided information indicates a shared notebook that no longer exists </li> </ul> Parameters: - authenticationToken - linkedNotebook - afterUSN - maxEntries - fullSyncOnly """ self.send_getLinkedNotebookSyncChunk(authenticationToken, linkedNotebook, afterUSN, maxEntries, fullSyncOnly) return self.recv_getLinkedNotebookSyncChunk() def send_getLinkedNotebookSyncChunk(self, authenticationToken, linkedNotebook, afterUSN, maxEntries, fullSyncOnly): self._oprot.writeMessageBegin('getLinkedNotebookSyncChunk', TMessageType.CALL, self._seqid) args = getLinkedNotebookSyncChunk_args() args.authenticationToken = authenticationToken args.linkedNotebook = linkedNotebook args.afterUSN = afterUSN args.maxEntries = maxEntries args.fullSyncOnly = fullSyncOnly args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getLinkedNotebookSyncChunk(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getLinkedNotebookSyncChunk_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getLinkedNotebookSyncChunk failed: unknown result"); def listNotebooks(self, authenticationToken): """ Returns a list of all of the notebooks in the account. Parameters: - authenticationToken """ self.send_listNotebooks(authenticationToken) return self.recv_listNotebooks() def send_listNotebooks(self, authenticationToken): self._oprot.writeMessageBegin('listNotebooks', TMessageType.CALL, self._seqid) args = listNotebooks_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listNotebooks(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listNotebooks_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "listNotebooks failed: unknown result"); def getNotebook(self, authenticationToken, guid): """ Returns the current state of the notebook with the provided GUID. The notebook may be active or deleted (but not expunged). @param guid The GUID of the notebook to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Notebook" - private notebook, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getNotebook(authenticationToken, guid) return self.recv_getNotebook() def send_getNotebook(self, authenticationToken, guid): self._oprot.writeMessageBegin('getNotebook', TMessageType.CALL, self._seqid) args = getNotebook_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNotebook failed: unknown result"); def getDefaultNotebook(self, authenticationToken): """ Returns the notebook that should be used to store new notes in the user's account when no other notebooks are specified. Parameters: - authenticationToken """ self.send_getDefaultNotebook(authenticationToken) return self.recv_getDefaultNotebook() def send_getDefaultNotebook(self, authenticationToken): self._oprot.writeMessageBegin('getDefaultNotebook', TMessageType.CALL, self._seqid) args = getDefaultNotebook_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getDefaultNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getDefaultNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getDefaultNotebook failed: unknown result"); def createNotebook(self, authenticationToken, notebook): """ Asks the service to make a notebook with the provided name. @param notebook The desired fields for the notebook must be provided on this object. The name of the notebook must be set, and either the 'active' or 'defaultNotebook' fields may be set by the client at creation. If a notebook exists in the account with the same name (via case-insensitive compare), this will throw an EDAMUserException. @return The newly created Notebook. The server-side GUID will be saved in this object's 'guid' field. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri </li> <li> BAD_DATA_FORMAT "Publishing.publicDescription" - if too long </li> <li> DATA_CONFLICT "Notebook.name" - name already in use </li> <li> DATA_CONFLICT "Publishing.uri" - if URI already in use </li> <li> DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing </li> <li> LIMIT_REACHED "Notebook" - at max number of notebooks </li> </ul> Parameters: - authenticationToken - notebook """ self.send_createNotebook(authenticationToken, notebook) return self.recv_createNotebook() def send_createNotebook(self, authenticationToken, notebook): self._oprot.writeMessageBegin('createNotebook', TMessageType.CALL, self._seqid) args = createNotebook_args() args.authenticationToken = authenticationToken args.notebook = notebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "createNotebook failed: unknown result"); def updateNotebook(self, authenticationToken, notebook): """ Submits notebook changes to the service. The provided data must include the notebook's guid field for identification. @param notebook The notebook object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri </li> <li> BAD_DATA_FORMAT "Publishing.publicDescription" - if too long </li> <li> DATA_CONFLICT "Notebook.name" - name already in use </li> <li> DATA_CONFLICT "Publishing.uri" - if URI already in use </li> <li> DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - notebook """ self.send_updateNotebook(authenticationToken, notebook) return self.recv_updateNotebook() def send_updateNotebook(self, authenticationToken, notebook): self._oprot.writeMessageBegin('updateNotebook', TMessageType.CALL, self._seqid) args = updateNotebook_args() args.authenticationToken = authenticationToken args.notebook = notebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateNotebook failed: unknown result"); def expungeNotebook(self, authenticationToken, guid): """ Permanently removes the notebook from the user's account. After this action, the notebook is no longer available for undeletion, etc. If the notebook contains any Notes, they will be moved to the current default notebook and moved into the trash (i.e. Note.active=false). <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the notebook to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing </li> <li> LIMIT_REACHED "Notebook" - trying to expunge the last Notebook </li> <li> PERMISSION_DENIED "Notebook" - private notebook, user doesn't own </li> </ul> Parameters: - authenticationToken - guid """ self.send_expungeNotebook(authenticationToken, guid) return self.recv_expungeNotebook() def send_expungeNotebook(self, authenticationToken, guid): self._oprot.writeMessageBegin('expungeNotebook', TMessageType.CALL, self._seqid) args = expungeNotebook_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeNotebook failed: unknown result"); def listTags(self, authenticationToken): """ Returns a list of the tags in the account. Evernote does not support the undeletion of tags, so this will only include active tags. Parameters: - authenticationToken """ self.send_listTags(authenticationToken) return self.recv_listTags() def send_listTags(self, authenticationToken): self._oprot.writeMessageBegin('listTags', TMessageType.CALL, self._seqid) args = listTags_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listTags(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listTags_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "listTags failed: unknown result"); def listTagsByNotebook(self, authenticationToken, notebookGuid): """ Returns a list of the tags that are applied to at least one note within the provided notebook. If the notebook is public, the authenticationToken may be ignored. @param notebookGuid the GUID of the notebook to use to find tags @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - notebook not found by GUID </li> </ul> Parameters: - authenticationToken - notebookGuid """ self.send_listTagsByNotebook(authenticationToken, notebookGuid) return self.recv_listTagsByNotebook() def send_listTagsByNotebook(self, authenticationToken, notebookGuid): self._oprot.writeMessageBegin('listTagsByNotebook', TMessageType.CALL, self._seqid) args = listTagsByNotebook_args() args.authenticationToken = authenticationToken args.notebookGuid = notebookGuid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listTagsByNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listTagsByNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "listTagsByNotebook failed: unknown result"); def getTag(self, authenticationToken, guid): """ Returns the current state of the Tag with the provided GUID. @param guid The GUID of the tag to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Tag" - private Tag, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getTag(authenticationToken, guid) return self.recv_getTag() def send_getTag(self, authenticationToken, guid): self._oprot.writeMessageBegin('getTag', TMessageType.CALL, self._seqid) args = getTag_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getTag(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getTag_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getTag failed: unknown result"); def createTag(self, authenticationToken, tag): """ Asks the service to make a tag with a set of information. @param tag The desired list of fields for the tag are specified in this object. The caller must specify the tag name, and may provide the parentGUID. @return The newly created Tag. The server-side GUID will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID </li> <li> DATA_CONFLICT "Tag.name" - name already in use </li> <li> LIMIT_REACHED "Tag" - at max number of tags </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.parentGuid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - tag """ self.send_createTag(authenticationToken, tag) return self.recv_createTag() def send_createTag(self, authenticationToken, tag): self._oprot.writeMessageBegin('createTag', TMessageType.CALL, self._seqid) args = createTag_args() args.authenticationToken = authenticationToken args.tag = tag args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createTag(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createTag_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "createTag failed: unknown result"); def updateTag(self, authenticationToken, tag): """ Submits tag changes to the service. The provided data must include the tag's guid field for identification. The service will apply updates to the following tag fields: name, parentGuid @param tag The tag object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID </li> <li> DATA_CONFLICT "Tag.name" - name already in use </li> <li> DATA_CONFLICT "Tag.parentGuid" - can't set parent: circular </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> <li> "Tag.parentGuid" - parent not found, by GUID </li> </ul> Parameters: - authenticationToken - tag """ self.send_updateTag(authenticationToken, tag) return self.recv_updateTag() def send_updateTag(self, authenticationToken, tag): self._oprot.writeMessageBegin('updateTag', TMessageType.CALL, self._seqid) args = updateTag_args() args.authenticationToken = authenticationToken args.tag = tag args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateTag(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateTag_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateTag failed: unknown result"); def untagAll(self, authenticationToken, guid): """ Removes the provided tag from every note that is currently tagged with this tag. If this operation is successful, the tag will still be in the account, but it will not be tagged on any notes. This function is not indended for use by full synchronizing clients, since it does not provide enough result information to the client to reconcile the local state without performing a follow-up sync from the service. This is intended for "thin clients" that need to efficiently support this as a UI operation. @param guid The GUID of the tag to remove from all notes. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_untagAll(authenticationToken, guid) self.recv_untagAll() def send_untagAll(self, authenticationToken, guid): self._oprot.writeMessageBegin('untagAll', TMessageType.CALL, self._seqid) args = untagAll_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_untagAll(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = untagAll_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException return def expungeTag(self, authenticationToken, guid): """ Permanently deletes the tag with the provided GUID, if present. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the tag to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing </li> <li> PERMISSION_DENIED "Tag" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "Tag.guid" - tag not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_expungeTag(authenticationToken, guid) return self.recv_expungeTag() def send_expungeTag(self, authenticationToken, guid): self._oprot.writeMessageBegin('expungeTag', TMessageType.CALL, self._seqid) args = expungeTag_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeTag(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeTag_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeTag failed: unknown result"); def listSearches(self, authenticationToken): """ Returns a list of the searches in the account. Evernote does not support the undeletion of searches, so this will only include active searches. Parameters: - authenticationToken """ self.send_listSearches(authenticationToken) return self.recv_listSearches() def send_listSearches(self, authenticationToken): self._oprot.writeMessageBegin('listSearches', TMessageType.CALL, self._seqid) args = listSearches_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listSearches(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listSearches_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "listSearches failed: unknown result"); def getSearch(self, authenticationToken, guid): """ Returns the current state of the search with the provided GUID. @param guid The GUID of the search to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "SavedSearch" - private Tag, user doesn't own </li> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getSearch(authenticationToken, guid) return self.recv_getSearch() def send_getSearch(self, authenticationToken, guid): self._oprot.writeMessageBegin('getSearch', TMessageType.CALL, self._seqid) args = getSearch_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getSearch(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getSearch_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getSearch failed: unknown result"); def createSearch(self, authenticationToken, search): """ Asks the service to make a saved search with a set of information. @param search The desired list of fields for the search are specified in this object. The caller must specify the name and query for the search, and may optionally specify a search scope. The SavedSearch.format field is ignored by the service. @return The newly created SavedSearch. The server-side GUID will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "SavedSearch.query" - invalid length </li> <li> DATA_CONFLICT "SavedSearch.name" - name already in use </li> <li> LIMIT_REACHED "SavedSearch" - at max number of searches </li> </ul> Parameters: - authenticationToken - search """ self.send_createSearch(authenticationToken, search) return self.recv_createSearch() def send_createSearch(self, authenticationToken, search): self._oprot.writeMessageBegin('createSearch', TMessageType.CALL, self._seqid) args = createSearch_args() args.authenticationToken = authenticationToken args.search = search args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createSearch(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createSearch_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "createSearch failed: unknown result"); def updateSearch(self, authenticationToken, search): """ Submits search changes to the service. The provided data must include the search's guid field for identification. The service will apply updates to the following search fields: name, query, and scope. @param search The search object containing the requested changes. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "SavedSearch.query" - invalid length </li> <li> DATA_CONFLICT "SavedSearch.name" - name already in use </li> <li> PERMISSION_DENIED "SavedSearch" - user doesn't own tag </li> </ul> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - search """ self.send_updateSearch(authenticationToken, search) return self.recv_updateSearch() def send_updateSearch(self, authenticationToken, search): self._oprot.writeMessageBegin('updateSearch', TMessageType.CALL, self._seqid) args = updateSearch_args() args.authenticationToken = authenticationToken args.search = search args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateSearch(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateSearch_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateSearch failed: unknown result"); def expungeSearch(self, authenticationToken, guid): """ Permanently deletes the saved search with the provided GUID, if present. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the search to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "SavedSearch.guid" - if the guid parameter is empty </li> <li> PERMISSION_DENIED "SavedSearch" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "SavedSearch.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_expungeSearch(authenticationToken, guid) return self.recv_expungeSearch() def send_expungeSearch(self, authenticationToken, guid): self._oprot.writeMessageBegin('expungeSearch', TMessageType.CALL, self._seqid) args = expungeSearch_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeSearch(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeSearch_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeSearch failed: unknown result"); def findNotes(self, authenticationToken, filter, offset, maxNotes): """ DEPRECATED. Use findNotesMetadata. Parameters: - authenticationToken - filter - offset - maxNotes """ self.send_findNotes(authenticationToken, filter, offset, maxNotes) return self.recv_findNotes() def send_findNotes(self, authenticationToken, filter, offset, maxNotes): self._oprot.writeMessageBegin('findNotes', TMessageType.CALL, self._seqid) args = findNotes_args() args.authenticationToken = authenticationToken args.filter = filter args.offset = offset args.maxNotes = maxNotes args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_findNotes(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = findNotes_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "findNotes failed: unknown result"); def findNoteOffset(self, authenticationToken, filter, guid): """ Finds the position of a note within a sorted subset of all of the user's notes. This may be useful for thin clients that are displaying a paginated listing of a large account, which need to know where a particular note sits in the list without retrieving all notes first. @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The list of criteria that will constrain the notes to be returned. @param guid The GUID of the note to be retrieved. @return If the note with the provided GUID is found within the matching note list, this will return the offset of that note within that list (where the first offset is 0). If the note is not found within the set of notes, this will return -1. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - guid """ self.send_findNoteOffset(authenticationToken, filter, guid) return self.recv_findNoteOffset() def send_findNoteOffset(self, authenticationToken, filter, guid): self._oprot.writeMessageBegin('findNoteOffset', TMessageType.CALL, self._seqid) args = findNoteOffset_args() args.authenticationToken = authenticationToken args.filter = filter args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_findNoteOffset(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = findNoteOffset_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "findNoteOffset failed: unknown result"); def findNotesMetadata(self, authenticationToken, filter, offset, maxNotes, resultSpec): """ Used to find the high-level information about a set of the notes from a user's account based on various criteria specified via a NoteFilter object. <p/> Web applications that wish to periodically check for new content in a user's Evernote account should consider using webhooks instead of polling this API. See http://dev.evernote.com/documentation/cloud/chapters/polling_notification.php for more information. @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The list of criteria that will constrain the notes to be returned. @param offset The numeric index of the first note to show within the sorted results. The numbering scheme starts with "0". This can be used for pagination. @param maxNotes The mximum notes to return in this query. The service will return a set of notes that is no larger than this number, but may return fewer notes if needed. The NoteList.totalNotes field in the return value will indicate whether there are more values available after the returned set. @param resultSpec This specifies which information should be returned for each matching Note. The fields on this structure can be used to eliminate data that the client doesn't need, which will reduce the time and bandwidth to receive and process the reply. @return The list of notes that match the criteria. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - offset - maxNotes - resultSpec """ self.send_findNotesMetadata(authenticationToken, filter, offset, maxNotes, resultSpec) return self.recv_findNotesMetadata() def send_findNotesMetadata(self, authenticationToken, filter, offset, maxNotes, resultSpec): self._oprot.writeMessageBegin('findNotesMetadata', TMessageType.CALL, self._seqid) args = findNotesMetadata_args() args.authenticationToken = authenticationToken args.filter = filter args.offset = offset args.maxNotes = maxNotes args.resultSpec = resultSpec args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_findNotesMetadata(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = findNotesMetadata_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "findNotesMetadata failed: unknown result"); def findNoteCounts(self, authenticationToken, filter, withTrash): """ This function is used to determine how many notes are found for each notebook and tag in the user's account, given a current set of filter parameters that determine the current selection. This function will return a structure that gives the note count for each notebook and tag that has at least one note under the requested filter. Any notebook or tag that has zero notes in the filtered set will not be listed in the reply to this function (so they can be assumed to be 0). @param authenticationToken Must be a valid token for the user's account unless the NoteFilter 'notebookGuid' is the GUID of a public notebook. @param filter The note selection filter that is currently being applied. The note counts are to be calculated with this filter applied to the total set of notes in the user's account. @param withTrash If true, then the NoteCollectionCounts.trashCount will be calculated and supplied in the reply. Otherwise, the trash value will be omitted. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - filter - withTrash """ self.send_findNoteCounts(authenticationToken, filter, withTrash) return self.recv_findNoteCounts() def send_findNoteCounts(self, authenticationToken, filter, withTrash): self._oprot.writeMessageBegin('findNoteCounts', TMessageType.CALL, self._seqid) args = findNoteCounts_args() args.authenticationToken = authenticationToken args.filter = filter args.withTrash = withTrash args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_findNoteCounts(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = findNoteCounts_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "findNoteCounts failed: unknown result"); def getNote(self, authenticationToken, guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData): """ Returns the current state of the note in the service with the provided GUID. The ENML contents of the note will only be provided if the 'withContent' parameter is true. The service will include the meta-data for each resource in the note, but the binary contents of the resources and their recognition data will be omitted. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). The applicationData fields are returned as keysOnly. @param guid The GUID of the note to be retrieved. @param withContent If true, the note will include the ENML contents of its 'content' field. @param withResourcesData If true, any Resource elements in this Note will include the binary contents of their 'data' field's body. @param withResourcesRecognition If true, any Resource elements will include the binary contents of the 'recognition' field's body if recognition data is present. @param withResourcesAlternateData If true, any Resource elements in this Note will include the binary contents of their 'alternateData' fields' body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - withContent - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ self.send_getNote(authenticationToken, guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData) return self.recv_getNote() def send_getNote(self, authenticationToken, guid, withContent, withResourcesData, withResourcesRecognition, withResourcesAlternateData): self._oprot.writeMessageBegin('getNote', TMessageType.CALL, self._seqid) args = getNote_args() args.authenticationToken = authenticationToken args.guid = guid args.withContent = withContent args.withResourcesData = withResourcesData args.withResourcesRecognition = withResourcesRecognition args.withResourcesAlternateData = withResourcesAlternateData args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNote failed: unknown result"); def getNoteApplicationData(self, authenticationToken, guid): """ Get all of the application data for the note identified by GUID, with values returned within the LazyMap fullMap field. If there are no applicationData entries, then a LazyMap with an empty fullMap will be returned. If your application only needs to fetch its own applicationData entry, use getNoteApplicationDataEntry instead. Parameters: - authenticationToken - guid """ self.send_getNoteApplicationData(authenticationToken, guid) return self.recv_getNoteApplicationData() def send_getNoteApplicationData(self, authenticationToken, guid): self._oprot.writeMessageBegin('getNoteApplicationData', TMessageType.CALL, self._seqid) args = getNoteApplicationData_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteApplicationData(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteApplicationData_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteApplicationData failed: unknown result"); def getNoteApplicationDataEntry(self, authenticationToken, guid, key): """ Get the value of a single entry in the applicationData map for the note identified by GUID. @throws EDAMNotFoundException <ul> <li> "Note.guid" - note not found, by GUID</li> <li> "NoteAttributes.applicationData.key" - note not found, by key</li> </ul> Parameters: - authenticationToken - guid - key """ self.send_getNoteApplicationDataEntry(authenticationToken, guid, key) return self.recv_getNoteApplicationDataEntry() def send_getNoteApplicationDataEntry(self, authenticationToken, guid, key): self._oprot.writeMessageBegin('getNoteApplicationDataEntry', TMessageType.CALL, self._seqid) args = getNoteApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteApplicationDataEntry failed: unknown result"); def setNoteApplicationDataEntry(self, authenticationToken, guid, key, value): """ Update, or create, an entry in the applicationData map for the note identified by guid. Parameters: - authenticationToken - guid - key - value """ self.send_setNoteApplicationDataEntry(authenticationToken, guid, key, value) return self.recv_setNoteApplicationDataEntry() def send_setNoteApplicationDataEntry(self, authenticationToken, guid, key, value): self._oprot.writeMessageBegin('setNoteApplicationDataEntry', TMessageType.CALL, self._seqid) args = setNoteApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.value = value args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_setNoteApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = setNoteApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "setNoteApplicationDataEntry failed: unknown result"); def unsetNoteApplicationDataEntry(self, authenticationToken, guid, key): """ Remove an entry identified by 'key' from the applicationData map for the note identified by 'guid'. Silently ignores an unset of a non-existing key. Parameters: - authenticationToken - guid - key """ self.send_unsetNoteApplicationDataEntry(authenticationToken, guid, key) return self.recv_unsetNoteApplicationDataEntry() def send_unsetNoteApplicationDataEntry(self, authenticationToken, guid, key): self._oprot.writeMessageBegin('unsetNoteApplicationDataEntry', TMessageType.CALL, self._seqid) args = unsetNoteApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_unsetNoteApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = unsetNoteApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "unsetNoteApplicationDataEntry failed: unknown result"); def getNoteContent(self, authenticationToken, guid): """ Returns XHTML contents of the note with the provided GUID. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the note to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getNoteContent(authenticationToken, guid) return self.recv_getNoteContent() def send_getNoteContent(self, authenticationToken, guid): self._oprot.writeMessageBegin('getNoteContent', TMessageType.CALL, self._seqid) args = getNoteContent_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteContent(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteContent_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteContent failed: unknown result"); def getNoteSearchText(self, authenticationToken, guid, noteOnly, tokenizeForIndexing): """ Returns a block of the extracted plain text contents of the note with the provided GUID. This text can be indexed for search purposes by a light client that doesn't have capabilities to extract all of the searchable text content from the note and its resources. If the Note is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the note to be retrieved. @param noteOnly If true, this will only return the text extracted from the ENML contents of the note itself. If false, this will also include the extracted text from any text-bearing resources (PDF, recognized images) @param tokenizeForIndexing If true, this will break the text into cleanly separated and sanitized tokens. If false, this will return the more raw text extraction, with its original punctuation, capitalization, spacing, etc. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - noteOnly - tokenizeForIndexing """ self.send_getNoteSearchText(authenticationToken, guid, noteOnly, tokenizeForIndexing) return self.recv_getNoteSearchText() def send_getNoteSearchText(self, authenticationToken, guid, noteOnly, tokenizeForIndexing): self._oprot.writeMessageBegin('getNoteSearchText', TMessageType.CALL, self._seqid) args = getNoteSearchText_args() args.authenticationToken = authenticationToken args.guid = guid args.noteOnly = noteOnly args.tokenizeForIndexing = tokenizeForIndexing args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteSearchText(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteSearchText_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteSearchText failed: unknown result"); def getResourceSearchText(self, authenticationToken, guid): """ Returns a block of the extracted plain text contents of the resource with the provided GUID. This text can be indexed for search purposes by a light client that doesn't have capability to extract all of the searchable text content from a resource. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getResourceSearchText(authenticationToken, guid) return self.recv_getResourceSearchText() def send_getResourceSearchText(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceSearchText', TMessageType.CALL, self._seqid) args = getResourceSearchText_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceSearchText(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceSearchText_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceSearchText failed: unknown result"); def getNoteTagNames(self, authenticationToken, guid): """ Returns a list of the names of the tags for the note with the provided guid. This can be used with authentication to get the tags for a user's own note, or can be used without valid authentication to retrieve the names of the tags for a note in a public notebook. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getNoteTagNames(authenticationToken, guid) return self.recv_getNoteTagNames() def send_getNoteTagNames(self, authenticationToken, guid): self._oprot.writeMessageBegin('getNoteTagNames', TMessageType.CALL, self._seqid) args = getNoteTagNames_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteTagNames(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteTagNames_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteTagNames failed: unknown result"); def createNote(self, authenticationToken, note): """ Asks the service to make a note with the provided set of information. @param note A Note object containing the desired fields to be populated on the service. @return The newly created Note from the service. The server-side GUIDs for the Note and any Resources will be saved in this object. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.title" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Note.content" - invalid length for ENML content </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> DATA_CONFLICT "Note.deleted" - deleted time set on active note </li> <li> DATA_REQUIRED "Resource.data" - resource data body missing </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> LIMIT_REACHED "Note" - at max number per account </li> <li> LIMIT_REACHED "Note.size" - total note size too large </li> <li> LIMIT_REACHED "Note.resources" - too many resources on Note </li> <li> LIMIT_REACHED "Note.tagGuids" - too many Tags on Note </li> <li> LIMIT_REACHED "Resource.data.size" - resource too large </li> <li> LIMIT_REACHED "NoteAttribute.*" - attribute string too long </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Note.notebookGuid" - NB not owned by user </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> <li> BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one of the specified tags had an invalid length or pattern </li> <li> LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required new tags would exceed the maximum number per account </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.notebookGuid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - note """ self.send_createNote(authenticationToken, note) return self.recv_createNote() def send_createNote(self, authenticationToken, note): self._oprot.writeMessageBegin('createNote', TMessageType.CALL, self._seqid) args = createNote_args() args.authenticationToken = authenticationToken args.note = note args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "createNote failed: unknown result"); def updateNote(self, authenticationToken, note): """ Submit a set of changes to a note to the service. The provided data must include the note's guid field for identification. The note's title must also be set. @param note A Note object containing the desired fields to be populated on the service. With the exception of the note's title and guid, fields that are not being changed do not need to be set. If the content is not being modified, note.content should be left unset. If the list of resources is not being modified, note.resources should be left unset. @return The metadata (no contents) for the Note on the server after the update @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.title" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "Note.content" - invalid length for ENML body </li> <li> BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> DATA_CONFLICT "Note.deleted" - deleted time set on active note </li> <li> DATA_REQUIRED "Resource.data" - resource data body missing </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> LIMIT_REACHED "Note.tagGuids" - too many Tags on Note </li> <li> LIMIT_REACHED "Note.resources" - too many resources on Note </li> <li> LIMIT_REACHED "Note.size" - total note size too large </li> <li> LIMIT_REACHED "Resource.data.size" - resource too large </li> <li> LIMIT_REACHED "NoteAttribute.*" - attribute string too long </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Note" - user doesn't own </li> <li> PERMISSION_DENIED "Note.notebookGuid" - user doesn't own destination </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> <li> BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one of the specified tags had an invalid length or pattern </li> <li> LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required new tags would exceed the maximum number per account </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - note not found, by GUID </li> <li> "Note.notebookGuid" - if notebookGuid provided, but not found </li> </ul> Parameters: - authenticationToken - note """ self.send_updateNote(authenticationToken, note) return self.recv_updateNote() def send_updateNote(self, authenticationToken, note): self._oprot.writeMessageBegin('updateNote', TMessageType.CALL, self._seqid) args = updateNote_args() args.authenticationToken = authenticationToken args.note = note args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateNote failed: unknown result"); def deleteNote(self, authenticationToken, guid): """ Moves the note into the trash. The note may still be undeleted, unless it is expunged. This is equivalent to calling updateNote() after setting Note.active = false @param guid The GUID of the note to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't have permission to update the note. </li> </ul> @throws EDAMUserException <ul> <li> DATA_CONFLICT "Note.guid" - the note is already deleted </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_deleteNote(authenticationToken, guid) return self.recv_deleteNote() def send_deleteNote(self, authenticationToken, guid): self._oprot.writeMessageBegin('deleteNote', TMessageType.CALL, self._seqid) args = deleteNote_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_deleteNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = deleteNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "deleteNote failed: unknown result"); def expungeNote(self, authenticationToken, guid): """ Permanently removes a Note, and all of its Resources, from the service. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The GUID of the note to delete. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_expungeNote(authenticationToken, guid) return self.recv_expungeNote() def send_expungeNote(self, authenticationToken, guid): self._oprot.writeMessageBegin('expungeNote', TMessageType.CALL, self._seqid) args = expungeNote_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeNote failed: unknown result"); def expungeNotes(self, authenticationToken, noteGuids): """ Permanently removes a list of Notes, and all of their Resources, from the service. This should be invoked with a small number of Note GUIDs (e.g. 100 or less) on each call. To expunge a larger number of notes, call this method multiple times. This should also be used to reduce the number of Notes in a notebook before calling expungeNotebook() or in the trash before calling expungeInactiveNotes(), since these calls may be prohibitively slow if there are more than a few hundred notes. If an exception is thrown for any of the GUIDs, then none of the notes will be deleted. I.e. this call can be treated as an atomic transaction. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param noteGuids The list of GUIDs for the Notes to remove. @return The account's updateCount at the end of this operation @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuids """ self.send_expungeNotes(authenticationToken, noteGuids) return self.recv_expungeNotes() def send_expungeNotes(self, authenticationToken, noteGuids): self._oprot.writeMessageBegin('expungeNotes', TMessageType.CALL, self._seqid) args = expungeNotes_args() args.authenticationToken = authenticationToken args.noteGuids = noteGuids args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeNotes(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeNotes_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeNotes failed: unknown result"); def expungeInactiveNotes(self, authenticationToken): """ Permanently removes all of the Notes that are currently marked as inactive. This is equivalent to "emptying the trash", and these Notes will be gone permanently. <p/> This operation may be relatively slow if the account contains a large number of inactive Notes. <p/> NOTE: This function is not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @return The number of notes that were expunged. Parameters: - authenticationToken """ self.send_expungeInactiveNotes(authenticationToken) return self.recv_expungeInactiveNotes() def send_expungeInactiveNotes(self, authenticationToken): self._oprot.writeMessageBegin('expungeInactiveNotes', TMessageType.CALL, self._seqid) args = expungeInactiveNotes_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeInactiveNotes(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeInactiveNotes_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeInactiveNotes failed: unknown result"); def copyNote(self, authenticationToken, noteGuid, toNotebookGuid): """ Performs a deep copy of the Note with the provided GUID 'noteGuid' into the Notebook with the provided GUID 'toNotebookGuid'. The caller must be the owner of both the Note and the Notebook. This creates a new Note in the destination Notebook with new content and Resources that match all of the content and Resources from the original Note, but with new GUID identifiers. The original Note is not modified by this operation. The copied note is considered as an "upload" for the purpose of upload transfer limit calculation, so its size is added to the upload count for the owner. @param noteGuid The GUID of the Note to copy. @param toNotebookGuid The GUID of the Notebook that should receive the new Note. @return The metadata for the new Note that was created. This will include the new GUID for this Note (and any copied Resources), but will not include the content body or the binary bodies of any Resources. @throws EDAMUserException <ul> <li> LIMIT_REACHED "Note" - at max number per account </li> <li> PERMISSION_DENIED "Notebook.guid" - destination not owned by user </li> <li> PERMISSION_DENIED "Note" - user doesn't own </li> <li> QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuid - toNotebookGuid """ self.send_copyNote(authenticationToken, noteGuid, toNotebookGuid) return self.recv_copyNote() def send_copyNote(self, authenticationToken, noteGuid, toNotebookGuid): self._oprot.writeMessageBegin('copyNote', TMessageType.CALL, self._seqid) args = copyNote_args() args.authenticationToken = authenticationToken args.noteGuid = noteGuid args.toNotebookGuid = toNotebookGuid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_copyNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = copyNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "copyNote failed: unknown result"); def listNoteVersions(self, authenticationToken, noteGuid): """ Returns a list of the prior versions of a particular note that are saved within the service. These prior versions are stored to provide a recovery from unintentional removal of content from a note. The identifiers that are returned by this call can be used with getNoteVersion to retrieve the previous note. The identifiers will be listed from the most recent versions to the oldest. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - noteGuid """ self.send_listNoteVersions(authenticationToken, noteGuid) return self.recv_listNoteVersions() def send_listNoteVersions(self, authenticationToken, noteGuid): self._oprot.writeMessageBegin('listNoteVersions', TMessageType.CALL, self._seqid) args = listNoteVersions_args() args.authenticationToken = authenticationToken args.noteGuid = noteGuid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listNoteVersions(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listNoteVersions_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "listNoteVersions failed: unknown result"); def getNoteVersion(self, authenticationToken, noteGuid, updateSequenceNum, withResourcesData, withResourcesRecognition, withResourcesAlternateData): """ This can be used to retrieve a previous version of a Note after it has been updated within the service. The caller must identify the note (via its guid) and the version (via the updateSequenceNumber of that version). to find a listing of the stored version USNs for a note, call listNoteVersions. This call is only available for notes in Premium accounts. (I.e. access to past versions of Notes is a Premium-only feature.) @param noteGuid The GUID of the note to be retrieved. @param updateSequenceNum The USN of the version of the note that is being retrieved @param withResourcesData If true, any Resource elements in this Note will include the binary contents of their 'data' field's body. @param withResourcesRecognition If true, any Resource elements will include the binary contents of the 'recognition' field's body if recognition data is present. @param withResourcesAlternateData If true, any Resource elements in this Note will include the binary contents of their 'alternateData' fields' body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> <li> PERMISSION_DENIED "updateSequenceNum" - The account isn't permitted to access previous versions of notes. (i.e. this is a Free account.) </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> <li> "Note.updateSequenceNumber" - the Note doesn't have a version with the corresponding USN. </li> </ul> Parameters: - authenticationToken - noteGuid - updateSequenceNum - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ self.send_getNoteVersion(authenticationToken, noteGuid, updateSequenceNum, withResourcesData, withResourcesRecognition, withResourcesAlternateData) return self.recv_getNoteVersion() def send_getNoteVersion(self, authenticationToken, noteGuid, updateSequenceNum, withResourcesData, withResourcesRecognition, withResourcesAlternateData): self._oprot.writeMessageBegin('getNoteVersion', TMessageType.CALL, self._seqid) args = getNoteVersion_args() args.authenticationToken = authenticationToken args.noteGuid = noteGuid args.updateSequenceNum = updateSequenceNum args.withResourcesData = withResourcesData args.withResourcesRecognition = withResourcesRecognition args.withResourcesAlternateData = withResourcesAlternateData args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getNoteVersion(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getNoteVersion_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getNoteVersion failed: unknown result"); def getResource(self, authenticationToken, guid, withData, withRecognition, withAttributes, withAlternateData): """ Returns the current state of the resource in the service with the provided GUID. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). Only the keys for the applicationData will be returned. @param guid The GUID of the resource to be retrieved. @param withData If true, the Resource will include the binary contents of the 'data' field's body. @param withRecognition If true, the Resource will include the binary contents of the 'recognition' field's body if recognition data is present. @param withAttributes If true, the Resource will include the attributes @param withAlternateData If true, the Resource will include the binary contents of the 'alternateData' field's body, if an alternate form is present. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid - withData - withRecognition - withAttributes - withAlternateData """ self.send_getResource(authenticationToken, guid, withData, withRecognition, withAttributes, withAlternateData) return self.recv_getResource() def send_getResource(self, authenticationToken, guid, withData, withRecognition, withAttributes, withAlternateData): self._oprot.writeMessageBegin('getResource', TMessageType.CALL, self._seqid) args = getResource_args() args.authenticationToken = authenticationToken args.guid = guid args.withData = withData args.withRecognition = withRecognition args.withAttributes = withAttributes args.withAlternateData = withAlternateData args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResource(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResource_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResource failed: unknown result"); def getResourceApplicationData(self, authenticationToken, guid): """ Get all of the application data for the Resource identified by GUID, with values returned within the LazyMap fullMap field. If there are no applicationData entries, then a LazyMap with an empty fullMap will be returned. If your application only needs to fetch its own applicationData entry, use getResourceApplicationDataEntry instead. Parameters: - authenticationToken - guid """ self.send_getResourceApplicationData(authenticationToken, guid) return self.recv_getResourceApplicationData() def send_getResourceApplicationData(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceApplicationData', TMessageType.CALL, self._seqid) args = getResourceApplicationData_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceApplicationData(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceApplicationData_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceApplicationData failed: unknown result"); def getResourceApplicationDataEntry(self, authenticationToken, guid, key): """ Get the value of a single entry in the applicationData map for the Resource identified by GUID. @throws EDAMNotFoundException <ul> <li> "Resource.guid" - Resource not found, by GUID</li> <li> "ResourceAttributes.applicationData.key" - Resource not found, by key</li> </ul> Parameters: - authenticationToken - guid - key """ self.send_getResourceApplicationDataEntry(authenticationToken, guid, key) return self.recv_getResourceApplicationDataEntry() def send_getResourceApplicationDataEntry(self, authenticationToken, guid, key): self._oprot.writeMessageBegin('getResourceApplicationDataEntry', TMessageType.CALL, self._seqid) args = getResourceApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceApplicationDataEntry failed: unknown result"); def setResourceApplicationDataEntry(self, authenticationToken, guid, key, value): """ Update, or create, an entry in the applicationData map for the Resource identified by guid. Parameters: - authenticationToken - guid - key - value """ self.send_setResourceApplicationDataEntry(authenticationToken, guid, key, value) return self.recv_setResourceApplicationDataEntry() def send_setResourceApplicationDataEntry(self, authenticationToken, guid, key, value): self._oprot.writeMessageBegin('setResourceApplicationDataEntry', TMessageType.CALL, self._seqid) args = setResourceApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.value = value args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_setResourceApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = setResourceApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "setResourceApplicationDataEntry failed: unknown result"); def unsetResourceApplicationDataEntry(self, authenticationToken, guid, key): """ Remove an entry identified by 'key' from the applicationData map for the Resource identified by 'guid'. Parameters: - authenticationToken - guid - key """ self.send_unsetResourceApplicationDataEntry(authenticationToken, guid, key) return self.recv_unsetResourceApplicationDataEntry() def send_unsetResourceApplicationDataEntry(self, authenticationToken, guid, key): self._oprot.writeMessageBegin('unsetResourceApplicationDataEntry', TMessageType.CALL, self._seqid) args = unsetResourceApplicationDataEntry_args() args.authenticationToken = authenticationToken args.guid = guid args.key = key args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_unsetResourceApplicationDataEntry(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = unsetResourceApplicationDataEntry_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "unsetResourceApplicationDataEntry failed: unknown result"); def updateResource(self, authenticationToken, resource): """ Submit a set of changes to a resource to the service. This can be used to update the meta-data about the resource, but cannot be used to change the binary contents of the resource (including the length and hash). These cannot be changed directly without creating a new resource and removing the old one via updateNote. @param resource A Resource object containing the desired fields to be populated on the service. The service will attempt to update the resource with the following fields from the client: <ul> <li>guid: must be provided to identify the resource </li> <li>mime </li> <li>width </li> <li>height </li> <li>duration </li> <li>attributes: optional. if present, the set of attributes will be replaced. </li> </ul> @return The Update Sequence Number of the resource after the changes have been applied. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type </li> <li> BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string </li> <li> LIMIT_REACHED "ResourceAttribute.*" - attribute string too long </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - resource """ self.send_updateResource(authenticationToken, resource) return self.recv_updateResource() def send_updateResource(self, authenticationToken, resource): self._oprot.writeMessageBegin('updateResource', TMessageType.CALL, self._seqid) args = updateResource_args() args.authenticationToken = authenticationToken args.resource = resource args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateResource(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateResource_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateResource failed: unknown result"); def getResourceData(self, authenticationToken, guid): """ Returns binary data of the resource with the provided GUID. For example, if this were an image resource, this would contain the raw bits of the image. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource to be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getResourceData(authenticationToken, guid) return self.recv_getResourceData() def send_getResourceData(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceData', TMessageType.CALL, self._seqid) args = getResourceData_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceData(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceData_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceData failed: unknown result"); def getResourceByHash(self, authenticationToken, noteGuid, contentHash, withData, withRecognition, withAlternateData): """ Returns the current state of a resource, referenced by containing note GUID and resource content hash. @param noteGuid The GUID of the note that holds the resource to be retrieved. @param contentHash The MD5 checksum of the resource within that note. Note that this is the binary checksum, for example from Resource.data.bodyHash, and not the hex-encoded checksum that is used within an en-media tag in a note body. @param withData If true, the Resource will include the binary contents of the 'data' field's body. @param withRecognition If true, the Resource will include the binary contents of the 'recognition' field's body. @param withAlternateData If true, the Resource will include the binary contents of the 'alternateData' field's body, if an alternate form is present. @throws EDAMUserException <ul> <li> DATA_REQUIRED "Note.guid" - noteGuid param missing </li> <li> DATA_REQUIRED "Note.contentHash" - contentHash param missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note" - not found, by guid </li> <li> "Resource" - not found, by hash </li> </ul> Parameters: - authenticationToken - noteGuid - contentHash - withData - withRecognition - withAlternateData """ self.send_getResourceByHash(authenticationToken, noteGuid, contentHash, withData, withRecognition, withAlternateData) return self.recv_getResourceByHash() def send_getResourceByHash(self, authenticationToken, noteGuid, contentHash, withData, withRecognition, withAlternateData): self._oprot.writeMessageBegin('getResourceByHash', TMessageType.CALL, self._seqid) args = getResourceByHash_args() args.authenticationToken = authenticationToken args.noteGuid = noteGuid args.contentHash = contentHash args.withData = withData args.withRecognition = withRecognition args.withAlternateData = withAlternateData args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceByHash(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceByHash_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceByHash failed: unknown result"); def getResourceRecognition(self, authenticationToken, guid): """ Returns the binary contents of the recognition index for the resource with the provided GUID. If the caller asks about a resource that has no recognition data, this will throw EDAMNotFoundException. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource whose recognition data should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> <li> "Resource.recognition" - resource has no recognition </li> </ul> Parameters: - authenticationToken - guid """ self.send_getResourceRecognition(authenticationToken, guid) return self.recv_getResourceRecognition() def send_getResourceRecognition(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceRecognition', TMessageType.CALL, self._seqid) args = getResourceRecognition_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceRecognition(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceRecognition_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceRecognition failed: unknown result"); def getResourceAlternateData(self, authenticationToken, guid): """ If the Resource with the provided GUID has an alternate data representation (indicated via the Resource.alternateData field), then this request can be used to retrieve the binary contents of that alternate data file. If the caller asks about a resource that has no alternate data form, this will throw EDAMNotFoundException. @param guid The GUID of the resource whose recognition data should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> <li> "Resource.alternateData" - resource has no recognition </li> </ul> Parameters: - authenticationToken - guid """ self.send_getResourceAlternateData(authenticationToken, guid) return self.recv_getResourceAlternateData() def send_getResourceAlternateData(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceAlternateData', TMessageType.CALL, self._seqid) args = getResourceAlternateData_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceAlternateData(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceAlternateData_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceAlternateData failed: unknown result"); def getResourceAttributes(self, authenticationToken, guid): """ Returns the set of attributes for the Resource with the provided GUID. If the Resource is found in a public notebook, the authenticationToken will be ignored (so it could be an empty string). @param guid The GUID of the resource whose attributes should be retrieved. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Resource" - private resource, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Resource.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_getResourceAttributes(authenticationToken, guid) return self.recv_getResourceAttributes() def send_getResourceAttributes(self, authenticationToken, guid): self._oprot.writeMessageBegin('getResourceAttributes', TMessageType.CALL, self._seqid) args = getResourceAttributes_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getResourceAttributes(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getResourceAttributes_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getResourceAttributes failed: unknown result"); def getPublicNotebook(self, userId, publicUri): """ <p> Looks for a user account with the provided userId on this NoteStore shard and determines whether that account contains a public notebook with the given URI. If the account is not found, or no public notebook exists with this URI, this will throw an EDAMNotFoundException, otherwise this will return the information for that Notebook. </p> <p> If a notebook is visible on the web with a full URL like http://www.evernote.com/pub/sethdemo/api Then 'sethdemo' is the username that can be used to look up the userId, and 'api' is the publicUri. </p> @param userId The numeric identifier for the user who owns the public notebook. To find this value based on a username string, you can invoke UserStore.getPublicUserInfo @param publicUri The uri string for the public notebook, from Notebook.publishing.uri. @throws EDAMNotFoundException <ul> <li>"Publishing.uri" - not found, by URI</li> </ul> @throws EDAMSystemException <ul> <li> TAKEN_DOWN "PublicNotebook" - The specified public notebook is taken down (for all requesters).</li> <li> TAKEN_DOWN "Country" - The specified public notebook is taken down for the requester because of an IP-based country lookup.</li> </ul> Parameters: - userId - publicUri """ self.send_getPublicNotebook(userId, publicUri) return self.recv_getPublicNotebook() def send_getPublicNotebook(self, userId, publicUri): self._oprot.writeMessageBegin('getPublicNotebook', TMessageType.CALL, self._seqid) args = getPublicNotebook_args() args.userId = userId args.publicUri = publicUri args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getPublicNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getPublicNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "getPublicNotebook failed: unknown result"); def createSharedNotebook(self, authenticationToken, sharedNotebook): """ Used to construct a shared notebook object. The constructed notebook will contain a "share key" which serve as a unique identifer and access token for a user to access the notebook of the shared notebook owner. @param sharedNotebook A shared notebook object populated with the email address of the share recipient, the notebook guid and the access permissions. All other attributes of the shared object are ignored. The SharedNotebook.allowPreview field must be explicitly set with either a true or false value. @return The fully populated SharedNotebook object including the server assigned share id and shareKey which can both be used to uniquely identify the SharedNotebook. @throws EDAMUserException <ul> <li>BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid</li> <li>BAD_DATA_FORMAT "requireLogin" - if the SharedNotebook.allowPreview field was not set, and the SharedNotebook.requireLogin was also not set or was set to false.</li> <li>PERMISSION_DENIED "SharedNotebook.recipientSettings" - if recipientSettings is set in the sharedNotebook. Only the recipient can set these values via the setSharedNotebookRecipientSettings method. </li> </ul> @throws EDAMNotFoundException <ul> <li>Notebook.guid - if the notebookGuid is not a valid GUID for the user. </li> </ul> Parameters: - authenticationToken - sharedNotebook """ self.send_createSharedNotebook(authenticationToken, sharedNotebook) return self.recv_createSharedNotebook() def send_createSharedNotebook(self, authenticationToken, sharedNotebook): self._oprot.writeMessageBegin('createSharedNotebook', TMessageType.CALL, self._seqid) args = createSharedNotebook_args() args.authenticationToken = authenticationToken args.sharedNotebook = sharedNotebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createSharedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createSharedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "createSharedNotebook failed: unknown result"); def updateSharedNotebook(self, authenticationToken, sharedNotebook): """ Update a SharedNotebook object. @param authenticationToken Must be an authentication token from the owner or a shared notebook authentication token or business authentication token with sufficient permissions to change invitations for a notebook. @param sharedNotebook The SharedNotebook object containing the requested changes. The "id" of the shared notebook must be set to allow the service to identify the SharedNotebook to be updated. In addition, you MUST set the email, permission, and allowPreview fields to the desired values. All other fields will be ignored if set. @return The Update Serial Number for this change within the account. @throws EDAMUserException <ul> <li>UNSUPPORTED_OPERATION "updateSharedNotebook" - if this service instance does not support shared notebooks.</li> <li>BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid.</li> <li>DATA_REQUIRED "SharedNotebook.id" - if the id field was not set.</li> <li>DATA_REQUIRED "SharedNotebook.privilege" - if the privilege field was not set.</li> <li>DATA_REQUIRED "SharedNotebook.allowPreview" - if the allowPreview field was not set.</li> </ul> @throws EDAMNotFoundException <ul> <li>SharedNotebook.id - if no shared notebook with the specified ID was found. </ul> Parameters: - authenticationToken - sharedNotebook """ self.send_updateSharedNotebook(authenticationToken, sharedNotebook) return self.recv_updateSharedNotebook() def send_updateSharedNotebook(self, authenticationToken, sharedNotebook): self._oprot.writeMessageBegin('updateSharedNotebook', TMessageType.CALL, self._seqid) args = updateSharedNotebook_args() args.authenticationToken = authenticationToken args.sharedNotebook = sharedNotebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateSharedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateSharedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateSharedNotebook failed: unknown result"); def setSharedNotebookRecipientSettings(self, authenticationToken, sharedNotebookId, recipientSettings): """ Set values for the recipient settings associated with a shared notebook. Having update rights to the shared notebook record itself has no effect on this call; only the recipient of the shared notebook can can the recipient settings. If you do <i>not</i> wish to, or cannot, change one of the reminderNotifyEmail or reminderNotifyInApp fields, you must leave that field unset in recipientSettings. This method will skip that field for updates and leave the existing state as it is. @return The update sequence number of the account to which the shared notebook belongs, which is the account from which we are sharing a notebook. @throws EDAMNotFoundException "sharedNotebookId" - Thrown if the service does not have a shared notebook record for the sharedNotebookId on the given shard. If you receive this exception, it is probable that the shared notebook record has been revoked or expired, or that you accessed the wrong shard. @throws EDAMUserException <ul> <li>PEMISSION_DENIED "authenticationToken" - If you do not have permission to set the recipient settings for the shared notebook. Only the recipient has permission to do this. <li>DATA_CONFLICT "recipientSettings.reminderNotifyEmail" - Setting whether or not you want to receive reminder e-mail notifications is possible on a business notebook in the business to which the user belongs. All others can safely unset the reminderNotifyEmail field from the recipientSettings parameter. </ul> Parameters: - authenticationToken - sharedNotebookId - recipientSettings """ self.send_setSharedNotebookRecipientSettings(authenticationToken, sharedNotebookId, recipientSettings) return self.recv_setSharedNotebookRecipientSettings() def send_setSharedNotebookRecipientSettings(self, authenticationToken, sharedNotebookId, recipientSettings): self._oprot.writeMessageBegin('setSharedNotebookRecipientSettings', TMessageType.CALL, self._seqid) args = setSharedNotebookRecipientSettings_args() args.authenticationToken = authenticationToken args.sharedNotebookId = sharedNotebookId args.recipientSettings = recipientSettings args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_setSharedNotebookRecipientSettings(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = setSharedNotebookRecipientSettings_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "setSharedNotebookRecipientSettings failed: unknown result"); def sendMessageToSharedNotebookMembers(self, authenticationToken, notebookGuid, messageText, recipients): """ Send a reminder message to some or all of the email addresses that a notebook has been shared with. The message includes the current link to view the notebook. @param authenticationToken The auth token of the user with permissions to share the notebook @param notebookGuid The guid of the shared notebook @param messageText User provided text to include in the email @param recipients The email addresses of the recipients. If this list is empty then all of the users that the notebook has been shared with are emailed. If an email address doesn't correspond to share invite members then that address is ignored. @return The number of messages sent @throws EDAMUserException <ul> <li> LIMIT_REACHED "(recipients)" - The email can't be sent because this would exceed the user's daily email limit. </li> <li> PERMISSION_DENIED "Notebook.guid" - The user doesn't have permission to send a message for the specified notebook. </li> </ul> @throws EDAMNotFoundException <ul> <li> "Notebook.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - notebookGuid - messageText - recipients """ self.send_sendMessageToSharedNotebookMembers(authenticationToken, notebookGuid, messageText, recipients) return self.recv_sendMessageToSharedNotebookMembers() def send_sendMessageToSharedNotebookMembers(self, authenticationToken, notebookGuid, messageText, recipients): self._oprot.writeMessageBegin('sendMessageToSharedNotebookMembers', TMessageType.CALL, self._seqid) args = sendMessageToSharedNotebookMembers_args() args.authenticationToken = authenticationToken args.notebookGuid = notebookGuid args.messageText = messageText args.recipients = recipients args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_sendMessageToSharedNotebookMembers(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = sendMessageToSharedNotebookMembers_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "sendMessageToSharedNotebookMembers failed: unknown result"); def listSharedNotebooks(self, authenticationToken): """ Lists the collection of shared notebooks for all notebooks in the users account. @return The list of all SharedNotebooks for the user Parameters: - authenticationToken """ self.send_listSharedNotebooks(authenticationToken) return self.recv_listSharedNotebooks() def send_listSharedNotebooks(self, authenticationToken): self._oprot.writeMessageBegin('listSharedNotebooks', TMessageType.CALL, self._seqid) args = listSharedNotebooks_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listSharedNotebooks(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listSharedNotebooks_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "listSharedNotebooks failed: unknown result"); def expungeSharedNotebooks(self, authenticationToken, sharedNotebookIds): """ Expunges the SharedNotebooks in the user's account using the SharedNotebook.id as the identifier. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param sharedNotebookIds - a list of ShardNotebook.id longs identifying the objects to delete permanently. @return The account's update sequence number. Parameters: - authenticationToken - sharedNotebookIds """ self.send_expungeSharedNotebooks(authenticationToken, sharedNotebookIds) return self.recv_expungeSharedNotebooks() def send_expungeSharedNotebooks(self, authenticationToken, sharedNotebookIds): self._oprot.writeMessageBegin('expungeSharedNotebooks', TMessageType.CALL, self._seqid) args = expungeSharedNotebooks_args() args.authenticationToken = authenticationToken args.sharedNotebookIds = sharedNotebookIds args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeSharedNotebooks(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeSharedNotebooks_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeSharedNotebooks failed: unknown result"); def createLinkedNotebook(self, authenticationToken, linkedNotebook): """ Asks the service to make a linked notebook with the provided name, username of the owner and identifiers provided. A linked notebook can be either a link to a public notebook or to a private shared notebook. @param linkedNotebook The desired fields for the linked notebook must be provided on this object. The name of the linked notebook must be set. Either a username uri or a shard id and share key must be provided otherwise a EDAMUserException is thrown. @return The newly created LinkedNotebook. The server-side id will be saved in this object's 'id' field. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern </li> <li> BAD_DATA_FORMAT "LinkedNotebook.username" - bad username format </li> <li> BAD_DATA_FORMAT "LinkedNotebook.uri" - if public notebook set but bad uri </li> <li> BAD_DATA_FORMAT "LinkedNotebook.shareKey" - if private notebook set but bad shareKey </li> <li> DATA_REQUIRED "LinkedNotebook.shardId" - if private notebook but shard id not provided </li> </ul> Parameters: - authenticationToken - linkedNotebook """ self.send_createLinkedNotebook(authenticationToken, linkedNotebook) return self.recv_createLinkedNotebook() def send_createLinkedNotebook(self, authenticationToken, linkedNotebook): self._oprot.writeMessageBegin('createLinkedNotebook', TMessageType.CALL, self._seqid) args = createLinkedNotebook_args() args.authenticationToken = authenticationToken args.linkedNotebook = linkedNotebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_createLinkedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = createLinkedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "createLinkedNotebook failed: unknown result"); def updateLinkedNotebook(self, authenticationToken, linkedNotebook): """ @param linkedNotebook Updates the name of a linked notebook. @return The Update Sequence Number for this change within the account. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern </li> </ul> Parameters: - authenticationToken - linkedNotebook """ self.send_updateLinkedNotebook(authenticationToken, linkedNotebook) return self.recv_updateLinkedNotebook() def send_updateLinkedNotebook(self, authenticationToken, linkedNotebook): self._oprot.writeMessageBegin('updateLinkedNotebook', TMessageType.CALL, self._seqid) args = updateLinkedNotebook_args() args.authenticationToken = authenticationToken args.linkedNotebook = linkedNotebook args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_updateLinkedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = updateLinkedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "updateLinkedNotebook failed: unknown result"); def listLinkedNotebooks(self, authenticationToken): """ Returns a list of linked notebooks Parameters: - authenticationToken """ self.send_listLinkedNotebooks(authenticationToken) return self.recv_listLinkedNotebooks() def send_listLinkedNotebooks(self, authenticationToken): self._oprot.writeMessageBegin('listLinkedNotebooks', TMessageType.CALL, self._seqid) args = listLinkedNotebooks_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_listLinkedNotebooks(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = listLinkedNotebooks_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "listLinkedNotebooks failed: unknown result"); def expungeLinkedNotebook(self, authenticationToken, guid): """ Permanently expunges the linked notebook from the account. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param guid The LinkedNotebook.guid field of the LinkedNotebook to permanently remove from the account. Parameters: - authenticationToken - guid """ self.send_expungeLinkedNotebook(authenticationToken, guid) return self.recv_expungeLinkedNotebook() def send_expungeLinkedNotebook(self, authenticationToken, guid): self._oprot.writeMessageBegin('expungeLinkedNotebook', TMessageType.CALL, self._seqid) args = expungeLinkedNotebook_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_expungeLinkedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = expungeLinkedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "expungeLinkedNotebook failed: unknown result"); def authenticateToSharedNotebook(self, shareKey, authenticationToken): """ Asks the service to produce an authentication token that can be used to access the contents of a shared notebook from someone else's account. This authenticationToken can be used with the various other NoteStore calls to find and retrieve notes, and if the permissions in the shared notebook are sufficient, to make changes to the contents of the notebook. @param shareKey The 'shareKey' identifier from the SharedNotebook that was granted to some recipient. This string internally encodes the notebook identifier and a security signature. @param authenticationToken If a non-empty string is provided, this is the full user-based authentication token that identifies the user who is currently logged in and trying to access the shared notebook. This may be required if the notebook was created with 'requireLogin'. If this string is empty, the service will attempt to authenticate to the shared notebook without any logged in user. @throws EDAMSystemException <ul> <li> BAD_DATA_FORMAT "shareKey" - invalid shareKey string </li> <li> INVALID_AUTH "shareKey" - bad signature on shareKey string </li> </ul> @throws EDAMNotFoundException <ul> <li> "SharedNotebook.id" - the shared notebook no longer exists </li> </ul> @throws EDAMUserException <ul> <li> DATA_REQUIRED "authenticationToken" - the share requires login, and no valid authentication token was provided. </li> <li> PERMISSION_DENIED "SharedNotebook.username" - share requires login, and another username has already been bound to this notebook. </li> </ul> Parameters: - shareKey - authenticationToken """ self.send_authenticateToSharedNotebook(shareKey, authenticationToken) return self.recv_authenticateToSharedNotebook() def send_authenticateToSharedNotebook(self, shareKey, authenticationToken): self._oprot.writeMessageBegin('authenticateToSharedNotebook', TMessageType.CALL, self._seqid) args = authenticateToSharedNotebook_args() args.shareKey = shareKey args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_authenticateToSharedNotebook(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = authenticateToSharedNotebook_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "authenticateToSharedNotebook failed: unknown result"); def getSharedNotebookByAuth(self, authenticationToken): """ This function is used to retrieve extended information about a shared notebook by a guest who has already authenticated to access that notebook. This requires an 'authenticationToken' parameter which should be the resut of a call to authenticateToSharedNotebook(...). I.e. this is the token that gives access to the particular shared notebook in someone else's account -- it's not the authenticationToken for the owner of the notebook itself. @param authenticationToken Should be the authentication token retrieved from the reply of authenticateToSharedNotebook(), proving access to a particular shared notebook. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "authenticationToken" - authentication token doesn't correspond to a valid shared notebook </li> </ul> @throws EDAMNotFoundException <ul> <li> "SharedNotebook.id" - the shared notebook no longer exists </li> </ul> Parameters: - authenticationToken """ self.send_getSharedNotebookByAuth(authenticationToken) return self.recv_getSharedNotebookByAuth() def send_getSharedNotebookByAuth(self, authenticationToken): self._oprot.writeMessageBegin('getSharedNotebookByAuth', TMessageType.CALL, self._seqid) args = getSharedNotebookByAuth_args() args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_getSharedNotebookByAuth(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = getSharedNotebookByAuth_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "getSharedNotebookByAuth failed: unknown result"); def emailNote(self, authenticationToken, parameters): """ Attempts to send a single note to one or more email recipients. <p/> NOTE: This function is generally not available to third party applications. Calls will result in an EDAMUserException with the error code PERMISSION_DENIED. @param authenticationToken The note will be sent as the user logged in via this token, using that user's registered email address. If the authenticated user doesn't have permission to read that note, the emailing will fail. @param parameters The note must be specified either by GUID (in which case it will be sent using the existing data in the service), or else the full Note must be passed to this call. This also specifies the additional email fields that will be used in the email. @throws EDAMUserException <ul> <li> LIMIT_REACHED "NoteEmailParameters.toAddresses" - The email can't be sent because this would exceed the user's daily email limit. </li> <li> BAD_DATA_FORMAT "(email address)" - email address malformed </li> <li> DATA_REQUIRED "NoteEmailParameters.toAddresses" - if there are no To: or Cc: addresses provided. </li> <li> DATA_REQUIRED "Note.title" - if the caller provides a Note parameter with no title </li> <li> DATA_REQUIRED "Note.content" - if the caller provides a Note parameter with no content </li> <li> ENML_VALIDATION "*" - note content doesn't validate against DTD </li> <li> DATA_REQUIRED "NoteEmailParameters.note" - if no guid or note provided </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - parameters """ self.send_emailNote(authenticationToken, parameters) self.recv_emailNote() def send_emailNote(self, authenticationToken, parameters): self._oprot.writeMessageBegin('emailNote', TMessageType.CALL, self._seqid) args = emailNote_args() args.authenticationToken = authenticationToken args.parameters = parameters args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_emailNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = emailNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException return def shareNote(self, authenticationToken, guid): """ If this note is not already shared (via its own direct URL), then this will start sharing that note. This will return the secret "Note Key" for this note that can currently be used in conjunction with the Note's GUID to gain direct read-only access to the Note. If the note is already shared, then this won't make any changes to the note, and the existing "Note Key" will be returned. The only way to change the Note Key for an existing note is to stopSharingNote first, and then call this function. @param guid The GUID of the note to be shared. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_shareNote(authenticationToken, guid) return self.recv_shareNote() def send_shareNote(self, authenticationToken, guid): self._oprot.writeMessageBegin('shareNote', TMessageType.CALL, self._seqid) args = shareNote_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_shareNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = shareNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "shareNote failed: unknown result"); def stopSharingNote(self, authenticationToken, guid): """ If this note is not already shared then this will stop sharing that note and invalidate its "Note Key", so any existing URLs to access that Note will stop working. If the Note is not shared, then this function will do nothing. @param guid The GUID of the note to be un-shared. @throws EDAMUserException <ul> <li> BAD_DATA_FORMAT "Note.guid" - if the parameter is missing </li> <li> PERMISSION_DENIED "Note" - private note, user doesn't own </li> </ul> @throws EDAMNotFoundException <ul> <li> "Note.guid" - not found, by GUID </li> </ul> Parameters: - authenticationToken - guid """ self.send_stopSharingNote(authenticationToken, guid) self.recv_stopSharingNote() def send_stopSharingNote(self, authenticationToken, guid): self._oprot.writeMessageBegin('stopSharingNote', TMessageType.CALL, self._seqid) args = stopSharingNote_args() args.authenticationToken = authenticationToken args.guid = guid args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_stopSharingNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = stopSharingNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException return def authenticateToSharedNote(self, guid, noteKey, authenticationToken): """ Asks the service to produce an authentication token that can be used to access the contents of a single Note which was individually shared from someone's account. This authenticationToken can be used with the various other NoteStore calls to find and retrieve the Note and its directly-referenced children. @param guid The GUID identifying this Note on this shard. @param noteKey The 'noteKey' identifier from the Note that was originally created via a call to shareNote() and then given to a recipient to access. @param authenticationToken An optional authenticationToken that identifies the user accessing the shared note. This parameter may be required to access some shared notes. @throws EDAMUserException <ul> <li> PERMISSION_DENIED "Note" - the Note with that GUID is either not shared, or the noteKey doesn't match the current key for this note </li> <li> PERMISSION_DENIED "authenticationToken" - an authentication token is required to access this Note, but either no authentication token or a "non-owner" authentication token was provided. </li> </ul> @throws EDAMNotFoundException <ul> <li> "guid" - the note with that GUID is not found </li> </ul> @throws EDAMSystemException <ul> <li> TAKEN_DOWN "Note" - The specified shared note is taken down (for all requesters). </li> <li> TAKEN_DOWN "Country" - The specified shared note is taken down for the requester because of an IP-based country lookup. </ul> </ul> Parameters: - guid - noteKey - authenticationToken """ self.send_authenticateToSharedNote(guid, noteKey, authenticationToken) return self.recv_authenticateToSharedNote() def send_authenticateToSharedNote(self, guid, noteKey, authenticationToken): self._oprot.writeMessageBegin('authenticateToSharedNote', TMessageType.CALL, self._seqid) args = authenticateToSharedNote_args() args.guid = guid args.noteKey = noteKey args.authenticationToken = authenticationToken args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_authenticateToSharedNote(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = authenticateToSharedNote_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.notFoundException is not None: raise result.notFoundException if result.systemException is not None: raise result.systemException raise TApplicationException(TApplicationException.MISSING_RESULT, "authenticateToSharedNote failed: unknown result"); def findRelated(self, authenticationToken, query, resultSpec): """ Identify related entities on the service, such as notes, notebooks, and tags related to notes or content. @param query The information about which we are finding related entities. @param resultSpec Allows the client to indicate the type and quantity of information to be returned, allowing a saving of time and bandwidth. @return The result of the query, with information considered to likely be relevantly related to the information described by the query. @throws EDAMUserException <ul> <li>BAD_DATA_FORMAT "RelatedQuery.plainText" - If you provided a a zero-length plain text value. </li> <li>BAD_DATA_FORMAT "RelatedQuery.noteGuid" - If you provided an invalid Note GUID, that is, one that does not match the constraints defined by EDAM_GUID_LEN_MIN, EDAM_GUID_LEN_MAX, EDAM_GUID_REGEX. </li> <li> BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed </li> <li> BAD_DATA_FORMAT "NoteFilter.words" - if search string too long </li> <li>PERMISSION_DENIED "Note" - If the caller does not have access to the note identified by RelatedQuery.noteGuid. </li> <li>DATA_REQUIRED "RelatedResultSpec" - If you did not not set any values in the result spec. </li> </ul> @throws EDAMNotFoundException <ul> <li>"RelatedQuery.noteGuid" - the note with that GUID is not found, if that field has been set in the query. </li> </ul> Parameters: - authenticationToken - query - resultSpec """ self.send_findRelated(authenticationToken, query, resultSpec) return self.recv_findRelated() def send_findRelated(self, authenticationToken, query, resultSpec): self._oprot.writeMessageBegin('findRelated', TMessageType.CALL, self._seqid) args = findRelated_args() args.authenticationToken = authenticationToken args.query = query args.resultSpec = resultSpec args.write(self._oprot) self._oprot.writeMessageEnd() self._oprot.trans.flush() def recv_findRelated(self, ): (fname, mtype, rseqid) = self._iprot.readMessageBegin() if mtype == TMessageType.EXCEPTION: x = TApplicationException() x.read(self._iprot) self._iprot.readMessageEnd() raise x result = findRelated_result() result.read(self._iprot) self._iprot.readMessageEnd() if result.success is not None: return result.success if result.userException is not None: raise result.userException if result.systemException is not None: raise result.systemException if result.notFoundException is not None: raise result.notFoundException raise TApplicationException(TApplicationException.MISSING_RESULT, "findRelated failed: unknown result"); class Processor(Iface, TProcessor): def __init__(self, handler): self._handler = handler self._processMap = {} self._processMap["getSyncState"] = Processor.process_getSyncState self._processMap["getSyncStateWithMetrics"] = Processor.process_getSyncStateWithMetrics self._processMap["getSyncChunk"] = Processor.process_getSyncChunk self._processMap["getFilteredSyncChunk"] = Processor.process_getFilteredSyncChunk self._processMap["getLinkedNotebookSyncState"] = Processor.process_getLinkedNotebookSyncState self._processMap["getLinkedNotebookSyncChunk"] = Processor.process_getLinkedNotebookSyncChunk self._processMap["listNotebooks"] = Processor.process_listNotebooks self._processMap["getNotebook"] = Processor.process_getNotebook self._processMap["getDefaultNotebook"] = Processor.process_getDefaultNotebook self._processMap["createNotebook"] = Processor.process_createNotebook self._processMap["updateNotebook"] = Processor.process_updateNotebook self._processMap["expungeNotebook"] = Processor.process_expungeNotebook self._processMap["listTags"] = Processor.process_listTags self._processMap["listTagsByNotebook"] = Processor.process_listTagsByNotebook self._processMap["getTag"] = Processor.process_getTag self._processMap["createTag"] = Processor.process_createTag self._processMap["updateTag"] = Processor.process_updateTag self._processMap["untagAll"] = Processor.process_untagAll self._processMap["expungeTag"] = Processor.process_expungeTag self._processMap["listSearches"] = Processor.process_listSearches self._processMap["getSearch"] = Processor.process_getSearch self._processMap["createSearch"] = Processor.process_createSearch self._processMap["updateSearch"] = Processor.process_updateSearch self._processMap["expungeSearch"] = Processor.process_expungeSearch self._processMap["findNotes"] = Processor.process_findNotes self._processMap["findNoteOffset"] = Processor.process_findNoteOffset self._processMap["findNotesMetadata"] = Processor.process_findNotesMetadata self._processMap["findNoteCounts"] = Processor.process_findNoteCounts self._processMap["getNote"] = Processor.process_getNote self._processMap["getNoteApplicationData"] = Processor.process_getNoteApplicationData self._processMap["getNoteApplicationDataEntry"] = Processor.process_getNoteApplicationDataEntry self._processMap["setNoteApplicationDataEntry"] = Processor.process_setNoteApplicationDataEntry self._processMap["unsetNoteApplicationDataEntry"] = Processor.process_unsetNoteApplicationDataEntry self._processMap["getNoteContent"] = Processor.process_getNoteContent self._processMap["getNoteSearchText"] = Processor.process_getNoteSearchText self._processMap["getResourceSearchText"] = Processor.process_getResourceSearchText self._processMap["getNoteTagNames"] = Processor.process_getNoteTagNames self._processMap["createNote"] = Processor.process_createNote self._processMap["updateNote"] = Processor.process_updateNote self._processMap["deleteNote"] = Processor.process_deleteNote self._processMap["expungeNote"] = Processor.process_expungeNote self._processMap["expungeNotes"] = Processor.process_expungeNotes self._processMap["expungeInactiveNotes"] = Processor.process_expungeInactiveNotes self._processMap["copyNote"] = Processor.process_copyNote self._processMap["listNoteVersions"] = Processor.process_listNoteVersions self._processMap["getNoteVersion"] = Processor.process_getNoteVersion self._processMap["getResource"] = Processor.process_getResource self._processMap["getResourceApplicationData"] = Processor.process_getResourceApplicationData self._processMap["getResourceApplicationDataEntry"] = Processor.process_getResourceApplicationDataEntry self._processMap["setResourceApplicationDataEntry"] = Processor.process_setResourceApplicationDataEntry self._processMap["unsetResourceApplicationDataEntry"] = Processor.process_unsetResourceApplicationDataEntry self._processMap["updateResource"] = Processor.process_updateResource self._processMap["getResourceData"] = Processor.process_getResourceData self._processMap["getResourceByHash"] = Processor.process_getResourceByHash self._processMap["getResourceRecognition"] = Processor.process_getResourceRecognition self._processMap["getResourceAlternateData"] = Processor.process_getResourceAlternateData self._processMap["getResourceAttributes"] = Processor.process_getResourceAttributes self._processMap["getPublicNotebook"] = Processor.process_getPublicNotebook self._processMap["createSharedNotebook"] = Processor.process_createSharedNotebook self._processMap["updateSharedNotebook"] = Processor.process_updateSharedNotebook self._processMap["setSharedNotebookRecipientSettings"] = Processor.process_setSharedNotebookRecipientSettings self._processMap["sendMessageToSharedNotebookMembers"] = Processor.process_sendMessageToSharedNotebookMembers self._processMap["listSharedNotebooks"] = Processor.process_listSharedNotebooks self._processMap["expungeSharedNotebooks"] = Processor.process_expungeSharedNotebooks self._processMap["createLinkedNotebook"] = Processor.process_createLinkedNotebook self._processMap["updateLinkedNotebook"] = Processor.process_updateLinkedNotebook self._processMap["listLinkedNotebooks"] = Processor.process_listLinkedNotebooks self._processMap["expungeLinkedNotebook"] = Processor.process_expungeLinkedNotebook self._processMap["authenticateToSharedNotebook"] = Processor.process_authenticateToSharedNotebook self._processMap["getSharedNotebookByAuth"] = Processor.process_getSharedNotebookByAuth self._processMap["emailNote"] = Processor.process_emailNote self._processMap["shareNote"] = Processor.process_shareNote self._processMap["stopSharingNote"] = Processor.process_stopSharingNote self._processMap["authenticateToSharedNote"] = Processor.process_authenticateToSharedNote self._processMap["findRelated"] = Processor.process_findRelated def process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if name not in self._processMap: iprot.skip(TType.STRUCT) iprot.readMessageEnd() x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() return else: self._processMap[name](self, seqid, iprot, oprot) return True def process_getSyncState(self, seqid, iprot, oprot): args = getSyncState_args() args.read(iprot) iprot.readMessageEnd() result = getSyncState_result() try: result.success = self._handler.getSyncState(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getSyncState", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getSyncStateWithMetrics(self, seqid, iprot, oprot): args = getSyncStateWithMetrics_args() args.read(iprot) iprot.readMessageEnd() result = getSyncStateWithMetrics_result() try: result.success = self._handler.getSyncStateWithMetrics(args.authenticationToken, args.clientMetrics) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getSyncStateWithMetrics", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getSyncChunk(self, seqid, iprot, oprot): args = getSyncChunk_args() args.read(iprot) iprot.readMessageEnd() result = getSyncChunk_result() try: result.success = self._handler.getSyncChunk(args.authenticationToken, args.afterUSN, args.maxEntries, args.fullSyncOnly) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getSyncChunk", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getFilteredSyncChunk(self, seqid, iprot, oprot): args = getFilteredSyncChunk_args() args.read(iprot) iprot.readMessageEnd() result = getFilteredSyncChunk_result() try: result.success = self._handler.getFilteredSyncChunk(args.authenticationToken, args.afterUSN, args.maxEntries, args.filter) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getFilteredSyncChunk", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getLinkedNotebookSyncState(self, seqid, iprot, oprot): args = getLinkedNotebookSyncState_args() args.read(iprot) iprot.readMessageEnd() result = getLinkedNotebookSyncState_result() try: result.success = self._handler.getLinkedNotebookSyncState(args.authenticationToken, args.linkedNotebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getLinkedNotebookSyncState", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getLinkedNotebookSyncChunk(self, seqid, iprot, oprot): args = getLinkedNotebookSyncChunk_args() args.read(iprot) iprot.readMessageEnd() result = getLinkedNotebookSyncChunk_result() try: result.success = self._handler.getLinkedNotebookSyncChunk(args.authenticationToken, args.linkedNotebook, args.afterUSN, args.maxEntries, args.fullSyncOnly) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getLinkedNotebookSyncChunk", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listNotebooks(self, seqid, iprot, oprot): args = listNotebooks_args() args.read(iprot) iprot.readMessageEnd() result = listNotebooks_result() try: result.success = self._handler.listNotebooks(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("listNotebooks", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNotebook(self, seqid, iprot, oprot): args = getNotebook_args() args.read(iprot) iprot.readMessageEnd() result = getNotebook_result() try: result.success = self._handler.getNotebook(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getDefaultNotebook(self, seqid, iprot, oprot): args = getDefaultNotebook_args() args.read(iprot) iprot.readMessageEnd() result = getDefaultNotebook_result() try: result.success = self._handler.getDefaultNotebook(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getDefaultNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createNotebook(self, seqid, iprot, oprot): args = createNotebook_args() args.read(iprot) iprot.readMessageEnd() result = createNotebook_result() try: result.success = self._handler.createNotebook(args.authenticationToken, args.notebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("createNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateNotebook(self, seqid, iprot, oprot): args = updateNotebook_args() args.read(iprot) iprot.readMessageEnd() result = updateNotebook_result() try: result.success = self._handler.updateNotebook(args.authenticationToken, args.notebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("updateNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeNotebook(self, seqid, iprot, oprot): args = expungeNotebook_args() args.read(iprot) iprot.readMessageEnd() result = expungeNotebook_result() try: result.success = self._handler.expungeNotebook(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("expungeNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listTags(self, seqid, iprot, oprot): args = listTags_args() args.read(iprot) iprot.readMessageEnd() result = listTags_result() try: result.success = self._handler.listTags(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("listTags", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listTagsByNotebook(self, seqid, iprot, oprot): args = listTagsByNotebook_args() args.read(iprot) iprot.readMessageEnd() result = listTagsByNotebook_result() try: result.success = self._handler.listTagsByNotebook(args.authenticationToken, args.notebookGuid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("listTagsByNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getTag(self, seqid, iprot, oprot): args = getTag_args() args.read(iprot) iprot.readMessageEnd() result = getTag_result() try: result.success = self._handler.getTag(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getTag", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createTag(self, seqid, iprot, oprot): args = createTag_args() args.read(iprot) iprot.readMessageEnd() result = createTag_result() try: result.success = self._handler.createTag(args.authenticationToken, args.tag) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("createTag", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateTag(self, seqid, iprot, oprot): args = updateTag_args() args.read(iprot) iprot.readMessageEnd() result = updateTag_result() try: result.success = self._handler.updateTag(args.authenticationToken, args.tag) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("updateTag", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_untagAll(self, seqid, iprot, oprot): args = untagAll_args() args.read(iprot) iprot.readMessageEnd() result = untagAll_result() try: self._handler.untagAll(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("untagAll", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeTag(self, seqid, iprot, oprot): args = expungeTag_args() args.read(iprot) iprot.readMessageEnd() result = expungeTag_result() try: result.success = self._handler.expungeTag(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("expungeTag", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listSearches(self, seqid, iprot, oprot): args = listSearches_args() args.read(iprot) iprot.readMessageEnd() result = listSearches_result() try: result.success = self._handler.listSearches(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("listSearches", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getSearch(self, seqid, iprot, oprot): args = getSearch_args() args.read(iprot) iprot.readMessageEnd() result = getSearch_result() try: result.success = self._handler.getSearch(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getSearch", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createSearch(self, seqid, iprot, oprot): args = createSearch_args() args.read(iprot) iprot.readMessageEnd() result = createSearch_result() try: result.success = self._handler.createSearch(args.authenticationToken, args.search) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("createSearch", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateSearch(self, seqid, iprot, oprot): args = updateSearch_args() args.read(iprot) iprot.readMessageEnd() result = updateSearch_result() try: result.success = self._handler.updateSearch(args.authenticationToken, args.search) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("updateSearch", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeSearch(self, seqid, iprot, oprot): args = expungeSearch_args() args.read(iprot) iprot.readMessageEnd() result = expungeSearch_result() try: result.success = self._handler.expungeSearch(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("expungeSearch", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_findNotes(self, seqid, iprot, oprot): args = findNotes_args() args.read(iprot) iprot.readMessageEnd() result = findNotes_result() try: result.success = self._handler.findNotes(args.authenticationToken, args.filter, args.offset, args.maxNotes) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("findNotes", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_findNoteOffset(self, seqid, iprot, oprot): args = findNoteOffset_args() args.read(iprot) iprot.readMessageEnd() result = findNoteOffset_result() try: result.success = self._handler.findNoteOffset(args.authenticationToken, args.filter, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("findNoteOffset", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_findNotesMetadata(self, seqid, iprot, oprot): args = findNotesMetadata_args() args.read(iprot) iprot.readMessageEnd() result = findNotesMetadata_result() try: result.success = self._handler.findNotesMetadata(args.authenticationToken, args.filter, args.offset, args.maxNotes, args.resultSpec) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("findNotesMetadata", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_findNoteCounts(self, seqid, iprot, oprot): args = findNoteCounts_args() args.read(iprot) iprot.readMessageEnd() result = findNoteCounts_result() try: result.success = self._handler.findNoteCounts(args.authenticationToken, args.filter, args.withTrash) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("findNoteCounts", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNote(self, seqid, iprot, oprot): args = getNote_args() args.read(iprot) iprot.readMessageEnd() result = getNote_result() try: result.success = self._handler.getNote(args.authenticationToken, args.guid, args.withContent, args.withResourcesData, args.withResourcesRecognition, args.withResourcesAlternateData) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteApplicationData(self, seqid, iprot, oprot): args = getNoteApplicationData_args() args.read(iprot) iprot.readMessageEnd() result = getNoteApplicationData_result() try: result.success = self._handler.getNoteApplicationData(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteApplicationData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteApplicationDataEntry(self, seqid, iprot, oprot): args = getNoteApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = getNoteApplicationDataEntry_result() try: result.success = self._handler.getNoteApplicationDataEntry(args.authenticationToken, args.guid, args.key) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_setNoteApplicationDataEntry(self, seqid, iprot, oprot): args = setNoteApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = setNoteApplicationDataEntry_result() try: result.success = self._handler.setNoteApplicationDataEntry(args.authenticationToken, args.guid, args.key, args.value) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("setNoteApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_unsetNoteApplicationDataEntry(self, seqid, iprot, oprot): args = unsetNoteApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = unsetNoteApplicationDataEntry_result() try: result.success = self._handler.unsetNoteApplicationDataEntry(args.authenticationToken, args.guid, args.key) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("unsetNoteApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteContent(self, seqid, iprot, oprot): args = getNoteContent_args() args.read(iprot) iprot.readMessageEnd() result = getNoteContent_result() try: result.success = self._handler.getNoteContent(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteContent", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteSearchText(self, seqid, iprot, oprot): args = getNoteSearchText_args() args.read(iprot) iprot.readMessageEnd() result = getNoteSearchText_result() try: result.success = self._handler.getNoteSearchText(args.authenticationToken, args.guid, args.noteOnly, args.tokenizeForIndexing) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteSearchText", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceSearchText(self, seqid, iprot, oprot): args = getResourceSearchText_args() args.read(iprot) iprot.readMessageEnd() result = getResourceSearchText_result() try: result.success = self._handler.getResourceSearchText(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceSearchText", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteTagNames(self, seqid, iprot, oprot): args = getNoteTagNames_args() args.read(iprot) iprot.readMessageEnd() result = getNoteTagNames_result() try: result.success = self._handler.getNoteTagNames(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteTagNames", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createNote(self, seqid, iprot, oprot): args = createNote_args() args.read(iprot) iprot.readMessageEnd() result = createNote_result() try: result.success = self._handler.createNote(args.authenticationToken, args.note) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("createNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateNote(self, seqid, iprot, oprot): args = updateNote_args() args.read(iprot) iprot.readMessageEnd() result = updateNote_result() try: result.success = self._handler.updateNote(args.authenticationToken, args.note) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("updateNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_deleteNote(self, seqid, iprot, oprot): args = deleteNote_args() args.read(iprot) iprot.readMessageEnd() result = deleteNote_result() try: result.success = self._handler.deleteNote(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("deleteNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeNote(self, seqid, iprot, oprot): args = expungeNote_args() args.read(iprot) iprot.readMessageEnd() result = expungeNote_result() try: result.success = self._handler.expungeNote(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("expungeNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeNotes(self, seqid, iprot, oprot): args = expungeNotes_args() args.read(iprot) iprot.readMessageEnd() result = expungeNotes_result() try: result.success = self._handler.expungeNotes(args.authenticationToken, args.noteGuids) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("expungeNotes", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeInactiveNotes(self, seqid, iprot, oprot): args = expungeInactiveNotes_args() args.read(iprot) iprot.readMessageEnd() result = expungeInactiveNotes_result() try: result.success = self._handler.expungeInactiveNotes(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("expungeInactiveNotes", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_copyNote(self, seqid, iprot, oprot): args = copyNote_args() args.read(iprot) iprot.readMessageEnd() result = copyNote_result() try: result.success = self._handler.copyNote(args.authenticationToken, args.noteGuid, args.toNotebookGuid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("copyNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listNoteVersions(self, seqid, iprot, oprot): args = listNoteVersions_args() args.read(iprot) iprot.readMessageEnd() result = listNoteVersions_result() try: result.success = self._handler.listNoteVersions(args.authenticationToken, args.noteGuid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("listNoteVersions", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getNoteVersion(self, seqid, iprot, oprot): args = getNoteVersion_args() args.read(iprot) iprot.readMessageEnd() result = getNoteVersion_result() try: result.success = self._handler.getNoteVersion(args.authenticationToken, args.noteGuid, args.updateSequenceNum, args.withResourcesData, args.withResourcesRecognition, args.withResourcesAlternateData) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getNoteVersion", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResource(self, seqid, iprot, oprot): args = getResource_args() args.read(iprot) iprot.readMessageEnd() result = getResource_result() try: result.success = self._handler.getResource(args.authenticationToken, args.guid, args.withData, args.withRecognition, args.withAttributes, args.withAlternateData) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResource", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceApplicationData(self, seqid, iprot, oprot): args = getResourceApplicationData_args() args.read(iprot) iprot.readMessageEnd() result = getResourceApplicationData_result() try: result.success = self._handler.getResourceApplicationData(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceApplicationData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceApplicationDataEntry(self, seqid, iprot, oprot): args = getResourceApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = getResourceApplicationDataEntry_result() try: result.success = self._handler.getResourceApplicationDataEntry(args.authenticationToken, args.guid, args.key) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_setResourceApplicationDataEntry(self, seqid, iprot, oprot): args = setResourceApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = setResourceApplicationDataEntry_result() try: result.success = self._handler.setResourceApplicationDataEntry(args.authenticationToken, args.guid, args.key, args.value) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("setResourceApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_unsetResourceApplicationDataEntry(self, seqid, iprot, oprot): args = unsetResourceApplicationDataEntry_args() args.read(iprot) iprot.readMessageEnd() result = unsetResourceApplicationDataEntry_result() try: result.success = self._handler.unsetResourceApplicationDataEntry(args.authenticationToken, args.guid, args.key) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("unsetResourceApplicationDataEntry", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateResource(self, seqid, iprot, oprot): args = updateResource_args() args.read(iprot) iprot.readMessageEnd() result = updateResource_result() try: result.success = self._handler.updateResource(args.authenticationToken, args.resource) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("updateResource", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceData(self, seqid, iprot, oprot): args = getResourceData_args() args.read(iprot) iprot.readMessageEnd() result = getResourceData_result() try: result.success = self._handler.getResourceData(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceByHash(self, seqid, iprot, oprot): args = getResourceByHash_args() args.read(iprot) iprot.readMessageEnd() result = getResourceByHash_result() try: result.success = self._handler.getResourceByHash(args.authenticationToken, args.noteGuid, args.contentHash, args.withData, args.withRecognition, args.withAlternateData) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceByHash", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceRecognition(self, seqid, iprot, oprot): args = getResourceRecognition_args() args.read(iprot) iprot.readMessageEnd() result = getResourceRecognition_result() try: result.success = self._handler.getResourceRecognition(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceRecognition", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceAlternateData(self, seqid, iprot, oprot): args = getResourceAlternateData_args() args.read(iprot) iprot.readMessageEnd() result = getResourceAlternateData_result() try: result.success = self._handler.getResourceAlternateData(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceAlternateData", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getResourceAttributes(self, seqid, iprot, oprot): args = getResourceAttributes_args() args.read(iprot) iprot.readMessageEnd() result = getResourceAttributes_result() try: result.success = self._handler.getResourceAttributes(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getResourceAttributes", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getPublicNotebook(self, seqid, iprot, oprot): args = getPublicNotebook_args() args.read(iprot) iprot.readMessageEnd() result = getPublicNotebook_result() try: result.success = self._handler.getPublicNotebook(args.userId, args.publicUri) except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("getPublicNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createSharedNotebook(self, seqid, iprot, oprot): args = createSharedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = createSharedNotebook_result() try: result.success = self._handler.createSharedNotebook(args.authenticationToken, args.sharedNotebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("createSharedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateSharedNotebook(self, seqid, iprot, oprot): args = updateSharedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = updateSharedNotebook_result() try: result.success = self._handler.updateSharedNotebook(args.authenticationToken, args.sharedNotebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("updateSharedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_setSharedNotebookRecipientSettings(self, seqid, iprot, oprot): args = setSharedNotebookRecipientSettings_args() args.read(iprot) iprot.readMessageEnd() result = setSharedNotebookRecipientSettings_result() try: result.success = self._handler.setSharedNotebookRecipientSettings(args.authenticationToken, args.sharedNotebookId, args.recipientSettings) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("setSharedNotebookRecipientSettings", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_sendMessageToSharedNotebookMembers(self, seqid, iprot, oprot): args = sendMessageToSharedNotebookMembers_args() args.read(iprot) iprot.readMessageEnd() result = sendMessageToSharedNotebookMembers_result() try: result.success = self._handler.sendMessageToSharedNotebookMembers(args.authenticationToken, args.notebookGuid, args.messageText, args.recipients) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("sendMessageToSharedNotebookMembers", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listSharedNotebooks(self, seqid, iprot, oprot): args = listSharedNotebooks_args() args.read(iprot) iprot.readMessageEnd() result = listSharedNotebooks_result() try: result.success = self._handler.listSharedNotebooks(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("listSharedNotebooks", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeSharedNotebooks(self, seqid, iprot, oprot): args = expungeSharedNotebooks_args() args.read(iprot) iprot.readMessageEnd() result = expungeSharedNotebooks_result() try: result.success = self._handler.expungeSharedNotebooks(args.authenticationToken, args.sharedNotebookIds) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("expungeSharedNotebooks", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_createLinkedNotebook(self, seqid, iprot, oprot): args = createLinkedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = createLinkedNotebook_result() try: result.success = self._handler.createLinkedNotebook(args.authenticationToken, args.linkedNotebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("createLinkedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_updateLinkedNotebook(self, seqid, iprot, oprot): args = updateLinkedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = updateLinkedNotebook_result() try: result.success = self._handler.updateLinkedNotebook(args.authenticationToken, args.linkedNotebook) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("updateLinkedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_listLinkedNotebooks(self, seqid, iprot, oprot): args = listLinkedNotebooks_args() args.read(iprot) iprot.readMessageEnd() result = listLinkedNotebooks_result() try: result.success = self._handler.listLinkedNotebooks(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("listLinkedNotebooks", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_expungeLinkedNotebook(self, seqid, iprot, oprot): args = expungeLinkedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = expungeLinkedNotebook_result() try: result.success = self._handler.expungeLinkedNotebook(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("expungeLinkedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_authenticateToSharedNotebook(self, seqid, iprot, oprot): args = authenticateToSharedNotebook_args() args.read(iprot) iprot.readMessageEnd() result = authenticateToSharedNotebook_result() try: result.success = self._handler.authenticateToSharedNotebook(args.shareKey, args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("authenticateToSharedNotebook", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_getSharedNotebookByAuth(self, seqid, iprot, oprot): args = getSharedNotebookByAuth_args() args.read(iprot) iprot.readMessageEnd() result = getSharedNotebookByAuth_result() try: result.success = self._handler.getSharedNotebookByAuth(args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("getSharedNotebookByAuth", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_emailNote(self, seqid, iprot, oprot): args = emailNote_args() args.read(iprot) iprot.readMessageEnd() result = emailNote_result() try: self._handler.emailNote(args.authenticationToken, args.parameters) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("emailNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_shareNote(self, seqid, iprot, oprot): args = shareNote_args() args.read(iprot) iprot.readMessageEnd() result = shareNote_result() try: result.success = self._handler.shareNote(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("shareNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_stopSharingNote(self, seqid, iprot, oprot): args = stopSharingNote_args() args.read(iprot) iprot.readMessageEnd() result = stopSharingNote_result() try: self._handler.stopSharingNote(args.authenticationToken, args.guid) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("stopSharingNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_authenticateToSharedNote(self, seqid, iprot, oprot): args = authenticateToSharedNote_args() args.read(iprot) iprot.readMessageEnd() result = authenticateToSharedNote_result() try: result.success = self._handler.authenticateToSharedNote(args.guid, args.noteKey, args.authenticationToken) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException oprot.writeMessageBegin("authenticateToSharedNote", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() def process_findRelated(self, seqid, iprot, oprot): args = findRelated_args() args.read(iprot) iprot.readMessageEnd() result = findRelated_result() try: result.success = self._handler.findRelated(args.authenticationToken, args.query, args.resultSpec) except evernote.edam.error.ttypes.EDAMUserException, userException: result.userException = userException except evernote.edam.error.ttypes.EDAMSystemException, systemException: result.systemException = systemException except evernote.edam.error.ttypes.EDAMNotFoundException, notFoundException: result.notFoundException = notFoundException oprot.writeMessageBegin("findRelated", TMessageType.REPLY, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES class getSyncState_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncState_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSyncState_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncState, SyncState.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncState() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncState_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSyncStateWithMetrics_args(object): """ Attributes: - authenticationToken - clientMetrics """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'clientMetrics', (ClientUsageMetrics, ClientUsageMetrics.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, clientMetrics=None,): self.authenticationToken = authenticationToken self.clientMetrics = clientMetrics def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.clientMetrics = ClientUsageMetrics() self.clientMetrics.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncStateWithMetrics_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.clientMetrics is not None: oprot.writeFieldBegin('clientMetrics', TType.STRUCT, 2) self.clientMetrics.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSyncStateWithMetrics_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncState, SyncState.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncState() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncStateWithMetrics_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSyncChunk_args(object): """ Attributes: - authenticationToken - afterUSN - maxEntries - fullSyncOnly """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.I32, 'afterUSN', None, None, ), # 2 (3, TType.I32, 'maxEntries', None, None, ), # 3 (4, TType.BOOL, 'fullSyncOnly', None, None, ), # 4 ) def __init__(self, authenticationToken=None, afterUSN=None, maxEntries=None, fullSyncOnly=None,): self.authenticationToken = authenticationToken self.afterUSN = afterUSN self.maxEntries = maxEntries self.fullSyncOnly = fullSyncOnly def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.afterUSN = iprot.readI32(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.maxEntries = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.fullSyncOnly = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncChunk_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.afterUSN is not None: oprot.writeFieldBegin('afterUSN', TType.I32, 2) oprot.writeI32(self.afterUSN) oprot.writeFieldEnd() if self.maxEntries is not None: oprot.writeFieldBegin('maxEntries', TType.I32, 3) oprot.writeI32(self.maxEntries) oprot.writeFieldEnd() if self.fullSyncOnly is not None: oprot.writeFieldBegin('fullSyncOnly', TType.BOOL, 4) oprot.writeBool(self.fullSyncOnly) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSyncChunk_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncChunk, SyncChunk.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncChunk() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSyncChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getFilteredSyncChunk_args(object): """ Attributes: - authenticationToken - afterUSN - maxEntries - filter """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.I32, 'afterUSN', None, None, ), # 2 (3, TType.I32, 'maxEntries', None, None, ), # 3 (4, TType.STRUCT, 'filter', (SyncChunkFilter, SyncChunkFilter.thrift_spec), None, ), # 4 ) def __init__(self, authenticationToken=None, afterUSN=None, maxEntries=None, filter=None,): self.authenticationToken = authenticationToken self.afterUSN = afterUSN self.maxEntries = maxEntries self.filter = filter def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.afterUSN = iprot.readI32(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.maxEntries = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRUCT: self.filter = SyncChunkFilter() self.filter.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getFilteredSyncChunk_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.afterUSN is not None: oprot.writeFieldBegin('afterUSN', TType.I32, 2) oprot.writeI32(self.afterUSN) oprot.writeFieldEnd() if self.maxEntries is not None: oprot.writeFieldBegin('maxEntries', TType.I32, 3) oprot.writeI32(self.maxEntries) oprot.writeFieldEnd() if self.filter is not None: oprot.writeFieldBegin('filter', TType.STRUCT, 4) self.filter.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getFilteredSyncChunk_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncChunk, SyncChunk.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncChunk() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getFilteredSyncChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getLinkedNotebookSyncState_args(object): """ Attributes: - authenticationToken - linkedNotebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'linkedNotebook', (evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, linkedNotebook=None,): self.authenticationToken = authenticationToken self.linkedNotebook = linkedNotebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.linkedNotebook = evernote.edam.type.ttypes.LinkedNotebook() self.linkedNotebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getLinkedNotebookSyncState_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.linkedNotebook is not None: oprot.writeFieldBegin('linkedNotebook', TType.STRUCT, 2) self.linkedNotebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getLinkedNotebookSyncState_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncState, SyncState.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncState() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getLinkedNotebookSyncState_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getLinkedNotebookSyncChunk_args(object): """ Attributes: - authenticationToken - linkedNotebook - afterUSN - maxEntries - fullSyncOnly """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'linkedNotebook', (evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec), None, ), # 2 (3, TType.I32, 'afterUSN', None, None, ), # 3 (4, TType.I32, 'maxEntries', None, None, ), # 4 (5, TType.BOOL, 'fullSyncOnly', None, None, ), # 5 ) def __init__(self, authenticationToken=None, linkedNotebook=None, afterUSN=None, maxEntries=None, fullSyncOnly=None,): self.authenticationToken = authenticationToken self.linkedNotebook = linkedNotebook self.afterUSN = afterUSN self.maxEntries = maxEntries self.fullSyncOnly = fullSyncOnly def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.linkedNotebook = evernote.edam.type.ttypes.LinkedNotebook() self.linkedNotebook.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.afterUSN = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.maxEntries = iprot.readI32(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.BOOL: self.fullSyncOnly = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getLinkedNotebookSyncChunk_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.linkedNotebook is not None: oprot.writeFieldBegin('linkedNotebook', TType.STRUCT, 2) self.linkedNotebook.write(oprot) oprot.writeFieldEnd() if self.afterUSN is not None: oprot.writeFieldBegin('afterUSN', TType.I32, 3) oprot.writeI32(self.afterUSN) oprot.writeFieldEnd() if self.maxEntries is not None: oprot.writeFieldBegin('maxEntries', TType.I32, 4) oprot.writeI32(self.maxEntries) oprot.writeFieldEnd() if self.fullSyncOnly is not None: oprot.writeFieldBegin('fullSyncOnly', TType.BOOL, 5) oprot.writeBool(self.fullSyncOnly) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getLinkedNotebookSyncChunk_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (SyncChunk, SyncChunk.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = SyncChunk() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getLinkedNotebookSyncChunk_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listNotebooks_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listNotebooks_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listNotebooks_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype196, _size193) = iprot.readListBegin() for _i197 in xrange(_size193): _elem198 = evernote.edam.type.ttypes.Notebook() _elem198.read(iprot) self.success.append(_elem198) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listNotebooks_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter199 in self.success: iter199.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNotebook_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNotebook_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Notebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getDefaultNotebook_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getDefaultNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getDefaultNotebook_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Notebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getDefaultNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createNotebook_args(object): """ Attributes: - authenticationToken - notebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'notebook', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, notebook=None,): self.authenticationToken = authenticationToken self.notebook = notebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notebook = evernote.edam.type.ttypes.Notebook() self.notebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.notebook is not None: oprot.writeFieldBegin('notebook', TType.STRUCT, 2) self.notebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createNotebook_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Notebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateNotebook_args(object): """ Attributes: - authenticationToken - notebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'notebook', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, notebook=None,): self.authenticationToken = authenticationToken self.notebook = notebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notebook = evernote.edam.type.ttypes.Notebook() self.notebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.notebook is not None: oprot.writeFieldBegin('notebook', TType.STRUCT, 2) self.notebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateNotebook_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNotebook_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNotebook_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listTags_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listTags_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listTags_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype203, _size200) = iprot.readListBegin() for _i204 in xrange(_size200): _elem205 = evernote.edam.type.ttypes.Tag() _elem205.read(iprot) self.success.append(_elem205) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listTags_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter206 in self.success: iter206.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listTagsByNotebook_args(object): """ Attributes: - authenticationToken - notebookGuid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'notebookGuid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, notebookGuid=None,): self.authenticationToken = authenticationToken self.notebookGuid = notebookGuid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.notebookGuid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listTagsByNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.notebookGuid is not None: oprot.writeFieldBegin('notebookGuid', TType.STRING, 2) oprot.writeString(self.notebookGuid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listTagsByNotebook_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype210, _size207) = iprot.readListBegin() for _i211 in xrange(_size207): _elem212 = evernote.edam.type.ttypes.Tag() _elem212.read(iprot) self.success.append(_elem212) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listTagsByNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter213 in self.success: iter213.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getTag_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTag_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getTag_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Tag() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getTag_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createTag_args(object): """ Attributes: - authenticationToken - tag """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'tag', (evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, tag=None,): self.authenticationToken = authenticationToken self.tag = tag def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.tag = evernote.edam.type.ttypes.Tag() self.tag.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createTag_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.tag is not None: oprot.writeFieldBegin('tag', TType.STRUCT, 2) self.tag.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createTag_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Tag() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createTag_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateTag_args(object): """ Attributes: - authenticationToken - tag """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'tag', (evernote.edam.type.ttypes.Tag, evernote.edam.type.ttypes.Tag.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, tag=None,): self.authenticationToken = authenticationToken self.tag = tag def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.tag = evernote.edam.type.ttypes.Tag() self.tag.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateTag_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.tag is not None: oprot.writeFieldBegin('tag', TType.STRUCT, 2) self.tag.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateTag_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateTag_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class untagAll_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('untagAll_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class untagAll_result(object): """ Attributes: - userException - systemException - notFoundException """ thrift_spec = ( None, # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, userException=None, systemException=None, notFoundException=None,): self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('untagAll_result') if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeTag_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeTag_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeTag_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeTag_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listSearches_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listSearches_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listSearches_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.SavedSearch, evernote.edam.type.ttypes.SavedSearch.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype217, _size214) = iprot.readListBegin() for _i218 in xrange(_size214): _elem219 = evernote.edam.type.ttypes.SavedSearch() _elem219.read(iprot) self.success.append(_elem219) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listSearches_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter220 in self.success: iter220.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSearch_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSearch_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSearch_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.SavedSearch, evernote.edam.type.ttypes.SavedSearch.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.SavedSearch() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSearch_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createSearch_args(object): """ Attributes: - authenticationToken - search """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'search', (evernote.edam.type.ttypes.SavedSearch, evernote.edam.type.ttypes.SavedSearch.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, search=None,): self.authenticationToken = authenticationToken self.search = search def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.search = evernote.edam.type.ttypes.SavedSearch() self.search.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createSearch_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.search is not None: oprot.writeFieldBegin('search', TType.STRUCT, 2) self.search.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createSearch_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.SavedSearch, evernote.edam.type.ttypes.SavedSearch.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.SavedSearch() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createSearch_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateSearch_args(object): """ Attributes: - authenticationToken - search """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'search', (evernote.edam.type.ttypes.SavedSearch, evernote.edam.type.ttypes.SavedSearch.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, search=None,): self.authenticationToken = authenticationToken self.search = search def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.search = evernote.edam.type.ttypes.SavedSearch() self.search.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateSearch_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.search is not None: oprot.writeFieldBegin('search', TType.STRUCT, 2) self.search.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateSearch_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateSearch_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeSearch_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeSearch_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeSearch_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeSearch_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNotes_args(object): """ Attributes: - authenticationToken - filter - offset - maxNotes """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'filter', (NoteFilter, NoteFilter.thrift_spec), None, ), # 2 (3, TType.I32, 'offset', None, None, ), # 3 (4, TType.I32, 'maxNotes', None, None, ), # 4 ) def __init__(self, authenticationToken=None, filter=None, offset=None, maxNotes=None,): self.authenticationToken = authenticationToken self.filter = filter self.offset = offset self.maxNotes = maxNotes def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.filter = NoteFilter() self.filter.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.offset = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.maxNotes = iprot.readI32(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNotes_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.filter is not None: oprot.writeFieldBegin('filter', TType.STRUCT, 2) self.filter.write(oprot) oprot.writeFieldEnd() if self.offset is not None: oprot.writeFieldBegin('offset', TType.I32, 3) oprot.writeI32(self.offset) oprot.writeFieldEnd() if self.maxNotes is not None: oprot.writeFieldBegin('maxNotes', TType.I32, 4) oprot.writeI32(self.maxNotes) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNotes_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (NoteList, NoteList.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = NoteList() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNotes_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNoteOffset_args(object): """ Attributes: - authenticationToken - filter - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'filter', (NoteFilter, NoteFilter.thrift_spec), None, ), # 2 (3, TType.STRING, 'guid', None, None, ), # 3 ) def __init__(self, authenticationToken=None, filter=None, guid=None,): self.authenticationToken = authenticationToken self.filter = filter self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.filter = NoteFilter() self.filter.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNoteOffset_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.filter is not None: oprot.writeFieldBegin('filter', TType.STRUCT, 2) self.filter.write(oprot) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 3) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNoteOffset_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNoteOffset_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNotesMetadata_args(object): """ Attributes: - authenticationToken - filter - offset - maxNotes - resultSpec """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'filter', (NoteFilter, NoteFilter.thrift_spec), None, ), # 2 (3, TType.I32, 'offset', None, None, ), # 3 (4, TType.I32, 'maxNotes', None, None, ), # 4 (5, TType.STRUCT, 'resultSpec', (NotesMetadataResultSpec, NotesMetadataResultSpec.thrift_spec), None, ), # 5 ) def __init__(self, authenticationToken=None, filter=None, offset=None, maxNotes=None, resultSpec=None,): self.authenticationToken = authenticationToken self.filter = filter self.offset = offset self.maxNotes = maxNotes self.resultSpec = resultSpec def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.filter = NoteFilter() self.filter.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.offset = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.maxNotes = iprot.readI32(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.STRUCT: self.resultSpec = NotesMetadataResultSpec() self.resultSpec.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNotesMetadata_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.filter is not None: oprot.writeFieldBegin('filter', TType.STRUCT, 2) self.filter.write(oprot) oprot.writeFieldEnd() if self.offset is not None: oprot.writeFieldBegin('offset', TType.I32, 3) oprot.writeI32(self.offset) oprot.writeFieldEnd() if self.maxNotes is not None: oprot.writeFieldBegin('maxNotes', TType.I32, 4) oprot.writeI32(self.maxNotes) oprot.writeFieldEnd() if self.resultSpec is not None: oprot.writeFieldBegin('resultSpec', TType.STRUCT, 5) self.resultSpec.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNotesMetadata_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (NotesMetadataList, NotesMetadataList.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = NotesMetadataList() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNotesMetadata_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNoteCounts_args(object): """ Attributes: - authenticationToken - filter - withTrash """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'filter', (NoteFilter, NoteFilter.thrift_spec), None, ), # 2 (3, TType.BOOL, 'withTrash', None, None, ), # 3 ) def __init__(self, authenticationToken=None, filter=None, withTrash=None,): self.authenticationToken = authenticationToken self.filter = filter self.withTrash = withTrash def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.filter = NoteFilter() self.filter.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.BOOL: self.withTrash = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNoteCounts_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.filter is not None: oprot.writeFieldBegin('filter', TType.STRUCT, 2) self.filter.write(oprot) oprot.writeFieldEnd() if self.withTrash is not None: oprot.writeFieldBegin('withTrash', TType.BOOL, 3) oprot.writeBool(self.withTrash) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findNoteCounts_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (NoteCollectionCounts, NoteCollectionCounts.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = NoteCollectionCounts() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findNoteCounts_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNote_args(object): """ Attributes: - authenticationToken - guid - withContent - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.BOOL, 'withContent', None, None, ), # 3 (4, TType.BOOL, 'withResourcesData', None, None, ), # 4 (5, TType.BOOL, 'withResourcesRecognition', None, None, ), # 5 (6, TType.BOOL, 'withResourcesAlternateData', None, None, ), # 6 ) def __init__(self, authenticationToken=None, guid=None, withContent=None, withResourcesData=None, withResourcesRecognition=None, withResourcesAlternateData=None,): self.authenticationToken = authenticationToken self.guid = guid self.withContent = withContent self.withResourcesData = withResourcesData self.withResourcesRecognition = withResourcesRecognition self.withResourcesAlternateData = withResourcesAlternateData def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.BOOL: self.withContent = iprot.readBool(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.withResourcesData = iprot.readBool(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.BOOL: self.withResourcesRecognition = iprot.readBool(); else: iprot.skip(ftype) elif fid == 6: if ftype == TType.BOOL: self.withResourcesAlternateData = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.withContent is not None: oprot.writeFieldBegin('withContent', TType.BOOL, 3) oprot.writeBool(self.withContent) oprot.writeFieldEnd() if self.withResourcesData is not None: oprot.writeFieldBegin('withResourcesData', TType.BOOL, 4) oprot.writeBool(self.withResourcesData) oprot.writeFieldEnd() if self.withResourcesRecognition is not None: oprot.writeFieldBegin('withResourcesRecognition', TType.BOOL, 5) oprot.writeBool(self.withResourcesRecognition) oprot.writeFieldEnd() if self.withResourcesAlternateData is not None: oprot.writeFieldBegin('withResourcesAlternateData', TType.BOOL, 6) oprot.writeBool(self.withResourcesAlternateData) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Note() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteApplicationData_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteApplicationData_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteApplicationData_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.LazyMap, evernote.edam.type.ttypes.LazyMap.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.LazyMap() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteApplicationData_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 ) def __init__(self, authenticationToken=None, guid=None, key=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setNoteApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key - value """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 (4, TType.STRING, 'value', None, None, ), # 4 ) def __init__(self, authenticationToken=None, guid=None, key=None, value=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key self.value = value def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRING: self.value = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setNoteApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() if self.value is not None: oprot.writeFieldBegin('value', TType.STRING, 4) oprot.writeString(self.value) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setNoteApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setNoteApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class unsetNoteApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 ) def __init__(self, authenticationToken=None, guid=None, key=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('unsetNoteApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class unsetNoteApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('unsetNoteApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteContent_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteContent_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteContent_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteContent_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteSearchText_args(object): """ Attributes: - authenticationToken - guid - noteOnly - tokenizeForIndexing """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.BOOL, 'noteOnly', None, None, ), # 3 (4, TType.BOOL, 'tokenizeForIndexing', None, None, ), # 4 ) def __init__(self, authenticationToken=None, guid=None, noteOnly=None, tokenizeForIndexing=None,): self.authenticationToken = authenticationToken self.guid = guid self.noteOnly = noteOnly self.tokenizeForIndexing = tokenizeForIndexing def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.BOOL: self.noteOnly = iprot.readBool(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.tokenizeForIndexing = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteSearchText_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.noteOnly is not None: oprot.writeFieldBegin('noteOnly', TType.BOOL, 3) oprot.writeBool(self.noteOnly) oprot.writeFieldEnd() if self.tokenizeForIndexing is not None: oprot.writeFieldBegin('tokenizeForIndexing', TType.BOOL, 4) oprot.writeBool(self.tokenizeForIndexing) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteSearchText_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteSearchText_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceSearchText_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceSearchText_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceSearchText_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceSearchText_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteTagNames_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteTagNames_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteTagNames_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRING,None), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype224, _size221) = iprot.readListBegin() for _i225 in xrange(_size221): _elem226 = iprot.readString(); self.success.append(_elem226) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteTagNames_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRING, len(self.success)) for iter227 in self.success: oprot.writeString(iter227) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createNote_args(object): """ Attributes: - authenticationToken - note """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'note', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, note=None,): self.authenticationToken = authenticationToken self.note = note def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.note = evernote.edam.type.ttypes.Note() self.note.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.note is not None: oprot.writeFieldBegin('note', TType.STRUCT, 2) self.note.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Note() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateNote_args(object): """ Attributes: - authenticationToken - note """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'note', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, note=None,): self.authenticationToken = authenticationToken self.note = note def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.note = evernote.edam.type.ttypes.Note() self.note.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.note is not None: oprot.writeFieldBegin('note', TType.STRUCT, 2) self.note.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Note() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class deleteNote_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deleteNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class deleteNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('deleteNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNote_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNotes_args(object): """ Attributes: - authenticationToken - noteGuids """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.LIST, 'noteGuids', (TType.STRING,None), None, ), # 2 ) def __init__(self, authenticationToken=None, noteGuids=None,): self.authenticationToken = authenticationToken self.noteGuids = noteGuids def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.LIST: self.noteGuids = [] (_etype231, _size228) = iprot.readListBegin() for _i232 in xrange(_size228): _elem233 = iprot.readString(); self.noteGuids.append(_elem233) iprot.readListEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNotes_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.noteGuids is not None: oprot.writeFieldBegin('noteGuids', TType.LIST, 2) oprot.writeListBegin(TType.STRING, len(self.noteGuids)) for iter234 in self.noteGuids: oprot.writeString(iter234) oprot.writeListEnd() oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeNotes_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeNotes_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeInactiveNotes_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeInactiveNotes_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeInactiveNotes_result(object): """ Attributes: - success - userException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, userException=None, systemException=None,): self.success = success self.userException = userException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeInactiveNotes_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class copyNote_args(object): """ Attributes: - authenticationToken - noteGuid - toNotebookGuid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'noteGuid', None, None, ), # 2 (3, TType.STRING, 'toNotebookGuid', None, None, ), # 3 ) def __init__(self, authenticationToken=None, noteGuid=None, toNotebookGuid=None,): self.authenticationToken = authenticationToken self.noteGuid = noteGuid self.toNotebookGuid = toNotebookGuid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.noteGuid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.toNotebookGuid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('copyNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.noteGuid is not None: oprot.writeFieldBegin('noteGuid', TType.STRING, 2) oprot.writeString(self.noteGuid) oprot.writeFieldEnd() if self.toNotebookGuid is not None: oprot.writeFieldBegin('toNotebookGuid', TType.STRING, 3) oprot.writeString(self.toNotebookGuid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class copyNote_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Note() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('copyNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listNoteVersions_args(object): """ Attributes: - authenticationToken - noteGuid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'noteGuid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, noteGuid=None,): self.authenticationToken = authenticationToken self.noteGuid = noteGuid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.noteGuid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listNoteVersions_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.noteGuid is not None: oprot.writeFieldBegin('noteGuid', TType.STRING, 2) oprot.writeString(self.noteGuid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listNoteVersions_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(NoteVersionId, NoteVersionId.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype238, _size235) = iprot.readListBegin() for _i239 in xrange(_size235): _elem240 = NoteVersionId() _elem240.read(iprot) self.success.append(_elem240) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listNoteVersions_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter241 in self.success: iter241.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteVersion_args(object): """ Attributes: - authenticationToken - noteGuid - updateSequenceNum - withResourcesData - withResourcesRecognition - withResourcesAlternateData """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'noteGuid', None, None, ), # 2 (3, TType.I32, 'updateSequenceNum', None, None, ), # 3 (4, TType.BOOL, 'withResourcesData', None, None, ), # 4 (5, TType.BOOL, 'withResourcesRecognition', None, None, ), # 5 (6, TType.BOOL, 'withResourcesAlternateData', None, None, ), # 6 ) def __init__(self, authenticationToken=None, noteGuid=None, updateSequenceNum=None, withResourcesData=None, withResourcesRecognition=None, withResourcesAlternateData=None,): self.authenticationToken = authenticationToken self.noteGuid = noteGuid self.updateSequenceNum = updateSequenceNum self.withResourcesData = withResourcesData self.withResourcesRecognition = withResourcesRecognition self.withResourcesAlternateData = withResourcesAlternateData def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.noteGuid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.updateSequenceNum = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.withResourcesData = iprot.readBool(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.BOOL: self.withResourcesRecognition = iprot.readBool(); else: iprot.skip(ftype) elif fid == 6: if ftype == TType.BOOL: self.withResourcesAlternateData = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteVersion_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.noteGuid is not None: oprot.writeFieldBegin('noteGuid', TType.STRING, 2) oprot.writeString(self.noteGuid) oprot.writeFieldEnd() if self.updateSequenceNum is not None: oprot.writeFieldBegin('updateSequenceNum', TType.I32, 3) oprot.writeI32(self.updateSequenceNum) oprot.writeFieldEnd() if self.withResourcesData is not None: oprot.writeFieldBegin('withResourcesData', TType.BOOL, 4) oprot.writeBool(self.withResourcesData) oprot.writeFieldEnd() if self.withResourcesRecognition is not None: oprot.writeFieldBegin('withResourcesRecognition', TType.BOOL, 5) oprot.writeBool(self.withResourcesRecognition) oprot.writeFieldEnd() if self.withResourcesAlternateData is not None: oprot.writeFieldBegin('withResourcesAlternateData', TType.BOOL, 6) oprot.writeBool(self.withResourcesAlternateData) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getNoteVersion_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Note, evernote.edam.type.ttypes.Note.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Note() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getNoteVersion_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResource_args(object): """ Attributes: - authenticationToken - guid - withData - withRecognition - withAttributes - withAlternateData """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.BOOL, 'withData', None, None, ), # 3 (4, TType.BOOL, 'withRecognition', None, None, ), # 4 (5, TType.BOOL, 'withAttributes', None, None, ), # 5 (6, TType.BOOL, 'withAlternateData', None, None, ), # 6 ) def __init__(self, authenticationToken=None, guid=None, withData=None, withRecognition=None, withAttributes=None, withAlternateData=None,): self.authenticationToken = authenticationToken self.guid = guid self.withData = withData self.withRecognition = withRecognition self.withAttributes = withAttributes self.withAlternateData = withAlternateData def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.BOOL: self.withData = iprot.readBool(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.withRecognition = iprot.readBool(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.BOOL: self.withAttributes = iprot.readBool(); else: iprot.skip(ftype) elif fid == 6: if ftype == TType.BOOL: self.withAlternateData = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResource_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.withData is not None: oprot.writeFieldBegin('withData', TType.BOOL, 3) oprot.writeBool(self.withData) oprot.writeFieldEnd() if self.withRecognition is not None: oprot.writeFieldBegin('withRecognition', TType.BOOL, 4) oprot.writeBool(self.withRecognition) oprot.writeFieldEnd() if self.withAttributes is not None: oprot.writeFieldBegin('withAttributes', TType.BOOL, 5) oprot.writeBool(self.withAttributes) oprot.writeFieldEnd() if self.withAlternateData is not None: oprot.writeFieldBegin('withAlternateData', TType.BOOL, 6) oprot.writeBool(self.withAlternateData) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResource_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Resource, evernote.edam.type.ttypes.Resource.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Resource() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResource_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceApplicationData_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceApplicationData_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceApplicationData_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.LazyMap, evernote.edam.type.ttypes.LazyMap.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.LazyMap() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceApplicationData_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 ) def __init__(self, authenticationToken=None, guid=None, key=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setResourceApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key - value """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 (4, TType.STRING, 'value', None, None, ), # 4 ) def __init__(self, authenticationToken=None, guid=None, key=None, value=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key self.value = value def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRING: self.value = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setResourceApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() if self.value is not None: oprot.writeFieldBegin('value', TType.STRING, 4) oprot.writeString(self.value) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setResourceApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setResourceApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class unsetResourceApplicationDataEntry_args(object): """ Attributes: - authenticationToken - guid - key """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 (3, TType.STRING, 'key', None, None, ), # 3 ) def __init__(self, authenticationToken=None, guid=None, key=None,): self.authenticationToken = authenticationToken self.guid = guid self.key = key def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.key = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('unsetResourceApplicationDataEntry_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.key is not None: oprot.writeFieldBegin('key', TType.STRING, 3) oprot.writeString(self.key) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class unsetResourceApplicationDataEntry_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('unsetResourceApplicationDataEntry_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateResource_args(object): """ Attributes: - authenticationToken - resource """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'resource', (evernote.edam.type.ttypes.Resource, evernote.edam.type.ttypes.Resource.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, resource=None,): self.authenticationToken = authenticationToken self.resource = resource def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.resource = evernote.edam.type.ttypes.Resource() self.resource.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateResource_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.resource is not None: oprot.writeFieldBegin('resource', TType.STRUCT, 2) self.resource.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateResource_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateResource_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceData_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceData_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceData_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceData_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceByHash_args(object): """ Attributes: - authenticationToken - noteGuid - contentHash - withData - withRecognition - withAlternateData """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'noteGuid', None, None, ), # 2 (3, TType.STRING, 'contentHash', None, None, ), # 3 (4, TType.BOOL, 'withData', None, None, ), # 4 (5, TType.BOOL, 'withRecognition', None, None, ), # 5 (6, TType.BOOL, 'withAlternateData', None, None, ), # 6 ) def __init__(self, authenticationToken=None, noteGuid=None, contentHash=None, withData=None, withRecognition=None, withAlternateData=None,): self.authenticationToken = authenticationToken self.noteGuid = noteGuid self.contentHash = contentHash self.withData = withData self.withRecognition = withRecognition self.withAlternateData = withAlternateData def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.noteGuid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.contentHash = iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.BOOL: self.withData = iprot.readBool(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.BOOL: self.withRecognition = iprot.readBool(); else: iprot.skip(ftype) elif fid == 6: if ftype == TType.BOOL: self.withAlternateData = iprot.readBool(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceByHash_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.noteGuid is not None: oprot.writeFieldBegin('noteGuid', TType.STRING, 2) oprot.writeString(self.noteGuid) oprot.writeFieldEnd() if self.contentHash is not None: oprot.writeFieldBegin('contentHash', TType.STRING, 3) oprot.writeString(self.contentHash) oprot.writeFieldEnd() if self.withData is not None: oprot.writeFieldBegin('withData', TType.BOOL, 4) oprot.writeBool(self.withData) oprot.writeFieldEnd() if self.withRecognition is not None: oprot.writeFieldBegin('withRecognition', TType.BOOL, 5) oprot.writeBool(self.withRecognition) oprot.writeFieldEnd() if self.withAlternateData is not None: oprot.writeFieldBegin('withAlternateData', TType.BOOL, 6) oprot.writeBool(self.withAlternateData) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceByHash_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Resource, evernote.edam.type.ttypes.Resource.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Resource() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceByHash_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceRecognition_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceRecognition_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceRecognition_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceRecognition_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceAlternateData_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceAlternateData_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceAlternateData_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceAlternateData_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceAttributes_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceAttributes_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getResourceAttributes_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.ResourceAttributes, evernote.edam.type.ttypes.ResourceAttributes.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.ResourceAttributes() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getResourceAttributes_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getPublicNotebook_args(object): """ Attributes: - userId - publicUri """ thrift_spec = ( None, # 0 (1, TType.I32, 'userId', None, None, ), # 1 (2, TType.STRING, 'publicUri', None, None, ), # 2 ) def __init__(self, userId=None, publicUri=None,): self.userId = userId self.publicUri = publicUri def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.userId = iprot.readI32(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.publicUri = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getPublicNotebook_args') if self.userId is not None: oprot.writeFieldBegin('userId', TType.I32, 1) oprot.writeI32(self.userId) oprot.writeFieldEnd() if self.publicUri is not None: oprot.writeFieldBegin('publicUri', TType.STRING, 2) oprot.writeString(self.publicUri) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getPublicNotebook_result(object): """ Attributes: - success - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.Notebook, evernote.edam.type.ttypes.Notebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 ) def __init__(self, success=None, systemException=None, notFoundException=None,): self.success = success self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.Notebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getPublicNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 1) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createSharedNotebook_args(object): """ Attributes: - authenticationToken - sharedNotebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'sharedNotebook', (evernote.edam.type.ttypes.SharedNotebook, evernote.edam.type.ttypes.SharedNotebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, sharedNotebook=None,): self.authenticationToken = authenticationToken self.sharedNotebook = sharedNotebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.sharedNotebook = evernote.edam.type.ttypes.SharedNotebook() self.sharedNotebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createSharedNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.sharedNotebook is not None: oprot.writeFieldBegin('sharedNotebook', TType.STRUCT, 2) self.sharedNotebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createSharedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.SharedNotebook, evernote.edam.type.ttypes.SharedNotebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.SharedNotebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createSharedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateSharedNotebook_args(object): """ Attributes: - authenticationToken - sharedNotebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'sharedNotebook', (evernote.edam.type.ttypes.SharedNotebook, evernote.edam.type.ttypes.SharedNotebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, sharedNotebook=None,): self.authenticationToken = authenticationToken self.sharedNotebook = sharedNotebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.sharedNotebook = evernote.edam.type.ttypes.SharedNotebook() self.sharedNotebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateSharedNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.sharedNotebook is not None: oprot.writeFieldBegin('sharedNotebook', TType.STRUCT, 2) self.sharedNotebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateSharedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateSharedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setSharedNotebookRecipientSettings_args(object): """ Attributes: - authenticationToken - sharedNotebookId - recipientSettings """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.I64, 'sharedNotebookId', None, None, ), # 2 (3, TType.STRUCT, 'recipientSettings', (evernote.edam.type.ttypes.SharedNotebookRecipientSettings, evernote.edam.type.ttypes.SharedNotebookRecipientSettings.thrift_spec), None, ), # 3 ) def __init__(self, authenticationToken=None, sharedNotebookId=None, recipientSettings=None,): self.authenticationToken = authenticationToken self.sharedNotebookId = sharedNotebookId self.recipientSettings = recipientSettings def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I64: self.sharedNotebookId = iprot.readI64(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.recipientSettings = evernote.edam.type.ttypes.SharedNotebookRecipientSettings() self.recipientSettings.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setSharedNotebookRecipientSettings_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.sharedNotebookId is not None: oprot.writeFieldBegin('sharedNotebookId', TType.I64, 2) oprot.writeI64(self.sharedNotebookId) oprot.writeFieldEnd() if self.recipientSettings is not None: oprot.writeFieldBegin('recipientSettings', TType.STRUCT, 3) self.recipientSettings.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class setSharedNotebookRecipientSettings_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('setSharedNotebookRecipientSettings_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class sendMessageToSharedNotebookMembers_args(object): """ Attributes: - authenticationToken - notebookGuid - messageText - recipients """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'notebookGuid', None, None, ), # 2 (3, TType.STRING, 'messageText', None, None, ), # 3 (4, TType.LIST, 'recipients', (TType.STRING,None), None, ), # 4 ) def __init__(self, authenticationToken=None, notebookGuid=None, messageText=None, recipients=None,): self.authenticationToken = authenticationToken self.notebookGuid = notebookGuid self.messageText = messageText self.recipients = recipients def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.notebookGuid = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.messageText = iprot.readString(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.LIST: self.recipients = [] (_etype245, _size242) = iprot.readListBegin() for _i246 in xrange(_size242): _elem247 = iprot.readString(); self.recipients.append(_elem247) iprot.readListEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('sendMessageToSharedNotebookMembers_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.notebookGuid is not None: oprot.writeFieldBegin('notebookGuid', TType.STRING, 2) oprot.writeString(self.notebookGuid) oprot.writeFieldEnd() if self.messageText is not None: oprot.writeFieldBegin('messageText', TType.STRING, 3) oprot.writeString(self.messageText) oprot.writeFieldEnd() if self.recipients is not None: oprot.writeFieldBegin('recipients', TType.LIST, 4) oprot.writeListBegin(TType.STRING, len(self.recipients)) for iter248 in self.recipients: oprot.writeString(iter248) oprot.writeListEnd() oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class sendMessageToSharedNotebookMembers_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('sendMessageToSharedNotebookMembers_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listSharedNotebooks_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listSharedNotebooks_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listSharedNotebooks_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.SharedNotebook, evernote.edam.type.ttypes.SharedNotebook.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype252, _size249) = iprot.readListBegin() for _i253 in xrange(_size249): _elem254 = evernote.edam.type.ttypes.SharedNotebook() _elem254.read(iprot) self.success.append(_elem254) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listSharedNotebooks_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter255 in self.success: iter255.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeSharedNotebooks_args(object): """ Attributes: - authenticationToken - sharedNotebookIds """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.LIST, 'sharedNotebookIds', (TType.I64,None), None, ), # 2 ) def __init__(self, authenticationToken=None, sharedNotebookIds=None,): self.authenticationToken = authenticationToken self.sharedNotebookIds = sharedNotebookIds def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.LIST: self.sharedNotebookIds = [] (_etype259, _size256) = iprot.readListBegin() for _i260 in xrange(_size256): _elem261 = iprot.readI64(); self.sharedNotebookIds.append(_elem261) iprot.readListEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeSharedNotebooks_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.sharedNotebookIds is not None: oprot.writeFieldBegin('sharedNotebookIds', TType.LIST, 2) oprot.writeListBegin(TType.I64, len(self.sharedNotebookIds)) for iter262 in self.sharedNotebookIds: oprot.writeI64(iter262) oprot.writeListEnd() oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeSharedNotebooks_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeSharedNotebooks_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createLinkedNotebook_args(object): """ Attributes: - authenticationToken - linkedNotebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'linkedNotebook', (evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, linkedNotebook=None,): self.authenticationToken = authenticationToken self.linkedNotebook = linkedNotebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.linkedNotebook = evernote.edam.type.ttypes.LinkedNotebook() self.linkedNotebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createLinkedNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.linkedNotebook is not None: oprot.writeFieldBegin('linkedNotebook', TType.STRUCT, 2) self.linkedNotebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class createLinkedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.LinkedNotebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('createLinkedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateLinkedNotebook_args(object): """ Attributes: - authenticationToken - linkedNotebook """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'linkedNotebook', (evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, linkedNotebook=None,): self.authenticationToken = authenticationToken self.linkedNotebook = linkedNotebook def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.linkedNotebook = evernote.edam.type.ttypes.LinkedNotebook() self.linkedNotebook.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateLinkedNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.linkedNotebook is not None: oprot.writeFieldBegin('linkedNotebook', TType.STRUCT, 2) self.linkedNotebook.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class updateLinkedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('updateLinkedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listLinkedNotebooks_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listLinkedNotebooks_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class listLinkedNotebooks_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(evernote.edam.type.ttypes.LinkedNotebook, evernote.edam.type.ttypes.LinkedNotebook.thrift_spec)), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.LIST: self.success = [] (_etype266, _size263) = iprot.readListBegin() for _i267 in xrange(_size263): _elem268 = evernote.edam.type.ttypes.LinkedNotebook() _elem268.read(iprot) self.success.append(_elem268) iprot.readListEnd() else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('listLinkedNotebooks_result') if self.success is not None: oprot.writeFieldBegin('success', TType.LIST, 0) oprot.writeListBegin(TType.STRUCT, len(self.success)) for iter269 in self.success: iter269.write(oprot) oprot.writeListEnd() oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeLinkedNotebook_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeLinkedNotebook_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class expungeLinkedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.I32, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.I32: self.success = iprot.readI32(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('expungeLinkedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.I32, 0) oprot.writeI32(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class authenticateToSharedNotebook_args(object): """ Attributes: - shareKey - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'shareKey', None, None, ), # 1 (2, TType.STRING, 'authenticationToken', None, None, ), # 2 ) def __init__(self, shareKey=None, authenticationToken=None,): self.shareKey = shareKey self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.shareKey = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('authenticateToSharedNotebook_args') if self.shareKey is not None: oprot.writeFieldBegin('shareKey', TType.STRING, 1) oprot.writeString(self.shareKey) oprot.writeFieldEnd() if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 2) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class authenticateToSharedNotebook_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.userstore.ttypes.AuthenticationResult, evernote.edam.userstore.ttypes.AuthenticationResult.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.userstore.ttypes.AuthenticationResult() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('authenticateToSharedNotebook_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSharedNotebookByAuth_args(object): """ Attributes: - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 ) def __init__(self, authenticationToken=None,): self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSharedNotebookByAuth_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class getSharedNotebookByAuth_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.type.ttypes.SharedNotebook, evernote.edam.type.ttypes.SharedNotebook.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.type.ttypes.SharedNotebook() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('getSharedNotebookByAuth_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class emailNote_args(object): """ Attributes: - authenticationToken - parameters """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'parameters', (NoteEmailParameters, NoteEmailParameters.thrift_spec), None, ), # 2 ) def __init__(self, authenticationToken=None, parameters=None,): self.authenticationToken = authenticationToken self.parameters = parameters def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.parameters = NoteEmailParameters() self.parameters.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('emailNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.parameters is not None: oprot.writeFieldBegin('parameters', TType.STRUCT, 2) self.parameters.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class emailNote_result(object): """ Attributes: - userException - notFoundException - systemException """ thrift_spec = ( None, # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, userException=None, notFoundException=None, systemException=None,): self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('emailNote_result') if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class shareNote_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('shareNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class shareNote_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRING, 'success', None, None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRING: self.success = iprot.readString(); else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('shareNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRING, 0) oprot.writeString(self.success) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class stopSharingNote_args(object): """ Attributes: - authenticationToken - guid """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRING, 'guid', None, None, ), # 2 ) def __init__(self, authenticationToken=None, guid=None,): self.authenticationToken = authenticationToken self.guid = guid def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('stopSharingNote_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 2) oprot.writeString(self.guid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class stopSharingNote_result(object): """ Attributes: - userException - notFoundException - systemException """ thrift_spec = ( None, # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, userException=None, notFoundException=None, systemException=None,): self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('stopSharingNote_result') if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class authenticateToSharedNote_args(object): """ Attributes: - guid - noteKey - authenticationToken """ thrift_spec = ( None, # 0 (1, TType.STRING, 'guid', None, None, ), # 1 (2, TType.STRING, 'noteKey', None, None, ), # 2 (3, TType.STRING, 'authenticationToken', None, None, ), # 3 ) def __init__(self, guid=None, noteKey=None, authenticationToken=None,): self.guid = guid self.noteKey = noteKey self.authenticationToken = authenticationToken def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.guid = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.noteKey = iprot.readString(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('authenticateToSharedNote_args') if self.guid is not None: oprot.writeFieldBegin('guid', TType.STRING, 1) oprot.writeString(self.guid) oprot.writeFieldEnd() if self.noteKey is not None: oprot.writeFieldBegin('noteKey', TType.STRING, 2) oprot.writeString(self.noteKey) oprot.writeFieldEnd() if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 3) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class authenticateToSharedNote_result(object): """ Attributes: - success - userException - notFoundException - systemException """ thrift_spec = ( (0, TType.STRUCT, 'success', (evernote.edam.userstore.ttypes.AuthenticationResult, evernote.edam.userstore.ttypes.AuthenticationResult.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, notFoundException=None, systemException=None,): self.success = success self.userException = userException self.notFoundException = notFoundException self.systemException = systemException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = evernote.edam.userstore.ttypes.AuthenticationResult() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('authenticateToSharedNote_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 2) self.notFoundException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 3) self.systemException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findRelated_args(object): """ Attributes: - authenticationToken - query - resultSpec """ thrift_spec = ( None, # 0 (1, TType.STRING, 'authenticationToken', None, None, ), # 1 (2, TType.STRUCT, 'query', (RelatedQuery, RelatedQuery.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'resultSpec', (RelatedResultSpec, RelatedResultSpec.thrift_spec), None, ), # 3 ) def __init__(self, authenticationToken=None, query=None, resultSpec=None,): self.authenticationToken = authenticationToken self.query = query self.resultSpec = resultSpec def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.authenticationToken = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.query = RelatedQuery() self.query.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.resultSpec = RelatedResultSpec() self.resultSpec.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findRelated_args') if self.authenticationToken is not None: oprot.writeFieldBegin('authenticationToken', TType.STRING, 1) oprot.writeString(self.authenticationToken) oprot.writeFieldEnd() if self.query is not None: oprot.writeFieldBegin('query', TType.STRUCT, 2) self.query.write(oprot) oprot.writeFieldEnd() if self.resultSpec is not None: oprot.writeFieldBegin('resultSpec', TType.STRUCT, 3) self.resultSpec.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class findRelated_result(object): """ Attributes: - success - userException - systemException - notFoundException """ thrift_spec = ( (0, TType.STRUCT, 'success', (RelatedResult, RelatedResult.thrift_spec), None, ), # 0 (1, TType.STRUCT, 'userException', (evernote.edam.error.ttypes.EDAMUserException, evernote.edam.error.ttypes.EDAMUserException.thrift_spec), None, ), # 1 (2, TType.STRUCT, 'systemException', (evernote.edam.error.ttypes.EDAMSystemException, evernote.edam.error.ttypes.EDAMSystemException.thrift_spec), None, ), # 2 (3, TType.STRUCT, 'notFoundException', (evernote.edam.error.ttypes.EDAMNotFoundException, evernote.edam.error.ttypes.EDAMNotFoundException.thrift_spec), None, ), # 3 ) def __init__(self, success=None, userException=None, systemException=None, notFoundException=None,): self.success = success self.userException = userException self.systemException = systemException self.notFoundException = notFoundException def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 0: if ftype == TType.STRUCT: self.success = RelatedResult() self.success.read(iprot) else: iprot.skip(ftype) elif fid == 1: if ftype == TType.STRUCT: self.userException = evernote.edam.error.ttypes.EDAMUserException() self.userException.read(iprot) else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.systemException = evernote.edam.error.ttypes.EDAMSystemException() self.systemException.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRUCT: self.notFoundException = evernote.edam.error.ttypes.EDAMNotFoundException() self.notFoundException.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('findRelated_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.write(oprot) oprot.writeFieldEnd() if self.userException is not None: oprot.writeFieldBegin('userException', TType.STRUCT, 1) self.userException.write(oprot) oprot.writeFieldEnd() if self.systemException is not None: oprot.writeFieldBegin('systemException', TType.STRUCT, 2) self.systemException.write(oprot) oprot.writeFieldEnd() if self.notFoundException is not None: oprot.writeFieldBegin('notFoundException', TType.STRUCT, 3) self.notFoundException.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other)
zapier/evernote-sdk-python
lib/evernote/edam/notestore/NoteStore.py
Python
bsd-2-clause
790,217
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from .composition_parts import DebugInfo from .composition_parts import WithIdentifier class Proxy(object): """ Proxies attribute access on this object to the target object. """ def __init__(self, target_object=None, target_attrs=None, target_attrs_with_priority=None): """ Creates a new proxy to |target_object|. Args: target_object: The object to which attribute access is proxied. This can be set later by set_target_object. target_attrs: None or list of attribute names to be proxied. If None, all the attribute access is proxied. target_attrs_with_priority: None or list of attribute names to be unconditionally proxied with priority over attributes defined on |self|. If None, no attribute has priority over own attributes. """ if target_attrs is not None: assert isinstance(target_attrs, (list, set, tuple)) assert all(isinstance(attr, str) for attr in target_attrs) self._target_object = target_object self._target_attrs = target_attrs self._target_attrs_with_priority = target_attrs_with_priority def __getattr__(self, attribute): try: target_object = object.__getattribute__(self, '_target_object') target_attrs = object.__getattribute__(self, '_target_attrs') except AttributeError: # When unpickling, __init__ does not get called. _target_object is # not defined yet during unpickling. Then, just fallback to the # default access. return object.__getattribute__(self, attribute) assert target_object is not None if target_attrs is None or attribute in target_attrs: return getattr(target_object, attribute) raise AttributeError def __getattribute__(self, attribute): try: target_object = object.__getattribute__(self, '_target_object') target_attrs = object.__getattribute__( self, '_target_attrs_with_priority') except AttributeError: # When unpickling, __init__ does not get called. _target_object is # not defined yet during unpickling. Then, just fallback to the # default access. return object.__getattribute__(self, attribute) # It's okay to access own attributes, such as 'identifier', even when # the target object is not yet resolved. if target_object is None: return object.__getattribute__(self, attribute) if target_attrs is not None and attribute in target_attrs: return getattr(target_object, attribute) return object.__getattribute__(self, attribute) @staticmethod def get_all_attributes(target_class): """ Returns all the attributes of |target_class| including its ancestors' attributes. Protected attributes (starting with an underscore, including two underscores) are excluded. """ def collect_attrs_recursively(target_class): attrs_sets = [set(vars(target_class).keys())] for base_class in target_class.__bases__: attrs_sets.append(collect_attrs_recursively(base_class)) return set.union(*attrs_sets) assert isinstance(target_class, type) return sorted([ attr for attr in collect_attrs_recursively(target_class) if not attr.startswith('_') ]) def make_copy(self, memo): return self def set_target_object(self, target_object): assert self._target_object is None assert isinstance(target_object, object) self._target_object = target_object @property def target_object(self): assert self._target_object is not None return self._target_object _REF_BY_ID_PASS_KEY = object() class RefById(Proxy, WithIdentifier): """ Represents a reference to an object specified with the given identifier, which reference will be resolved later. This reference is also a proxy to the object for convenience so that you can treat this reference as if the object itself. """ def __init__(self, identifier, debug_info=None, target_attrs=None, target_attrs_with_priority=None, pass_key=None): assert debug_info is None or isinstance(debug_info, DebugInfo) assert pass_key is _REF_BY_ID_PASS_KEY Proxy.__init__( self, target_attrs=target_attrs, target_attrs_with_priority=target_attrs_with_priority) WithIdentifier.__init__(self, identifier) self._ref_own_debug_info = debug_info @property def ref_own_debug_info(self): """This reference's own DebugInfo.""" return self._ref_own_debug_info class RefByIdFactory(object): """ Creates a group of references that are later resolvable. All the references created by this factory are grouped per factory, and you can apply a function to all the references. This allows you to resolve all the references at very end of the compilation phases. """ def __init__(self, target_attrs=None, target_attrs_with_priority=None): self._references = [] # |_is_frozen| is initially False and you can create new references. # The first invocation of |for_each| freezes the factory and you can no # longer create a new reference self._is_frozen = False self._target_attrs = target_attrs self._target_attrs_with_priority = target_attrs_with_priority def create(self, identifier, debug_info=None): """ Creates a new instance of RefById. Args: identifier: An identifier to be resolved later. debug_info: Where the reference is created, which is useful especially when the reference is unresolvable. """ assert not self._is_frozen ref = RefById( identifier, debug_info=debug_info, target_attrs=self._target_attrs, target_attrs_with_priority=self._target_attrs_with_priority, pass_key=_REF_BY_ID_PASS_KEY) self._references.append(ref) return ref def init_subclass_instance(self, instance, identifier, debug_info=None): """ Initializes an instance of a subclass of RefById. """ assert type(instance) is not RefById assert isinstance(instance, RefById) assert not self._is_frozen RefById.__init__( instance, identifier, debug_info=debug_info, target_attrs=self._target_attrs, target_attrs_with_priority=self._target_attrs_with_priority, pass_key=_REF_BY_ID_PASS_KEY) self._references.append(instance) def for_each(self, callback): """ Applies |callback| to all the references created by this factory. You can no longer create a new reference. Args: callback: A callable that takes a reference as only the argument. Return value is not used. """ assert callable(callback) self._is_frozen = True for ref in self._references: callback(ref)
scheib/chromium
third_party/blink/renderer/bindings/scripts/web_idl/reference.py
Python
bsd-3-clause
7,668
# -*-coding:utf-8 -* # Copyright (c) 2011-2015, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Renaming domains testcases List of tested functions : -------------------------- - [renameDomain] function Test cases : ------------ - Nominal cases - Renaming errors - Special cases """ import os from Util.PfwUnitTestLib import PfwTestCase from Util import ACTLogging log=ACTLogging.Logger() # Test of Domains - Rename class TestCases(PfwTestCase): def setUp(self): self.pfw.sendCmd("setTuningMode", "on") self.domain_name = "domain_white" self.new_domain_name = "domain_black" self.renaming_iterations = 5 def tearDown(self): self.pfw.sendCmd("setTuningMode", "off") def test_Nominal_Case(self): """ Nominal case ------------ Test case description : ~~~~~~~~~~~~~~~~~~~~~~~ - Renaming a domain Tested commands : ~~~~~~~~~~~~~~~~~ - [renameDomain] function - [createDomain] function - [listDomains] function Expected result : ~~~~~~~~~~~~~~~~~ - domains correctly renamed """ log.D(self.test_Nominal_Case.__doc__) # New domain creation log.I("New domain creation : %s" % (self.domain_name)) log.I("command [createDomain]" ) out, err = self.pfw.sendCmd("createDomain",self.domain_name, "") assert out == "Done", out assert err == None, "ERROR : command [createDomain] - ERROR while creating domain %s" % (self.domain_name) log.I("command [createDomain] correctly executed") log.I("Domain %s created" % (self.domain_name)) # Initial domains listing using "listDomains" command log.I("Creating a domains listing backup") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "INFO : command [listDomains] - ERROR while listing domains" log.I("command [listDomains] correctly executed") # Saving initial domains names f_init_domains = open("f_init_domains", "w") f_init_domains.write(out) f_init_domains.close() log.I("Domains listing backup created") # Checking domains number f_init_domains = open("f_init_domains", "r") domains_nbr = 0 line=f_init_domains.readline() while line!="": line=f_init_domains.readline() domains_nbr+=1 f_init_domains.close() os.remove("f_init_domains") log.I("%s domains names saved" % domains_nbr) # Domain renaming iterations log.I("Checking domain renaming - %s iterations" % self.renaming_iterations) old_name = self.domain_name new_name = self.new_domain_name for iteration in range (self.renaming_iterations): log.I("Iteration %s" % (iteration)) log.I("Renaming domain %s to %s" % (old_name,new_name)) log.I("command [renameDomain]") out, err = self.pfw.sendCmd("renameDomain",old_name,new_name) assert out == "Done", out assert err == None, "ERROR : command [renameDomain] - ERROR while renaming domain %s" % (old_name) # Domains listing using "listDomains" command log.I("Creating a domains listing") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "ERROR : command [listDomains] - ERROR while listing domains" log.I("command [listDomains] correctly executed") # Saving domains names f_domains = open("f_domains", "w") f_domains.write(out) f_domains.close() log.I("Domains listing created") # Checking renaming log.I("Checking that renaming is correct in domains listing") f_domains = open("f_domains", "r") for line in range(domains_nbr): if (line >= (domains_nbr - 1)): domain_renamed = f_domains.readline().strip('\n') assert domain_renamed==new_name, "ERROR : Error while renaming domain %s" % (old_name) else: f_domains.readline() f_domains.close() log.I("New domain name %s conform to expected value" % (new_name)) temp = old_name old_name = new_name new_name = temp os.remove("f_domains") def test_Renaming_Error(self): """ Renaming errors --------------- Test case description : ~~~~~~~~~~~~~~~~~~~~~~~ - renaming a non existent domain - renaming a domain with an already existent domain name Tested commands : ~~~~~~~~~~~~~~~~~ - [renameDomain] function - [createDomain] function - [renameDomain] function Expected result : ~~~~~~~~~~~~~~~~~ - error detected - domains names remain unchanged """ log.D(self.test_Renaming_Error.__doc__) # New domains creation log.I("New domain creation : %s" % (self.domain_name)) log.I("command [createDomain]") out, err = self.pfw.sendCmd("createDomain",self.domain_name, "") assert out == "Done", out assert err == None, "ERROR : command [createDomain] - Error while creating domain %s" % (self.domain_name) log.I("command [createDomain] - correctly executed") log.I("command Domain %s created" % (self.domain_name)) # Initial domains listing using "listDomains" command log.I("Creating a domains listing backup") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "INFO : command [listDomains] - Error while listing domains" log.I("command [listDomains] correctly executed") # Saving initial domains names f_init_domains = open("f_init_domains", "w") f_init_domains.write(out) f_init_domains.close() log.I("Domains listing backup created") # Checking domains number f_init_domains = open("f_init_domains", "r") domains_nbr = 0 line=f_init_domains.readline() while line!="": line=f_init_domains.readline() domains_nbr+=1 f_init_domains.close() log.I("%s domains names saved" % domains_nbr) # Domain renaming error : renamed domain does not exist log.I("Renaming a non existent domain") log.I("Renaming domain FAKE to NEW_NAME") log.I("command [renameDomain]") out, err = self.pfw.sendCmd("renameDomain",'FAKE','NEW_NAME') assert out != "Done", out assert err == None, "ERROR : command [renameDomain] - Error while renaming domain" log.I("command [renameDomain] - renaming error correctly detected") # Domains listing using "listDomains" command log.I("Creating a domains listing") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "ERROR : command [listDomains] - Error while listing domains" log.I("command [listDomains] correctly executed") # Saving domains names f_domains = open("f_domains", "w") f_domains.write(out) f_domains.close() log.I("Domains listing created") # Checking domains names integrity log.I("Checking domains names integrity") f_domains = open("f_domains", "r") f_init_domains = open("f_init_domains", "r") for line in range(domains_nbr): domain_name = f_domains.readline().strip('\n') domain_backup_name = f_init_domains.readline().strip('\n') assert domain_name==domain_backup_name, "ERROR : Domain name %s affected by the renaming error" % (domain_backup_name) f_domains.close() f_init_domains.close() log.I("Domains names not affected by the renaming error") os.remove("f_domains") # Domain renaming error : renaming a domain with an already existent domain name log.I("renaming a domain with an already existent domain name") log.I("Renaming domain %s to %s" % (self.domain_name,self.new_domain_name) ) log.I("command [renameDomain]") out, err = self.pfw.sendCmd("renameDomain",self.domain_name,self.new_domain_name) assert out != "Done", out assert err == None, "INFO : command [renameDomain] - Error while renaming domain" log.I("command [renameDomain] - renaming error correctly detected") # Domains listing using "listDomains" command log.I("Creating a domains listing") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "ERROR : command [listDomains] - Error while listing domains" log.I("command [listDomains] correctly executed") # Saving domains names f_domains = open("f_domains", "w") f_domains.write(out) f_domains.close() log.I("Domains listing created") # Checking domains names integrity log.I("Checking domains names integrity") f_domains = open("f_domains", "r") f_init_domains = open("f_init_domains", "r") for line in range(domains_nbr): domain_name = f_domains.readline().strip('\n') domain_backup_name = f_init_domains.readline().strip('\n') assert domain_name==domain_backup_name, "ERROR : domain name %s affected by the renaming error" % (domain_backup_name) f_domains.close() f_init_domains.close() log.I("Domains names not affected by the renaming error") os.remove("f_domains") os.remove("f_init_domains") def test_Special_Cases(self): """ Special cases ------------- Test case description : ~~~~~~~~~~~~~~~~~~~~~~~ - renaming a domain with its own name Tested commands : ~~~~~~~~~~~~~~~~~ - [renameDomain] function - [createDomain] function - [listDomains] function Expected result : ~~~~~~~~~~~~~~~~~ - no error - domains names remain unchanged """ log.D(self.test_Special_Cases.__doc__) # New domain creation # Already created in previous test # Initial domains listing using "listDomains" command log.I("Creating a domains listing backup") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "ERROR : command [listDomains] - Error while listing domains" log.I("command [listDomains] correctly executed") # Saving initial domains names f_init_domains = open("f_init_domains", "w") f_init_domains.write(out) f_init_domains.close() log.I("Domains listing backup created") # Checking domains number f_init_domains = open("f_init_domains", "r") domains_nbr = 0 line=f_init_domains.readline() while line!="": line=f_init_domains.readline() domains_nbr+=1 f_init_domains.close() log.I("%s domains names saved" % domains_nbr) # Domain renaming error : renaming a domain with its own name log.I("renaming a domain with its own name") log.I("Renaming domain %s to %s" % (self.domain_name,self.domain_name)) log.I("command [renameDomain]") out, err = self.pfw.sendCmd("renameDomain",self.domain_name,self.domain_name) assert out == "Done", out assert err == None, "ERROR : command [renameDomain] - Error while renaming domain" log.I("command [renameDomain] correctly executed") # Domains listing using "listDomains" command log.I("Creating a domains listing") log.I("command [listDomains]") out, err = self.pfw.sendCmd("listDomains","","") assert err == None, "ERROR : command [listDomains] - Error while listing domains" log.I("command [listDomains] correctly executed") # Saving domains names f_domains = open("f_domains", "w") f_domains.write(out) f_domains.close() log.I("Domains listing created") # Checking domains names integrity log.I("Checking domains names integrity") f_domains = open("f_domains", "r") f_init_domains = open("f_init_domains", "r") for line in range(domains_nbr): domain_name = f_domains.readline().strip('\n') domain_backup_name = f_init_domains.readline().strip('\n') assert domain_name==domain_backup_name, "ERROR : domain name %s affected by the renaming" % (domain_backup_name) f_domains.close() f_init_domains.close() log.I("Domains names not affected by the renaming") os.remove("f_domains") os.remove("f_init_domains")
android-ia/hardware_intel_parameter-framework
test/functional-tests/PfwTestCase/Domains/tDomain_rename.py
Python
bsd-3-clause
14,770
# orm/relationships.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Heuristics related to join conditions as used in :func:`.relationship`. Provides the :class:`.JoinCondition` object, which encapsulates SQL annotation and aliasing behavior focused on the `primaryjoin` and `secondaryjoin` aspects of :func:`.relationship`. """ from __future__ import absolute_import from .. import sql, util, exc as sa_exc, schema, log import weakref from .util import CascadeOptions, _orm_annotate, _orm_deannotate from . import dependency from . import attributes from ..sql.util import ( ClauseAdapter, join_condition, _shallow_annotate, visit_binary_product, _deep_deannotate, selectables_overlap, adapt_criterion_to_null ) from ..sql import operators, expression, visitors from .interfaces import (MANYTOMANY, MANYTOONE, ONETOMANY, StrategizedProperty, PropComparator) from ..inspection import inspect from . import mapper as mapperlib import collections def remote(expr): """Annotate a portion of a primaryjoin expression with a 'remote' annotation. See the section :ref:`relationship_custom_foreign` for a description of use. .. versionadded:: 0.8 .. seealso:: :ref:`relationship_custom_foreign` :func:`.foreign` """ return _annotate_columns(expression._clause_element_as_expr(expr), {"remote": True}) def foreign(expr): """Annotate a portion of a primaryjoin expression with a 'foreign' annotation. See the section :ref:`relationship_custom_foreign` for a description of use. .. versionadded:: 0.8 .. seealso:: :ref:`relationship_custom_foreign` :func:`.remote` """ return _annotate_columns(expression._clause_element_as_expr(expr), {"foreign": True}) @log.class_logger @util.langhelpers.dependency_for("sqlalchemy.orm.properties") class RelationshipProperty(StrategizedProperty): """Describes an object property that holds a single item or list of items that correspond to a related database table. Public constructor is the :func:`.orm.relationship` function. See also: :ref:`relationship_config_toplevel` """ strategy_wildcard_key = 'relationship' _dependency_processor = None def __init__(self, argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, comparator_factory=None, single_parent=False, innerjoin=False, distinct_target_key=None, doc=None, active_history=False, cascade_backrefs=True, load_on_pending=False, bake_queries=True, strategy_class=None, _local_remote_pairs=None, query_class=None, info=None): """Provide a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship. The constructed class is an instance of :class:`.RelationshipProperty`. A typical :func:`.relationship`, used in a classical mapping:: mapper(Parent, properties={ 'children': relationship(Child) }) Some arguments accepted by :func:`.relationship` optionally accept a callable function, which when called produces the desired value. The callable is invoked by the parent :class:`.Mapper` at "mapper initialization" time, which happens only when mappers are first used, and is assumed to be after all mappings have been constructed. This can be used to resolve order-of-declaration and other dependency issues, such as if ``Child`` is declared below ``Parent`` in the same file:: mapper(Parent, properties={ "children":relationship(lambda: Child, order_by=lambda: Child.id) }) When using the :ref:`declarative_toplevel` extension, the Declarative initializer allows string arguments to be passed to :func:`.relationship`. These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the need to import related classes at all into the local module space:: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", order_by="Child.id") .. seealso:: :ref:`relationship_config_toplevel` - Full introductory and reference documentation for :func:`.relationship`. :ref:`orm_tutorial_relationship` - ORM tutorial introduction. :param argument: a mapped class, or actual :class:`.Mapper` instance, representing the target of the relationship. :paramref:`~.relationship.argument` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. .. seealso:: :ref:`declarative_configuring_relationships` - further detail on relationship configuration when using Declarative. :param secondary: for a many-to-many relationship, specifies the intermediary table, and is typically an instance of :class:`.Table`. In less common circumstances, the argument may also be specified as an :class:`.Alias` construct, or even a :class:`.Join` construct. :paramref:`~.relationship.secondary` may also be passed as a callable function which is evaluated at mapper initialization time. When using Declarative, it may also be a string argument noting the name of a :class:`.Table` that is present in the :class:`.MetaData` collection associated with the parent-mapped :class:`.Table`. The :paramref:`~.relationship.secondary` keyword argument is typically applied in the case where the intermediary :class:`.Table` is not otherwise expressed in any direct class mapping. If the "secondary" table is also explicitly mapped elsewhere (e.g. as in :ref:`association_pattern`), one should consider applying the :paramref:`~.relationship.viewonly` flag so that this :func:`.relationship` is not used for persistence operations which may conflict with those of the association object pattern. .. seealso:: :ref:`relationships_many_to_many` - Reference example of "many to many". :ref:`orm_tutorial_many_to_many` - ORM tutorial introduction to many-to-many relationships. :ref:`self_referential_many_to_many` - Specifics on using many-to-many in a self-referential case. :ref:`declarative_many_to_many` - Additional options when using Declarative. :ref:`association_pattern` - an alternative to :paramref:`~.relationship.secondary` when composing association table relationships, allowing additional attributes to be specified on the association table. :ref:`composite_secondary_join` - a lesser-used pattern which in some cases can enable complex :func:`.relationship` SQL conditions to be used. .. versionadded:: 0.9.2 :paramref:`~.relationship.secondary` works more effectively when referring to a :class:`.Join` instance. :param active_history=False: When ``True``, indicates that the "previous" value for a many-to-one reference should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple many-to-ones only needs to be aware of the "new" value in order to perform a flush. This flag is available for applications that make use of :func:`.attributes.get_history` which also need to know the "previous" value of the attribute. :param backref: indicates the string name of a property to be placed on the related mapper's class that will handle this relationship in the other direction. The other property will be created automatically when the mappers are configured. Can also be passed as a :func:`.backref` object to control the configuration of the new relationship. .. seealso:: :ref:`relationships_backref` - Introductory documentation and examples. :paramref:`~.relationship.back_populates` - alternative form of backref specification. :func:`.backref` - allows control over :func:`.relationship` configuration when using :paramref:`~.relationship.backref`. :param back_populates: Takes a string name and has the same meaning as :paramref:`~.relationship.backref`, except the complementing property is **not** created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate :paramref:`~.relationship.back_populates` to this relationship to ensure proper functioning. .. seealso:: :ref:`relationships_backref` - Introductory documentation and examples. :paramref:`~.relationship.backref` - alternative form of backref specification. :param bake_queries: Use the :class:`.BakedQuery` cache to cache queries used in lazy loads. True by default, as this typically improves performance significantly. Set to False to reduce ORM memory use, or if unresolved stability issues are observed with the baked query cache system. .. versionadded:: 1.0.0 :param cascade: a comma-separated list of cascade rules which determines how Session operations should be "cascaded" from parent to child. This defaults to ``False``, which means the default cascade should be used - this default cascade is ``"save-update, merge"``. The available cascades are ``save-update``, ``merge``, ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``. An additional option, ``all`` indicates shorthand for ``"save-update, merge, refresh-expire, expunge, delete"``, and is often used as in ``"all, delete-orphan"`` to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. .. seealso:: :ref:`unitofwork_cascades` - Full detail on each of the available cascade options. :ref:`tutorial_delete_cascade` - Tutorial example describing a delete cascade. :param cascade_backrefs=True: a boolean value indicating if the ``save-update`` cascade should operate along an assignment event intercepted by a backref. When set to ``False``, the attribute managed by this relationship will not cascade an incoming transient object into the session of a persistent parent, if the event is received via backref. .. seealso:: :ref:`backref_cascade` - Full discussion and examples on how the :paramref:`~.relationship.cascade_backrefs` option is used. :param collection_class: a class or callable that returns a new list-holding object. will be used in place of a plain list for storing elements. .. seealso:: :ref:`custom_collections` - Introductory documentation and examples. :param comparator_factory: a class which extends :class:`.RelationshipProperty.Comparator` which provides custom SQL clause generation for comparison operations. .. seealso:: :class:`.PropComparator` - some detail on redefining comparators at this level. :ref:`custom_comparators` - Brief intro to this feature. :param distinct_target_key=None: Indicate if a "subquery" eager load should apply the DISTINCT keyword to the innermost SELECT statement. When left as ``None``, the DISTINCT keyword will be applied in those cases when the target columns do not comprise the full primary key of the target table. When set to ``True``, the DISTINCT keyword is applied to the innermost SELECT unconditionally. It may be desirable to set this flag to False when the DISTINCT is reducing performance of the innermost subquery beyond that of what duplicate innermost rows may be causing. .. versionadded:: 0.8.3 - :paramref:`~.relationship.distinct_target_key` allows the subquery eager loader to apply a DISTINCT modifier to the innermost SELECT. .. versionchanged:: 0.9.0 - :paramref:`~.relationship.distinct_target_key` now defaults to ``None``, so that the feature enables itself automatically for those cases where the innermost query targets a non-unique key. .. seealso:: :ref:`loading_toplevel` - includes an introduction to subquery eager loading. :param doc: docstring which will be applied to the resulting descriptor. :param extension: an :class:`.AttributeExtension` instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. .. deprecated:: 0.7 Please see :class:`.AttributeEvents`. :param foreign_keys: a list of columns which are to be used as "foreign key" columns, or columns which refer to the value in a remote column, within the context of this :func:`.relationship` object's :paramref:`~.relationship.primaryjoin` condition. That is, if the :paramref:`~.relationship.primaryjoin` condition of this :func:`.relationship` is ``a.id == b.a_id``, and the values in ``b.a_id`` are required to be present in ``a.id``, then the "foreign key" column of this :func:`.relationship` is ``b.a_id``. In normal cases, the :paramref:`~.relationship.foreign_keys` parameter is **not required.** :func:`.relationship` will automatically determine which columns in the :paramref:`~.relationship.primaryjoin` conditition are to be considered "foreign key" columns based on those :class:`.Column` objects that specify :class:`.ForeignKey`, or are otherwise listed as referencing columns in a :class:`.ForeignKeyConstraint` construct. :paramref:`~.relationship.foreign_keys` is only needed when: 1. There is more than one way to construct a join from the local table to the remote table, as there are multiple foreign key references present. Setting ``foreign_keys`` will limit the :func:`.relationship` to consider just those columns specified here as "foreign". .. versionchanged:: 0.8 A multiple-foreign key join ambiguity can be resolved by setting the :paramref:`~.relationship.foreign_keys` parameter alone, without the need to explicitly set :paramref:`~.relationship.primaryjoin` as well. 2. The :class:`.Table` being mapped does not actually have :class:`.ForeignKey` or :class:`.ForeignKeyConstraint` constructs present, often because the table was reflected from a database that does not support foreign key reflection (MySQL MyISAM). 3. The :paramref:`~.relationship.primaryjoin` argument is used to construct a non-standard join condition, which makes use of columns or expressions that do not normally refer to their "parent" column, such as a join condition expressed by a complex comparison using a SQL function. The :func:`.relationship` construct will raise informative error messages that suggest the use of the :paramref:`~.relationship.foreign_keys` parameter when presented with an ambiguous condition. In typical cases, if :func:`.relationship` doesn't raise any exceptions, the :paramref:`~.relationship.foreign_keys` parameter is usually not needed. :paramref:`~.relationship.foreign_keys` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. .. seealso:: :ref:`relationship_foreign_keys` :ref:`relationship_custom_foreign` :func:`.foreign` - allows direct annotation of the "foreign" columns within a :paramref:`~.relationship.primaryjoin` condition. .. versionadded:: 0.8 The :func:`.foreign` annotation can also be applied directly to the :paramref:`~.relationship.primaryjoin` expression, which is an alternate, more specific system of describing which columns in a particular :paramref:`~.relationship.primaryjoin` should be considered "foreign". :param info: Optional data dictionary which will be populated into the :attr:`.MapperProperty.info` attribute of this object. .. versionadded:: 0.8 :param innerjoin=False: when ``True``, joined eager loads will use an inner join to join against related tables instead of an outer join. The purpose of this option is generally one of performance, as inner joins generally perform better than outer joins. This flag can be set to ``True`` when the relationship references an object via many-to-one using local foreign keys that are not nullable, or when the reference is one-to-one or a collection that is guaranteed to have one or at least one entry. The option supports the same "nested" and "unnested" options as that of :paramref:`.joinedload.innerjoin`. See that flag for details on nested / unnested behaviors. .. seealso:: :paramref:`.joinedload.innerjoin` - the option as specified by loader option, including detail on nesting behavior. :ref:`what_kind_of_loading` - Discussion of some details of various loader options. :param join_depth: when non-``None``, an integer value indicating how many levels deep "eager" loaders should join on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of ``None``, eager loaders will stop chaining when they encounter a the same target mapper which is already higher up in the chain. This option applies both to joined- and subquery- eager loaders. .. seealso:: :ref:`self_referential_eager_loading` - Introductory documentation and examples. :param lazy='select': specifies how the related items should be loaded. Default value is ``select``. Values include: * ``select`` - items should be loaded lazily when the property is first accessed, using a separate SELECT statement, or identity map fetch for simple many-to-one references. * ``immediate`` - items should be loaded as the parents are loaded, using a separate SELECT statement, or identity map fetch for simple many-to-one references. * ``joined`` - items should be loaded "eagerly" in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is "outer" or not is determined by the :paramref:`~.relationship.innerjoin` parameter. * ``subquery`` - items should be loaded "eagerly" as the parents are loaded, using one additional SQL statement, which issues a JOIN to a subquery of the original statement, for each collection requested. * ``noload`` - no loading should occur at any time. This is to support "write-only" attributes, or attributes which are populated in some manner specific to the application. * ``dynamic`` - the attribute will return a pre-configured :class:`.Query` object for all read operations, onto which further filtering operations can be applied before iterating the results. See the section :ref:`dynamic_relationship` for more details. * True - a synonym for 'select' * False - a synonym for 'joined' * None - a synonym for 'noload' .. seealso:: :doc:`/orm/loading_relationships` - Full documentation on relationship loader configuration. :ref:`dynamic_relationship` - detail on the ``dynamic`` option. :param load_on_pending=False: Indicates loading behavior for transient or pending parent objects. When set to ``True``, causes the lazy-loader to issue a query for a parent object that is not persistent, meaning it has never been flushed. This may take effect for a pending object when autoflush is disabled, or for a transient object that has been "attached" to a :class:`.Session` but is not part of its pending collection. The :paramref:`~.relationship.load_on_pending` flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. This flag is not not intended for general use. .. seealso:: :meth:`.Session.enable_relationship_loading` - this method establishes "load on pending" behavior for the whole object, and also allows loading on objects that remain transient or detached. :param order_by: indicates the ordering that should be applied when loading these items. :paramref:`~.relationship.order_by` is expected to refer to one of the :class:`.Column` objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column. :paramref:`~.relationship.order_by` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. :param passive_deletes=False: Indicates loading behavior during delete operations. A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side. Additionally, setting the flag to the string value 'all' will disable the "nulling out" of the child foreign keys, when there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting. .. seealso:: :ref:`passive_deletes` - Introductory documentation and examples. :param passive_updates=True: Indicates the persistence behavior to take when a referenced primary key value changes in place, indicating that the referencing foreign key columns will also need their value changed. When True, it is assumed that ``ON UPDATE CASCADE`` is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. When False, the SQLAlchemy :func:`.relationship` construct will attempt to emit its own UPDATE statements to modify related targets. However note that SQLAlchemy **cannot** emit an UPDATE for more than one level of cascade. Also, setting this flag to False is not compatible in the case where the database is in fact enforcing referential integrity, unless those constraints are explicitly "deferred", if the target backend supports it. It is highly advised that an application which is employing mutable primary keys keeps ``passive_updates`` set to True, and instead uses the referential integrity features of the database itself in order to handle the change efficiently and fully. .. seealso:: :ref:`passive_updates` - Introductory documentation and examples. :paramref:`.mapper.passive_updates` - a similar flag which takes effect for joined-table inheritance mappings. :param post_update: this indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush operation returns an error that a "cyclical dependency" was detected, this is a cue that you might want to use :paramref:`~.relationship.post_update` to "break" the cycle. .. seealso:: :ref:`post_update` - Introductory documentation and examples. :param primaryjoin: a SQL expression that will be used as the primary join of this child object against the parent object, or in a many-to-many relationship the join of the primary object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table). :paramref:`~.relationship.primaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. .. seealso:: :ref:`relationship_primaryjoin` :param remote_side: used for self-referential relationships, indicates the column or list of columns that form the "remote side" of the relationship. :paramref:`.relationship.remote_side` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. .. versionchanged:: 0.8 The :func:`.remote` annotation can also be applied directly to the ``primaryjoin`` expression, which is an alternate, more specific system of describing which columns in a particular ``primaryjoin`` should be considered "remote". .. seealso:: :ref:`self_referential` - in-depth explanation of how :paramref:`~.relationship.remote_side` is used to configure self-referential relationships. :func:`.remote` - an annotation function that accomplishes the same purpose as :paramref:`~.relationship.remote_side`, typically when a custom :paramref:`~.relationship.primaryjoin` condition is used. :param query_class: a :class:`.Query` subclass that will be used as the base of the "appender query" returned by a "dynamic" relationship, that is, a relationship that specifies ``lazy="dynamic"`` or was otherwise constructed using the :func:`.orm.dynamic_loader` function. .. seealso:: :ref:`dynamic_relationship` - Introduction to "dynamic" relationship loaders. :param secondaryjoin: a SQL expression that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables. :paramref:`~.relationship.secondaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. .. seealso:: :ref:`relationship_primaryjoin` :param single_parent: when True, installs a validator which will prevent objects from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage is optional, except for :func:`.relationship` constructs which are many-to-one or many-to-many and also specify the ``delete-orphan`` cascade option. The :func:`.relationship` construct itself will raise an error instructing when this option is required. .. seealso:: :ref:`unitofwork_cascades` - includes detail on when the :paramref:`~.relationship.single_parent` flag may be appropriate. :param uselist: a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by :func:`.relationship` at mapper configuration time, based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, set :paramref:`~.relationship.uselist` to False. The :paramref:`~.relationship.uselist` flag is also available on an existing :func:`.relationship` construct as a read-only attribute, which can be used to determine if this :func:`.relationship` deals with collections or scalar attributes:: >>> User.addresses.property.uselist True .. seealso:: :ref:`relationships_one_to_one` - Introduction to the "one to one" relationship pattern, which is typically when the :paramref:`~.relationship.uselist` flag is needed. :param viewonly=False: when set to True, the relationship is used only for loading objects, and not for any persistence operation. A :func:`.relationship` which specifies :paramref:`~.relationship.viewonly` can work with a wider range of SQL operations within the :paramref:`~.relationship.primaryjoin` condition, including operations that feature the use of a variety of comparison operators as well as SQL functions such as :func:`~.sql.expression.cast`. The :paramref:`~.relationship.viewonly` flag is also of general use when defining any kind of :func:`~.relationship` that doesn't represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations. """ super(RelationshipProperty, self).__init__() self.uselist = uselist self.argument = argument self.secondary = secondary self.primaryjoin = primaryjoin self.secondaryjoin = secondaryjoin self.post_update = post_update self.direction = None self.viewonly = viewonly self.lazy = lazy self.single_parent = single_parent self._user_defined_foreign_keys = foreign_keys self.collection_class = collection_class self.passive_deletes = passive_deletes self.cascade_backrefs = cascade_backrefs self.passive_updates = passive_updates self.remote_side = remote_side self.enable_typechecks = enable_typechecks self.query_class = query_class self.innerjoin = innerjoin self.distinct_target_key = distinct_target_key self.doc = doc self.active_history = active_history self.join_depth = join_depth self.local_remote_pairs = _local_remote_pairs self.extension = extension self.bake_queries = bake_queries self.load_on_pending = load_on_pending self.comparator_factory = comparator_factory or \ RelationshipProperty.Comparator self.comparator = self.comparator_factory(self, None) util.set_creation_order(self) if info is not None: self.info = info if strategy_class: self.strategy_class = strategy_class else: self.strategy_class = self._strategy_lookup(("lazy", self.lazy)) self._reverse_property = set() self.cascade = cascade if cascade is not False \ else "save-update, merge" self.order_by = order_by self.back_populates = back_populates if self.back_populates: if backref: raise sa_exc.ArgumentError( "backref and back_populates keyword arguments " "are mutually exclusive") self.backref = None else: self.backref = backref def instrument_class(self, mapper): attributes.register_descriptor( mapper.class_, self.key, comparator=self.comparator_factory(self, mapper), parententity=mapper, doc=self.doc, ) class Comparator(PropComparator): """Produce boolean, comparison, and other operators for :class:`.RelationshipProperty` attributes. See the documentation for :class:`.PropComparator` for a brief overview of ORM level operator definition. See also: :class:`.PropComparator` :class:`.ColumnProperty.Comparator` :class:`.ColumnOperators` :ref:`types_operators` :attr:`.TypeEngine.comparator_factory` """ _of_type = None def __init__( self, prop, parentmapper, adapt_to_entity=None, of_type=None): """Construction of :class:`.RelationshipProperty.Comparator` is internal to the ORM's attribute mechanics. """ self.prop = prop self._parententity = parentmapper self._adapt_to_entity = adapt_to_entity if of_type: self._of_type = of_type def adapt_to_entity(self, adapt_to_entity): return self.__class__(self.property, self._parententity, adapt_to_entity=adapt_to_entity, of_type=self._of_type) @util.memoized_property def mapper(self): """The target :class:`.Mapper` referred to by this :class:`.RelationshipProperty.Comparator`. This is the "target" or "remote" side of the :func:`.relationship`. """ return self.property.mapper @util.memoized_property def _parententity(self): return self.property.parent def _source_selectable(self): if self._adapt_to_entity: return self._adapt_to_entity.selectable else: return self.property.parent._with_polymorphic_selectable def __clause_element__(self): adapt_from = self._source_selectable() if self._of_type: of_type = inspect(self._of_type).mapper else: of_type = None pj, sj, source, dest, \ secondary, target_adapter = self.property._create_joins( source_selectable=adapt_from, source_polymorphic=True, of_type=of_type) if sj is not None: return pj & sj else: return pj def of_type(self, cls): """Produce a construct that represents a particular 'subtype' of attribute for the parent class. Currently this is usable in conjunction with :meth:`.Query.join` and :meth:`.Query.outerjoin`. """ return RelationshipProperty.Comparator( self.property, self._parententity, adapt_to_entity=self._adapt_to_entity, of_type=cls) def in_(self, other): """Produce an IN clause - this is not implemented for :func:`~.orm.relationship`-based attributes at this time. """ raise NotImplementedError('in_() not yet supported for ' 'relationships. For a simple ' 'many-to-one, use in_() against ' 'the set of foreign key values.') __hash__ = None def __eq__(self, other): """Implement the ``==`` operator. In a many-to-one context, such as:: MyClass.some_prop == <some object> this will typically produce a clause such as:: mytable.related_id == <some id> Where ``<some id>`` is the primary key of the given object. The ``==`` operator provides partial functionality for non- many-to-one comparisons: * Comparisons against collections are not supported. Use :meth:`~.RelationshipProperty.Comparator.contains`. * Compared to a scalar one-to-many, will produce a clause that compares the target columns in the parent to the given target. * Compared to a scalar many-to-many, an alias of the association table will be rendered as well, forming a natural join that is part of the main body of the query. This will not work for queries that go beyond simple AND conjunctions of comparisons, such as those which use OR. Use explicit joins, outerjoins, or :meth:`~.RelationshipProperty.Comparator.has` for more comprehensive non-many-to-one scalar membership tests. * Comparisons against ``None`` given in a one-to-many or many-to-many context produce a NOT EXISTS clause. """ if isinstance(other, (util.NoneType, expression.Null)): if self.property.direction in [ONETOMANY, MANYTOMANY]: return ~self._criterion_exists() else: return _orm_annotate(self.property._optimized_compare( None, adapt_source=self.adapter)) elif self.property.uselist: raise sa_exc.InvalidRequestError( "Can't compare a collection to an object or collection; " "use contains() to test for membership.") else: return _orm_annotate( self.property._optimized_compare( other, adapt_source=self.adapter)) def _criterion_exists(self, criterion=None, **kwargs): if getattr(self, '_of_type', None): info = inspect(self._of_type) target_mapper, to_selectable, is_aliased_class = \ info.mapper, info.selectable, info.is_aliased_class if self.property._is_self_referential and not \ is_aliased_class: to_selectable = to_selectable.alias() single_crit = target_mapper._single_table_criterion if single_crit is not None: if criterion is not None: criterion = single_crit & criterion else: criterion = single_crit else: is_aliased_class = False to_selectable = None if self.adapter: source_selectable = self._source_selectable() else: source_selectable = None pj, sj, source, dest, secondary, target_adapter = \ self.property._create_joins( dest_polymorphic=True, dest_selectable=to_selectable, source_selectable=source_selectable) for k in kwargs: crit = getattr(self.property.mapper.class_, k) == kwargs[k] if criterion is None: criterion = crit else: criterion = criterion & crit # annotate the *local* side of the join condition, in the case # of pj + sj this is the full primaryjoin, in the case of just # pj its the local side of the primaryjoin. if sj is not None: j = _orm_annotate(pj) & sj else: j = _orm_annotate(pj, exclude=self.property.remote_side) if criterion is not None and target_adapter and not \ is_aliased_class: # limit this adapter to annotated only? criterion = target_adapter.traverse(criterion) # only have the "joined left side" of what we # return be subject to Query adaption. The right # side of it is used for an exists() subquery and # should not correlate or otherwise reach out # to anything in the enclosing query. if criterion is not None: criterion = criterion._annotate( {'no_replacement_traverse': True}) crit = j & sql.True_._ifnone(criterion) ex = sql.exists([1], crit, from_obj=dest).correlate_except(dest) if secondary is not None: ex = ex.correlate_except(secondary) return ex def any(self, criterion=None, **kwargs): """Produce an expression that tests a collection against particular criterion, using EXISTS. An expression like:: session.query(MyClass).filter( MyClass.somereference.any(SomeRelated.x==2) ) Will produce a query like:: SELECT * FROM my_table WHERE EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id AND related.x=2) Because :meth:`~.RelationshipProperty.Comparator.any` uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join. :meth:`~.RelationshipProperty.Comparator.any` is particularly useful for testing for empty collections:: session.query(MyClass).filter( ~MyClass.somereference.any() ) will produce:: SELECT * FROM my_table WHERE NOT EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id) :meth:`~.RelationshipProperty.Comparator.any` is only valid for collections, i.e. a :func:`.relationship` that has ``uselist=True``. For scalar references, use :meth:`~.RelationshipProperty.Comparator.has`. """ if not self.property.uselist: raise sa_exc.InvalidRequestError( "'any()' not implemented for scalar " "attributes. Use has()." ) return self._criterion_exists(criterion, **kwargs) def has(self, criterion=None, **kwargs): """Produce an expression that tests a scalar reference against particular criterion, using EXISTS. An expression like:: session.query(MyClass).filter( MyClass.somereference.has(SomeRelated.x==2) ) Will produce a query like:: SELECT * FROM my_table WHERE EXISTS (SELECT 1 FROM related WHERE related.id==my_table.related_id AND related.x=2) Because :meth:`~.RelationshipProperty.Comparator.has` uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join. :meth:`~.RelationshipProperty.Comparator.has` is only valid for scalar references, i.e. a :func:`.relationship` that has ``uselist=False``. For collection references, use :meth:`~.RelationshipProperty.Comparator.any`. """ if self.property.uselist: raise sa_exc.InvalidRequestError( "'has()' not implemented for collections. " "Use any().") return self._criterion_exists(criterion, **kwargs) def contains(self, other, **kwargs): """Return a simple expression that tests a collection for containment of a particular item. :meth:`~.RelationshipProperty.Comparator.contains` is only valid for a collection, i.e. a :func:`~.orm.relationship` that implements one-to-many or many-to-many with ``uselist=True``. When used in a simple one-to-many context, an expression like:: MyClass.contains(other) Produces a clause like:: mytable.id == <some id> Where ``<some id>`` is the value of the foreign key attribute on ``other`` which refers to the primary key of its parent object. From this it follows that :meth:`~.RelationshipProperty.Comparator.contains` is very useful when used with simple one-to-many operations. For many-to-many operations, the behavior of :meth:`~.RelationshipProperty.Comparator.contains` has more caveats. The association table will be rendered in the statement, producing an "implicit" join, that is, includes multiple tables in the FROM clause which are equated in the WHERE clause:: query(MyClass).filter(MyClass.contains(other)) Produces a query like:: SELECT * FROM my_table, my_association_table AS my_association_table_1 WHERE my_table.id = my_association_table_1.parent_id AND my_association_table_1.child_id = <some id> Where ``<some id>`` would be the primary key of ``other``. From the above, it is clear that :meth:`~.RelationshipProperty.Comparator.contains` will **not** work with many-to-many collections when used in queries that move beyond simple AND conjunctions, such as multiple :meth:`~.RelationshipProperty.Comparator.contains` expressions joined by OR. In such cases subqueries or explicit "outer joins" will need to be used instead. See :meth:`~.RelationshipProperty.Comparator.any` for a less-performant alternative using EXISTS, or refer to :meth:`.Query.outerjoin` as well as :ref:`ormtutorial_joins` for more details on constructing outer joins. """ if not self.property.uselist: raise sa_exc.InvalidRequestError( "'contains' not implemented for scalar " "attributes. Use ==") clause = self.property._optimized_compare( other, adapt_source=self.adapter) if self.property.secondaryjoin is not None: clause.negation_clause = \ self.__negated_contains_or_equals(other) return clause def __negated_contains_or_equals(self, other): if self.property.direction == MANYTOONE: state = attributes.instance_state(other) def state_bindparam(x, state, col): dict_ = state.dict return sql.bindparam( x, unique=True, callable_=self.property._get_attr_w_warn_on_none( col, self.property.mapper._get_state_attr_by_column, state, dict_, col, passive=attributes.PASSIVE_OFF ) ) def adapt(col): if self.adapter: return self.adapter(col) else: return col if self.property._use_get: return sql.and_(*[ sql.or_( adapt(x) != state_bindparam(adapt(x), state, y), adapt(x) == None) for (x, y) in self.property.local_remote_pairs]) criterion = sql.and_(*[ x == y for (x, y) in zip( self.property.mapper.primary_key, self.property.mapper.primary_key_from_instance(other) ) ]) return ~self._criterion_exists(criterion) def __ne__(self, other): """Implement the ``!=`` operator. In a many-to-one context, such as:: MyClass.some_prop != <some object> This will typically produce a clause such as:: mytable.related_id != <some id> Where ``<some id>`` is the primary key of the given object. The ``!=`` operator provides partial functionality for non- many-to-one comparisons: * Comparisons against collections are not supported. Use :meth:`~.RelationshipProperty.Comparator.contains` in conjunction with :func:`~.expression.not_`. * Compared to a scalar one-to-many, will produce a clause that compares the target columns in the parent to the given target. * Compared to a scalar many-to-many, an alias of the association table will be rendered as well, forming a natural join that is part of the main body of the query. This will not work for queries that go beyond simple AND conjunctions of comparisons, such as those which use OR. Use explicit joins, outerjoins, or :meth:`~.RelationshipProperty.Comparator.has` in conjunction with :func:`~.expression.not_` for more comprehensive non-many-to-one scalar membership tests. * Comparisons against ``None`` given in a one-to-many or many-to-many context produce an EXISTS clause. """ if isinstance(other, (util.NoneType, expression.Null)): if self.property.direction == MANYTOONE: return _orm_annotate(~self.property._optimized_compare( None, adapt_source=self.adapter)) else: return self._criterion_exists() elif self.property.uselist: raise sa_exc.InvalidRequestError( "Can't compare a collection" " to an object or collection; use " "contains() to test for membership.") else: return _orm_annotate(self.__negated_contains_or_equals(other)) @util.memoized_property def property(self): if mapperlib.Mapper._new_mappers: mapperlib.Mapper._configure_all() return self.prop def _with_parent(self, instance, alias_secondary=True): assert instance is not None return self._optimized_compare( instance, value_is_parent=True, alias_secondary=alias_secondary) def _optimized_compare(self, state, value_is_parent=False, adapt_source=None, alias_secondary=True): if state is not None: state = attributes.instance_state(state) reverse_direction = not value_is_parent if state is None: return self._lazy_none_clause( reverse_direction, adapt_source=adapt_source) if not reverse_direction: criterion, bind_to_col = \ self._lazy_strategy._lazywhere, \ self._lazy_strategy._bind_to_col else: criterion, bind_to_col = \ self._lazy_strategy._rev_lazywhere, \ self._lazy_strategy._rev_bind_to_col if reverse_direction: mapper = self.mapper else: mapper = self.parent dict_ = attributes.instance_dict(state.obj()) def visit_bindparam(bindparam): if bindparam._identifying_key in bind_to_col: bindparam.callable = self._get_attr_w_warn_on_none( bind_to_col[bindparam._identifying_key], mapper._get_state_attr_by_column, state, dict_, bind_to_col[bindparam._identifying_key], passive=attributes.PASSIVE_OFF) if self.secondary is not None and alias_secondary: criterion = ClauseAdapter( self.secondary.alias()).\ traverse(criterion) criterion = visitors.cloned_traverse( criterion, {}, {'bindparam': visit_bindparam}) if adapt_source: criterion = adapt_source(criterion) return criterion def _get_attr_w_warn_on_none(self, column, fn, *arg, **kw): def _go(): value = fn(*arg, **kw) if value is None: util.warn( "Got None for value of column %s; this is unsupported " "for a relationship comparison and will not " "currently produce an IS comparison " "(but may in a future release)" % column) return value return _go def _lazy_none_clause(self, reverse_direction=False, adapt_source=None): if not reverse_direction: criterion, bind_to_col = \ self._lazy_strategy._lazywhere, \ self._lazy_strategy._bind_to_col else: criterion, bind_to_col = \ self._lazy_strategy._rev_lazywhere, \ self._lazy_strategy._rev_bind_to_col criterion = adapt_criterion_to_null(criterion, bind_to_col) if adapt_source: criterion = adapt_source(criterion) return criterion def __str__(self): return str(self.parent.class_.__name__) + "." + self.key def merge(self, session, source_state, source_dict, dest_state, dest_dict, load, _recursive): if load: for r in self._reverse_property: if (source_state, r) in _recursive: return if "merge" not in self._cascade: return if self.key not in source_dict: return if self.uselist: instances = source_state.get_impl(self.key).\ get(source_state, source_dict) if hasattr(instances, '_sa_adapter'): # convert collections to adapters to get a true iterator instances = instances._sa_adapter if load: # for a full merge, pre-load the destination collection, # so that individual _merge of each item pulls from identity # map for those already present. # also assumes CollectionAttrbiuteImpl behavior of loading # "old" list in any case dest_state.get_impl(self.key).get(dest_state, dest_dict) dest_list = [] for current in instances: current_state = attributes.instance_state(current) current_dict = attributes.instance_dict(current) _recursive[(current_state, self)] = True obj = session._merge(current_state, current_dict, load=load, _recursive=_recursive) if obj is not None: dest_list.append(obj) if not load: coll = attributes.init_state_collection(dest_state, dest_dict, self.key) for c in dest_list: coll.append_without_event(c) else: dest_state.get_impl(self.key)._set_iterable( dest_state, dest_dict, dest_list) else: current = source_dict[self.key] if current is not None: current_state = attributes.instance_state(current) current_dict = attributes.instance_dict(current) _recursive[(current_state, self)] = True obj = session._merge(current_state, current_dict, load=load, _recursive=_recursive) else: obj = None if not load: dest_dict[self.key] = obj else: dest_state.get_impl(self.key).set(dest_state, dest_dict, obj, None) def _value_as_iterable(self, state, dict_, key, passive=attributes.PASSIVE_OFF): """Return a list of tuples (state, obj) for the given key. returns an empty list if the value is None/empty/PASSIVE_NO_RESULT """ impl = state.manager[key].impl x = impl.get(state, dict_, passive=passive) if x is attributes.PASSIVE_NO_RESULT or x is None: return [] elif hasattr(impl, 'get_collection'): return [ (attributes.instance_state(o), o) for o in impl.get_collection(state, dict_, x, passive=passive) ] else: return [(attributes.instance_state(x), x)] def cascade_iterator(self, type_, state, dict_, visited_states, halt_on=None): # assert type_ in self._cascade # only actively lazy load on the 'delete' cascade if type_ != 'delete' or self.passive_deletes: passive = attributes.PASSIVE_NO_INITIALIZE else: passive = attributes.PASSIVE_OFF if type_ == 'save-update': tuples = state.manager[self.key].impl.\ get_all_pending(state, dict_) else: tuples = self._value_as_iterable(state, dict_, self.key, passive=passive) skip_pending = type_ == 'refresh-expire' and 'delete-orphan' \ not in self._cascade for instance_state, c in tuples: if instance_state in visited_states: continue if c is None: # would like to emit a warning here, but # would not be consistent with collection.append(None) # current behavior of silently skipping. # see [ticket:2229] continue instance_dict = attributes.instance_dict(c) if halt_on and halt_on(instance_state): continue if skip_pending and not instance_state.key: continue instance_mapper = instance_state.manager.mapper if not instance_mapper.isa(self.mapper.class_manager.mapper): raise AssertionError("Attribute '%s' on class '%s' " "doesn't handle objects " "of type '%s'" % ( self.key, self.parent.class_, c.__class__ )) visited_states.add(instance_state) yield c, instance_mapper, instance_state, instance_dict def _add_reverse_property(self, key): other = self.mapper.get_property(key, _configure_mappers=False) self._reverse_property.add(other) other._reverse_property.add(self) if not other.mapper.common_parent(self.parent): raise sa_exc.ArgumentError( 'reverse_property %r on ' 'relationship %s references relationship %s, which ' 'does not reference mapper %s' % (key, self, other, self.parent)) if self.direction in (ONETOMANY, MANYTOONE) and self.direction \ == other.direction: raise sa_exc.ArgumentError( '%s and back-reference %s are ' 'both of the same direction %r. Did you mean to ' 'set remote_side on the many-to-one side ?' % (other, self, self.direction)) @util.memoized_property def mapper(self): """Return the targeted :class:`.Mapper` for this :class:`.RelationshipProperty`. This is a lazy-initializing static attribute. """ if util.callable(self.argument) and \ not isinstance(self.argument, (type, mapperlib.Mapper)): argument = self.argument() else: argument = self.argument if isinstance(argument, type): mapper_ = mapperlib.class_mapper(argument, configure=False) elif isinstance(self.argument, mapperlib.Mapper): mapper_ = argument else: raise sa_exc.ArgumentError( "relationship '%s' expects " "a class or a mapper argument (received: %s)" % (self.key, type(argument))) return mapper_ @util.memoized_property @util.deprecated("0.7", "Use .target") def table(self): """Return the selectable linked to this :class:`.RelationshipProperty` object's target :class:`.Mapper`. """ return self.target def do_init(self): self._check_conflicts() self._process_dependent_arguments() self._setup_join_conditions() self._check_cascade_settings(self._cascade) self._post_init() self._generate_backref() self._join_condition._warn_for_conflicting_sync_targets() super(RelationshipProperty, self).do_init() self._lazy_strategy = self._get_strategy((("lazy", "select"),)) def _process_dependent_arguments(self): """Convert incoming configuration arguments to their proper form. Callables are resolved, ORM annotations removed. """ # accept callables for other attributes which may require # deferred initialization. This technique is used # by declarative "string configs" and some recipes. for attr in ( 'order_by', 'primaryjoin', 'secondaryjoin', 'secondary', '_user_defined_foreign_keys', 'remote_side', ): attr_value = getattr(self, attr) if util.callable(attr_value): setattr(self, attr, attr_value()) # remove "annotations" which are present if mapped class # descriptors are used to create the join expression. for attr in 'primaryjoin', 'secondaryjoin': val = getattr(self, attr) if val is not None: setattr(self, attr, _orm_deannotate( expression._only_column_elements(val, attr)) ) # ensure expressions in self.order_by, foreign_keys, # remote_side are all columns, not strings. if self.order_by is not False and self.order_by is not None: self.order_by = [ expression._only_column_elements(x, "order_by") for x in util.to_list(self.order_by)] self._user_defined_foreign_keys = \ util.column_set( expression._only_column_elements(x, "foreign_keys") for x in util.to_column_set( self._user_defined_foreign_keys )) self.remote_side = \ util.column_set( expression._only_column_elements(x, "remote_side") for x in util.to_column_set(self.remote_side)) self.target = self.mapper.mapped_table def _setup_join_conditions(self): self._join_condition = jc = JoinCondition( parent_selectable=self.parent.mapped_table, child_selectable=self.mapper.mapped_table, parent_local_selectable=self.parent.local_table, child_local_selectable=self.mapper.local_table, primaryjoin=self.primaryjoin, secondary=self.secondary, secondaryjoin=self.secondaryjoin, parent_equivalents=self.parent._equivalent_columns, child_equivalents=self.mapper._equivalent_columns, consider_as_foreign_keys=self._user_defined_foreign_keys, local_remote_pairs=self.local_remote_pairs, remote_side=self.remote_side, self_referential=self._is_self_referential, prop=self, support_sync=not self.viewonly, can_be_synced_fn=self._columns_are_mapped ) self.primaryjoin = jc.deannotated_primaryjoin self.secondaryjoin = jc.deannotated_secondaryjoin self.direction = jc.direction self.local_remote_pairs = jc.local_remote_pairs self.remote_side = jc.remote_columns self.local_columns = jc.local_columns self.synchronize_pairs = jc.synchronize_pairs self._calculated_foreign_keys = jc.foreign_key_columns self.secondary_synchronize_pairs = jc.secondary_synchronize_pairs def _check_conflicts(self): """Test that this relationship is legal, warn about inheritance conflicts.""" if self.parent.non_primary and not mapperlib.class_mapper( self.parent.class_, configure=False).has_property(self.key): raise sa_exc.ArgumentError( "Attempting to assign a new " "relationship '%s' to a non-primary mapper on " "class '%s'. New relationships can only be added " "to the primary mapper, i.e. the very first mapper " "created for class '%s' " % (self.key, self.parent.class_.__name__, self.parent.class_.__name__)) # check for conflicting relationship() on superclass if not self.parent.concrete: for inheriting in self.parent.iterate_to_root(): if inheriting is not self.parent \ and inheriting.has_property(self.key): util.warn("Warning: relationship '%s' on mapper " "'%s' supersedes the same relationship " "on inherited mapper '%s'; this can " "cause dependency issues during flush" % (self.key, self.parent, inheriting)) def _get_cascade(self): """Return the current cascade setting for this :class:`.RelationshipProperty`. """ return self._cascade def _set_cascade(self, cascade): cascade = CascadeOptions(cascade) if 'mapper' in self.__dict__: self._check_cascade_settings(cascade) self._cascade = cascade if self._dependency_processor: self._dependency_processor.cascade = cascade cascade = property(_get_cascade, _set_cascade) def _check_cascade_settings(self, cascade): if cascade.delete_orphan and not self.single_parent \ and (self.direction is MANYTOMANY or self.direction is MANYTOONE): raise sa_exc.ArgumentError( 'On %s, delete-orphan cascade is not supported ' 'on a many-to-many or many-to-one relationship ' 'when single_parent is not set. Set ' 'single_parent=True on the relationship().' % self) if self.direction is MANYTOONE and self.passive_deletes: util.warn("On %s, 'passive_deletes' is normally configured " "on one-to-many, one-to-one, many-to-many " "relationships only." % self) if self.passive_deletes == 'all' and \ ("delete" in cascade or "delete-orphan" in cascade): raise sa_exc.ArgumentError( "On %s, can't set passive_deletes='all' in conjunction " "with 'delete' or 'delete-orphan' cascade" % self) if cascade.delete_orphan: self.mapper.primary_mapper()._delete_orphans.append( (self.key, self.parent.class_) ) def _columns_are_mapped(self, *cols): """Return True if all columns in the given collection are mapped by the tables referenced by this :class:`.Relationship`. """ for c in cols: if self.secondary is not None \ and self.secondary.c.contains_column(c): continue if not self.parent.mapped_table.c.contains_column(c) and \ not self.target.c.contains_column(c): return False return True def _generate_backref(self): """Interpret the 'backref' instruction to create a :func:`.relationship` complementary to this one.""" if self.parent.non_primary: return if self.backref is not None and not self.back_populates: if isinstance(self.backref, util.string_types): backref_key, kwargs = self.backref, {} else: backref_key, kwargs = self.backref mapper = self.mapper.primary_mapper() check = set(mapper.iterate_to_root()).\ union(mapper.self_and_descendants) for m in check: if m.has_property(backref_key): raise sa_exc.ArgumentError( "Error creating backref " "'%s' on relationship '%s': property of that " "name exists on mapper '%s'" % (backref_key, self, m)) # determine primaryjoin/secondaryjoin for the # backref. Use the one we had, so that # a custom join doesn't have to be specified in # both directions. if self.secondary is not None: # for many to many, just switch primaryjoin/ # secondaryjoin. use the annotated # pj/sj on the _join_condition. pj = kwargs.pop( 'primaryjoin', self._join_condition.secondaryjoin_minus_local) sj = kwargs.pop( 'secondaryjoin', self._join_condition.primaryjoin_minus_local) else: pj = kwargs.pop( 'primaryjoin', self._join_condition.primaryjoin_reverse_remote) sj = kwargs.pop('secondaryjoin', None) if sj: raise sa_exc.InvalidRequestError( "Can't assign 'secondaryjoin' on a backref " "against a non-secondary relationship." ) foreign_keys = kwargs.pop('foreign_keys', self._user_defined_foreign_keys) parent = self.parent.primary_mapper() kwargs.setdefault('viewonly', self.viewonly) kwargs.setdefault('post_update', self.post_update) kwargs.setdefault('passive_updates', self.passive_updates) self.back_populates = backref_key relationship = RelationshipProperty( parent, self.secondary, pj, sj, foreign_keys=foreign_keys, back_populates=self.key, **kwargs) mapper._configure_property(backref_key, relationship) if self.back_populates: self._add_reverse_property(self.back_populates) def _post_init(self): if self.uselist is None: self.uselist = self.direction is not MANYTOONE if not self.viewonly: self._dependency_processor = \ dependency.DependencyProcessor.from_relationship(self) @util.memoized_property def _use_get(self): """memoize the 'use_get' attribute of this RelationshipLoader's lazyloader.""" strategy = self._lazy_strategy return strategy.use_get @util.memoized_property def _is_self_referential(self): return self.mapper.common_parent(self.parent) def _create_joins(self, source_polymorphic=False, source_selectable=None, dest_polymorphic=False, dest_selectable=None, of_type=None): if source_selectable is None: if source_polymorphic and self.parent.with_polymorphic: source_selectable = self.parent._with_polymorphic_selectable aliased = False if dest_selectable is None: if dest_polymorphic and self.mapper.with_polymorphic: dest_selectable = self.mapper._with_polymorphic_selectable aliased = True else: dest_selectable = self.mapper.mapped_table if self._is_self_referential and source_selectable is None: dest_selectable = dest_selectable.alias() aliased = True else: aliased = True dest_mapper = of_type or self.mapper single_crit = dest_mapper._single_table_criterion aliased = aliased or (source_selectable is not None) primaryjoin, secondaryjoin, secondary, target_adapter, dest_selectable = \ self._join_condition.join_targets( source_selectable, dest_selectable, aliased, single_crit ) if source_selectable is None: source_selectable = self.parent.local_table if dest_selectable is None: dest_selectable = self.mapper.local_table return (primaryjoin, secondaryjoin, source_selectable, dest_selectable, secondary, target_adapter) def _annotate_columns(element, annotations): def clone(elem): if isinstance(elem, expression.ColumnClause): elem = elem._annotate(annotations.copy()) elem._copy_internals(clone=clone) return elem if element is not None: element = clone(element) return element class JoinCondition(object): def __init__(self, parent_selectable, child_selectable, parent_local_selectable, child_local_selectable, primaryjoin=None, secondary=None, secondaryjoin=None, parent_equivalents=None, child_equivalents=None, consider_as_foreign_keys=None, local_remote_pairs=None, remote_side=None, self_referential=False, prop=None, support_sync=True, can_be_synced_fn=lambda *c: True ): self.parent_selectable = parent_selectable self.parent_local_selectable = parent_local_selectable self.child_selectable = child_selectable self.child_local_selectable = child_local_selectable self.parent_equivalents = parent_equivalents self.child_equivalents = child_equivalents self.primaryjoin = primaryjoin self.secondaryjoin = secondaryjoin self.secondary = secondary self.consider_as_foreign_keys = consider_as_foreign_keys self._local_remote_pairs = local_remote_pairs self._remote_side = remote_side self.prop = prop self.self_referential = self_referential self.support_sync = support_sync self.can_be_synced_fn = can_be_synced_fn self._determine_joins() self._annotate_fks() self._annotate_remote() self._annotate_local() self._setup_pairs() self._check_foreign_cols(self.primaryjoin, True) if self.secondaryjoin is not None: self._check_foreign_cols(self.secondaryjoin, False) self._determine_direction() self._check_remote_side() self._log_joins() def _log_joins(self): if self.prop is None: return log = self.prop.logger log.info('%s setup primary join %s', self.prop, self.primaryjoin) log.info('%s setup secondary join %s', self.prop, self.secondaryjoin) log.info('%s synchronize pairs [%s]', self.prop, ','.join('(%s => %s)' % (l, r) for (l, r) in self.synchronize_pairs)) log.info('%s secondary synchronize pairs [%s]', self.prop, ','.join('(%s => %s)' % (l, r) for (l, r) in self.secondary_synchronize_pairs or [])) log.info('%s local/remote pairs [%s]', self.prop, ','.join('(%s / %s)' % (l, r) for (l, r) in self.local_remote_pairs)) log.info('%s remote columns [%s]', self.prop, ','.join('%s' % col for col in self.remote_columns) ) log.info('%s local columns [%s]', self.prop, ','.join('%s' % col for col in self.local_columns) ) log.info('%s relationship direction %s', self.prop, self.direction) def _determine_joins(self): """Determine the 'primaryjoin' and 'secondaryjoin' attributes, if not passed to the constructor already. This is based on analysis of the foreign key relationships between the parent and target mapped selectables. """ if self.secondaryjoin is not None and self.secondary is None: raise sa_exc.ArgumentError( "Property %s specified with secondary " "join condition but " "no secondary argument" % self.prop) # find a join between the given mapper's mapped table and # the given table. will try the mapper's local table first # for more specificity, then if not found will try the more # general mapped table, which in the case of inheritance is # a join. try: consider_as_foreign_keys = self.consider_as_foreign_keys or None if self.secondary is not None: if self.secondaryjoin is None: self.secondaryjoin = \ join_condition( self.child_selectable, self.secondary, a_subset=self.child_local_selectable, consider_as_foreign_keys=consider_as_foreign_keys ) if self.primaryjoin is None: self.primaryjoin = \ join_condition( self.parent_selectable, self.secondary, a_subset=self.parent_local_selectable, consider_as_foreign_keys=consider_as_foreign_keys ) else: if self.primaryjoin is None: self.primaryjoin = \ join_condition( self.parent_selectable, self.child_selectable, a_subset=self.parent_local_selectable, consider_as_foreign_keys=consider_as_foreign_keys ) except sa_exc.NoForeignKeysError: if self.secondary is not None: raise sa_exc.NoForeignKeysError( "Could not determine join " "condition between parent/child tables on " "relationship %s - there are no foreign keys " "linking these tables via secondary table '%s'. " "Ensure that referencing columns are associated " "with a ForeignKey or ForeignKeyConstraint, or " "specify 'primaryjoin' and 'secondaryjoin' " "expressions." % (self.prop, self.secondary)) else: raise sa_exc.NoForeignKeysError( "Could not determine join " "condition between parent/child tables on " "relationship %s - there are no foreign keys " "linking these tables. " "Ensure that referencing columns are associated " "with a ForeignKey or ForeignKeyConstraint, or " "specify a 'primaryjoin' expression." % self.prop) except sa_exc.AmbiguousForeignKeysError: if self.secondary is not None: raise sa_exc.AmbiguousForeignKeysError( "Could not determine join " "condition between parent/child tables on " "relationship %s - there are multiple foreign key " "paths linking the tables via secondary table '%s'. " "Specify the 'foreign_keys' " "argument, providing a list of those columns which " "should be counted as containing a foreign key " "reference from the secondary table to each of the " "parent and child tables." % (self.prop, self.secondary)) else: raise sa_exc.AmbiguousForeignKeysError( "Could not determine join " "condition between parent/child tables on " "relationship %s - there are multiple foreign key " "paths linking the tables. Specify the " "'foreign_keys' argument, providing a list of those " "columns which should be counted as containing a " "foreign key reference to the parent table." % self.prop) @property def primaryjoin_minus_local(self): return _deep_deannotate(self.primaryjoin, values=("local", "remote")) @property def secondaryjoin_minus_local(self): return _deep_deannotate(self.secondaryjoin, values=("local", "remote")) @util.memoized_property def primaryjoin_reverse_remote(self): """Return the primaryjoin condition suitable for the "reverse" direction. If the primaryjoin was delivered here with pre-existing "remote" annotations, the local/remote annotations are reversed. Otherwise, the local/remote annotations are removed. """ if self._has_remote_annotations: def replace(element): if "remote" in element._annotations: v = element._annotations.copy() del v['remote'] v['local'] = True return element._with_annotations(v) elif "local" in element._annotations: v = element._annotations.copy() del v['local'] v['remote'] = True return element._with_annotations(v) return visitors.replacement_traverse( self.primaryjoin, {}, replace) else: if self._has_foreign_annotations: # TODO: coverage return _deep_deannotate(self.primaryjoin, values=("local", "remote")) else: return _deep_deannotate(self.primaryjoin) def _has_annotation(self, clause, annotation): for col in visitors.iterate(clause, {}): if annotation in col._annotations: return True else: return False @util.memoized_property def _has_foreign_annotations(self): return self._has_annotation(self.primaryjoin, "foreign") @util.memoized_property def _has_remote_annotations(self): return self._has_annotation(self.primaryjoin, "remote") def _annotate_fks(self): """Annotate the primaryjoin and secondaryjoin structures with 'foreign' annotations marking columns considered as foreign. """ if self._has_foreign_annotations: return if self.consider_as_foreign_keys: self._annotate_from_fk_list() else: self._annotate_present_fks() def _annotate_from_fk_list(self): def check_fk(col): if col in self.consider_as_foreign_keys: return col._annotate({"foreign": True}) self.primaryjoin = visitors.replacement_traverse( self.primaryjoin, {}, check_fk ) if self.secondaryjoin is not None: self.secondaryjoin = visitors.replacement_traverse( self.secondaryjoin, {}, check_fk ) def _annotate_present_fks(self): if self.secondary is not None: secondarycols = util.column_set(self.secondary.c) else: secondarycols = set() def is_foreign(a, b): if isinstance(a, schema.Column) and \ isinstance(b, schema.Column): if a.references(b): return a elif b.references(a): return b if secondarycols: if a in secondarycols and b not in secondarycols: return a elif b in secondarycols and a not in secondarycols: return b def visit_binary(binary): if not isinstance(binary.left, sql.ColumnElement) or \ not isinstance(binary.right, sql.ColumnElement): return if "foreign" not in binary.left._annotations and \ "foreign" not in binary.right._annotations: col = is_foreign(binary.left, binary.right) if col is not None: if col.compare(binary.left): binary.left = binary.left._annotate( {"foreign": True}) elif col.compare(binary.right): binary.right = binary.right._annotate( {"foreign": True}) self.primaryjoin = visitors.cloned_traverse( self.primaryjoin, {}, {"binary": visit_binary} ) if self.secondaryjoin is not None: self.secondaryjoin = visitors.cloned_traverse( self.secondaryjoin, {}, {"binary": visit_binary} ) def _refers_to_parent_table(self): """Return True if the join condition contains column comparisons where both columns are in both tables. """ pt = self.parent_selectable mt = self.child_selectable result = [False] def visit_binary(binary): c, f = binary.left, binary.right if ( isinstance(c, expression.ColumnClause) and isinstance(f, expression.ColumnClause) and pt.is_derived_from(c.table) and pt.is_derived_from(f.table) and mt.is_derived_from(c.table) and mt.is_derived_from(f.table) ): result[0] = True visitors.traverse( self.primaryjoin, {}, {"binary": visit_binary} ) return result[0] def _tables_overlap(self): """Return True if parent/child tables have some overlap.""" return selectables_overlap( self.parent_selectable, self.child_selectable) def _annotate_remote(self): """Annotate the primaryjoin and secondaryjoin structures with 'remote' annotations marking columns considered as part of the 'remote' side. """ if self._has_remote_annotations: return if self.secondary is not None: self._annotate_remote_secondary() elif self._local_remote_pairs or self._remote_side: self._annotate_remote_from_args() elif self._refers_to_parent_table(): self._annotate_selfref(lambda col: "foreign" in col._annotations, False) elif self._tables_overlap(): self._annotate_remote_with_overlap() else: self._annotate_remote_distinct_selectables() def _annotate_remote_secondary(self): """annotate 'remote' in primaryjoin, secondaryjoin when 'secondary' is present. """ def repl(element): if self.secondary.c.contains_column(element): return element._annotate({"remote": True}) self.primaryjoin = visitors.replacement_traverse( self.primaryjoin, {}, repl) self.secondaryjoin = visitors.replacement_traverse( self.secondaryjoin, {}, repl) def _annotate_selfref(self, fn, remote_side_given): """annotate 'remote' in primaryjoin, secondaryjoin when the relationship is detected as self-referential. """ def visit_binary(binary): equated = binary.left.compare(binary.right) if isinstance(binary.left, expression.ColumnClause) and \ isinstance(binary.right, expression.ColumnClause): # assume one to many - FKs are "remote" if fn(binary.left): binary.left = binary.left._annotate({"remote": True}) if fn(binary.right) and not equated: binary.right = binary.right._annotate( {"remote": True}) elif not remote_side_given: self._warn_non_column_elements() self.primaryjoin = visitors.cloned_traverse( self.primaryjoin, {}, {"binary": visit_binary}) def _annotate_remote_from_args(self): """annotate 'remote' in primaryjoin, secondaryjoin when the 'remote_side' or '_local_remote_pairs' arguments are used. """ if self._local_remote_pairs: if self._remote_side: raise sa_exc.ArgumentError( "remote_side argument is redundant " "against more detailed _local_remote_side " "argument.") remote_side = [r for (l, r) in self._local_remote_pairs] else: remote_side = self._remote_side if self._refers_to_parent_table(): self._annotate_selfref(lambda col: col in remote_side, True) else: def repl(element): if element in remote_side: return element._annotate({"remote": True}) self.primaryjoin = visitors.replacement_traverse( self.primaryjoin, {}, repl) def _annotate_remote_with_overlap(self): """annotate 'remote' in primaryjoin, secondaryjoin when the parent/child tables have some set of tables in common, though is not a fully self-referential relationship. """ def visit_binary(binary): binary.left, binary.right = proc_left_right(binary.left, binary.right) binary.right, binary.left = proc_left_right(binary.right, binary.left) check_entities = self.prop is not None and \ self.prop.mapper is not self.prop.parent def proc_left_right(left, right): if isinstance(left, expression.ColumnClause) and \ isinstance(right, expression.ColumnClause): if self.child_selectable.c.contains_column(right) and \ self.parent_selectable.c.contains_column(left): right = right._annotate({"remote": True}) elif check_entities and \ right._annotations.get('parentmapper') is self.prop.mapper: right = right._annotate({"remote": True}) elif check_entities and \ left._annotations.get('parentmapper') is self.prop.mapper: left = left._annotate({"remote": True}) else: self._warn_non_column_elements() return left, right self.primaryjoin = visitors.cloned_traverse( self.primaryjoin, {}, {"binary": visit_binary}) def _annotate_remote_distinct_selectables(self): """annotate 'remote' in primaryjoin, secondaryjoin when the parent/child tables are entirely separate. """ def repl(element): if self.child_selectable.c.contains_column(element) and \ (not self.parent_local_selectable.c. contains_column(element) or self.child_local_selectable.c. contains_column(element)): return element._annotate({"remote": True}) self.primaryjoin = visitors.replacement_traverse( self.primaryjoin, {}, repl) def _warn_non_column_elements(self): util.warn( "Non-simple column elements in primary " "join condition for property %s - consider using " "remote() annotations to mark the remote side." % self.prop ) def _annotate_local(self): """Annotate the primaryjoin and secondaryjoin structures with 'local' annotations. This annotates all column elements found simultaneously in the parent table and the join condition that don't have a 'remote' annotation set up from _annotate_remote() or user-defined. """ if self._has_annotation(self.primaryjoin, "local"): return if self._local_remote_pairs: local_side = util.column_set([l for (l, r) in self._local_remote_pairs]) else: local_side = util.column_set(self.parent_selectable.c) def locals_(elem): if "remote" not in elem._annotations and \ elem in local_side: return elem._annotate({"local": True}) self.primaryjoin = visitors.replacement_traverse( self.primaryjoin, {}, locals_ ) def _check_remote_side(self): if not self.local_remote_pairs: raise sa_exc.ArgumentError( 'Relationship %s could ' 'not determine any unambiguous local/remote column ' 'pairs based on join condition and remote_side ' 'arguments. ' 'Consider using the remote() annotation to ' 'accurately mark those elements of the join ' 'condition that are on the remote side of ' 'the relationship.' % (self.prop, )) def _check_foreign_cols(self, join_condition, primary): """Check the foreign key columns collected and emit error messages.""" can_sync = False foreign_cols = self._gather_columns_with_annotation( join_condition, "foreign") has_foreign = bool(foreign_cols) if primary: can_sync = bool(self.synchronize_pairs) else: can_sync = bool(self.secondary_synchronize_pairs) if self.support_sync and can_sync or \ (not self.support_sync and has_foreign): return # from here below is just determining the best error message # to report. Check for a join condition using any operator # (not just ==), perhaps they need to turn on "viewonly=True". if self.support_sync and has_foreign and not can_sync: err = "Could not locate any simple equality expressions "\ "involving locally mapped foreign key columns for "\ "%s join condition "\ "'%s' on relationship %s." % ( primary and 'primary' or 'secondary', join_condition, self.prop ) err += \ " Ensure that referencing columns are associated "\ "with a ForeignKey or ForeignKeyConstraint, or are "\ "annotated in the join condition with the foreign() "\ "annotation. To allow comparison operators other than "\ "'==', the relationship can be marked as viewonly=True." raise sa_exc.ArgumentError(err) else: err = "Could not locate any relevant foreign key columns "\ "for %s join condition '%s' on relationship %s." % ( primary and 'primary' or 'secondary', join_condition, self.prop ) err += \ ' Ensure that referencing columns are associated '\ 'with a ForeignKey or ForeignKeyConstraint, or are '\ 'annotated in the join condition with the foreign() '\ 'annotation.' raise sa_exc.ArgumentError(err) def _determine_direction(self): """Determine if this relationship is one to many, many to one, many to many. """ if self.secondaryjoin is not None: self.direction = MANYTOMANY else: parentcols = util.column_set(self.parent_selectable.c) targetcols = util.column_set(self.child_selectable.c) # fk collection which suggests ONETOMANY. onetomany_fk = targetcols.intersection( self.foreign_key_columns) # fk collection which suggests MANYTOONE. manytoone_fk = parentcols.intersection( self.foreign_key_columns) if onetomany_fk and manytoone_fk: # fks on both sides. test for overlap of local/remote # with foreign key. # we will gather columns directly from their annotations # without deannotating, so that we can distinguish on a column # that refers to itself. # 1. columns that are both remote and FK suggest # onetomany. onetomany_local = self._gather_columns_with_annotation( self.primaryjoin, "remote", "foreign") # 2. columns that are FK but are not remote (e.g. local) # suggest manytoone. manytoone_local = set([c for c in self._gather_columns_with_annotation( self.primaryjoin, "foreign") if "remote" not in c._annotations]) # 3. if both collections are present, remove columns that # refer to themselves. This is for the case of # and_(Me.id == Me.remote_id, Me.version == Me.version) if onetomany_local and manytoone_local: self_equated = self.remote_columns.intersection( self.local_columns ) onetomany_local = onetomany_local.difference(self_equated) manytoone_local = manytoone_local.difference(self_equated) # at this point, if only one or the other collection is # present, we know the direction, otherwise it's still # ambiguous. if onetomany_local and not manytoone_local: self.direction = ONETOMANY elif manytoone_local and not onetomany_local: self.direction = MANYTOONE else: raise sa_exc.ArgumentError( "Can't determine relationship" " direction for relationship '%s' - foreign " "key columns within the join condition are present " "in both the parent and the child's mapped tables. " "Ensure that only those columns referring " "to a parent column are marked as foreign, " "either via the foreign() annotation or " "via the foreign_keys argument." % self.prop) elif onetomany_fk: self.direction = ONETOMANY elif manytoone_fk: self.direction = MANYTOONE else: raise sa_exc.ArgumentError( "Can't determine relationship " "direction for relationship '%s' - foreign " "key columns are present in neither the parent " "nor the child's mapped tables" % self.prop) def _deannotate_pairs(self, collection): """provide deannotation for the various lists of pairs, so that using them in hashes doesn't incur high-overhead __eq__() comparisons against original columns mapped. """ return [(x._deannotate(), y._deannotate()) for x, y in collection] def _setup_pairs(self): sync_pairs = [] lrp = util.OrderedSet([]) secondary_sync_pairs = [] def go(joincond, collection): def visit_binary(binary, left, right): if "remote" in right._annotations and \ "remote" not in left._annotations and \ self.can_be_synced_fn(left): lrp.add((left, right)) elif "remote" in left._annotations and \ "remote" not in right._annotations and \ self.can_be_synced_fn(right): lrp.add((right, left)) if binary.operator is operators.eq and \ self.can_be_synced_fn(left, right): if "foreign" in right._annotations: collection.append((left, right)) elif "foreign" in left._annotations: collection.append((right, left)) visit_binary_product(visit_binary, joincond) for joincond, collection in [ (self.primaryjoin, sync_pairs), (self.secondaryjoin, secondary_sync_pairs) ]: if joincond is None: continue go(joincond, collection) self.local_remote_pairs = self._deannotate_pairs(lrp) self.synchronize_pairs = self._deannotate_pairs(sync_pairs) self.secondary_synchronize_pairs = \ self._deannotate_pairs(secondary_sync_pairs) _track_overlapping_sync_targets = weakref.WeakKeyDictionary() def _warn_for_conflicting_sync_targets(self): if not self.support_sync: return # we would like to detect if we are synchronizing any column # pairs in conflict with another relationship that wishes to sync # an entirely different column to the same target. This is a # very rare edge case so we will try to minimize the memory/overhead # impact of this check for from_, to_ in [ (from_, to_) for (from_, to_) in self.synchronize_pairs ] + [ (from_, to_) for (from_, to_) in self.secondary_synchronize_pairs ]: # save ourselves a ton of memory and overhead by only # considering columns that are subject to a overlapping # FK constraints at the core level. This condition can arise # if multiple relationships overlap foreign() directly, but # we're going to assume it's typically a ForeignKeyConstraint- # level configuration that benefits from this warning. if len(to_.foreign_keys) < 2: continue if to_ not in self._track_overlapping_sync_targets: self._track_overlapping_sync_targets[to_] = \ weakref.WeakKeyDictionary({self.prop: from_}) else: other_props = [] prop_to_from = self._track_overlapping_sync_targets[to_] for pr, fr_ in prop_to_from.items(): if pr.mapper in mapperlib._mapper_registry and \ fr_ is not from_ and \ pr not in self.prop._reverse_property: other_props.append((pr, fr_)) if other_props: util.warn( "relationship '%s' will copy column %s to column %s, " "which conflicts with relationship(s): %s. " "Consider applying " "viewonly=True to read-only relationships, or provide " "a primaryjoin condition marking writable columns " "with the foreign() annotation." % ( self.prop, from_, to_, ", ".join( "'%s' (copies %s to %s)" % (pr, fr_, to_) for (pr, fr_) in other_props) ) ) self._track_overlapping_sync_targets[to_][self.prop] = from_ @util.memoized_property def remote_columns(self): return self._gather_join_annotations("remote") @util.memoized_property def local_columns(self): return self._gather_join_annotations("local") @util.memoized_property def foreign_key_columns(self): return self._gather_join_annotations("foreign") @util.memoized_property def deannotated_primaryjoin(self): return _deep_deannotate(self.primaryjoin) @util.memoized_property def deannotated_secondaryjoin(self): if self.secondaryjoin is not None: return _deep_deannotate(self.secondaryjoin) else: return None def _gather_join_annotations(self, annotation): s = set( self._gather_columns_with_annotation( self.primaryjoin, annotation) ) if self.secondaryjoin is not None: s.update( self._gather_columns_with_annotation( self.secondaryjoin, annotation) ) return set([x._deannotate() for x in s]) def _gather_columns_with_annotation(self, clause, *annotation): annotation = set(annotation) return set([ col for col in visitors.iterate(clause, {}) if annotation.issubset(col._annotations) ]) def join_targets(self, source_selectable, dest_selectable, aliased, single_crit=None): """Given a source and destination selectable, create a join between them. This takes into account aliasing the join clause to reference the appropriate corresponding columns in the target objects, as well as the extra child criterion, equivalent column sets, etc. """ # place a barrier on the destination such that # replacement traversals won't ever dig into it. # its internal structure remains fixed # regardless of context. dest_selectable = _shallow_annotate( dest_selectable, {'no_replacement_traverse': True}) primaryjoin, secondaryjoin, secondary = self.primaryjoin, \ self.secondaryjoin, self.secondary # adjust the join condition for single table inheritance, # in the case that the join is to a subclass # this is analogous to the # "_adjust_for_single_table_inheritance()" method in Query. if single_crit is not None: if secondaryjoin is not None: secondaryjoin = secondaryjoin & single_crit else: primaryjoin = primaryjoin & single_crit if aliased: if secondary is not None: secondary = secondary.alias(flat=True) primary_aliasizer = ClauseAdapter(secondary) secondary_aliasizer = \ ClauseAdapter(dest_selectable, equivalents=self.child_equivalents).\ chain(primary_aliasizer) if source_selectable is not None: primary_aliasizer = \ ClauseAdapter(secondary).\ chain(ClauseAdapter( source_selectable, equivalents=self.parent_equivalents)) secondaryjoin = \ secondary_aliasizer.traverse(secondaryjoin) else: primary_aliasizer = ClauseAdapter( dest_selectable, exclude_fn=_ColInAnnotations("local"), equivalents=self.child_equivalents) if source_selectable is not None: primary_aliasizer.chain( ClauseAdapter(source_selectable, exclude_fn=_ColInAnnotations("remote"), equivalents=self.parent_equivalents)) secondary_aliasizer = None primaryjoin = primary_aliasizer.traverse(primaryjoin) target_adapter = secondary_aliasizer or primary_aliasizer target_adapter.exclude_fn = None else: target_adapter = None return primaryjoin, secondaryjoin, secondary, \ target_adapter, dest_selectable def create_lazy_clause(self, reverse_direction=False): binds = util.column_dict() equated_columns = util.column_dict() has_secondary = self.secondaryjoin is not None if has_secondary: lookup = collections.defaultdict(list) for l, r in self.local_remote_pairs: lookup[l].append((l, r)) equated_columns[r] = l elif not reverse_direction: for l, r in self.local_remote_pairs: equated_columns[r] = l else: for l, r in self.local_remote_pairs: equated_columns[l] = r def col_to_bind(col): if ( (not reverse_direction and 'local' in col._annotations) or reverse_direction and ( (has_secondary and col in lookup) or (not has_secondary and 'remote' in col._annotations) ) ): if col not in binds: binds[col] = sql.bindparam( None, None, type_=col.type, unique=True) return binds[col] return None lazywhere = self.primaryjoin if self.secondaryjoin is None or not reverse_direction: lazywhere = visitors.replacement_traverse( lazywhere, {}, col_to_bind) if self.secondaryjoin is not None: secondaryjoin = self.secondaryjoin if reverse_direction: secondaryjoin = visitors.replacement_traverse( secondaryjoin, {}, col_to_bind) lazywhere = sql.and_(lazywhere, secondaryjoin) bind_to_col = dict((binds[col].key, col) for col in binds) # this is probably not necessary lazywhere = _deep_deannotate(lazywhere) return lazywhere, bind_to_col, equated_columns class _ColInAnnotations(object): """Seralizable equivalent to: lambda c: "name" in c._annotations """ def __init__(self, name): self.name = name def __call__(self, c): return self.name in c._annotations
gdimitris/FleetManagerBackend
virtual_env/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py
Python
mit
116,411
def my_generator(): print 'starting up' yield 1 print "workin'" yield 2 print "still workin'" yield 3 print 'done' for n in my_generator(): print n
shankisg/twisted-intro
inline-callbacks/gen-1.py
Python
mit
182
#!/usr/bin/env python import ConfigParser import os import sys from base import get_parser, run_command def get_repo_info(config_file="config_test_repos.cfg"): config = ConfigParser.ConfigParser() config.read(config_file) repos = {} for repo_id in config.sections(): repos[repo_id] = {"id":repo_id} for item,value in config.items(repo_id): repos[repo_id][item] = value return repos def create_test_repo(repo_id, repo_feed, ca_cert, client_cert, client_key): cmd = "sudo pulp-admin repo create --id %s --feed %s --consumer_ca %s --consumer_cert %s --consumer_key %s" % \ (repo_id, repo_feed, ca_cert, client_cert, client_key) return run_command(cmd) def sync_test_repo(repo_id): cmd = "sudo pulp-admin repo sync --id %s -F" % (repo["id"]) return run_command(cmd) if __name__ == "__main__": parser = get_parser(description="Creat test repos", limit_options=['ca_cert', 'client_key', 'client_cert']) (opts, args) = parser.parse_args() client_key = opts.client_key client_cert = opts.client_cert ca_cert = opts.ca_cert repos = get_repo_info() for repo in repos.values(): if not create_test_repo(repo["id"], repo["feed"], ca_cert, client_cert, client_key): print "Failed to create repo <%s> with feed <%s>" % (repo["id"], repo["feed"]) sys.exit(1) if not sync_test_repo(repo["id"]): print "Failed to sync repo <%s>" % (repo["id"]) sys.exit(1)
nthien/pulp
playpen/certs/create_test_repos.py
Python
gpl-2.0
1,527
# (c) 2016 Red Hat Inc. # # (c) 2017 Dell EMC. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json from units.compat.mock import patch from units.modules.utils import set_module_args from .dellos10_module import TestDellos10Module, load_fixture from ansible.modules.network.dellos10 import dellos10_facts class TestDellos10Facts(TestDellos10Module): module = dellos10_facts def setUp(self): super(TestDellos10Facts, self).setUp() self.mock_run_command = patch( 'ansible.modules.network.dellos10.dellos10_facts.run_commands') self.run_command = self.mock_run_command.start() def tearDown(self): super(TestDellos10Facts, self).tearDown() self.mock_run_command.stop() def load_fixtures(self, commands=None): def load_from_file(*args, **kwargs): module, commands = args output = list() for item in commands: try: obj = json.loads(item) command = obj['command'] except ValueError: command = item if '|' in command: command = str(command).replace('|', '') filename = str(command).replace(' ', '_') filename = filename.replace('/', '7') filename = filename.replace(':', '_colon_') output.append(load_fixture(filename)) return output self.run_command.side_effect = load_from_file def test_dellos10_facts_gather_subset_default(self): set_module_args(dict()) result = self.execute_module() ansible_facts = result['ansible_facts'] self.assertIn('hardware', ansible_facts['ansible_net_gather_subset']) self.assertIn('default', ansible_facts['ansible_net_gather_subset']) self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset']) self.assertEqual('os10', ansible_facts['ansible_net_hostname']) self.assertIn('ethernet1/1/8', ansible_facts['ansible_net_interfaces'].keys()) self.assertEqual(7936, ansible_facts['ansible_net_memtotal_mb']) self.assertEqual(5693, ansible_facts['ansible_net_memfree_mb']) def test_dellos10_facts_gather_subset_config(self): set_module_args({'gather_subset': 'config'}) result = self.execute_module() ansible_facts = result['ansible_facts'] self.assertIn('default', ansible_facts['ansible_net_gather_subset']) self.assertIn('config', ansible_facts['ansible_net_gather_subset']) self.assertEqual('os10', ansible_facts['ansible_net_hostname']) self.assertIn('ansible_net_config', ansible_facts) def test_dellos10_facts_gather_subset_hardware(self): set_module_args({'gather_subset': 'hardware'}) result = self.execute_module() ansible_facts = result['ansible_facts'] self.assertIn('default', ansible_facts['ansible_net_gather_subset']) self.assertIn('hardware', ansible_facts['ansible_net_gather_subset']) self.assertEqual('x86_64', ansible_facts['ansible_net_cpu_arch']) self.assertEqual(7936, ansible_facts['ansible_net_memtotal_mb']) self.assertEqual(5693, ansible_facts['ansible_net_memfree_mb']) def test_dellos10_facts_gather_subset_interfaces(self): set_module_args({'gather_subset': 'interfaces'}) result = self.execute_module() ansible_facts = result['ansible_facts'] self.assertIn('default', ansible_facts['ansible_net_gather_subset']) self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset']) self.assertIn('ethernet1/1/8', ansible_facts['ansible_net_interfaces'].keys()) self.assertEqual(sorted(['mgmt1/1/1', 'ethernet1/1/4', 'ethernet1/1/2', 'ethernet1/1/3', 'ethernet1/1/1']), sorted(list(ansible_facts['ansible_net_neighbors'].keys()))) self.assertIn('ansible_net_interfaces', ansible_facts)
simonwydooghe/ansible
test/units/modules/network/dellos10/test_dellos10_facts.py
Python
gpl-3.0
4,729
# # Author: Gregory Fleischer (gfleischer@gmail.com) # # Copyright (c) 2011 RAFT Team # # This file is part of RAFT. # # RAFT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # RAFT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with RAFT. If not, see <http://www.gnu.org/licenses/>. # from io import StringIO import re from .TemplateItem import TemplateItem class TemplateDefinition(object): def __init__(self, template_text): self.re_word = re.compile('\w') self.re_space = re.compile('\s') self.template_items = [] self.parameter_names = set() self.function_names = set() self.__crack(template_text) def __crack(self, template_text): # lex and scan current_item = self.template_items current_io = StringIO() have_dollar, have_parameter, have_function, have_definition = False, False, False, False paren_stack = [] state_stack = [] lineno = 0 for c in template_text: if have_parameter: if '}' == c: # finished have_parameter = False current_value = current_io.getvalue() if current_value in ["method", "request_uri", "user_agent", "host"]: current_item.append(TemplateItem(current_value, TemplateItem.T_BUILTIN)) else: self.parameter_names.add(current_value) current_item.append(TemplateItem(current_value, TemplateItem.T_PAYLOAD)) current_io = StringIO() elif self.re_word.match(c): current_io.write(c) elif self.re_space.match(c): pass else: raise Exception('invalid template parameter:' + c) elif have_function: if ')' == c: # finished have_function = False elif self.re_word.match(c): current_io.write(c) elif self.re_space.match(c): pass elif '(' == c: # found function definition current_value = current_io.getvalue() if not current_value: raise Exception('invalid function definition') self.function_names.add(current_value) next_item = TemplateItem(current_value, TemplateItem.T_FUNCTION) current_item.append(next_item) current_io = StringIO() state_stack.append((current_item, current_io, have_dollar, have_parameter, have_function, have_definition, paren_stack)) paren_stack = [] current_item = next_item current_io = StringIO() have_dollar, have_parameter, have_function = False, False, False have_definition = True else: raise Exception('invalid template parameter in function:' + c) elif have_dollar: if '(' == c: have_function = True have_dollar = False current_value = current_io.getvalue() if current_value: current_item.append(TemplateItem(current_value, TemplateItem.T_TEXT)) current_io = StringIO() elif '{' == c: have_parameter = True have_dollar = False current_value = current_io.getvalue() if current_value: current_item.append(TemplateItem(current_value, TemplateItem.T_TEXT)) current_io = StringIO() else: # regular dollar have_dollar = False current_io.write('$') current_io.write(c) elif '$' == c: have_dollar = True elif '(' == c and have_definition: paren_stack.append(c) current_io.write(c) elif ')' == c and have_definition: if len(paren_stack) > 0: paren_stack.pop() current_io.write(c) else: current_value = current_io.getvalue() if current_value: current_item.append(TemplateItem(current_value, TemplateItem.T_TEXT)) current_item, current_io, have_dollar, have_parameter, have_function, have_definition, paren_stack = state_stack.pop() else: current_io.write(c) if 0 != len(state_stack): raise Exception('stack error: %s' % repr(state_stack)) current_value = current_io.getvalue() if current_value: current_item.append(TemplateItem(current_value, TemplateItem.T_TEXT))
basicScandal/raft
core/fuzzer/TemplateDefinition.py
Python
gpl-3.0
5,500
""" Validate JSON format. Licensed under MIT Copyright (c) 2012-2015 Isaac Muse <isaacmuse@gmail.com> """ import re import codecs import json RE_LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE) RE_COMMENT = re.compile( r'''(?x) (?P<comments> /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments | [ \t]*//(?:[^\r\n])* # single line comments ) | (?P<code> "(?:\\.|[^"\\])*" # double quotes | .[^/"']* # everything else ) ''', re.DOTALL ) RE_TRAILING_COMMA = re.compile( r'''(?x) ( (?P<square_comma> , # trailing comma (?P<square_ws>[\s\r\n]*) # white space (?P<square_bracket>\]) # bracket ) | (?P<curly_comma> , # trailing comma (?P<curly_ws>[\s\r\n]*) # white space (?P<curly_bracket>\}) # bracket ) ) | (?P<code> "(?:\\.|[^"\\])*" # double quoted string | .[^,"']* # everything else ) ''', re.DOTALL ) RE_LINE_INDENT_TAB = re.compile(r'^(?:(\t+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$') RE_LINE_INDENT_SPACE = re.compile(r'^(?:((?: {4})+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$') RE_TRAILING_SPACES = re.compile(r'^.*?[ \t]+\r?\n?$') RE_COMMENT_END = re.compile(r'\*/') PATTERN_COMMENT_INDENT_SPACE = r'^(%s *?[^\t\r\n][^\r\n]*)?\r?\n$' PATTERN_COMMENT_INDENT_TAB = r'^(%s[ \t]*[^ \t\r\n][^\r\n]*)?\r?\n$' E_MALFORMED = "E0" E_COMMENTS = "E1" E_COMMA = "E2" W_NL_START = "W1" W_NL_END = "W2" W_INDENT = "W3" W_TRAILING_SPACE = "W4" W_COMMENT_INDENT = "W5" VIOLATION_MSG = { E_MALFORMED: 'JSON content is malformed.', E_COMMENTS: 'Comments are not part of the JSON spec.', E_COMMA: 'Dangling comma found.', W_NL_START: 'Unnecessary newlines at the start of file.', W_NL_END: 'Missing a new line at the end of the file.', W_INDENT: 'Indentation Error.', W_TRAILING_SPACE: 'Trailing whitespace.', W_COMMENT_INDENT: 'Comment Indentation Error.' } class CheckJsonFormat(object): """ Test JSON for format irregularities. - Trailing spaces. - Inconsistent indentation. - New lines at end of file. - Unnecessary newlines at start of file. - Trailing commas. - Malformed JSON. """ def __init__(self, use_tabs=False, allow_comments=False): """Setup the settings.""" self.use_tabs = use_tabs self.allow_comments = allow_comments self.fail = False def index_lines(self, text): """Index the char range of each line.""" self.line_range = [] count = 1 last = 0 for m in re.finditer('\n', text): self.line_range.append((last, m.end(0) - 1, count)) last = m.end(0) count += 1 def get_line(self, pt): """Get the line from char index.""" line = None for r in self.line_range: if pt >= r[0] and pt <= r[1]: line = r[2] break return line def check_comments(self, text): """ Check for JavaScript comments. Log them and strip them out so we can continue. """ def remove_comments(group): return ''.join([x[0] for x in RE_LINE_PRESERVE.findall(group)]) def evaluate(m): text = '' g = m.groupdict() if g["code"] is None: if not self.allow_comments: self.log_failure(E_COMMENTS, self.get_line(m.start(0))) text = remove_comments(g["comments"]) else: text = g["code"] return text content = ''.join(map(lambda m: evaluate(m), RE_COMMENT.finditer(text))) return content def check_dangling_commas(self, text): """ Check for dangling commas. Log them and strip them out so we can continue. """ def check_comma(g, m, line): # ,] -> ] or ,} -> } self.log_failure(E_COMMA, line) if g["square_comma"] is not None: return g["square_ws"] + g["square_bracket"] else: return g["curly_ws"] + g["curly_bracket"] def evaluate(m): g = m.groupdict() return check_comma(g, m, self.get_line(m.start(0))) if g["code"] is None else g["code"] return ''.join(map(lambda m: evaluate(m), RE_TRAILING_COMMA.finditer(text))) def log_failure(self, code, line=None): """ Log failure. Log failure code, line number (if available) and message. """ if line: print("%s: Line %d - %s" % (code, line, VIOLATION_MSG[code])) else: print("%s: %s" % (code, VIOLATION_MSG[code])) self.fail = True def check_format(self, file_name): """Initiate the check.""" self.fail = False comment_align = None with codecs.open(file_name, encoding='utf-8') as f: count = 1 for line in f: indent_match = (RE_LINE_INDENT_TAB if self.use_tabs else RE_LINE_INDENT_SPACE).match(line) end_comment = ( (comment_align is not None or (indent_match and indent_match.group(2))) and RE_COMMENT_END.search(line) ) # Don't allow empty lines at file start. if count == 1 and line.strip() == '': self.log_failure(W_NL_START, count) # Line must end in new line if not line.endswith('\n'): self.log_failure(W_NL_END, count) # Trailing spaces if RE_TRAILING_SPACES.match(line): self.log_failure(W_TRAILING_SPACE, count) # Handle block comment content indentation if comment_align is not None: if comment_align.match(line) is None: self.log_failure(W_COMMENT_INDENT, count) if end_comment: comment_align = None # Handle general indentation elif indent_match is None: self.log_failure(W_INDENT, count) # Enter into block comment elif comment_align is None and indent_match.group(2): alignment = indent_match.group(1) if indent_match.group(1) is not None else "" if not end_comment: comment_align = re.compile( (PATTERN_COMMENT_INDENT_TAB if self.use_tabs else PATTERN_COMMENT_INDENT_SPACE) % alignment ) count += 1 f.seek(0) text = f.read() self.index_lines(text) text = self.check_comments(text) self.index_lines(text) text = self.check_dangling_commas(text) try: json.loads(text) except Exception as e: self.log_failure(E_MALFORMED) print(e) return self.fail if __name__ == "__main__": import sys cjf = CheckJsonFormat(False, True) cjf.check_format(sys.argv[1])
facelessuser/TabsExtra
tests/validate_json_format.py
Python
mit
7,430
import uwsgi import time def slow_task(args): time.sleep(10) return uwsgi.SPOOL_OK uwsgi.spooler = slow_task def application(env, start_response): name = uwsgi.spool({'Hello':'World', 'I am a':'long running task'}) print("spooled as %s" % name) start_response('200 Ok', [('Content-Type','text/plain'),('uWSGI-Status', 'spooled')]) return "task spooled"
jyotikamboj/container
uw-tests/spoolme.py
Python
mit
385
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout This file is part of SleekXMPP. See the file LICENSE for copying permission. """ import socket import threading from sleekxmpp.util import Queue class TestLiveSocket(object): """ A live test socket that reads and writes to queues in addition to an actual networking socket. Methods: next_sent -- Return the next sent stanza. next_recv -- Return the next received stanza. recv_data -- Dummy method to have same interface as TestSocket. recv -- Read the next stanza from the socket. send -- Write a stanza to the socket. makefile -- Dummy call, returns self. read -- Read the next stanza from the socket. """ def __init__(self, *args, **kwargs): """ Create a new, live test socket. Arguments: Same as arguments for socket.socket """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.recv_buffer = [] self.recv_queue = Queue() self.send_queue = Queue() self.send_queue_lock = threading.Lock() self.recv_queue_lock = threading.Lock() self.is_live = True def __getattr__(self, name): """ Return attribute values of internal, live socket. Arguments: name -- Name of the attribute requested. """ return getattr(self.socket, name) # ------------------------------------------------------------------ # Testing Interface def disconnect_errror(self): """ Used to simulate a socket disconnection error. Not used by live sockets. """ try: self.socket.shutdown() self.socket.close() except: pass def next_sent(self, timeout=None): """ Get the next stanza that has been sent. Arguments: timeout -- Optional timeout for waiting for a new value. """ args = {'block': False} if timeout is not None: args = {'block': True, 'timeout': timeout} try: return self.send_queue.get(**args) except: return None def next_recv(self, timeout=None): """ Get the next stanza that has been received. Arguments: timeout -- Optional timeout for waiting for a new value. """ args = {'block': False} if timeout is not None: args = {'block': True, 'timeout': timeout} try: if self.recv_buffer: return self.recv_buffer.pop(0) else: return self.recv_queue.get(**args) except: return None def recv_data(self, data): """ Add data to a receive buffer for cases when more than a single stanza was received. """ self.recv_buffer.append(data) # ------------------------------------------------------------------ # Socket Interface def recv(self, *args, **kwargs): """ Read data from the socket. Store a copy in the receive queue. Arguments: Placeholders. Same as for socket.recv. """ data = self.socket.recv(*args, **kwargs) with self.recv_queue_lock: self.recv_queue.put(data) return data def send(self, data): """ Send data on the socket. Store a copy in the send queue. Arguments: data -- String value to write. """ with self.send_queue_lock: self.send_queue.put(data) return self.socket.send(data) # ------------------------------------------------------------------ # File Socket def makefile(self, *args, **kwargs): """ File socket version to use with ElementTree. Arguments: Placeholders, same as socket.makefile() """ return self def read(self, *args, **kwargs): """ Implement the file socket read interface. Arguments: Placeholders, same as socket.recv() """ return self.recv(*args, **kwargs) def clear(self): """ Empty the send queue, typically done once the session has started to remove the feature negotiation and log in stanzas. """ with self.send_queue_lock: for i in range(0, self.send_queue.qsize()): self.send_queue.get(block=False) with self.recv_queue_lock: for i in range(0, self.recv_queue.qsize()): self.recv_queue.get(block=False)
danielvdao/facebookMacBot
venv/lib/python2.7/site-packages/sleekxmpp/test/livesocket.py
Python
mit
4,752
# pylint: skip-file # pylint: disable=too-many-instance-attributes class RoleBindingConfig(object): ''' Handle route options ''' # pylint: disable=too-many-arguments def __init__(self, sname, namespace, kubeconfig, group_names=None, role_ref=None, subjects=None, usernames=None): ''' constructor for handling route options ''' self.kubeconfig = kubeconfig self.name = sname self.namespace = namespace self.group_names = group_names self.role_ref = role_ref self.subjects = subjects self.usernames = usernames self.data = {} self.create_dict() def create_dict(self): ''' return a service as a dict ''' self.data['apiVersion'] = 'v1' self.data['kind'] = 'RoleBinding' self.data['groupNames'] = self.group_names self.data['metadata']['name'] = self.name self.data['metadata']['namespace'] = self.namespace self.data['roleRef'] = self.role_ref self.data['subjects'] = self.subjects self.data['userNames'] = self.usernames # pylint: disable=too-many-instance-attributes,too-many-public-methods class RoleBinding(Yedit): ''' Class to wrap the oc command line tools ''' group_names_path = "groupNames" role_ref_path = "roleRef" subjects_path = "subjects" user_names_path = "userNames" kind = 'RoleBinding' def __init__(self, content): '''RoleBinding constructor''' super(RoleBinding, self).__init__(content=content) self._subjects = None self._role_ref = None self._group_names = None self._user_names = None @property def subjects(self): ''' subjects property ''' if self._subjects == None: self._subjects = self.get_subjects() return self._subjects @subjects.setter def subjects(self, data): ''' subjects property setter''' self._subjects = data @property def role_ref(self): ''' role_ref property ''' if self._role_ref == None: self._role_ref = self.get_role_ref() return self._role_ref @role_ref.setter def role_ref(self, data): ''' role_ref property setter''' self._role_ref = data @property def group_names(self): ''' group_names property ''' if self._group_names == None: self._group_names = self.get_group_names() return self._group_names @group_names.setter def group_names(self, data): ''' group_names property setter''' self._group_names = data @property def user_names(self): ''' user_names property ''' if self._user_names == None: self._user_names = self.get_user_names() return self._user_names @user_names.setter def user_names(self, data): ''' user_names property setter''' self._user_names = data def get_group_names(self): ''' return groupNames ''' return self.get(RoleBinding.group_names_path) or [] def get_user_names(self): ''' return usernames ''' return self.get(RoleBinding.user_names_path) or [] def get_role_ref(self): ''' return role_ref ''' return self.get(RoleBinding.role_ref_path) or {} def get_subjects(self): ''' return subjects ''' return self.get(RoleBinding.subjects_path) or [] #### ADD ##### def add_subject(self, inc_subject): ''' add a subject ''' if self.subjects: self.subjects.append(inc_subject) else: self.put(RoleBinding.subjects_path, [inc_subject]) return True def add_role_ref(self, inc_role_ref): ''' add a role_ref ''' if not self.role_ref: self.put(RoleBinding.role_ref_path, {"name": inc_role_ref}) return True return False def add_group_names(self, inc_group_names): ''' add a group_names ''' if self.group_names: self.group_names.append(inc_group_names) else: self.put(RoleBinding.group_names_path, [inc_group_names]) return True def add_user_name(self, inc_user_name): ''' add a username ''' if self.user_names: self.user_names.append(inc_user_name) else: self.put(RoleBinding.user_names_path, [inc_user_name]) return True #### /ADD ##### #### Remove ##### def remove_subject(self, inc_subject): ''' remove a subject ''' try: self.subjects.remove(inc_subject) except ValueError as _: return False return True def remove_role_ref(self, inc_role_ref): ''' remove a role_ref ''' if self.role_ref and self.role_ref['name'] == inc_role_ref: del self.role_ref['name'] return True return False def remove_group_name(self, inc_group_name): ''' remove a groupname ''' try: self.group_names.remove(inc_group_name) except ValueError as _: return False return True def remove_user_name(self, inc_user_name): ''' remove a username ''' try: self.user_names.remove(inc_user_name) except ValueError as _: return False return True #### /REMOVE ##### #### UPDATE ##### def update_subject(self, inc_subject): ''' update a subject ''' try: index = self.subjects.index(inc_subject) except ValueError as _: return self.add_subject(inc_subject) self.subjects[index] = inc_subject return True def update_group_name(self, inc_group_name): ''' update a groupname ''' try: index = self.group_names.index(inc_group_name) except ValueError as _: return self.add_group_names(inc_group_name) self.group_names[index] = inc_group_name return True def update_user_name(self, inc_user_name): ''' update a username ''' try: index = self.user_names.index(inc_user_name) except ValueError as _: return self.add_user_name(inc_user_name) self.user_names[index] = inc_user_name return True def update_role_ref(self, inc_role_ref): ''' update a role_ref ''' self.role_ref['name'] = inc_role_ref return True #### /UPDATE ##### #### FIND #### def find_subject(self, inc_subject): ''' find a subject ''' index = None try: index = self.subjects.index(inc_subject) except ValueError as _: return index return index def find_group_name(self, inc_group_name): ''' find a group_name ''' index = None try: index = self.group_names.index(inc_group_name) except ValueError as _: return index return index def find_user_name(self, inc_user_name): ''' find a user_name ''' index = None try: index = self.user_names.index(inc_user_name) except ValueError as _: return index return index def find_role_ref(self, inc_role_ref): ''' find a user_name ''' if self.role_ref and self.role_ref['name'] == inc_role_ref['name']: return self.role_ref return None
appuio/ansible-role-openshift-zabbix-monitoring
vendor/openshift-tools/ansible/roles/lib_openshift_3.2/build/lib/rolebinding.py
Python
apache-2.0
7,587
from swampdragon.route_handler import BaseModelPublisherRouter from swampdragon.serializers.model_serializer import ModelSerializer from swampdragon.testing.dragon_testcase import DragonTestCase from .models import TwoFieldModel class Serializer(ModelSerializer): class Meta: publish_fields = ('id') update_fields = ('text', 'number') model = TwoFieldModel class Router(BaseModelPublisherRouter): model = TwoFieldModel serializer_class = Serializer def get_object(self, **kwargs): return self.model.objects.get(**kwargs) class TestBaseModelPublisherRouter(DragonTestCase): def setUp(self): self.router = Router(self.connection) self.obj = self.router.model.objects.create(text='text', number=5) def test_deleted(self): data = {'id': self.obj.pk} self.router.subscribe(**{'channel': 'client-channel'}) self.router.delete(**data) actual = self.connection.get_last_published() expected = {'action': 'deleted', 'channel': 'twofieldmodel|', 'data': {'_type': 'twofieldmodel', 'id': 1}} self.assertDictEqual(actual, expected)
jonashagstedt/swampdragon
tests/test_base_model_publisher_router_deleted.py
Python
bsd-3-clause
1,148
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import purchase from . import mrp_production from . import stock_move
jeremiahyan/odoo
addons/purchase_mrp/models/__init__.py
Python
gpl-3.0
177
# testing/warnings.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """NOTE: copied/adapted from SQLAlchemy master for backwards compatibility; this should be removable when Alembic targets SQLAlchemy 0.9.4. """ from __future__ import absolute_import import warnings from sqlalchemy import exc as sa_exc import re def setup_filters(): """Set global warning behavior for the test suite.""" warnings.filterwarnings('ignore', category=sa_exc.SAPendingDeprecationWarning) warnings.filterwarnings('error', category=sa_exc.SADeprecationWarning) warnings.filterwarnings('error', category=sa_exc.SAWarning) def assert_warnings(fn, warning_msgs, regex=False): """Assert that each of the given warnings are emitted by fn.""" from .assertions import eq_ with warnings.catch_warnings(record=True) as log: # ensure that nothing is going into __warningregistry__ warnings.filterwarnings("always") result = fn() for warning in log: popwarn = warning_msgs.pop(0) if regex: assert re.match(popwarn, str(warning.message)) else: eq_(popwarn, str(warning.message)) return result
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/alembic/testing/warnings.py
Python
mit
1,380
#!/usr/bin/env python # File created on 05 Jun 2011 from __future__ import division __author__ = "Greg Caporaso" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Greg Caporaso", "Jose Antonio Navas Molina", "Daniel McDonald"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Greg Caporaso" __email__ = "gregcaporaso@gmail.com" import numpy as np from unittest import TestCase, main from tempfile import mkdtemp, NamedTemporaryFile from shutil import rmtree from qiime.split_libraries_fastq import ( process_fastq_single_end_read_file, quality_filter_sequence, bad_chars_from_threshold, get_illumina_qual_chars, quality_filter_sequence, FastqParseError, check_header_match_pre180, check_header_match_180_or_later, correct_barcode, process_fastq_single_end_read_file_no_barcode, extract_reads_from_interleaved ) from qiime.golay import decode_golay_12 import skbio.parse.sequences from skbio.parse.sequences.fastq import ascii_to_phred64, ascii_to_phred33 class FakeFile(object): def __init__(self, d=""): self.s = d def write(self, s): self.s += s def close(self): pass class SplitLibrariesFastqTests(TestCase): """ """ def setUp(self): self.fastq1 = fastq1.split('\n') self.barcode_fastq1 = barcode_fastq1.split('\n') self.fastq2 = fastq2.split('\n') self.barcode_fastq2 = barcode_fastq2.split('\n') self.fastq1_expected_no_qual_unassigned = fastq1_expected_no_qual_unassigned self.fastq1_expected_default = fastq1_expected_default self.fastq2_expected_default = fastq2_expected_default self.fastq1_expected_single_barcode = fastq1_expected_single_barcode self.barcode_map1 = barcode_map1 # vars for test_create_forward_and_reverse_fp self.temp_dir_path = mkdtemp() self.create_forward_and_reverse = NamedTemporaryFile( prefix='create_forward_and_reverse_fp_', suffix='.fastq', dir=self.temp_dir_path, delete=False) self.create_forward_and_reverse_fp = self.create_forward_and_reverse.name self.create_forward_and_reverse.write(forward_reads) self.create_forward_and_reverse.write(reverse_reads) self.create_forward_and_reverse.close() def tearDown(self): """Remove all temp files""" rmtree(self.temp_dir_path) def test_correct_barcode_exact_match(self): """correct_barcode functions as expected w exact match""" barcode = "GGAGACAAGGGA" barcode_to_sample_id = { "GGAGACAAGGGA": "s1", "ACACCTGGTGAT": "s2"} correction_fn = None actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (0, barcode, False, 's1') self.assertEqual(actual, expected) correction_fn = decode_golay_12 actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (0, barcode, False, 's1') self.assertEqual(actual, expected) def test_correct_barcode_no_error_correction(self): """correct_barcode functions as expected w no error correction""" barcode = "GGAGACAAGGGT" barcode_to_sample_id = { "GGAGACAAGGGA": "s1", "ACACCTGGTGAT": "s2"} correction_fn = None actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (0, barcode, False, None) self.assertEqual(actual, expected) # barcode contains N barcode = "CCAGTGTANGCA" actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (0, "CCAGTGTANGCA", False, None) self.assertEqual(actual, expected) def test_correct_barcode_golay_correction(self): """correct_barcode functions as expected w golay correction""" barcode = "GGAGACAAGGGT" barcode_to_sample_id = { "GGAGACAAGGGA": "s1", "ACACCTGGTGAT": "s2"} correction_fn = decode_golay_12 actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (1, "GGAGACAAGGGA", True, "s1") self.assertEqual(actual, expected) barcode = "ACACCTGGTGAC" actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (1, "ACACCTGGTGAT", True, "s2") self.assertEqual(actual, expected) # valid code, but not in barcode_to_sample_id map barcode = "CCAGTGTATGCA" actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (0, "CCAGTGTATGCA", True, None) self.assertEqual(actual, expected) # invalid code, corrected not in barcode_to_sample_id map barcode = "CCTGTGTATGCA" actual = correct_barcode(barcode, barcode_to_sample_id, correction_fn) expected = (1, "CCAGTGTATGCA", True, None) self.assertEqual(actual, expected) def test_process_fastq_single_end_read_file_invalid_phred_offset(self): # passing phred_offset that isn't 33 or 64 raises error with self.assertRaises(ValueError): list(process_fastq_single_end_read_file( self.fastq1,self.barcode_fastq1, self.barcode_map1, store_unassigned=True, max_bad_run_length=1000, phred_quality_threshold=None, min_per_read_length_fraction=0., rev_comp=False, rev_comp_barcode=False, seq_max_N=1000, start_seq_id=0, filter_bad_illumina_qual_digit=False, phred_offset=42)) # passing wrong phred_offset for illumina1.8+ data raises error with self.assertRaises(skbio.parse.sequences.FastqParseError): list(process_fastq_single_end_read_file( self.fastq2, self.barcode_fastq2, self.barcode_map1, min_per_read_length_fraction=0.45, phred_offset=64)) def test_process_fastq_single_end_read_file(self): """process_fastq_single_end_read_file functions as expected w no qual filter """ actual = process_fastq_single_end_read_file(self.fastq1, self.barcode_fastq1, self.barcode_map1, store_unassigned=True, max_bad_run_length=1000, phred_quality_threshold=None, min_per_read_length_fraction=0., rev_comp=False, rev_comp_barcode=False, seq_max_N=1000, start_seq_id=0, filter_bad_illumina_qual_digit=False) actual = list(actual) expected = self.fastq1_expected_no_qual_unassigned self.assertEqual(len(actual), len(expected)) for i in range(len(expected)): np.testing.assert_equal(actual[i], expected[i]) def test_process_fastq_single_end_read_file_w_defaults(self): """process_fastq_single_end_read_file functions as expected w default filters """ actual = process_fastq_single_end_read_file(self.fastq1, self.barcode_fastq1, self.barcode_map1, min_per_read_length_fraction=0.45) actual = list(actual) expected = self.fastq1_expected_default self.assertEqual(len(actual), len(expected)) for i in range(len(expected)): np.testing.assert_equal(actual[i], expected[i]) def test_process_fastq_single_end_read_file_no_barcode(self): """process_fastq_single_end_read_file functions as expected for non-barcoded lane """ actual = process_fastq_single_end_read_file_no_barcode( self.fastq1, 's1', min_per_read_length_fraction=0.45) actual = list(actual) expected = self.fastq1_expected_single_barcode self.assertEqual(len(actual), len(expected)) for i in range(len(expected)): np.testing.assert_equal(actual[i], expected[i]) def test_process_fastq_single_end_read_file_w_defaults_v180(self): """process_fastq_single_end_read_file functions as expected w default filters on casava 180 data """ # test autodetection of phred_offset (phred_offset=None) and # phred_offset=33 gives same results for phred_offset in None, 33: actual = process_fastq_single_end_read_file( self.fastq2, self.barcode_fastq2, self.barcode_map1, min_per_read_length_fraction=0.45, phred_offset=phred_offset) actual = list(actual) expected = self.fastq2_expected_default self.assertEqual(len(actual), len(expected)) for i in range(len(expected)): np.testing.assert_equal(actual[i], expected[i]) def test_process_fastq_single_end_read_file_handles_log(self): """ process_fastq_single_end_read_file generates log when expected """ log = FakeFile() list(process_fastq_single_end_read_file(self.fastq1, self.barcode_fastq1, self.barcode_map1, min_per_read_length_fraction=0.45, log_f=log)) self.assertTrue(log.s.startswith("Quality filter results")) def test_process_fastq_single_end_read_file_handles_histogram(self): """ process_fastq_single_end_read_file generates histogram when expected """ histogram = FakeFile() list(process_fastq_single_end_read_file(self.fastq1, self.barcode_fastq1, self.barcode_map1, min_per_read_length_fraction=0.45, histogram_f=histogram)) self.assertTrue(histogram.s.startswith("Length")) def test_check_header_match_pre180(self): """check_header_match_pre180 functions as expected with varied input """ # match w illumina qual string self.assertTrue(check_header_match_pre180("@990:2:4:11272:5533#1/1", "@990:2:4:11272:5533#1/2")) self.assertTrue(check_header_match_pre180("@990:2:4:11272:5533#1/1", "@990:2:4:11272:5533#1/3")) # qual string differs (this is acceptable) self.assertTrue(check_header_match_pre180("@990:2:4:11272:5533#1/1", "@990:2:4:11272:5533#0/3")) # match wo illumina qual string self.assertTrue(check_header_match_pre180("@990:2:4:11272:5533/1", "@990:2:4:11272:5533/2")) self.assertTrue(check_header_match_pre180("@990:2:4:11272:5533/1", "@990:2:4:11272:5533/3")) # mismatch w illumina qual string self.assertFalse(check_header_match_pre180("@990:2:4:11272:5533#1/1", "@990:2:4:11272:5532#1/2")) self.assertFalse(check_header_match_pre180("@990:2:4:11272:5533#1/1", "@890:2:4:11272:5533#1/2")) # mismatch wo illumina qual string self.assertFalse(check_header_match_pre180("@990:2:4:11272:5533/1", "@990:2:4:11272:5532/2")) self.assertFalse(check_header_match_pre180("@990:2:4:11272:5533/1", "@890:2:4:11272:5533/2")) def test_check_header_match_180_or_later(self): """check_header_match_180_or_later functions as expected with varied input """ # identical self.assertTrue(check_header_match_180_or_later( "M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0", "M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0")) # identical except read number self.assertTrue(check_header_match_180_or_later( "M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0", "M00176:17:000000000-A0CNA:1:1:15487:1773 2:N:0:0")) # identical except read number self.assertTrue(check_header_match_180_or_later( "M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0", "M00176:17:000000000-A0CNA:1:1:15487:1773 3:N:0:0")) # different reads self.assertFalse(check_header_match_180_or_later( "M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0", "M00176:17:000000000-A0CNA:1:1:16427:1774 1:N:0:0")) def test_process_fastq_single_end_read_file_toggle_store_unassigned(self): """process_fastq_single_end_read_file handles store_unassigned """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5533#1/2", "GAAAAAAAAAAT", "+", "bbbbbbbbbbbb"] barcode_to_sample_id = {'AAAAAAAAAAAA': 's1'} # empty results when store_unassigned=False actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [] self.assertEqual(actual, expected) # non-empty results when store_unassigned=True actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=True, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [( 'Unassigned_0 990:2:4:11272:5533#1/1 orig_bc=GAAAAAAAAAAT new_bc=GAAAAAAAAAAT bc_diffs=0', "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", np.array([34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 25, 32, 32, 28, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 32, 34, 34, 34, 34, 33, 34, 32, 33, 32, 31, 27, 34, 33, 31, 33, 33, 29, 34, 30, 31, 34, 9, 23, 20, 20, 17, 30, 25, 18, 30, 21, 32], dtype=np.int8) , 0)] np.testing.assert_equal(actual, expected) def test_process_fastq_single_end_read_file_toggle_thirteen_base_barcodes( self): """process_fastq_single_end_read_file handles thriteen base reads of tweleve base barcodes """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5533#1/2", "AAAAAAAAAAAAT", "+", "bbbbbbbbbbbbb"] barcode_to_sample_id = {'AAAAAAAAAAAA': 's1', 'TAAAAAAAAAAA': 's2'} # rev_comp = False actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [( 's1_0 990:2:4:11272:5533#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0', "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", np.array([34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 25, 32, 32, 28, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 32, 34, 34, 34, 34, 33, 34, 32, 33, 32, 31, 27, 34, 33, 31, 33, 33, 29, 34, 30, 31, 34, 9, 23, 20, 20, 17, 30, 25, 18, 30, 21, 32], dtype=np.int8), 0)] np.testing.assert_equal(actual, expected) def test_process_fastq_single_end_read_file_toggle_rev_comp(self): """process_fastq_single_end_read_file handles rev_comp """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5533#1/2", "AAAAAAAAAAAA", "+", "bbbbbbbbbbbb"] barcode_to_sample_id = {'AAAAAAAAAAAA': 's1'} # rev_comp = False actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [( 's1_0 990:2:4:11272:5533#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0', "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", np.array([34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 25, 32, 32, 28, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 32, 34, 34, 34, 34, 33, 34, 32, 33, 32, 31, 27, 34, 33, 31, 33, 33, 29, 34, 30, 31, 34, 9, 23, 20, 20, 17, 30, 25, 18, 30, 21, 32], dtype=np.int8), 0)] np.testing.assert_equal(actual, expected) # rev_comp = True actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=True, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [( 's1_0 990:2:4:11272:5533#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0', "GGCTGGCTCCCCTTTCGGGGTTACCTCACCGACTTCGGGTGTTGCCGACTCTCGTGGTGTGACGGGCGGTGTGTGC", ascii_to_phred64("`U^RY^QTTWIb_^b]aa_ab[_`a`babbbb`bbbbbbbbbbbbb`\``Ybbbbbbbbbbbbbbbbbbbbbbbbb"), 0)] np.testing.assert_equal(actual, expected) def test_process_fastq_single_end_read_file_error_on_header_mismatch(self): """ValueError on barcode/read header mismatch """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5532#1/2", "TTTTTTTTTTTT", "+", "bbbbbbbbbbbb"] barcode_to_sample_id = {'AAAAAAAAAAAA': 's1'} actual = process_fastq_single_end_read_file( fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) self.assertRaises(FastqParseError, list, actual) def test_process_fastq_single_end_read_file_toggle_rev_comp_barcode(self): """process_fastq_single_end_read_file handles rev_comp_barcode """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5533#1/2", "TTTTTTTTTTTT", "+", "bbbbbbbbbbbb"] barcode_to_sample_id = {'AAAAAAAAAAAA': 's1'} # empty results when rev_comp_barcode=False actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [] self.assertEqual(actual, expected) # non-empty results when rev_comp_barcode=True actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=True, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [( 's1_0 990:2:4:11272:5533#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0', "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", np.array([34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 25, 32, 32, 28, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 32, 34, 34, 34, 34, 33, 34, 32, 33, 32, 31, 27, 34, 33, 31, 33, 33, 29, 34, 30, 31, 34, 9, 23, 20, 20, 17, 30, 25, 18, 30, 21, 32], dtype=np.int8), 0)] np.testing.assert_equal(actual, expected) # forward orientation no longer matches when rev_comp_barcode=True barcode_to_sample_id = {'TTTTTTTTTTTT': 's1'} actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=True, seq_max_N=0, start_seq_id=0) actual = list(actual) expected = [] self.assertEqual(actual, expected) def test_process_fastq_single_end_read_file_w_golay_correction(self): """process_fastq_single_end_read_file handles golay correction """ fastq_f = [ "@990:2:4:11272:5533#1/1", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", "+", "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"] barcode_fastq_f = [ "@990:2:4:11272:5533#1/2", "ACAGACCACTCT", "+", "bbbbbbbbbbbb"] barcode_to_sample_id = {'ACAGACCACTCA': 's1'} # empty result with single barcode error and golay correction actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0, barcode_correction_fn=decode_golay_12, max_barcode_errors=1.5) actual = list(actual) expected = [( 's1_0 990:2:4:11272:5533#1/1 orig_bc=ACAGACCACTCT new_bc=ACAGACCACTCA bc_diffs=1', "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", np.array([34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 25, 32, 32, 28, 32, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 32, 34, 34, 34, 34, 33, 34, 32, 33, 32, 31, 27, 34, 33, 31, 33, 33, 29, 34, 30, 31, 34, 9, 23, 20, 20, 17, 30, 25, 18, 30, 21, 32], dtype=np.int8), 0)] np.testing.assert_equal(actual, expected) # empty result with adjusted max_barcode_errors actual = process_fastq_single_end_read_file(fastq_f, barcode_fastq_f, barcode_to_sample_id, store_unassigned=False, max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length_fraction=0.75, rev_comp=False, rev_comp_barcode=False, seq_max_N=0, start_seq_id=0, barcode_correction_fn=decode_golay_12, max_barcode_errors=0.9) actual = list(actual) expected = [] self.assertEqual(actual, expected) def test_bad_chars_from_threshold(self): """bad_chars_from_threshold selects correct chars as bad """ exp1 = [ '\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B'] exp2 = ['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'] exp3 = [ '\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@'] self.assertEqual(bad_chars_from_threshold('B'), {}.fromkeys(exp1)) self.assertEqual(bad_chars_from_threshold(''), {}) self.assertEqual(bad_chars_from_threshold('~'), {}.fromkeys(exp2)) self.assertEqual(bad_chars_from_threshold('@'), {}.fromkeys(exp3)) def test_quality_filter_sequence_pass(self): """quality_filter_sequence functions as expected for good read """ header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) def test_quality_filter_illumina_qual(self): """quality_filter_sequence functions as expected with bad illumina qual digit """ # header with no qual data passes header = "990:2:4:11271:5323/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=0.75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # header with no qual data passes header = "990:2:4:11271:5323/0" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # header with no qual data passes (old barcode in header format) header = "HWI-6X_9267:1:1:4:1699#ACCACCC/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # bad qual fails filter header = "@HWI-ST753_50:6:1101:1138:1965#0/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (3, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # bad qual passes filter if filter turned off header = "@HWI-ST753_50:6:1101:1138:1965#0/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=False) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # good qual passes filter header = "@HWI-ST753_50:6:1101:1138:1965#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) def test_quality_filter_sequence_fail_w_B(self): """quality_filter_sequence handles bad qual score as expected """ # early 'B' in sequence causes truncation and too short of a read header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal( actual, (1, "GCACTCACCGCCCGTCAC", ascii_to_phred64("bbbbbbbbbbbbbbbbbb"))) # increasing max_bad_run_length rescues read header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=1, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # changing threshold rescues read header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=1, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal(actual, (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"))) # changing min_per_read_length_fraction rescues read header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbBbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=5, seq_max_N=0, filter_bad_illumina_qual_digit=True) np.testing.assert_equal( actual, (0, "GCACTCACCGCCCGTCAC", ascii_to_phred64("bbbbbbbbbbbbbbbbbb"))) def test_quality_filter_sequence_fail_w_N(self): """quality_filter_sequence handles N as expected """ # 'N' in sequence causes failure header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTNGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=0, filter_bad_illumina_qual_digit=True) expected = (2, "GCACTCACCGCCCGTCACACCACGAAAGTNGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`")) np.testing.assert_equal(actual, expected) # increasing max N rescues sequence header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTNGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=75, seq_max_N=1, filter_bad_illumina_qual_digit=True) expected = (0, "GCACTCACCGCCCGTCACACCACGAAAGTNGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`")) np.testing.assert_equal(actual, expected) # truncation of N rescues sequence (sequence is truncated when # the quality hits B, and the truncated sequence is above the # length threshold and no longer contains an N) header = "990:2:4:11271:5323#1/1" sequence = \ "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTN" quality = \ "bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^B`" actual = quality_filter_sequence(header, sequence, ascii_to_phred64(quality), max_bad_run_length=0, phred_quality_threshold=2, min_per_read_length=50, seq_max_N=0, filter_bad_illumina_qual_digit=True) expected = (0, "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^")) np.testing.assert_equal(actual, expected) def test_create_forward_and_reverse_fp(self): """ perform different tests for extract_reads_from_interleaved """ # regular processing extract_reads_from_interleaved( self.create_forward_and_reverse_fp, '1:N:0', '2:N:0', self.temp_dir_path) forward = open(self.temp_dir_path + '/forward_reads.fastq', 'U').read() reverse = open(self.temp_dir_path + '/reverse_reads.fastq', 'U').read() self.assertEqual(forward, forward_reads) self.assertEqual(reverse, reverse_reads) # should raise an error due to no matching id with self.assertRaises(ValueError): extract_reads_from_interleaved( self.create_forward_and_reverse_fp, '1N', '2N', self.temp_dir_path) barcode_map1 = {'AAAAAAAAAAAA': 's1', 'AAAAAAAAAAAC': 's2', 'AAAAAAAAAAAG': 's3', 'AAAAAAAAAAAT': 's4', } fastq1 = """@990:2:4:11271:5323#1/1 GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC + bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U` @990:2:4:11271:5323#1/1 GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG + bbcbbbbbbbbbbbbbbbbbbbbbbbbbb_bbbbbbbbaba_b^bY_`aa^bPb`bbbbHYGYZTbb^_ab[^baT @990:2:4:11272:9538#1/1 GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG + b_bbbbbbbbbbbbbbbbbbbbbbbbbbabaa^a`[bbbb`bbbbTbbabb]b][_a`a]acaaacbaca_a^`aa @990:2:4:11272:9538#1/1 GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC + bb^bbbbbbbbbbbbbbbbbbbbbbbabbbb``bbb`__bbbbbbIWRXX`R``\`\Y\^__ba^a[Saaa_]O]O @990:2:4:11272:7447#1/1 GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGGCAGTCTAACCGCAAGGAGGACGCTGTCG + b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`BBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:7447#1/1 GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACAGCGTCCTCCTTGCTGTTAGACTTCCGGC + b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`BBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:19991#1/1 GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGGTGGGGCAACCGGCTGTCCCTTTTAGCGG + bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`TbBBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:19991#1/1 GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGGCTGGCCCTTTCCACCCA + bbbbbbbbbbbbbbbbbbbba`bbbbbbbbbb`abb_aacbbbbb]___]\[\^^[aOcBBBBBBBBBBBBBBBBB @990:2:4:11272:4315#1/1 GTACTCACCGCCCGTCACGCCATGGGAGTTGGGCTTACCTGAAGCCCGCGAGCTAACCGGAAAGGGGGGGATGTGG + bbbb_bbbbbbbbbb```Q```BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:4315#1/1 GGCTACCTTGTTACGACTTCACCCCCGTCGCTCGGCGTACCTTCGACCGCTGCCTCCTTTTGGTTATATCTCCGGG + ``Q``````_``````````K]]aBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:5533#1/1 GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC + ``Q``````_``````````K]]aBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB @990:2:4:11272:5533#0/1 GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCGGCTGGCTCCCCTTTCGGGGGTACCTCAC + bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`TbBBBBBBBBBBBBBBBBBBBBBBBBBBBB """ barcode_fastq1 = """@990:2:4:11271:5323#1/2 AAAAAAAAAAAA + bbbbbbbbbbbb @990:2:4:11271:5323#1/2 AAAAAAAAAAAC + bbcbbbbbbbbb @990:2:4:11272:9538#1/2 AAAAAAAAAAAA + b_bbbbbbbbbb @990:2:4:11272:9538#1/2 AAAAAAAAAAAT + bb^bbbbbbbbb @990:2:4:11272:7447#1/2 AAAAAAAAAAAA + b`bbbbbbbbbb @990:2:4:11272:7447#1/2 AAAAAAAAAAAA + b`bbbbbbbbbb @990:2:4:11272:19991#1/2 AAAAAAAAAAAC + bbbbbbbbbbbb @990:2:4:11272:19991#1/2 AAAAAAAAAAAC + bbbbbbbbbbbb @990:2:4:11272:4315#1/2 AAAAAAAAAAAT + bbbb_bbbbbbb @990:2:4:11272:4315#1/2 AAAAAAAAAAAT + ``Q``````_`` @990:2:4:11272:5533#1/2 GAAAAAAAAAAT + ``Q``````_`` @990:2:4:11272:5533#0/2 AAAAAAAAAAAT + bbbbbbbbbbbb """ fastq2 = """@M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0 GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC + CCCCCCCCCCAAAAAAAAAAAAAAA:AA=ACCCCCCCCCCCCCACCCCBCABA@<CB@BB>C?@C*8552?:3?6A @M00176:17:000000000-A0CNA:1:1:17088:1773 1:N:0:0 GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG + CCDCCCCCCCCCCCCCCCCCCCCCCCCCC@CCCCCCCCBCB@C?C:@ABB?C1CACCCC):(:;5CC?@BC<?CB5 @M00176:17:000000000-A0CNA:1:1:16738:1773 1:N:0:0 GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG + C@CCCCCCCCCCCCCCCCCCCCCCCCCCBCBB?BA<CCCCACCCC5CCBCC>C><@BAB>BDBBBDCBDB@B?ABB @M00176:17:000000000-A0CNA:1:1:12561:1773 1:N:0:0 GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC + CC?CCCAAAACCCCCCCCCCCCCCCCBCCCCAACCCA@@CCCCCC*8399A3AA=A=:=?@@CB?B<4BBB@>0>0 @M00176:17:000000000-A0CNA:1:1:14596:1773 1:N:0:0 GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGGCAGTCTAACCGCAAGGAGGACGCTGTCG + CACCCCCCCCCCCCCCCA?CCCCC:CCCCC=@@@A@CCBC?BBB6?=A############################ @M00176:17:000000000-A0CNA:1:1:12515:1774 1:N:0:0 GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACAGCGTCCTCCTTGCTGTTAGACTTCCGGC + CACCCCCCCCCCCCCCCA?CCCCC:CCCCC=@@@A@CCBC?BBB6?=A############################ @M00176:17:000000000-A0CNA:1:1:17491:1774 1:N:0:0 GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGGTGGGGCAACCGGCTGTCCCTTTTAGCGG + CCCCCCCCCCCCCCCCCCCCC9CCC@CCCBCCCAB;<6>=05:97A5C############################ @M00176:17:000000000-A0CNA:1:1:16427:1774 1:N:0:0 GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGGCTGGCCCTTTCCACCCA + CCCCCCCCCCCCCCCCCCCCBACCCCCCCCCCABCC@BBDCCCCC>@@@>=<=??<B0D################# @M00176:17:000000000-A0CNA:1:1:13372:1775 1:N:0:0 GTACTCACCGCCCGTCACGCCATGGGAGTTGGGCTTACCTGAAGCCCGCGAGCTAACCGGAAAGGGGGGGATGTGG + CCCC@CCCCCCCCCCAAA2AAA###################################################### @M00176:17:000000000-A0CNA:1:1:14806:1775 1:N:0:0 GGCTACCTTGTTACGACTTCACCCCCGTCGCTCGGCGTACCTTCGACCGCTGCCTCCTTTTGGTTATATCTCCGGG + AA2AAAAAA@AA####AAAA,>>B#################################################### @M00176:17:000000000-A0CNA:1:1:13533:1775 1:N:0:0 GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC + AA2AAAAAA@AAAAAAAAAA,>>B#################################################### @M00176:17:000000000-A0CNA:1:1:18209:1775 1:N:0:0 GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCGGCTGGCTCCCCTTTCGGGGGTACCTCAC + CCCCCCCCCCCCCCCCCCCCC9CCC@CCCBCCCAB;<6>=05:97A5C############################ """ barcode_fastq2 = """@M00176:17:000000000-A0CNA:1:1:15487:1773 2:N:0:0 AAAAAAAAAAAA + AAAAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:17088:1773 2:N:0:0 AAAAAAAAAAAC + AABAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:16738:1773 2:N:0:0 AAAAAAAAAAAA + A>AAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:12561:1773 2:N:0:0 AAAAAAAAAAAT + AA:AAAAAAAAA @M00176:17:000000000-A0CNA:1:1:14596:1773 2:N:0:0 AAAAAAAAAAAA + A?AAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:12515:1774 2:N:0:0 AAAAAAAAAAAA + A?AAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:17491:1774 2:N:0:0 AAAAAAAAAAAC + AAAAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:16427:1774 2:N:0:0 AAAAAAAAAAAC + AAAAAAAAAAAA @M00176:17:000000000-A0CNA:1:1:13372:1775 2:N:0:0 AAAAAAAAAAAT + AAAA>AAAAAAA @M00176:17:000000000-A0CNA:1:1:14806:1775 2:N:0:0 AAAAAAAAAAAT + >>1>>>>>>;>> @M00176:17:000000000-A0CNA:1:1:13533:1775 2:N:0:0 GAAAAAAAAAAT + >>1>>>>>>;>> @M00176:17:000000000-A0CNA:1:1:18209:1775 2:N:0:0 AAAAAAAAAAAT + AAAAAAAAAAAA """ fastq1_expected_no_qual_unassigned = [ ("s1_0 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"), 0), ("s2_1 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG", ascii_to_phred64("bbcbbbbbbbbbbbbbbbbbbbbbbbbbb_bbbbbbbbaba_b^bY_`aa^bPb`bbbbHYGYZTbb^_ab[^baT"), 1), ("s1_2 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG", ascii_to_phred64("b_bbbbbbbbbbbbbbbbbbbbbbbbbbabaa^a`[bbbb`bbbbTbbabb]b][_a`a]acaaacbaca_a^`aa"), 2), ("s4_3 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC", ascii_to_phred64("bb^bbbbbbbbbbbbbbbbbbbbbbbabbbb``bbb`__bbbbbbIWRXX`R``\`\Y\^__ba^a[Saaa_]O]O"), 3), ("s1_4 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGGCAGTCTAACCGCAAGGAGGACGCTGTCG", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`BBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 4), ("s1_5 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACAGCGTCCTCCTTGCTGTTAGACTTCCGGC", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`BBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 5), ("s2_6 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGGTGGGGCAACCGGCTGTCCCTTTTAGCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`TbBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 6), ("s2_7 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGGCTGGCCCTTTCCACCCA", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbba`bbbbbbbbbb`abb_aacbbbbb]___]\[\^^[aOcBBBBBBBBBBBBBBBBB"), 7), ("s4_8 990:2:4:11272:4315#1/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GTACTCACCGCCCGTCACGCCATGGGAGTTGGGCTTACCTGAAGCCCGCGAGCTAACCGGAAAGGGGGGGATGTGG", ascii_to_phred64("bbbb_bbbbbbbbbb```Q```BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 8), ("s4_9 990:2:4:11272:4315#1/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGCTACCTTGTTACGACTTCACCCCCGTCGCTCGGCGTACCTTCGACCGCTGCCTCCTTTTGGTTATATCTCCGGG", ascii_to_phred64("``Q``````_``````````K]]aBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 9), ("Unassigned_10 990:2:4:11272:5533#1/1 orig_bc=GAAAAAAAAAAT new_bc=GAAAAAAAAAAT bc_diffs=0", "GCACACACCGCCCGTCACACCACGAGAGTCGGCAACACCCGAAGTCGGTGAGGTAACCCCGAAAGGGGAGCCAGCC", ascii_to_phred64("``Q``````_``````````K]]aBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 10), ("s4_11 990:2:4:11272:5533#0/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCGGCTGGCTCCCCTTTCGGGGGTACCTCAC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`TbBBBBBBBBBBBBBBBBBBBBBBBBBBBB"), 11)] fastq1_expected_default = [ ("s1_0 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"), 0), ("s2_1 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG", ascii_to_phred64("bbcbbbbbbbbbbbbbbbbbbbbbbbbbb_bbbbbbbbaba_b^bY_`aa^bPb`bbbbHYGYZTbb^_ab[^baT"), 1), ("s1_2 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG", ascii_to_phred64("b_bbbbbbbbbbbbbbbbbbbbbbbbbbabaa^a`[bbbb`bbbbTbbabb]b][_a`a]acaaacbaca_a^`aa"), 2), ("s4_3 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC", ascii_to_phred64("bb^bbbbbbbbbbbbbbbbbbbbbbbabbbb``bbb`__bbbbbbIWRXX`R``\`\Y\^__ba^a[Saaa_]O]O"), 3), ("s1_4 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGG", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 4), ("s1_5 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACA", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 5), ("s2_6 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 6), ("s2_7 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbba`bbbbbbbbbb`abb_aacbbbbb]___]\[\^^[aOc"), 7), ("s4_8 990:2:4:11272:5533#0/1 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 8)] fastq1_expected_single_barcode = [ ("s1_0 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbbbbbY``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"), 0), ("s1_1 990:2:4:11271:5323#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG", ascii_to_phred64("bbcbbbbbbbbbbbbbbbbbbbbbbbbbb_bbbbbbbbaba_b^bY_`aa^bPb`bbbbHYGYZTbb^_ab[^baT"), 1), ("s1_2 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG", ascii_to_phred64("b_bbbbbbbbbbbbbbbbbbbbbbbbbbabaa^a`[bbbb`bbbbTbbabb]b][_a`a]acaaacbaca_a^`aa"), 2), ("s1_3 990:2:4:11272:9538#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC", ascii_to_phred64("bb^bbbbbbbbbbbbbbbbbbbbbbbabbbb``bbb`__bbbbbbIWRXX`R``\`\Y\^__ba^a[Saaa_]O]O"), 3), ("s1_4 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGG", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 4), ("s1_5 990:2:4:11272:7447#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACA", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 5), ("s1_6 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 6), ("s1_7 990:2:4:11272:19991#1/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbba`bbbbbbbbbb`abb_aacbbbbb]___]\[\^^[aOc"), 7), ("s1_8 990:2:4:11272:5533#0/1 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 8)] fastq2_expected_default = [ ("s1_0 M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACTCACCGCCCGTCACACCACGAAAGTTGGTAACACCCGAAGCCGGTGAGATAACCTTTTAGGAGTCAGCTGTC", ascii_to_phred64("bbbbbbbbbb```````````````Y``\`bbbbbbbbbbbbb`bbbbab`a`_[ba_aa]b^_bIWTTQ^YR^U`"), 0), ("s2_1 M00176:17:000000000-A0CNA:1:1:17088:1773 1:N:0:0 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGTTACCTTGTTACGACTTCACCCCAATCATCGGCCCCACCTTAGACAGCTGACTCCTAAAAGGTTATCTCACCGG", ascii_to_phred64("bbcbbbbbbbbbbbbbbbbbbbbbbbbbb_bbbbbbbbaba_b^bY_`aa^bPb`bbbbHYGYZTbb^_ab[^baT"), 1), ("s1_2 M00176:17:000000000-A0CNA:1:1:16738:1773 1:N:0:0 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGAGGTACCCGAAGCCGGTAGTCTAACCGCAAGGAGGACGCTGTCG", ascii_to_phred64("b_bbbbbbbbbbbbbbbbbbbbbbbbbbabaa^a`[bbbb`bbbbTbbabb]b][_a`a]acaaacbaca_a^`aa"), 2), ("s4_3 M00176:17:000000000-A0CNA:1:1:12561:1773 1:N:0:0 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGCTACCTTGTTACGACTTCACCCTCCTCACTAAACGTACCTTCGACAGCGTCCTCCTTGCGGTTAGACTACCGGC", ascii_to_phred64("bb^bbb````bbbbbbbbbbbbbbbbabbbb``bbb`__bbbbbbIWRXX`R``\`\Y\^__ba^a[Saaa_]O]O"), 3), ("s1_4 M00176:17:000000000-A0CNA:1:1:14596:1773 1:N:0:0 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GCACACACCGCCCGTCACACCATCCGAGTTGGGGGTACCCGAAGCCGG", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 4), ("s1_5 M00176:17:000000000-A0CNA:1:1:12515:1774 1:N:0:0 orig_bc=AAAAAAAAAAAA new_bc=AAAAAAAAAAAA bc_diffs=0", "GGATACCTTGTTACGACTTCACCCTCCTCACTCATCGTACCCTCGACA", ascii_to_phred64("b`bbbbbbbbbbbbbbb`^bbbbbYbbbbb\___`_bbab^aaaU^\`"), 5), ("s2_6 M00176:17:000000000-A0CNA:1:1:17491:1774 1:N:0:0 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GCACTCACCGCCCGTCACGCCACGGAAGCCGGCTGCACCTGAAGCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 6), ("s2_7 M00176:17:000000000-A0CNA:1:1:16427:1774 1:N:0:0 orig_bc=AAAAAAAAAAAC new_bc=AAAAAAAAAAAC bc_diffs=0", "GGCTACCTTGTTACGACTTCGCCCCAGTCACCGACCACACCCTCGACGGCTGCCTCCGG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbba`bbbbbbbbbb`abb_aacbbbbb]___]\[\^^[aOc"), 7), ("s4_8 M00176:17:000000000-A0CNA:1:1:18209:1775 1:N:0:0 orig_bc=AAAAAAAAAAAT new_bc=AAAAAAAAAAAT bc_diffs=0", "GGATACCTTGTTACGACTTCACCCCAATCATCGACCCCACCTTCGGCG", ascii_to_phred64("bbbbbbbbbbbbbbbbbbbbbXbbb_bbbabbb`aZ[U]\OTYXV`Tb"), 8)] forward_reads = """@MISEQ03:64:000000000-A2H3D:1:1101:14358:1530 1:N:0:TCCACAGGAGT TNCAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTGAAACTGACACTGAGGGGCGAAAGCGGGGGGGGCAAACG + ?#5<????DDDDDDDDEEEEFFHHHHHHHHHHHHHHDCCHHFGDEHEH>CCE5AEEHHHHHHHHHHHHHHHHHFFFFHHHHHHEEADEEEEEEEEEEEEEEEEEEEEEEE?BEEEEEEEEEEEAEEEE0?A:?EE)8;)0ACEEECECCECAACEE?>)8CCC?CCA8?88ACC*A*::A??:0?C?.?0:?8884>'.''..'0?8C?C**0:0::?ECEE?############################ @MISEQ03:64:000000000-A2H3D:1:1101:14206:1564 1:N:0:TCCACAGGAGT TACGTAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGCGTGCGCAGGCGGTTTTGTAAGTCAGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCGTTTGAAACTACAAGGCTAGAGTGTAGCAGAGGGGGGTAGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGGGGAGGAATACCAATGGCGAAGGCAGCCCCCGGGGTTAACACTGACGCCAAGGCACGAAAGCGGGGGGGGCAAACG + ?????BB?DDDDDD@DDCEEFFH>EEFHHHHHHGHHHCEEFFDC5EECCCCCCDECEHF;?DFDDFHDDBBDF?CFDCCFEA@@::;EEEEEEEECBA,BBE?:>AA?CA*:**0:??A:8*:*0*0**0*:?CE?DD'..0????:*:?*0?EC*'.)4.?A***00)'.00*0*08)8??8*0:CEE*0:082.4;**?AEAA?############################################# @MISEQ03:64:000000000-A2H3D:1:1101:14943:1619 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCTGGACTGAAACTGACACTGAGGGGCGAAAGCGGGGGGGGCAAAAG + ?AAAABBADDDEDEDDGGGGGGIIHHHIIIIIIIHHHCCHHFFEFHHHDCDH5CFHIIHIIIIHHHHHHHHHHHHHHHHHHHGGGEGGGGDDEGEGGGGGGGGGGGGGGEEEGCCGGGGGGEGCEEEECE?ECGE.84.8CEEGGGE:CCCC0:?C<8.48CC:C??.8.8?C:*:0:*9)??CCEE**)0'''42<2C8'8..8801**0*.1*1?:?EEEC?########################### @MISEQ03:64:000000000-A2H3D:1:1101:15764:1660 1:N:0:TCCACAGGAGT TACGAAGGGGGCTAGCGTTGCTCGGAATCACTGGGCGTAAAGCGCACGTAGGCGGATTGTTAAGTCAGGGGTGAAATCCTGGAGCTCAACTCCAGAACTGCCTTTGATACTGGCGATCTTGAGTCCGGGAGAGGTGAGTGGAACTGCGAGTGTAGAGGTGAAATTCGTAGATATTCGCAAGAACACCAGTGGCGAAGGCGGCTCACTGGCCCGGAACTGACGCTGAGGGGCGAAAGCTGGGGGAGCAAACG + ???????@DDDDDDBDFEEFEFHEHHHHHHHHHHHHHEHHHHFEHHHHAEFHGEHAHHHHHHHHHHHHHHH=@FEFEEFEFEDAEEEFFE=CEBCFFFCECEFEFFFCEEEFFCD>>FFFEFF*?EED;?8AEE08*A*1)?E::???;>2?*01::A?EEEFEEE?:C.8:CE?:?8EE8AECEFE?C0::8'488DE>882)*1?A*8A######################################## @MISEQ03:64:000000000-A2H3D:1:1101:15211:1752 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGGGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATGGGAAGGAACACCAGGGGCGAAGGCGACCACCTGGACTGATACTGACACTGGGGTGGGAAAGGGGGGGGAGGAAAAG + ?????<B?DBBDDDBACCEEFFHFHHHHHHHHHHHHH5>EFFFEAACEC7>E5AFEFHHHHHHF=GHFGHFHHHHFHFHH;CED8@DDDE=4@EEEEECE=CECECEECCBB34,=CAB,40:?EEEE:?AAAE8'.4'..8*:AEEECCCA::A################################################################################################ @MISEQ03:64:000000000-A2H3D:1:1101:15201:1774 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTGATACTGACACTGAGGTGCGAAAGCGGGGGGGGCAAACG + ?????BB?DDDDDDBDEEEEFFHFHHHHHHHHHHHFH>CEHDGDDCDE5CCEACFHHHHHHHHFFHHHHHHHHFHHFHHHHHHDEBFEEE@DEEEEEEEEEEEEEEBBCBECEEEEEEEEEEEEEEE?ACCEEEA)84)0.?EEE:AEACA?0?CEDD'.4?A:ACA)0'80:A:?*0*0)8CEEEEE?*0*)88888A'.5;2A)*0000*8:*0:?CEEEE?A*?A####################### @MISEQ03:64:000000000-A2H3D:1:1101:15976:1791 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTCGTTAAGTTGGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATGGGAAGGAACACCGGGGGGGAGGGGGGCTCTCGGGTCCTTTTCGGCGGCTGGGGGCGGAAGGCAGGGGGGGCAACCG + ?????BB?DDDDDDDDEEEEFFIFHHHHHHIIIHIFHCCHF@F>CECHCDDECCFEADEHHHHHHHHFGHHHHHHFHHHHHHF8:<DEEEADEEFFFFFFABEFFEFFECBCEEFEFFFFEACEEEEE*10*1??.08.888AEF?EEEC1:1:??>>'88AC?::?AA################################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:16031:1840 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCTGGACGGATACTGACACTGAGGGGCGAAAGGGTGGGGAGAAAAAG + ?????BB?DDDDDDDDGFEGGGIHHHHIIIIIIIHFE>CFFFFDCHCH>>CE-5EEIIHHHIHHHHHHHHHHGHFDFHFHEHGBEEEEGGEDGGGGEGGEGGGGGCEGCCEEGGG><CEECCGCEEEG?C:1?EG.8<.88CCCEEGE?C?C*:1:<>'.8?8:C:?00.0?:?*1::*9CC?EEEG*?############################################################## @MISEQ03:64:000000000-A2H3D:1:1101:12964:1852 1:N:0:TCCACAGGAGT TNCAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGCAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGAAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCAACCACCGGGACTGAAACTGAACCGGAGGGGGGAAAGCGGGGGGGGAAAACG + ?#55????DDDDDDDDEEEEFFHHBHHHFFGHHFHDC+5>C/?E7DCHCCCD5AECFHHHFHHHHHHHHHFFFFFHFFDFEFF5)@=DEFDEFEEFF;AEAABC,4BECCC=B,5?C8?CC?CC*:?E010:?EA)0.)08C?A:?A######################################################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:17245:1906 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAGGGAACACAAGGGGCGAAGGCGACCACCGGGACGGAAACTGCAACTGGGGGGGGAAAGCGGGGGGGGAAACAG + AAA??BB?DDDDDDDDGGEGGGIHGHIIIIIIHF?CFCCDFFFDCHEHC>DH5AFEHIHHHHHHHHHHHHHHFFFFFHHHHHGDBEEGGGGGGG@EGEGGGGGGGCGEGACC>EGEGGGGC:C0CEEG:0::CEE)88)08?:CECCE:C*10*104A.4CE:*:?C8)'8CC############################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:18171:1983 1:N:0:TCCACAGGAGT GACGTAGGAGGCGAGCGTTGTCCGGATTCATTGGGCGTAAAGAGCGCGCAGGCGGCTTGGTAAGTCGGATGTGAAATCCCGAGGCTCAACCTCGGGTCTGCATCCGATACTGCCCGGCTAGAGGTAGGTAGGGGAGATCGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGGGGCGAAGGCGGATCTCTGGGCCTTCCCTGACGCTCAGGCGCGAAAGCGGGGGGGGCGAACG + ??????B?DDDDDDDDFFEFFFIHFEEEHHIHHHFHHEHHFGFFFHCEHEHCDECCEFFE4DDFDBEEEEEFFFFEEFFCE8B>BEFEEFFCEFE>8>EFFE*A?A?ADDAAEE8E>;>EA:??1*:?111?C<88AA08?ACECF:*:?*08:0:8<.4?EE*A:))'..0*01*?:08?A*?CA################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:14225:2009 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTGAAACGGACACTGAGGGGCGAAAGCGGGGGGGGCAAACG + ?????BB?DDDDDDBDEEEEFFHHHHIIIIHHIIIIHHEHIFGEHHHHCCEHAEFHIIHIIIIHHHHHHHHHHFHHHHHHHHFFFEFFFFFEFFFFFFEFFFFFFEFFFEFCACEFFFFFF:C?CEEE*?:AAEE88;088?AEFCEAEECEEEFE>?).?ECCEEE8?4AFFE0?*0088ACFFFAAC*0?C888>>CD?D;8CE*:*:A?CF*::)0?DD?:::?######################## @MISEQ03:64:000000000-A2H3D:1:1101:16656:2052 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCGGGACTGAAACTGACACTGAGGGGGGAAAGCGGGGGGGGAAAACA + ?????BB?BDDDDDDDGFFEGGIIHHIIIIIHHHHIHCCFFDEEEHEHFFEH5AFHHIHIHIHGGHHHHHHHFHHFHHHHHHGEG@EGEGGEGGGGCEGGEGGGGEGGACECGGGGGGGGEGGCCEGG?CCCEGC088)0.?EGG?EC*::C*:??<8.48?C:?C808.8CEE############################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:18209:2060 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCACGTAGGCGGCTCAGCAAGTCAGGGGTGAAATCCCGGGGCTCAACCCCGGAACTGCCCTTGAAACTGCTAAGCTAGAATCTTGGAGAGGCGAGTGGAATTCCGAGTGTAGAGGGGAAATTCGTAGATATTCGGAAGAACACCAGGGGCGAAGGCGACCCCCTGGACAAGCATTGACGCTGAGGGGGGAAAGCGGGGGGGGCAAAAG + ?????BB?BDDDDDDDECEEFFHHHHAHFHHHHHHHHCCHHH=@DEEHFHFCGHHB)?ECGHHH?DHHHHHCCCFFHHHFEEEEEEEEEEEEEB)>EDACEECEECEEECEE:*0A:AEAECA:0::ACE??E?.8'4.88?EC*00:08).0:*00?)..8AAAAA*0)0::?::?0A8)?C:?A################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:13824:2095 1:N:0:TCCACAGGAGT TACGTAGGGGGCTAGCGTTGTCCGGAATCATTGGGCGTAAAGCGCGTGTAGGCGGCCCGGTAAGTCCGCTGTGAAAGTCGGGGGCTCAACCCTCGAAAGCCGGGGGATACTGTCGGGCTAGAGTACGGAAGAGGCGAGTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCCATTGCGAAGGCAGCTCGCTGGGACGTTACTGAGGCTGAGACCGGAAAGGGGGGGGGGCAAAAG + ??A??BBADDDDDDBDFEEFFFHHHHHFHHHIHHFHHCCHHFHDCCDEEHHFIHAHHHHH@EFFDFFEBDEDEFFECBBEEEED?28CCFFECE;EF8?ECD;'488?EEFCE:A>>?>EECEE::A8E8.8?8).'.'08AEE*?:*::*001:?<D.'8??*:*))'''01***10*088CEEEEA8C############################################################# @MISEQ03:64:000000000-A2H3D:1:1101:17839:2106 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACAACCGGGACGGAAACTGACACTGAGGGGCGAAAGCGGGGGGGGCAAAAG + AAA?ABB?DDDDDDDEGFEGGFHIHHIIIIIIIIDFH5CFHHGHEH=DC>CE5AEEHFHIHIFHHHHHHHHHFHHFHHHHHHGGGGGEEGGGGGDEGGGGGGGGGGGGGCE>AEGEGGGGEEECEGEE1:??CEC08>.88CEEECG*:C?CC:?0.4.4CE?CECC?)4?CC:*11?:?)CCEGG).9*1:?8<2<<C#################################################### @MISEQ03:64:000000000-A2H3D:1:1101:17831:2124 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGGGGGGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTGAAACTGACACTGAGGGGCGAAAGCGGGGGGAGCAAACG + AAAAABB?DDDDDDDDGFGFGGIIHHIIIIIHIIDFH>CFHHGDCFDH>CDHAEFEHIEFFGGHHHHHHHFH=CFFHHHHEHG8DEEGEGGGGGDEEEEGEEGGGCGGEEECCACCEGGGCEE::?CE0?CCEGE'.<'..4CEGEGGEEEE*::C>20>?C?*1:C..'8:??*:*?*0)??9CEG8?*1*8'4.44?58<28?C############################################# @MISEQ03:64:000000000-A2H3D:1:1101:12555:2129 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTCGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACGAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACGGAAACTGACACTGAGGTGCGAAAGCGTGGGGACCAACCG + ????ABBADDDDDEDDGGGGGGIIHHIIIIIHIIHHHFFHHHFHHHHH>CDHAEFHFGHHFHHHHHHHHHFHHFHFFHHHHHGBEEAD;DGGGGEGGGCGCEEEGEGGGCE>>>CEDGDGE:C:CGGG:?C??EE08<)0?ECEGEGCCECEEGGGGG08CECE?CE8)4?CC:*:*:0989*9CEC8C*:?C'842.8'.4.2?E9?*:?'.8).::::?CC:*110*0C8C<8??C############# @MISEQ03:64:000000000-A2H3D:1:1101:13627:2170 1:N:0:TCCACAGGAGT GACAGAGGGTGCAAACGTTGTTCGGAATTACTGGGCATAAAGAGCACGTAGGTGGTCTGCTAAGTCACGTGTGAAATCCCCCGGCTCAACCGGGGAATTGCGCGTGATACTGGCCGGCTCGAGGTGGGTAGGGGGGAGCGGAACTCCAGGGGGAGCGGGGAAATGCGTAGATATCTGGAGGAACACCGGGGGCGAAAGCGGCTCACGGGACCCAATCTGACACTGAGGGGCGAAAGCTAGGGTGGCAAACG + ?????BB?DDDDDDDDEFFFFFHHHHHIHIIHIIFHCEHIIHBFHIHHAAFH5CF@FHHHGHIIGHHHHFHIHIIIHIIIHHHHHHHHHHFHHHFFEFEFEDBE<>BBEEFECECE?D'..2AD)8A>40?AED''''.4<D>>AC**1?).2'888D'5<EACEEEAEDEFEE:*??*08A?AAC)58'4>2<>D8A:A82'.*:*.'?>E)AA#################################### @MISEQ03:64:000000000-A2H3D:1:1101:11781:2223 1:N:0:TCCACAGGAGT TACGTAGGGCGCAAGCGTTATCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGTTTGTCGCGTCTGCCGTGAAAGTCCGGGGCTCAACTCCGGATCTGCGGTGGGTACGGGCAGACTAGAGTGATGTAGGGGAGATTGGAATTCCTGGTGTAGCGGGGAAATGCGCAGATATCAGGAGGAACACCGATGGCGAAGGCAGGTCTCTGGGCATTAACTGACGCTGAGGAGCGAAAGCAGGGGGGGCGAACG + ???A?BB?DDDDDDDDEEECFFHHHHHIHHHIIIHHHECEHFCFHGGH>CFEFEHHHHHFFDFHCDEFFHHEBFFFF?BBEEEEEEEFFFBEEEEAEDEFEDD.8A8.ACEDDD;AEFFFFEF:*1:?ACCFFD8<AE?EFFFF:EEEEFFFA:CEDD'.8??CEF?ADDDFF:C:?::?AEEFFFA>8'08:2448DE?E?8:*:*1A***0*:AA*?AEEEEE?######################### @MISEQ03:64:000000000-A2H3D:1:1101:17996:2254 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCGGGCCTGAAACTGACACTGAGGGGGGAAAGCGGGGGGGGAAAACG + ?????BB?DDDDDDDDGGGGGGIHHHHIIIIHHHFFH>CHFHGHHHEHCCCE5AFEHIHHHHHHHHHHHHHHHHHHHHHHHHGGEEGGEGEGGGEGEGGGCGGGGGGGECGEECGAECGGEEEC**CE?C::CCC.8<)08?CCC:CCCEC?CC?:8>'4<?.1C:8082CCGG*:*:0C8?EC*0C89.?############################################################ @MISEQ03:64:000000000-A2H3D:1:1101:13712:2276 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGTGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTGATACTGACACTGAGGGGGGAAAGCGGGGGGGGAAAACG + ?????BBADDDDDDDDGGEGGGIHHHHIIIIIIIIIHCCHHDCECHEHCDEH-AFEHIHIHHIHHHHHHHHHHHFFFHHHHHGEGEDDEEDDDGGGGGEGGGGGEEEGEEGEGGGGGGGCEGEGCEGG:C::CEE)88.8?EGGG:C?:?:C??:*52'.888:CEE).2CCGE*C??:C.?EGGGGC9*118>>.4>C''.8<CC*?*:**00*01?:CEGCC########################### @MISEQ03:64:000000000-A2H3D:1:1101:15819:2301 1:N:0:TCCACAGGAGT TACGTAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGCGTGCGCAGGCGGTGAGTTAAGTCTGCTGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGGGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCTGGACTGAAACTGACACTGAGGGGCGAAAGCGGGGGGGGCAAACG + ?????BB?DEDDDDDDFDEEFFHHHEFHHIIIIIIHHCHHFHHHCEEACCHHHEH)<<CCDGFFDFFFBCB@DFHFHFHHEEFB8@EEEFFEEFFFFFFFFFEFCEFFFCAAC?EF??AC???0*:?C*:::?EE)0>'.42AAECEFE:*0:AAC?D'..8C?:?A)).0001*11::??8A**?A################################################################ @MISEQ03:64:000000000-A2H3D:1:1101:11958:2304 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAAGCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGTGGGGGAATTTCCTGTGTAGCGGGGAAATGCGTAGATATAGGAAGGAACACCAGGGGCGAAGGCGACCACCGGGACTGAAACTGACACTGAGGGGCGAAAGCGTGGGGGGCAAACG + ????ABBADDDDDDDDEEEEFFHHHHHIFHHIIIHFEECEFGDECECE5>C:55EEHIHIFGHFGHHHHHFHFFHHFHHHHHFBFEEDEEFFFFEFFFEFEFABEEFFFEEBEFFEFF=::AE*:AEE0?:?CFE8A>'.<?EEE??E?A??CEEF<>'.8AC?ECE)848?0**::AAC???EEE)*0)084'48<'8'882<CA).2<408?*1:??EEE############################# @MISEQ03:64:000000000-A2H3D:1:1101:19110:2311 1:N:0:TCCACAGGAGT TACAGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGTGGTTTGTTAAGTTGGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATTCAAAACTGACAAGCTAGAGTATGGTAGAGGGGGGTGGAATTTCCTGTGTAGCGGTGAAATGCGTAGATATAGGAAGGAACACCAGTGGCGAAGGCGACCACCTGGACTAAAACTGACACTGAGGGGCGAAAGCGGGGGGGGCAAACG + ????9BB?BBBBBBBBEEECFAFHHHHHHHFHHHHHHCCEFF/CDCCE>DCH5AECFHHHFHHHHHHHHHHHGFHHCFHHHHHEEEDEDEED@EEEEEEEEEEEEEEEEE;;BEEE?EEEEEE?*?CA?EE::?8'.''..?CEE*::/:?A:C?E??82?CCEEEE))4?EEEEA:?*80?AEEC################################################################# """ # For reference. Data used to make the 'joined_reads' reference string. reverse_reads = """@MISEQ03:64:000000000-A2H3D:1:1101:14358:1530 2:N:0:TCCACAGGAGT ACGGACTACAAGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGGATTTCACATCCAACTTAACAACCCACATACCCGCCTTTTCGCCCAGGTAATCC + ?????@@BDDBDDDBBCFFCFFHIIIIIIIIFGHHHHEHHHIIIHHHHHFHIIHIGHHIDGGHHHHIIIIICEFHIHHCDEHHHHHHFHHCFHDF?FHHFHHHFFDFFFDEDDD..=DDDE@<BFEEFCFFCECE==CACFE?*0:*CCAA?:*:*:0*A?A80:???A?*00:**0*1*:C??C?A?01*0?);>>'.8::A?############################################### @MISEQ03:64:000000000-A2H3D:1:1101:14206:1564 2:N:0:TCCACAGGAGT ACGGACTACAGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGTGCATGAGCGTCAGTGTTAACCCAGGGGGCTGCCTTCGCCATTGGTATTCCTCCACATCTCTACGCATTTCACTGCTACACGTGGAATTCTACCCCCCTCTGCTACACTCTAGCCTTGTAGTTTCAAACGCAGTTCCCAGGTTGAGCCCGGGGCTTTCACATCTGCCTTACAAAACCGCCTGCGCACGCTTTACGCCCCGTAATTC + ?????@@BDDBDDD?@CFFFFFHHHHHFFHHHHHHHHHHH@FFHEDFFH@FHBGCDHHHBFHHHHHHHEHHHHDCCEFFDFFFEE:=?FF?DFDFDFFF==BEE=DBDDEEEEEB,4??EE@EEE,3,3*3,?:?*0ACCEDD88:***?*0:*0***0*?C?00:AE:?EE:*A8'.?:CAA?A80*0*??AA88;28;C################################################## @MISEQ03:64:000000000-A2H3D:1:1101:14943:1619 2:N:0:TCCACAGGAGT ACGGACTACAGGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCAAGGTTGAGCCCGGGGCTTTCACATCCAACTTACAAAACCACCTACCCGACCTTTACGCCCAGAAATTC + ?????@@BDDDDDD?AFFFFFFIIHHIHIIHIIIIHIHHHHHHHHHHHHHHHHHHIHHHIIHHIHIIIIII?EFEGHHHHHIIHHDHHFD@FFEHFHFHFHFHFFFFFFFFEEEEFFFDEB<E@EFEEABA=B=CAEFEEFEA?A:*AC::??:**10??:00::*??EC*?:?C*::A*?C*1:8A################################################################ @MISEQ03:64:000000000-A2H3D:1:1101:15764:1660 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTATCTAATCCTGTTTGCTCCCCTAGCTTTCGCACCTCAGCGTCAGTACCGGGCCAGTGAGCCGCCTTCGCCACTGGTGTTCTTGCGAATATCTACGAATTTCACCTCTACACTCGCAGTTCCACTCACCTCTCCCGGACTCAAGACCGCCAGTACCAAAGGCAGTTCTGGAGTTGAGCTCCAGGTTTTCACCCCTGCTTTAAAAATCCCCCAACGCGGCCTTTCCCCCCAGTGACTC + ?????@=BB?BBBB<?>ACFFCECFCHCFHH=CGHHDFH=E?ACDEHHCCFFGHHDHH@CBEFHHCHHHF,5@?DF)4<C3D4DD+=,BD5;DE=DBDE=<E<;?E?B;3?;A?;;;EBBC:??EEEEE?;AA*:A??################################################################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:15211:1752 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGGATTTCCCATACAACTTAACAAACCACTTACGCGGGTTTTCGCCCCACAAATTC + ?????@@BB-<@BBBBEA?FFFA8ACFCBHHHGHHHHBHHHHFCDDD7CHHFE?CCDDCFGBHHHGGHFGFGFFHFDCDHHC?=CDHFFDCDDDF,EFF5?BFEDBBDB@@EEACCE;,?::@BEEEEACC*??//:AA*8AAAEE?ECC##################################################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:15201:1774 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTAAGCCCGGGGATTTCCAATCCAACTAAACAAAACACACACCCGCTCTTTACGCCCACCATTTC + ?????@=BBBBBBB<=CFFFFFFHFCFCEHHDGHHEFEHHHHHHHHHHHFHHGC-AEGFCGHHHFFHFHHBFGDEDDCEDDH+DDDHHF,,7D@DFDFFFBFFEDEDEEDE:@:B?C;,3@<><EEEE*BEEC?E*0AEEEEE*8*:CCE:CA*?*A?:AAA######################################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:15976:1791 2:N:0:TCCACAGGAGT ACGGACTACAAGGGTTTCTAATCCCGTTTGCTCCCCTAGCTTTCGCACCTCAGCGTCAGAAATGGACCAGAGAGCCGCCTTCGCCACCGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGGTTTTCCAATCCAATTTAACGACCAACCACGCGGCGCTTTAGGCCCGGTAATGC + ?<???@=BBBBBBB556CFFBCEFFEHHHHHHHHHE=EHHHHHHHHHHHHHHHFHHEDCGFHHHHHHHHH;A?EFHHHHHHHHH+=EHHC)8@+?BFFFDFEEEEE;DDEEEEBCEECEEEBEEEEEEEEEEE:?*/:ACEE)*8*:C:A*0?:A*:C?A:?**:AECE?*?:*:C:????C##################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:16031:1840 2:N:0:TCCACAGGAGT ACGGACTACTGGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTTAACAATACTCTAGCTTGTCAGTTTTAAATGCAGTCCCCAGGTTGAGCCCGGGGCTTTCACATCAAATTTACAAAACCACCCACGCGCGTTCTACGCCGGACAATCC + ?????==<BBBBBBBBFFFFF?FFF?FFFHHFEFFHHHH:@>CHEDHHHFFFGBCCDDFGGHHHHEHHHHH5AE+C*>==+EDHHDEFCFCDF3@.D=,CFH=,@,4DFFE:=DDDDEB:)1:1;;?B;BE;??,?EE;AEE??**0*/:0??:***:?E*:8?A*:CEE################################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:12964:1852 2:N:0:TCCACAGGAGT ACGGACTACTCGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCAACCACCCTCTACCATACTCTAGCTTGTAAGTTTTGAATGCAGTTCCAAGGTTGAGCCCGGGGCTTTCACACCCAACTTAACAACCCACCTACGCGGCATTTACGCCCACTACTTC + ?????@=BBBB9?=55AACCC?ECFFFHB>FFHGFHFHHHHHHHHHHHHFHHHGGGHHHGGHHHHHHDDFEGH;EBCEHD+AFE@C+@F=.7D+@CDCFFHHFFFD?DF@E+=:BDDB;D=@BE?BCE*,33,,?,3;;:?).0**::***0/*/0A??:*:****00/**8*0?AE:?AAC**0):??C############################################################# @MISEQ03:64:000000000-A2H3D:1:1101:17245:1906 2:N:0:TCCACAGGAGT ACGGACTACAGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGGCTTTCAAATCCAACTTAACAAACAACCAACCGGCGCTTTACGCCCAGTAATTC + ?????@@BDDDDBDABEFFFFFHHHHHHHHGGHGHHHHHHEH@FEHEEHHHFHHH=EGHHHHDGHHHHFHHGGHHHCCEDEHHHHHHHHHDFHHF=DBDFHFD?BB.BF;@DDDD.=DD*>6)@==ABAACBB5=B,=,88A)???:E*::::??*:**1**8??CCCEE8A:A::AAACAC??A)1:0**1*)48;'42A?EA**1?*1*0::??:ACEF############################## @MISEQ03:64:000000000-A2H3D:1:1101:18171:1983 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTTTCTAATCCTGTTCGCTCCCCACGCTTTCGCGCCTGAGCGTCAGGTAAGGCCCAGAGATCCGCCTTCGCCACCGGTGTTCCTCCTGATATCTGCGCATTTCACCGCTACACCAGGAATTCCGATCTCCCCTACATACCTCTAGCCGGGCAGTATCGGATGCAGACCCGAGGTTGAGCCCCGGGATTTCACATCGGCTTACCAAAGCGCCCGGCGCCCCCTTTACGCCCCAGAAACC + ?????@@BDBDDDD=BCFFFFFIIIIHHFEHHHHIHIHHHEFCGDEHHHEFFEGC>EEHI?EHHGHHHHFH+C=,,?FHDDHFEE@EFE=1;A;EECCE==BEB,BBC=@@<?EE:?E:8>24;:CEAA8?CC*??:0?;*1?AE?CE*10:0*1:CAA*;22;2A##################################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:14225:2009 2:N:0:TCCACAGGAGT ACGGACTACAGGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGGCTTTCACATCCAACTTAACAAACAACCACGCCGCGCTTTAGCCCAGGTAATTC + ?????@@BDDDDDD??CFFFFFHIHHHHIIIIHIIHIHHHHHIHHHHHHFFHHIHHHIHHHHHIIHIHIIIFFFEGHHEDEHHHHDHHHHCFFDFFHHHHHHFFFFFFF@EDEED=DDEED@EBFCEEEFECCCEEEFB<CA888:AEEFEFEA??CCEFF:?:ACCFFE?E:AC?:*:?EFE*:):???::A).;D>D>8:?################################################ @MISEQ03:64:000000000-A2H3D:1:1101:16656:2052 2:N:0:TCCACAGGAGT ACGGACTACCCGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCCCCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCAAGGTTGAGCCCGGGGCTTTCACACCCAACTTAACAAACCACCTACGCGCGCTTTACGCCCAGCATTTC + ?????@@BDDDDDD<@CFFFFFIHHFHHFHHHHHHHIHHHHHFHCEHHHHIIFHHAFHHHFFHIIHHIIIHGHFEH<DDEDH;DEHHHHHFFH;FFHFHFFFFD?FBFF=BDEDDDFEEAE@BEFFFF<BE=B,=,5?*).;>8A:*:::?E?*::A::?AE8AEFEEEC?A:CE?AEA:EF*008:?EF*:C)8;D228A0:??:*.8A8):*:*1::CE############################## @MISEQ03:64:000000000-A2H3D:1:1101:18209:2060 2:N:0:TCCACAGGAGT ACGGACTACTAGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGCGTCAATACTTGTCCAGCGAGTCCCCTTCGCCACTGGTGTTCTTCGGAATATCTACGAATTTCACCTCTACACCCGGAATTCCACTCCCCCTTCCAAGATTCCAGCTTAGCAGTTTCAAGGGCAGTTCCGGGGTTGGCACCCGGGATTTCACCCCTGCCTTGCTCAACCCCCCACGGGGCCTTTACCCCCAGCATTCC + =9<=9<7<@@@@@@<@A8A>C>8E>-8AE;C99CEEECC>>EECE@CCDE,C@E++5>E-A=E-C@@=@5@C>C<D-5A5CC<CD+<4DE3=<C+4==+<@D++2:9DEE1<9DE######################################################################################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:13824:2095 2:N:0:TCCACAGGAGT ACGGACTACCAGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCGTCTCAGCGTCAGTAACGTCCCAGCGAGCTGCCTTCGCAATGGGTGTTCCTCCTGATATCTGCGCATTTCACCGCTACACCAGGAATTCCACTCCCCCCTTCCGTACCCTAGCCCGACAGTACCCCCCGGCTTCCGAGGCTTGACCCCCCGCCTTTCACACCGGACTTACCGGGCCGCCTACCCGGCCTTTCGCCCCACCGTTTC + ??<??@@BBBBBBBBBCFCFFFHHHHHHBHHGHHHHHCHHEH>GDEHCA:DFGHHEEEEFFHHHHHHDHED7<CHEGHFFDFFHEDHHHDDDE@D??DD;=B,,5B,,56)):?;BEE?*1::):?**8AEAC*?*:?################################################################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:17839:2106 2:N:0:TCCACAGGAGT ACGGACTACAAGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGAAGTTCCAAGTTTGAGCCCGGGGCTTTCACATCCAATTTAAAAAACAACCAACGCGCGCTTCACCCCAGGTAATAC + ?????@@BBBBBBB<5ACFFFFHHHHHHHHHHHHHHHHHHHHFFHHHHHHHHHGHHHFHGHHHHFGHHHHH?EFEECCEEEHHHEHHHHHDFHDFDHDHHHHFFDFFFHFEDDDD,5DD@BB<EEEEECBB?B3B;,?,3?E8CE?*?A*/:/:::??AE::**0:AEE################################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:17831:2124 2:N:0:TCCACAGGAGT ACGGACTACAAGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTCGAATGCAGTTCCCAGGTTGAGCCCGGGCCTTCAACCTCCACTTTACAAAACAACCAAACGCCGCTTACCGCCACGAAATCC + ?????@=BBBBBBB5<CFFFFCFHHHHHFHHHHHHHHHHHHHFHEEHHEHFGHGHFGDF?EEFHHHHDGHH=EHEGCCEEEHHHHHH@FFCFH+CFHCFHHHHHFFFHHFE:DDD,=EBDEBE<EEEE?;B?B?E?CEEEEEE8A?CC####################################################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:12555:2129 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCCCGTCAGTTTTGAATGCATTTCCCAGGTTGAGCCCGGGGCTTTCAAACCCAACTAAACAAACAACCAACGCGCGTTTTCCGCCACGTAATTC + ?????@@BDDDDDDDDEFFFFFHHHFHIIIHHHIIHHHHHEHFHEHHHHIFGHHIHIHFHI=FHFIHIIIHDFHHHHEHEDHHHHHHHHHHHH@FBFFFFFFFEFDEFE6@:@ACBEFFEEB@BCB=A<<A?C:A::C8AEE)0?A*?A:*:**10?1**1.4A88?EE?################################################################################# @MISEQ03:64:000000000-A2H3D:1:1101:13627:2170 2:N:0:TCCACAGGAGT ACGGACTACTAGGGTATCTAATCCCGTTTGCTACCCTAGCTTTCGCACCTCAGTGTCAGATTGGGTCCAGTGAGCCGCTTTCGCCACCGGTGTTCCTCCAGATATCTACGCATTTCACCGCTCCACCTGGAGTTCCGCTCACCCCTACCCACCTCGAGCCGGCCAGTATCCCGCGCAATTCCCCGTTTGAGCCGGGGGTTTTCCCAAGGGTCTTAACAGCCCACCTACGTCCCCTTTATGCCAGGTAATTC + ?????@=BD?BBDD?58ACFFCHHHHHHHHFGHHHEEFHHHHHCDEEEECFDGFHDGHHHHFFFHEHHHHHHHFFFHAEHFFEHHHHFHH<DE:C--@F-CCF=,,4BDFE:@E,BBED@:)2>=C?;BC=?C,==*3.84?EC?88A8A:A?*8?############################################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:11781:2223 2:N:0:TCCACAGGAGT ACGGACTACTGGGGTATCTAATCCTGTTCGCTCCCCATGCTTTCGCTCCTCAGCGTCAGTTAATGCCCAGAGACCTGCCTTCGCCATCGGTGTTCCTCCTGATATCTGCGCATTTCACCGCTACACCAGGAATTCCAATCTCCCCTACATCACTCTAGTCTGCCCGTACCCACCGCAGATCCGGAGTTGAGCCCCGGACTTTCACGGCAGACGCGCAAACCGCCCACAGAGCTCTTTCCCCCCAAAAATCC + ?????@@BDDDDDDBDCFFFFFHHHHHHHHHHHEHEHDFHHHHHHEDEEHHHFHHHHEHHHHHFGHHHHDD;EFFHCFECAGFEEE+@E@3?E:DFFFHBDHC?BBDFFE8;=DD,,=DEE<@),==?B*44=,=,4**0*0:CA*A?::*0::?0AC:CE*?:*8.4AE?*8?)'82;*?0?#################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:17996:2254 2:N:0:TCCACAGGAGT ACGGACTACCAGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTGGAGCCCGGGGCTTTACAATCAAACTTAACAAACCCCCTACGCGCGCTTTAGCCCCACAATTTC + ?9???@@BBDDDDD<BEFFFFFHHHHCEFHGGHHHHHAEHEHFHEEHHCBFHFFHEGHFCGGFCGHHFHHFGHHHHDHHECEDEHDDHH?@?FDFDHHHFHFFDDHDFFFEEEEEDEDB=>BBEE=BECEEEE,B=?CBACE)*0**?C?*:*0:*:?:A:??**::?E**80::::??:CAC:C8C################################################################ @MISEQ03:64:000000000-A2H3D:1:1101:13712:2276 2:N:0:TCCACAGGAGT ACGGACTACTGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGAAGTTCCAAGGTTAAGCCGGGGGCTTTCACATCCAACTAACCAAACCACTAACCGCCGCTTTAGGCCCAGCAATTC + ?????@@BDDDDDDBDEFFFFFHFHHHIFFHIHIIHHEHHHHFHHHEHCFHHDFGGHIIHIHFGHHHGFHF-AEEGHHHHEGFHHHDFHB?FHEHCF?FDDFH??BFFFF=DDEEEFFEDE8>:BECCAEEAECE,ABAACEA*0**?*01?001*::*A**0:*::CE1*8:?**11:*CE##################################################################### @MISEQ03:64:000000000-A2H3D:1:1101:15819:2301 2:N:0:TCCACAGGAGT ACGGACTACCGGGGTTTCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGAAGTTCCCAGGTTGACCCCGGGGCTTTCACAGCAGCCTTAACTCACCCCCTGCCAACCCTTTACTCCCCGAAATTC + ?9???@=BDDDDDD<@CFFFFFHHHBFFHHHFGHHHHHHHEHFGEHHHHEDGD?FCGHHFHHHHHHHHBDF?FHHHFHH@DHHHH+DHHDCFHDFDFBFFDFFEDFEEDEEDEEC=CCEEEBEEFCEFEEFEE?:CEE*8CA800*:E*:AA::***1??*:**1::CF################################################################################## @MISEQ03:64:000000000-A2H3D:1:1101:11958:2304 2:N:0:TCCACAGGAGT ACGGACTACTGGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGTGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTGAGCCCGGGCCTTTAAAATCCAACTTAAAAAACAACTAACCGCCGCTTTCCGCCCAGAAATCC + ?????@@BDBDDD@@BFFFFFFHFHHHHFHHHHHHHHHHHHHHHHHHHHHFHHHHHFGH=CGEH=FHFGHFEFHEHHCEEEHHHDCEFHH.?FDFFHHHHBFHFFHFFFFEEEEEEEEEEB@EEEECE;CC?BCEEEC;;CEA*8:AE**00::C0A::?:*0*AEE?E?*A**:C?*:?:?**0)00::**?8>'8';ACA*0*0C?:?******::??E?CE########################### @MISEQ03:64:000000000-A2H3D:1:1101:19110:2311 2:N:0:TCCACAGGAGT ACGGACTACCAGGGTATCTAATCCTGTTTGCTCCCCACGCTTTCGCACCTCAGTGTCAGTATCAGTCCAGGGGGTCGCCTTCGCCACTGGTGTTCCTTCCTATATCTACGCATTTCACCGCTACACAGGAAATTCCACCACCCTCTACCATACTCTAGCTTGTCAGTTTTGAATGCAGTTCCCAGGTTAAGCCCGGGGCTTTCCAACCCAACTTAACAAACCACCTACCCCCGCTTTACGCCCAGAAATTC + ?????@=BDDDDDD<5CFFFFFHHHHHF>CGFHHHHHHHEEHFHEHHHHHHHGAFGHHHHH-5AF5AFHHD+5*5CCCDDHFFHEEHFHHBFF:BDD4?=.=DEFFEBEDEBEEECEFFEE<::CEAACE?:A*1:*C88?AE.?:*::**1:**11*01***1?C??:?0?:C:C**1*1::*:8A?10*1?########################################################## """ if __name__ == "__main__": main()
ssorgatem/qiime
tests/test_split_libraries_fastq.py
Python
gpl-2.0
96,688
#!/usr/bin/env python from __future__ import division __author__ = "Justin Kuczynski" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["Justin Kuczynski", "Jose Carlos Clemente Litran", "Rob Knight", "Greg Caporaso", "Jai Ram Rideout"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Justin Kuczynski" __email__ = "justinak@gmail.com" """Contains code for generating rarefied OTU tables at varying depth this takes an otu table and generates a series of subsampled (without replacement) otu tables. """ import os.path import numpy from numpy import inf from skbio.stats import subsample from biom.err import errstate from qiime.util import FunctionWithParams, write_biom_table from qiime.filter import (filter_samples_from_otu_table, filter_otus_from_otu_table) class SingleRarefactionMaker(FunctionWithParams): def __init__(self, otu_path, depth): """ init a singlerarefactionmaker otu_path has to be a parseable BIOM table, we just ignore any rarefaction levels beyond any sample in the data """ self.depth = depth self.otu_table = self.getBiomData(otu_path) self.max_num_taxa = -1 for val in self.otu_table.iter_data(axis='observation'): self.max_num_taxa = max(self.max_num_taxa, val.sum()) def rarefy_to_file(self, output_fname, small_included=False, include_lineages=False, empty_otus_removed=False, subsample_f=subsample): """ computes rarefied otu tables and writes them, one at a time this prevents large memory usage for depth in self.rare_depths: for rep in range(self.num_reps):""" if not include_lineages: for (val, id, meta) in self.otu_table.iter(axis='observation'): del meta['taxonomy'] sub_otu_table = get_rare_data(self.otu_table, self.depth, small_included, subsample_f=subsample_f) if empty_otus_removed: sub_otu_table = filter_otus_from_otu_table( sub_otu_table, sub_otu_table.ids(axis='observation'), 1, inf, 0, inf) self._write_rarefaction(output_fname, sub_otu_table) def _write_rarefaction(self, fname, sub_otu_table): """ depth and rep can be numbers or strings """ if sub_otu_table.is_empty(): return write_biom_table(sub_otu_table, fname) class RarefactionMaker(FunctionWithParams): def __init__(self, otu_path, min, max, step, num_reps): """ init a rarefactionmaker otu_path is path to .biom otu table we just ignore any rarefaction levels beyond any sample in the data """ self.rare_depths = range(min, max + 1, step) self.num_reps = num_reps self.otu_table = self.getBiomData(otu_path) self.max_num_taxa = -1 tmp = -1 for val in self.otu_table.iter_data(axis='observation'): if val.sum() > tmp: tmp = val.sum() self.max_num_taxa = tmp def rarefy_to_files(self, output_dir, small_included=False, include_full=False, include_lineages=False, empty_otus_removed=False, subsample_f=subsample): """ computes rarefied otu tables and writes them, one at a time this prevents large memory usage""" if not include_lineages: for (val, id, meta) in self.otu_table.iter(axis='observation'): try: del meta['taxonomy'] except (TypeError, KeyError) as e: # no meta or just no taxonomy present pass self.output_dir = output_dir for depth in self.rare_depths: for rep in range(self.num_reps): sub_otu_table = get_rare_data(self.otu_table, depth, small_included, subsample_f=subsample_f) if empty_otus_removed: sub_otu_table = filter_otus_from_otu_table( sub_otu_table, sub_otu_table.ids(axis='observation'), 1, inf, 0, inf) self._write_rarefaction(depth, rep, sub_otu_table) if include_full: self._write_rarefaction('full', 0, self.otu_table) def rarefy_to_list(self, small_included=False, include_full=False, include_lineages=False): """ computes rarefied otu tables and returns a list each element is (depth, rep, sample_ids, taxon_ids, otu_table) depth is string "full" for one instance """ if include_lineages: otu_lineages = self.lineages else: otu_lineages = None res = [] for depth in self.rare_depths: for rep in range(self.num_reps): sub_otu_table = get_rare_data(self.otu_table, depth, small_included) res.append([depth, rep, sub_otu_table]) if include_full: res.append(['full', 0, self.otu_table]) return res def _write_rarefaction(self, depth, rep, sub_otu_table): """ depth and rep can be numbers or strings """ if sub_otu_table.is_empty(): return fname = 'rarefaction_' + str(depth) + '_' + str(rep) + '.biom' fname = os.path.join(self.output_dir, fname) write_biom_table(sub_otu_table, fname) def get_rare_data(otu_table, seqs_per_sample, include_small_samples=False, subsample_f=subsample): """Filter OTU table to keep only desired sample sizes. - include_small_sampes=False => do not write samples with < seqs_per_sample total sequecnes - otu_table (input and out) is otus(rows) by samples (cols) - no otus are removed, even if they are absent in the rarefied table""" with errstate(empty='raise'): if not include_small_samples: otu_table = filter_samples_from_otu_table( otu_table, otu_table.ids(), seqs_per_sample, inf) # subsample samples that have too many sequences def func(x, s_id, s_md): if x.sum() < seqs_per_sample: return x else: return subsample_f(x.astype(int), seqs_per_sample) subsampled_otu_table = otu_table.transform(func, axis='sample') return subsampled_otu_table
antgonza/qiime
qiime/rarefaction.py
Python
gpl-2.0
6,795
import os import base64 import shutil import gettext import unittest from test.test_support import run_suite # TODO: # - Add new tests, for example for "dgettext" # - Remove dummy tests, for example testing for single and double quotes # has no sense, it would have if we were testing a parser (i.e. pygettext) # - Tests should have only one assert. GNU_MO_DATA = '''\ 3hIElQAAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== ''' UMO_DATA = '''\ 3hIElQAAAAACAAAAHAAAACwAAAAFAAAAPAAAAAAAAABQAAAABAAAAFEAAAAPAQAAVgAAAAQAAABm AQAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAYWLDngBQcm9qZWN0LUlkLVZlcnNpb246IDIuMApQTy1S ZXZpc2lvbi1EYXRlOiAyMDAzLTA0LTExIDEyOjQyLTA0MDAKTGFzdC1UcmFuc2xhdG9yOiBCYXJy eSBBLiBXQXJzYXcgPGJhcnJ5QHB5dGhvbi5vcmc+Ckxhbmd1YWdlLVRlYW06IFhYIDxweXRob24t ZGV2QHB5dGhvbi5vcmc+Ck1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFp bjsgY2hhcnNldD11dGYtOApDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiA3Yml0CkdlbmVyYXRl ZC1CeTogbWFudWFsbHkKAMKkeXoA ''' MMO_DATA = '''\ 3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6 NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA= ''' LOCALEDIR = os.path.join('xx', 'LC_MESSAGES') MOFILE = os.path.join(LOCALEDIR, 'gettext.mo') UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo') MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo') try: LANG = os.environ['LANGUAGE'] except: LANG = 'en' class GettextBaseTest(unittest.TestCase): def setUp(self): if not os.path.isdir(LOCALEDIR): os.makedirs(LOCALEDIR) fp = open(MOFILE, 'wb') fp.write(base64.decodestring(GNU_MO_DATA)) fp.close() fp = open(UMOFILE, 'wb') fp.write(base64.decodestring(UMO_DATA)) fp.close() fp = open(MMOFILE, 'wb') fp.write(base64.decodestring(MMO_DATA)) fp.close() os.environ['LANGUAGE'] = 'xx' def tearDown(self): os.environ['LANGUAGE'] = LANG shutil.rmtree(os.path.split(LOCALEDIR)[0]) class GettextTestCase1(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir self.mofile = MOFILE gettext.install('gettext', self.localedir) def test_some_translations(self): eq = self.assertEqual # test some translations eq(_('albatross'), 'albatross') eq(_(u'mullusk'), 'bacon') eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') eq(_(ur'nudge nudge'), 'wink wink') def test_double_quotes(self): eq = self.assertEqual # double quotes eq(_("albatross"), 'albatross') eq(_(u"mullusk"), 'bacon') eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') eq(_(ur"nudge nudge"), 'wink wink') def test_triple_single_quotes(self): eq = self.assertEqual # triple single quotes eq(_('''albatross'''), 'albatross') eq(_(u'''mullusk'''), 'bacon') eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') eq(_(ur'''nudge nudge'''), 'wink wink') def test_triple_double_quotes(self): eq = self.assertEqual # triple double quotes eq(_("""albatross"""), 'albatross') eq(_(u"""mullusk"""), 'bacon') eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') eq(_(ur"""nudge nudge"""), 'wink wink') def test_multiline_strings(self): eq = self.assertEqual # multiline strings eq(_('''This module provides internationalization and localization support for your Python programs by providing an interface to the GNU gettext message catalog library.'''), '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH trggrkg zrffntr pngnybt yvoenel.''') def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface fp = open(self.mofile, 'rb') t = gettext.GNUTranslations(fp) fp.close() # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install(unicode=True) eq(_('mullusk'), 'bacon') class GettextTestCase2(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.localedir = os.curdir # Set up the bindings gettext.bindtextdomain('gettext', self.localedir) gettext.textdomain('gettext') # For convenience self._ = gettext.gettext def test_bindtextdomain(self): self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir) def test_textdomain(self): self.assertEqual(gettext.textdomain(), 'gettext') def test_some_translations(self): eq = self.assertEqual # test some translations eq(self._('albatross'), 'albatross') eq(self._(u'mullusk'), 'bacon') eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') eq(self._(ur'nudge nudge'), 'wink wink') def test_double_quotes(self): eq = self.assertEqual # double quotes eq(self._("albatross"), 'albatross') eq(self._(u"mullusk"), 'bacon') eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') eq(self._(ur"nudge nudge"), 'wink wink') def test_triple_single_quotes(self): eq = self.assertEqual # triple single quotes eq(self._('''albatross'''), 'albatross') eq(self._(u'''mullusk'''), 'bacon') eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') eq(self._(ur'''nudge nudge'''), 'wink wink') def test_triple_double_quotes(self): eq = self.assertEqual # triple double quotes eq(self._("""albatross"""), 'albatross') eq(self._(u"""mullusk"""), 'bacon') eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') eq(self._(ur"""nudge nudge"""), 'wink wink') def test_multiline_strings(self): eq = self.assertEqual # multiline strings eq(self._('''This module provides internationalization and localization support for your Python programs by providing an interface to the GNU gettext message catalog library.'''), '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH trggrkg zrffntr pngnybt yvoenel.''') class PluralFormsTestCase(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) self.mofile = MOFILE def test_plural_forms1(self): eq = self.assertEqual x = gettext.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = gettext.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros') def test_plural_forms2(self): eq = self.assertEqual fp = open(self.mofile, 'rb') t = gettext.GNUTranslations(fp) fp.close() x = t.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = t.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros') def test_hu(self): eq = self.assertEqual f = gettext.c2py('0') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") def test_de(self): eq = self.assertEqual f = gettext.c2py('n != 1') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") def test_fr(self): eq = self.assertEqual f = gettext.c2py('n>1') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") def test_gd(self): eq = self.assertEqual f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_gd2(self): eq = self.assertEqual # Tests the combination of parentheses and "?:" f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") def test_lt(self): eq = self.assertEqual f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111") def test_ru(self): eq = self.assertEqual f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222") def test_pl(self): eq = self.assertEqual f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222") def test_sl(self): eq = self.assertEqual f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3') s = ''.join([ str(f(x)) for x in range(200) ]) eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333") def test_security(self): raises = self.assertRaises # Test for a dangerous expression raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)") class UnicodeTranslationsTest(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) fp = open(UMOFILE, 'rb') try: self.t = gettext.GNUTranslations(fp) finally: fp.close() self._ = self.t.ugettext def test_unicode_msgid(self): unless = self.failUnless unless(isinstance(self._(''), unicode)) unless(isinstance(self._(u''), unicode)) def test_unicode_msgstr(self): eq = self.assertEqual eq(self._(u'ab\xde'), u'\xa4yz') class WeirdMetadataTest(GettextBaseTest): def setUp(self): GettextBaseTest.setUp(self) fp = open(MMOFILE, 'rb') try: try: self.t = gettext.GNUTranslations(fp) except: self.tearDown() raise finally: fp.close() def test_weird_metadata(self): info = self.t.info() self.assertEqual(info['last-translator'], 'John Doe <jdoe@example.com>\nJane Foobar <jfoobar@example.com>') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(GettextTestCase1)) suite.addTest(unittest.makeSuite(GettextTestCase2)) suite.addTest(unittest.makeSuite(PluralFormsTestCase)) suite.addTest(unittest.makeSuite(UnicodeTranslationsTest)) suite.addTest(unittest.makeSuite(WeirdMetadataTest)) return suite def test_main(): run_suite(suite()) if __name__ == '__main__': test_main() # For reference, here's the .po file used to created the GNU_MO_DATA above. # # The original version was automatically generated from the sources with # pygettext. Later it was manually modified to add plural forms support. ''' # Dummy translation for the Python test_gettext.py module. # Copyright (C) 2001 Python Software Foundation # Barry Warsaw <barry@python.org>, 2000. # msgid "" msgstr "" "Project-Id-Version: 2.0\n" "PO-Revision-Date: 2003-04-11 14:32-0400\n" "Last-Translator: J. David Ibanez <j-david@noos.fr>\n" "Language-Team: XX <python-dev@python.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-1\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: pygettext.py 1.1\n" "Plural-Forms: nplurals=2; plural=n!=1;\n" #: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37 #: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92 #: test_gettext.py:98 msgid "nudge nudge" msgstr "wink wink" #: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34 #: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95 msgid "albatross" msgstr "" #: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36 #: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97 msgid "Raymond Luxury Yach-t" msgstr "Throatwobbler Mangrove" #: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35 #: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90 #: test_gettext.py:96 msgid "mullusk" msgstr "bacon" #: test_gettext.py:40 test_gettext.py:101 msgid "" "This module provides internationalization and localization\n" "support for your Python programs by providing an interface to the GNU\n" "gettext message catalog library." msgstr "" "Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n" "fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n" "trggrkg zrffntr pngnybt yvoenel." # Manually added, as neither pygettext nor xgettext support plural forms # in Python. msgid "There is %s file" msgid_plural "There are %s files" msgstr[0] "Hay %s fichero" msgstr[1] "Hay %s ficheros" ''' # Here's the second example po file example, used to generate the UMO_DATA # containing utf-8 encoded Unicode strings ''' # Dummy translation for the Python test_gettext.py module. # Copyright (C) 2001 Python Software Foundation # Barry Warsaw <barry@python.org>, 2000. # msgid "" msgstr "" "Project-Id-Version: 2.0\n" "PO-Revision-Date: 2003-04-11 12:42-0400\n" "Last-Translator: Barry A. WArsaw <barry@python.org>\n" "Language-Team: XX <python-dev@python.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 7bit\n" "Generated-By: manually\n" #: nofile:0 msgid "ab\xc3\x9e" msgstr "\xc2\xa4yz" ''' # Here's the third example po file, used to generate MMO_DATA ''' msgid "" msgstr "" "Project-Id-Version: No Project 0.0\n" "POT-Creation-Date: Wed Dec 11 07:44:15 2002\n" "PO-Revision-Date: 2002-08-14 01:18:58+00:00\n" "Last-Translator: John Doe <jdoe@example.com>\n" "Jane Foobar <jfoobar@example.com>\n" "Language-Team: xx <xx@example.com>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-15\n" "Content-Transfer-Encoding: quoted-printable\n" "Generated-By: pygettext.py 1.3\n" '''
xbmc/atv2
xbmc/lib/libPython/Python/Lib/test/test_gettext.py
Python
gpl-2.0
17,583
""" Defines the URL routes for this app. NOTE: These views are deprecated. These routes are superseded by ``/api/user/v1/accounts/{username}/image``, found in ``openedx.core.djangoapps.user_api.urls``. """ from django.conf import settings from django.conf.urls import url from .views import ProfileImageRemoveView, ProfileImageUploadView urlpatterns = [ url( r'^v1/' + settings.USERNAME_PATTERN + '/upload$', ProfileImageUploadView.as_view(), name="profile_image_upload" ), url( r'^v1/' + settings.USERNAME_PATTERN + '/remove$', ProfileImageRemoveView.as_view(), name="profile_image_remove" ), ]
BehavioralInsightsTeam/edx-platform
openedx/core/djangoapps/profile_images/urls.py
Python
agpl-3.0
665