本文整理汇总了Python中validator.Validator类的典型用法代码示例。如果您正苦于以下问题:Python Validator类的具体用法?Python Validator怎么用?Python Validator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Validator类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_surplus
def test_surplus(self):
simple_validator = Validator({'test': 'hello'})
error_bucket = simple_validator.validate(
{'test': 'hello',
'wow so': 'doge'})
self.assertEquals(error_bucket.errors,
{'surplus_key': {'': SurplusKey('wow so', 'doge')}})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:7,代码来源:test_dict.py
示例2: main
def main():
"""
To run the UF model.
"""
# k: number of folds for cross validation.
k = 10
input_filename = sys.argv[1]
if_average = bool(int(sys.argv[2]))
nums = []
with open(input_filename, 'r') as f:
for line in f:
nums.append(line.strip().split(" "))
for city in nums[0]:
ratings_filename = "../data/reviews" + city
network_filename = "../data/network" + city + "b.csv"
# Creating an object for my model
val = Validator(ratings_filename, network_filename, k, 0.)
for llimit in map(int, nums[1]):
for ulimit in map(int, nums[2]):
uf = Using_Friends(val.get_network(),
n_ratings_lower_limit=llimit, n_ratings_upper_limit=ulimit,
if_average=if_average)
(val_results, ratios) = val.validate(uf, run_all=True)
print 'validation results: '
print city, llimit, ulimit, ratios, val_results, \
np.mean(val_results)
开发者ID:suhanree,项目名称:network-recommender,代码行数:29,代码来源:run_nf.py
示例3: test_missing_custom_error
def test_missing_custom_error(self):
validator = Validator(
{'test': CustomMissingkeyError('MISSINGKEY!', 'hello')})
error_bucket = validator.validate({})
self.assertEquals(error_bucket.errors,
{'missing_key': {'': MissingKey('test', 'hello')}})
self.assertEquals(error_bucket.custom_errors, ['MISSINGKEY!'])
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:7,代码来源:test_dict.py
示例4: install_service
def install_service(self, service_name, service_code):
"""
Installs new service code in the execution environment.
@type service_name: str
@param service_name: The name of the service. This name must be on
the form name1.name2.name3, e.g., daimi.imaging.scale
@type service_code: str
@param service_code: The code of the service. The code will be validated
by the Locusts code validator and thus must adhere to a lot of different
rules.
@raise Exception: Raised if the code fails to validate.
"""
# Check the validity of the service name.
if not Jailor.valid_service_name(service_name):
self.__logger.info('Service with invalid name given (%s)'%service_name)
raise Exception('Invalid service name.')
# Check that the service is not already installed.
if self.registry.has_service(service_name):
self.__logger.info('Attempt to re-install service.')
raise Exception('Service %s already installed.'%service_name)
# Avoid malicious attempts to push __init__.py this way...
if service_name[-8:] == '__init__':
self.__logger.info('Attempt to hack by pushing __init__.py')
raise Exception('Stop trying to hack me!')
# Validate the code.
v = Validator(service_code)
try:
v.validate()
except ValidationError, error:
self.__logger.info('Validation error: %s'%error.message)
raise Exception(error.message)
开发者ID:Danaze,项目名称:scavenger-cf,代码行数:34,代码来源:jailor.py
示例5: test_str
def test_str(self):
hello_validator = Validator('hello')
self.assertTrue(hello_validator.validate('hello').isEmpty())
error_bucket = hello_validator.validate('Not hello')
self.assertEquals(error_bucket.errors,
{'not_equal': {'': NotEqual('hello', 'Not hello')}})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:7,代码来源:test_comparable.py
示例6: main
def main():
"""
To run the CF model.
"""
input_filename = sys.argv[1]
user_bias = bool(int(sys.argv[2]))
item_bias = bool(int(sys.argv[3]))
nums = []
with open(input_filename, 'r') as f:
for line in f:
nums.append(line.strip().split(" "))
for city in nums[0]:
# Filenames needed.
ratings_filename = "../data/reviews" + city
network_filename = "../data/network" + city + "b.csv"
# Create the Validator object.
# k: number of folds for cross validation.
k = 10
# Creating an object for my model
val = Validator(ratings_filename, network_filename, k, 0.)
for nfeat in map(int, nums[1]):
for lrate in map(float, nums[2]):
for rparam in map(float, nums[3]):
my_rec = Matrix_Factorization(n_features=nfeat,
learn_rate=lrate,
regularization_param=rparam,
optimizer_pct_improvement_criterion=2,
user_bias_correction=user_bias,
item_bias_correction=item_bias)
(val_results, ratios) = val.validate(my_rec, run_all=True)
print 'validation results: '
print city, nfeat, lrate, rparam, ratios, val_results, \
np.mean(val_results)
开发者ID:suhanree,项目名称:network-recommender,代码行数:34,代码来源:run_cf.py
示例7: testBadTitleNumber
def testBadTitleNumber(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('<h1>Foo v. Bar - U.S. 200 (2013)</h1>')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a title containing an improperly'
'formatted case number.'):
v.validateTitleParts()
开发者ID:molly,项目名称:brandeis,代码行数:7,代码来源:testvalidator.py
示例8: test_str_list_one_int
def test_str_list_one_int(self):
str_validator = Validator([str])
test_data = ['hello', 'oh no', 777, 'doge']
error_bucket = str_validator.validate(test_data)
error_expected = WrongType(int, str)
self.assertEquals(error_bucket.errors,
{'wrong_type': {'2': error_expected}})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:7,代码来源:test_iterableschema.py
示例9: testIdentifyCaseGroup
def testIdentifyCaseGroup(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\t\t\t<h1>Group of Cases - 100 U.S. 200 (2013)</h1>\t\t\t')
v = Validator('buffer.txt')
with self.assertRaises(GroupedCase, msg='Validator failed to identify a group of cases'
' as such.'):
v.validateTitleParts()
开发者ID:molly,项目名称:brandeis,代码行数:7,代码来源:testvalidator.py
示例10: test_and
def test_and(self):
def always_true(data):
return True
def len_lt_7(data):
return len(data) < 7
def always_false(data):
return False
lt7_validator = Validator(And(always_true, len_lt_7))
self.assertTrue(lt7_validator.validate('hello').isEmpty())
errorbucket = lt7_validator.validate('solongmorethan7')
self.assertEquals(
errorbucket.errors,
{'func_fail': {'': FuncFail(len_lt_7, 'solongmorethan7')}})
lt7_falsy_validator = Validator(And(always_true, always_false,
len_lt_7))
errorbucket = lt7_falsy_validator.validate('solongmorethan7')
self.assertEquals(errorbucket.errors, {
'func_fail': {
'': OrderedList(FuncFail(len_lt_7, 'solongmorethan7'),
FuncFail(always_false, 'solongmorethan7'))
}
})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:25,代码来源:test_and.py
示例11: testPoorlyPlacedTitle
def testPoorlyPlacedTitle(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\n\n\t\t\t\t<div></div><h1>Person v. Person - 100 U.S. 25 (2000)</h1>')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a title that was not at the '
'beginning of the file.'):
v.validateTitlePlacement()
开发者ID:molly,项目名称:brandeis,代码行数:7,代码来源:testvalidator.py
示例12: are_fields_valid
def are_fields_valid(self, f_def):
"""Returns true if the hash of field definitions are all valid."""
if not f_def:
return True
if not Validator:
logging.warn("Can't validate data: python-validator not installed.")
return True
data = self.field_data(f_def)
errors = None
field_list = []
# Translate to xsd style syntax by transposing
# the name into the hash from the key.
for name in f_def.keys():
field = f_def[name]
field['name'] = name
field['type'] = field.get('type', 'string')
field_list.append( field )
validator = Validator( { 'root' : field_list } )
# try:
errors = validator.validate( data )
# except Exception, error:
# logging.warn("Couldn't validate page, skipping validation: %s" % error)
# Collect the errors and report on what fields failed
if errors:
result = []
for err in errors.keys():
if errors[err]:
result.append(err)
return result
# Otherwise we pass!
return True
开发者ID:doctormo,项目名称:gtkme,代码行数:31,代码来源:forms.py
示例13: main
def main():
import argparse
parser = argparse.ArgumentParser(
description='Check for common mistakes in LaTeX documents.')
parser.add_argument('filenames', action='append',
help='List of filenames to check')
args = parser.parse_args()
# Count the total number of errors
num_errors = 0
for fname in args.filenames:
with open(fname, 'r') as infile:
validator = Validator()
for lineno, line in enumerate(infile):
for rule, span in validator.validate(line):
print_warning(fname, lineno, line.strip(), span, rule, args)
num_errors += 1
if num_errors > 0:
print '\nTotal of {0} mistakes found.'.format(num_errors)
return 1
else:
print 'No mistakes found.'
return 0
开发者ID:ebnn,项目名称:draftcheck,代码行数:28,代码来源:script.py
示例14: validate
def validate(self):
from validator import Validator
v = Validator(self.ui)
errors = v.validate()
if errors:
obj, msg = errors[0]
QtGui.QMessageBox.critical(self, "Error", msg)
try:
obj.setFocus()
obj.selectAll()
except: pass
return False
else:
iter = QtGui.QTreeWidgetItemIterator(self.ui.treeWidgetFiles)
while iter.value():
attachment = iter.value().attachment
if attachment.size > self.current_account.max_size_bytes:
QtGui.QMessageBox.critical(self,
"Error",
"'%s' larger than %s %s" % (attachment.name, self.current_account.max_size, self.current_account.max_size_type))
return False
iter += 1
return True
开发者ID:flaramusician,项目名称:kurir,代码行数:26,代码来源:kurir_main.py
示例15: main
def main(schema=None, output_dir=None, config_path=None):
"""
Validate the schema file and output directory parameters.
Build a tree from the schema file.
Walk the tree, calling the registered callbacks on each node.
"""
validator = Validator(schema, output_dir=output_dir)
if not validator.validate():
click.echo(validator.error['msg'])
sys.exit(1)
directory_tree = Tree(
indent_size = validator.indent_size,
output_dir = output_dir,
base_path = os.path.abspath(os.curdir)
)
directory_tree.load_data(schema)
directory_tree.build_tree()
callbacks = [ pprint_node ]
if config_path:
process_hooks = make_config_processor(config_path)
callbacks.append(process_hooks)
directory_tree.walk(callbacks=callbacks)
开发者ID:foundling,项目名称:scaffolder,代码行数:30,代码来源:superdir.py
示例16: test_email
def test_email(self):
csvfile = open('/home/clyde/lot18/email_test.csv')
v = Validator(csvfile)
v.validators = ['email']
v.prohibited_states = prohibited_states
r = v()
csvfile.close()
self.assertEqual([False,True,False], [i['valid'] for i in r])
开发者ID:amalgamatedclyde,项目名称:acme_wine,代码行数:8,代码来源:validator-test.py
示例17: testGoodTitlePlacement
def testGoodTitlePlacement(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\n\n\t\t\t\t<h1>Person v. Person - 100 U.S. 25 (2000)</h1>')
v = Validator('buffer.txt')
try:
v.validateTitlePlacement()
except:
self.fail('Validator did not pass a good title.')
开发者ID:molly,项目名称:brandeis,代码行数:8,代码来源:testvalidator.py
示例18: test_net
def test_net(self):
csvfile = open('/home/clyde/lot18/net_test.csv')
v = Validator(csvfile)
v.validators = ['ny_net']
v.prohibited_states = prohibited_states
r = v()
csvfile.close()
self.assertTrue([i['valid'] for i in r][0])
开发者ID:amalgamatedclyde,项目名称:acme_wine,代码行数:8,代码来源:validator-test.py
示例19: test_str
def test_str(self):
str_validator = Validator(str)
test_data = 'hello'
str_validator.validate(test_data)
test_error_data = 1234
self.assertErrorBucket(
str_validator, test_error_data,
errors={'wrong_type': _EBN([WrongType(int, str)])})
开发者ID:devdoomari,项目名称:pyvalidator,代码行数:8,代码来源:test_typeschema.py
示例20: testGoodTitleParts
def testGoodTitleParts(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\t\t\t\t<h1>Foo v. Bar - 100 U.S. 200 (2013)</h1><div>Extra stuff</div>')
v = Validator('buffer.txt')
try:
v.validateTitleParts()
except:
self.fail('Validator did not pass a title with good parts.')
开发者ID:molly,项目名称:brandeis,代码行数:8,代码来源:testvalidator.py
注:本文中的validator.Validator类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论