本文整理汇总了Python中bool函数的典型用法代码示例。如果您正苦于以下问题:Python bool函数的具体用法?Python bool怎么用?Python bool使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bool函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _queryapi
def _queryapi(self, method_url, get, post):
c = pycurl.Curl()
if bool(get):
query_url = method_url + '?' + urlencode(get)
else:
query_url = method_url
c.setopt(c.URL, query_url)
if bool(post):
# first clear all fields that are None
post_cleared = {}
for i in post:
if post[i] is not None:
post_cleared[i] = post[i]
postfields = urlencode(post_cleared)
c.setopt(c.POSTFIELDS, postfields)
buffer = StringIO()
c.setopt(c.WRITEFUNCTION, buffer.write)
c.setopt(c.HTTPHEADER, ['PddToken: ' + self.token])
c.perform()
http_response_code = c.getinfo(c.RESPONSE_CODE)
http_response_data = json.loads(buffer.getvalue())
c.close()
if 200 != http_response_code:
self.module.fail_json(msg='Error querying yandex pdd api, HTTP status=' + c.getinfo(c.RESPONSE_CODE) + ' error=' + http_response_data.error)
return (http_response_code, http_response_data)
开发者ID:shabarin,项目名称:ansible-yandexdns,代码行数:25,代码来源:yandexdns.py
示例2: relpath
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
pardir, splitunc
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
开发者ID:SibghatullahSheikh,项目名称:nupic-darwin64,代码行数:29,代码来源:plot_directive.py
示例3: check
def check(rv, ans):
assert bool(rv[1]) == bool(ans[1])
if ans[1]:
return s_check(rv, ans)
e = rv[0].expand()
a = ans[0].expand()
return e in [a, -a] and rv[1] == ans[1]
开发者ID:skirpichev,项目名称:diofant,代码行数:7,代码来源:test_sqrtdenest.py
示例4: onOK
def onOK(self, event): # wxGlade: PreferencesPanel.<event_handler>
"""Record all of the preferences and return to fitting mode."""
# Record structure viewer stuff
executable = str(self.textCtrlViewer.GetValue()).strip()
argstr = str(self.textCtrlArgument.GetValue()).strip()
fileformat = str(self.choiceFormat.GetStringSelection())
config = {
"executable" : executable,
"argstr" : argstr,
"fileformat" : fileformat,
}
viewer = structureviewer.getStructureViewer()
viewer.setConfig(config)
# Structures path
remember = bool(self.structureDirCheckBox.GetValue())
if not self.cP.has_section("PHASE"):
self.cP.add_section("PHASE")
self.cP.set("PHASE", "remember", str(remember))
# Data set path
remember = bool(self.dataDirCheckBox.GetValue())
if not self.cP.has_section("DATASET"):
self.cP.add_section("DATASET")
self.cP.set("DATASET", "remember", str(remember))
# Get out of here
self.onCancel(event)
return
开发者ID:cfarrow,项目名称:diffpy.pdfgui,代码行数:31,代码来源:preferencespanel.py
示例5: get_visibility_errors
def get_visibility_errors(self, customer):
if self.product.deleted:
yield ValidationError(_('This product has been deleted.'), code="product_deleted")
if customer and customer.is_all_seeing: # None of the further conditions matter for omniscient customers.
return
if not self.visible:
yield ValidationError(_('This product is not visible.'), code="product_not_visible")
is_logged_in = (bool(customer) and not customer.is_anonymous)
if not is_logged_in and self.visibility_limit != ProductVisibility.VISIBLE_TO_ALL:
yield ValidationError(
_('The Product is invisible to users not logged in.'),
code="product_not_visible_to_anonymous")
if is_logged_in and self.visibility_limit == ProductVisibility.VISIBLE_TO_GROUPS:
# TODO: Optimization
user_groups = set(customer.groups.all().values_list("pk", flat=True))
my_groups = set(self.visibility_groups.values_list("pk", flat=True))
if not bool(user_groups & my_groups):
yield ValidationError(
_('This product is not visible to your group.'),
code="product_not_visible_to_group"
)
for receiver, response in get_visibility_errors.send(ShopProduct, shop_product=self, customer=customer):
for error in response:
yield error
开发者ID:taedori81,项目名称:shoop,代码行数:30,代码来源:product_shops.py
示例6: _update
def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
"""
Posts the given xml message to http://<self.url>/update and
returns the result.
Passing `sanitize` as False will prevent the message from being cleaned
of control characters (default True). This is done by default because
these characters would cause Solr to fail to parse the XML. Only pass
False if you're positive your data is clean.
"""
path = 'update/'
# Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
# ``commit=true`` to the URL and have the commit happen without a
# second request.
query_vars = []
if commit is not None:
query_vars.append('commit=%s' % str(bool(commit)).lower())
if waitFlush is not None:
query_vars.append('waitFlush=%s' % str(bool(waitFlush)).lower())
if waitSearcher is not None:
query_vars.append('waitSearcher=%s' % str(bool(waitSearcher)).lower())
if query_vars:
path = '%s?%s' % (path, '&'.join(query_vars))
# Clean the message of ctrl characters.
if clean_ctrl_chars:
message = sanitize(message)
return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
开发者ID:eberle1080,项目名称:tesserae-ng,代码行数:34,代码来源:pysolr.py
示例7: IncBench
def IncBench(inc):
NR_CYCLES = 201
m = 8
n = 2 ** m
count = Signal(intbv(0)[m:])
count_v = Signal(intbv(0)[m:])
enable = Signal(bool(0))
clock, reset = [Signal(bool(0)) for i in range(2)]
inc_inst = inc(count, enable, clock, reset, n=n)
@instance
def clockgen():
clock.next = 1
for i in range(NR_CYCLES):
yield delay(10)
clock.next = not clock
@instance
def monitor():
reset.next = 0
enable.next = 1
yield clock.negedge
reset.next = 1
yield clock.negedge
while True:
yield clock.negedge
print count
return inc_inst, clockgen, monitor
开发者ID:BackupTheBerlios,项目名称:osocgen-svn,代码行数:34,代码来源:test_inc.py
示例8: _process
def _process(self):
self.user.settings.set('suggest_categories', True)
tz = session.tzinfo
hours, minutes = timedelta_split(tz.utcoffset(datetime.now()))[:2]
categories = get_related_categories(self.user)
categories_events = []
if categories:
category_ids = {c['categ'].id for c in categories.itervalues()}
today = now_utc(False).astimezone(tz).date()
query = (Event.query
.filter(~Event.is_deleted,
Event.category_chain_overlaps(category_ids),
Event.start_dt.astimezone(session.tzinfo) >= today)
.options(joinedload('category').load_only('id', 'title'),
joinedload('series'),
subqueryload('acl_entries'),
load_only('id', 'category_id', 'start_dt', 'end_dt', 'title', 'access_key',
'protection_mode', 'series_id', 'series_pos', 'series_count'))
.order_by(Event.start_dt, Event.id))
categories_events = get_n_matching(query, 10, lambda x: x.can_access(self.user))
from_dt = now_utc(False) - relativedelta(weeks=1, hour=0, minute=0, second=0)
linked_events = [(event, {'management': bool(roles & self.management_roles),
'reviewing': bool(roles & self.reviewer_roles),
'attendance': bool(roles & self.attendance_roles)})
for event, roles in get_linked_events(self.user, from_dt, 10).iteritems()]
return WPUser.render_template('dashboard.html', 'dashboard',
offset='{:+03d}:{:02d}'.format(hours, minutes), user=self.user,
categories=categories,
categories_events=categories_events,
suggested_categories=get_suggested_categories(self.user),
linked_events=linked_events)
开发者ID:jas01,项目名称:indico,代码行数:31,代码来源:controllers.py
示例9: database_filename
def database_filename(subreddit=None, username=None):
'''
Given a subreddit name or username, return the appropriate database filename.
'''
if bool(subreddit) == bool(username):
raise ValueError('Enter subreddit or username but not both')
text = subreddit or username
text = text.replace('/', os.sep)
if os.sep in text:
# If they've given us a full path, don't mess
# with it
return text
text = text.replace('\\', os.sep)
if not text.endswith('.db'):
text += '.db'
if subreddit:
full_path = DATABASE_SUBREDDIT % text
else:
full_path = DATABASE_USER % text
basename = os.path.basename(full_path)
if os.path.exists(basename):
# Prioritize existing local files of the same name before creating
# the deeper, proper one.
return basename
return full_path
开发者ID:Electronickss,项目名称:reddit,代码行数:31,代码来源:timesearch.py
示例10: GetDisplayModes
def GetDisplayModes():
res = []
displayDevice = DISPLAY_DEVICE()
displayDevice.cb = sizeof(DISPLAY_DEVICE)
devMode = DEVMODE()
devMode.dmSize = sizeof(DEVMODE)
iDevNum = 0
while True:
if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
break
iDevNum += 1
if displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER:
continue
EnumDisplaySettingsEx(
displayDevice.DeviceName,
ENUM_CURRENT_SETTINGS,
pointer(devMode),
0
)
displayMode = (
displayDevice.DeviceName,
devMode.dmPosition.x,
devMode.dmPosition.y,
devMode.dmPelsWidth,
devMode.dmPelsHeight,
devMode.dmDisplayFrequency,
devMode.dmBitsPerPel,
bool(
displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
),
bool(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE),
devMode.dmDisplayFlags,
)
res.append(displayMode)
return tuple(res)
开发者ID:bruinlax,项目名称:EventGhost,代码行数:35,代码来源:Display.py
示例11: _get_no_init
def _get_no_init( self ):
if None is self._no_init and False == bool( self.indexing_suite ):
#select all public constructors and exclude copy constructor
cs = self.constructors( lambda c: not c.is_copy_constructor and c.access_type == 'public'
, recursive=False, allow_empty=True )
has_suitable_constructor = bool( cs )
if cs and len(cs) == 1 and cs[0].is_trivial_constructor and self.find_noncopyable_vars():
has_suitable_constructor = False
has_nonpublic_destructor = declarations.has_destructor( self ) \
and not declarations.has_public_destructor( self )
trivial_constructor = self.find_trivial_constructor()
if has_nonpublic_destructor \
or ( self.is_abstract and not self.is_wrapper_needed() ) \
or not has_suitable_constructor:
self._no_init = True
elif not trivial_constructor or trivial_constructor.access_type != 'public':
exportable_cs = [c for c in cs if c.exportable and c.ignore == False]
if not exportable_cs:
self._no_init = True
else:
pass
if None is self._no_init:
self._no_init = False
return self._no_init
开发者ID:detoxhby,项目名称:lambdawars,代码行数:28,代码来源:class_wrapper.py
示例12: get_columns
def get_columns(self, connection, table_name, schema=None, **kw):
table_id = self.get_table_id(connection, table_name, schema,
info_cache=kw.get("info_cache"))
COLUMN_SQL = text("""
SELECT col.name AS name,
t.name AS type,
(col.status & 8) AS nullable,
(col.status & 128) AS autoincrement,
com.text AS 'default',
col.prec AS precision,
col.scale AS scale,
col.length AS length
FROM systypes t, syscolumns col LEFT OUTER JOIN syscomments com ON
col.cdefault = com.id
WHERE col.usertype = t.usertype
AND col.id = :table_id
ORDER BY col.colid
""")
results = connection.execute(COLUMN_SQL, table_id=table_id)
columns = []
for (name, type_, nullable, autoincrement, default, precision, scale,
length) in results:
col_info = self._get_column_info(name, type_, bool(nullable),
bool(autoincrement), default, precision, scale,
length)
columns.append(col_info)
return columns
开发者ID:Cushychicken,项目名称:tubejam,代码行数:31,代码来源:base.py
示例13: __init__
def __init__(
self,
host=None,
port=6379,
unix_sock=None,
database=0,
password=None,
encoding=None,
conn_timeout=2,
read_timeout=2,
sentinel=False):
if not bool(host) != bool(unix_sock):
raise PyRedisError('Ether host or unix_sock has to be provided')
self._closed = False
self._conn_timeout = conn_timeout
self._read_timeout = read_timeout
self._encoding = encoding
self._reader = None
self._sentinel = sentinel
self._writer = writer
self._sock = None
self.host = host
self.port = port
self.unix_sock = unix_sock
self.password = password
self.database = database
开发者ID:d0znpp,项目名称:pyredis,代码行数:27,代码来源:connection.py
示例14: test_page
def test_page(request):
title = 'Pyramid Debugtoolbar'
log.info(title)
return {
'title': title,
'show_jinja2_link': bool(pyramid_jinja2),
'show_sqla_link': bool(sqlalchemy)}
开发者ID:wwitzel3,项目名称:pyramid_debugtoolbar,代码行数:7,代码来源:demo.py
示例15: __init__
def __init__(self, announce, piece_length=262144, **kw):
self.piece_length = piece_length
if not bool(urlparse.urlparse(announce).scheme):
raise ValueError('No schema present for url')
self.tdict = {
'announce': announce,
'creation date': int(time()),
'info': {
'piece length': self.piece_length
}
}
if kw.get('comment'):
self.tdict.update({'comment': kw.get('comment')})
if kw.get('httpseeds'):
if not isinstance(kw.get('httpseeds'), list):
raise TypeError('httpseeds must be a list')
else:
self.tdict.update({'httpseeds': kw.get('httpseeds')})
if kw.get('announcelist'):
if not isinstance(kw.get('announcelist'), list):
raise TypeError('announcelist must be a list of lists')
if False in [isinstance(l, list) for l in kw.get('announcelist')]:
raise TypeError('announcelist must be a list of lists')
if False in [bool(urlparse.urlparse(f[0]).scheme) for f in kw.get('announcelist')]:
raise ValueError('No schema present for url')
else:
self.tdict.update({'announce-list': kw.get('announcelist')})
开发者ID:TheTerrasque,项目名称:makeTorrent,代码行数:27,代码来源:makeTorrent.py
示例16: _plugin_current_changed
def _plugin_current_changed(self, current, previous):
if current.isValid():
actual_idx = self.proxy_model.mapToSource(current)
display_plugin = self.model.display_plugins[actual_idx.row()]
self.description.setText(display_plugin.description)
self.forum_link = display_plugin.forum_link
self.zip_url = display_plugin.zip_url
self.forum_action.setEnabled(bool(self.forum_link))
self.install_button.setEnabled(display_plugin.is_valid_to_install())
self.install_action.setEnabled(self.install_button.isEnabled())
self.uninstall_action.setEnabled(display_plugin.is_installed())
self.history_action.setEnabled(display_plugin.has_changelog)
self.configure_button.setEnabled(display_plugin.is_installed())
self.configure_action.setEnabled(self.configure_button.isEnabled())
self.toggle_enabled_action.setEnabled(display_plugin.is_installed())
self.donate_enabled_action.setEnabled(bool(display_plugin.donation_link))
else:
self.description.setText('')
self.forum_link = None
self.zip_url = None
self.forum_action.setEnabled(False)
self.install_button.setEnabled(False)
self.install_action.setEnabled(False)
self.uninstall_action.setEnabled(False)
self.history_action.setEnabled(False)
self.configure_button.setEnabled(False)
self.configure_action.setEnabled(False)
self.toggle_enabled_action.setEnabled(False)
self.donate_enabled_action.setEnabled(False)
self.update_forum_label()
开发者ID:j-howell,项目名称:calibre,代码行数:30,代码来源:plugin_updater.py
示例17: setSaveOptionsPNG
def setSaveOptionsPNG(self, optimize=None, palette=None, palette256=None):
""" Optional arguments are added to self.png_options for pickup when saving.
Palette argument is a URL relative to the configuration file,
and it implies bits and optional transparency options.
More information about options:
http://effbot.org/imagingbook/format-png.htm
"""
if optimize is not None:
self.png_options['optimize'] = bool(optimize)
if palette is not None:
palette = urljoin(self.config.dirpath, palette)
palette, bits, t_index = load_palette(palette)
self.bitmap_palette, self.png_options['bits'] = palette, bits
if t_index is not None:
self.png_options['transparency'] = t_index
if palette256 is not None:
self.palette256 = bool(palette256)
else:
self.palette256 = None
开发者ID:pjmtdw,项目名称:TileStache,代码行数:25,代码来源:Core.py
示例18: __init__
def __init__(self,
tx=False, # safe assumption
agc=True, # show useless controls > hide functionality
dc_cancel=True, # ditto
dc_offset=True, # safe assumption
tune_delay=DEFAULT_DELAY,
e4000=False):
"""
All values are booleans.
tx: The device supports transmitting (osmosdr.sink).
agc: The device has a hardware AGC (set_gain_mode works).
dc_cancel: The device supports DC offset auto cancellation
(set_dc_offset_mode auto works).
dc_offset: The output has a DC offset and tuning should
avoid the area around DC.
e4000: The device is an RTL2832U + E4000 tuner and can be
confused into tuning to 0 Hz.
"""
# TODO: If the user specifies an OsmoSDRProfile without a full set of explicit args, derive the rest from the device string instead of using defaults.
self.tx = bool(tx)
self.agc = bool(agc)
self.dc_cancel = bool(dc_cancel)
self.dc_offset = bool(dc_offset)
self.tune_delay = float(tune_delay)
self.e4000 = bool(e4000)
开发者ID:thefinn93,项目名称:shinysdr,代码行数:27,代码来源:osmosdr.py
示例19: _create_bootstrap
def _create_bootstrap(script_name, packages_to_install, paver_command_line,
install_paver=True, more_text="", dest_dir='.',
no_site_packages=None, system_site_packages=None,
unzip_setuptools=False, distribute=None, index_url=None,
find_links=None):
# configure easy install template
easy_install_options = []
if index_url:
easy_install_options.extend(["--index-url", index_url])
if find_links:
easy_install_options.extend(
["--find-links", " ".join(find_links)])
easy_install_options = (
easy_install_options
and "'%s', " % "', '".join(easy_install_options) or '')
confd_easy_install_tmpl = (_easy_install_tmpl %
('bin_dir', easy_install_options))
if install_paver:
paver_install = (confd_easy_install_tmpl %
('paver==%s' % setup_meta['version']))
else:
paver_install = ""
options = ""
# if deprecated 'no_site_packages' was specified and 'system_site_packages'
# wasn't, set it from that value
if system_site_packages is None and no_site_packages is not None:
system_site_packages = not no_site_packages
if system_site_packages is not None:
options += (" options.system_site_packages = %s\n" %
bool(system_site_packages))
if unzip_setuptools:
options += " options.unzip_setuptools = True\n"
if distribute is not None:
options += " options.use_distribute = %s\n" % bool(distribute)
options += "\n"
extra_text = """def adjust_options(options, args):
args[:] = ['%s']
%s
def after_install(options, home_dir):
if sys.platform == 'win32':
bin_dir = join(home_dir, 'Scripts')
else:
bin_dir = join(home_dir, 'bin')
%s""" % (dest_dir, options, paver_install)
for package in packages_to_install:
extra_text += confd_easy_install_tmpl % package
if paver_command_line:
command_list = list(paver_command_line.split())
extra_text += " subprocess.call([join(bin_dir, 'paver'),%s)" % repr(command_list)[1:]
extra_text += more_text
bootstrap_contents = venv.create_bootstrap_script(extra_text)
fn = script_name
debug("Bootstrap script extra text: " + extra_text)
def write_script():
open(fn, "w").write(bootstrap_contents)
dry("Write bootstrap script %s" % fn, write_script)
开发者ID:drewrm,项目名称:paver,代码行数:60,代码来源:virtual.py
示例20: __init__
def __init__(self, isoform_filename, sam_filename, output_prefix,
min_aln_coverage, min_aln_identity, min_flnc_coverage,
max_fuzzy_junction, allow_extra_5exon, skip_5_exon_alt):
"""
Parameters:
isoform_filename -- input file containing isoforms, as fastq|fasta|contigset
sam_filename -- input sam file produced by mapping fastq_filename to reference and sorted.
#collapsed_isoform_filename -- file to output collapsed isoforms as fasta|fastq|contigset
min_aln_coverage -- min coverage over reference to collapse a group of isoforms
min_aln_identity -- min identity aligning to reference to collapse a group of isoforms
min_flnc_coverage -- min supportive flnc reads to not ignore an isoform
Must be 1 when collapsing consensus isoforms, which is the case in production isoseq.
Can be >= 1 only when directly collapsing FLNC reads.
max_fuzzy_junction -- max edit distance between fuzzy-matching exons
allow_extra_5exon -- whether or not to allow shorter 5' exons
skip_5_exon_alt -- whether or not to skip alternative 5' exons
"""
self.suffix = parse_ds_filename(isoform_filename)[1]
super(CollapseIsoformsRunner, self).__init__(prefix=output_prefix,
allow_extra_5exon=allow_extra_5exon)
self.isoform_filename = isoform_filename # input, uncollapsed fa|fq|ds
self.sam_filename = sam_filename # input, sorted, gmap sam
#self.collapsed_isoform_filename = collapsed_isoform_filename # output, collapsed, fa|fq|ds
self.min_aln_coverage = float(min_aln_coverage)
self.min_aln_identity = float(min_aln_identity)
self.min_flnc_coverage = int(min_flnc_coverage)
self.max_fuzzy_junction = int(max_fuzzy_junction)
self.allow_extra_5exon = bool(allow_extra_5exon)
self.skip_5_exon_alt = bool(skip_5_exon_alt)
开发者ID:ylipacbio,项目名称:pbtranscript,代码行数:31,代码来源:CollapseIsoforms.py
注:本文中的bool函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论