本文整理汇总了Python中tinydb.where函数的典型用法代码示例。如果您正苦于以下问题:Python where函数的具体用法?Python where怎么用?Python where使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了where函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: reference_energy
def reference_energy(self, phase, symbols, param_search):
"""
Returns the weighted average of the endmember energies
in symbolic form.
"""
# TODO: Handle wildcards in constituent array
pure_energy_term = S.Zero
# Normalize site ratios
site_ratio_normalization = 0
for idx, sublattice in enumerate(phase.constituents):
# sublattices with only vacancies don't count
if len(sublattice) == 1 and sublattice[0] == 'VA':
continue
site_ratio_normalization += phase.sublattices[idx]
pure_param_query = (
(where('phase_name') == phase.name) & \
(where('parameter_order') == 0) & \
(where('parameter_type') == "G") & \
(where('constituent_array').test(self._purity_test))
)
pure_params = param_search(pure_param_query)
for param in pure_params:
site_fraction_product = S.One
for subl_index, comp in enumerate(param['constituent_array']):
# We know that comp has one entry, by filtering
sitefrac = \
v.SiteFraction(phase.name, subl_index, comp[0])
site_fraction_product *= sitefrac
pure_energy_term += (
site_fraction_product * param['parameter'].subs(symbols)
) / site_ratio_normalization
return pure_energy_term
开发者ID:Teslos,项目名称:pycalphad,代码行数:35,代码来源:model.py
示例2: test_json_readwrite
def test_json_readwrite(tmpdir):
"""
Regression test for issue #1
"""
path = str(tmpdir.join('test.db'))
# Create TinyDB instance
db = TinyDB(path, storage=JSONStorage)
item = {'name': 'A very long entry'}
item2 = {'name': 'A short one'}
get = lambda s: db.get(where('name') == s)
db.insert(item)
assert get('A very long entry') == item
db.remove(where('name') == 'A very long entry')
assert get('A very long entry') is None
db.insert(item2)
assert get('A short one') == item2
db.remove(where('name') == 'A short one')
assert get('A short one') is None
开发者ID:lordjabez,项目名称:tinydb,代码行数:25,代码来源:test_storages.py
示例3: getfeed
def getfeed(cid):
postrec = []
print "feed"
for bid in msgtable.search(where ('customer_id') == cid):
print bid
postrec.append(posttable.search(where ('busid') == bid['busid']))
return postrec
开发者ID:nvijay83,项目名称:smallbiz,代码行数:7,代码来源:post.py
示例4: test_write_back
def test_write_back(db):
docs = db.search(where('int') == 1)
for doc in docs:
doc['int'] = [1, 2, 3]
db.write_back(docs)
assert db.count(where('int') == [1, 2, 3]) == 3
开发者ID:msiemens,项目名称:tinydb,代码行数:7,代码来源:test_tinydb.py
示例5: scan
def scan(self):
print "Scan Start"
while True:
cell = Cell.all(interface)
print "Rescanning"
timer = 0
while timer < 100:
timer +=1
S = []
count = 0
for c in cell:
count += 1
#print ":"+ str(count), " ssid:", c.ssid
#create dictionary with informnation on the accesss point
SSIDS = {"no" : count ,"ssid": c.ssid, "channel":c.channel,"encrypted":c.encrypted, \
"frequency":c.frequency,"address":c.address, "signal":c.signal, "mode":c.mode}
#if not db.search((where('ssid') == ap["ssid"])) == []:
# res = db.search(where('ssid') == c.ssid)
#print db.search(where('ssid') == c.ssid)
print "=----------------------------------"
# print c.address
print "---------------------------------------"
if db.contains(where('ssid') == c.ssid):
print (db.contains((where('ssid') == c.ssid) & (where('address') == str(c.address))))
开发者ID:baggybin,项目名称:RogueDetection,代码行数:26,代码来源:wifii_scanner.py
示例6: test_smart_query_cache
def test_smart_query_cache(db):
db.table_class = SmartCacheTable
table = db.table('table3')
query = where('int') == 1
dummy = where('int') == 2
assert not table.search(query)
assert not table.search(dummy)
# Test insert
table.insert({'int': 1})
assert len(table._query_cache) == 2
assert len(table._query_cache[query]) == 1
# Test update
table.update({'int': 2}, where('int') == 1)
assert len(table._query_cache[dummy]) == 1
assert table.count(query) == 0
# Test remove
table.insert({'int': 1})
table.remove(where('int') == 1)
assert table.count(where('int') == 1) == 0
开发者ID:GeWu,项目名称:tinydb,代码行数:26,代码来源:test_tables.py
示例7: main
def main():
if len(sys.argv) == 1 or sys.argv[1] == "proximity":
pprint(db.search(tinydb.where('seen') >= int(time.time()) - 60*15))
elif sys.argv[1] == "hostnames":
pprint(db.search(tinydb.where('hostname')))
else:
print("Unknown debug command")
开发者ID:DavidChouinard,项目名称:recap-client,代码行数:7,代码来源:debug.py
示例8: update_document
def update_document(self, field, new_val, doc_id):
if type(new_val) is list:
self._db.update(_update_entry_list(field, new_val), where('id') == doc_id)
else:
if type(new_val) is set:
new_val = list(new_val)
self._db.update({field: new_val}, where('id') == doc_id)
开发者ID:cjonghyun,项目名称:filesystem-connector,代码行数:7,代码来源:managers.py
示例9: test_search_path
def test_search_path(db):
assert not db._query_cache
assert len(db.search(where('int'))) == 3
assert len(db._query_cache) == 1
assert len(db.search(where('asd'))) == 0
assert len(db.search(where('int'))) == 3 # Query result from cache
开发者ID:msiemens,项目名称:tinydb,代码行数:7,代码来源:test_tinydb.py
示例10: search
def search(args):
filename = args['<outputfile>']
if args['--fuzzy']:
results = db.search(where('outputs').any(lambda x: re.match(".+%s.+" % filename, x)))
elif args['--regex']:
results = db.search(where('outputs').any(lambda x: re.match(filename, x)))
else:
results = db.search(where('outputs').any(os.path.abspath(filename)))
results = [_change_date(result) for result in results]
# Sort the results
results = sorted(results, key = lambda x: parse(x['date']))
if len(results) == 0:
print("No results found")
else:
if args['--all']:
for r in results:
print_result(r)
print("-"*40)
else:
print_result(results[-1])
if len(results) > 1:
print("** Previous runs creating this output have been found. Run with --all to show. **")
if args['--diff']:
if 'diff' in results[-1]:
print("\n\n")
print(results[-1]['diff'])
db.close()
开发者ID:oew1v07,项目名称:recipy,代码行数:33,代码来源:recipycmd.py
示例11: is_user_existent
def is_user_existent(name):
field_existence = user_table.search(where('name').exists())
if not field_existence:
return False
user_existence = user_table.search(where('name') == name)
return True if len(user_existence) is 1 else False
开发者ID:abrasumente233,项目名称:mpsign,代码行数:7,代码来源:cmd.py
示例12: ticket_detail
def ticket_detail(ticket_id):
if not session.get("logged_in"):
return redirect(url_for("login"))
else:
if request.method == "GET":
results = ticket_db.search(where("uuid") == ticket_id)
action_url = request.path
status = int(request.args.get("status", 10))
if status < 0 or status > 3:
pass
else:
t = ticket_db.get(where('uuid') == ticket_id)
t["status"] = status
ticket_db.update(t, eids=[t.eid])
if len(results) == 0:
abort(404)
else:
results[0]["text"].replace("\;", ";")
return render_template("ticket_detail.html", details=results[0], actionurl=action_url)
else:
content = request.form["content"].replace("\n", "<br>")
user = session.get("username")
t = ticket_db.get(where('uuid') == ticket_id)
if t["replies"] == None:
t["replies"] = []
t["replies"].append({"content" : content, "author": user})
ticket_db.update(t, eids=[t.eid])
return redirect(request.path)
开发者ID:fhebert-perkins,项目名称:helpdesk,代码行数:28,代码来源:main.py
示例13: get_obj_by_brush_and_mtl
def get_obj_by_brush_and_mtl(self, brush, mtl):
if self.db.contains(
(where("brush") == str(brush)) & (where("mtl") == str(mtl))
):
return self.db.search(
(where("brush") == str(brush)) & (where("mtl") == str(mtl))
)[0]
开发者ID:csprance,项目名称:CE_Python,代码行数:7,代码来源:__init__.py
示例14: test_one_table
def test_one_table(db):
table1 = db.table('table1')
table1.insert_multiple({'int': 1, 'char': c} for c in 'abc')
assert table1.get(where('int') == 1)['char'] == 'a'
assert table1.get(where('char') == 'b')['char'] == 'b'
开发者ID:dinever,项目名称:tinydb,代码行数:7,代码来源:test_tables.py
示例15: index
def index():
form = SearchForm()
query = request.args.get('query', '').strip()
db = TinyDB(recipyGui.config.get('tinydb'))
if not query:
runs = db.all()
else:
# Search run outputs using the query string
runs = db.search(
where('outputs').any(lambda x: listsearch(query, x)) |
where('inputs').any(lambda x: listsearch(query, x)) |
where('script').search(query) |
where('notes').search(query) |
where('unique_id').search(query))
runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')) if x['date'] is not None else x['eid'], reverse=True)
run_ids = []
for run in runs:
if 'notes' in run.keys():
run['notes'] = str(escape(run['notes']))
run_ids.append(run.eid)
db.close()
return render_template('list.html', runs=runs, query=query, form=form,
run_ids=str(run_ids),
dbfile=recipyGui.config.get('tinydb'))
开发者ID:pablo-esteban,项目名称:recipy,代码行数:30,代码来源:views.py
示例16: print_month_usage
def print_month_usage():
M = strftime("%m", NOW)
Y = strftime("%y", NOW)
month= raw_input("Month[{}]:".format(M)) or M
year = raw_input("Year [{}]:".format(Y)) or Y
assert(month)
assert(year)
R = DB.search((where('year') == year) & (where('month')==month))
R.sort(key=lambda x: (x['mess'],x['host'],int(x['day']),["B","L","S","D"].index(x['session'])))
messes = set([r['mess'] for r in R])
hosts = set([r['host'] for r in R])
days = set([r['day' ] for r in R])
print ""
print "Summary for month {}".format(month)
for mess in messes:
print "Mess : {} ".format(mess),
for host in hosts:
print "Host : {}".format(host)
for day in sorted(days, key=lambda x:int(x)):
print "{:2s} ".format(day),
D = [r for r in R if r['mess']==mess and r['host']==host and r['day']==day]
D.sort(key=lambda x: (["B","L","S","D"].index(x['session'])))
for d in D:
print d['session'],
print ""
开发者ID:nithishdivakar,项目名称:scripts,代码行数:25,代码来源:mess.py
示例17: test_update
def test_update(db):
assert db.count(where('int') == 1) == 3
db.update({'int': 2}, where('char') == 'a')
assert db.count(where('int') == 2) == 1
assert db.count(where('int') == 1) == 2
开发者ID:drmaize,项目名称:compvision,代码行数:7,代码来源:test_tinydb.py
示例18: start
def start():
"""Start monitoring the Indiegogo campaign.
"""
# Retrieve the current campaign information
campaign = get_campaign_info()
CONFIGS['slug'] = campaign['slug']
CONFIGS['campaign_id'] = campaign['id']
CONFIGS['campaign_preview_url'] = campaign['preview_url']
CONFIGS['campaign_thumbnail_image_url'] = campaign['thumbnail_image_url']
# Initialize timestamps
last_comment_ts = DB.search(where('type') == 'comment')
if not last_comment_ts:
DB.insert({'ts': 0, 'type': 'comment'})
last_contrib_ts = DB.search(where('type') == 'contrib')
if not last_contrib_ts:
DB.insert({'ts': 0, 'type': 'contrib'})
# Insert markers for each campaign goal
goal = campaign['goal']
funds = campaign['collected_funds']
achieved = int(funds * 100 / goal)
for i in [30, 70, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]:
# notify at each achievement
p = 'p' + str(i)
marker = DB.search(where('type') == p)
if not marker and achieved >= i:
DB.insert({'ts': time.time(), 'type': p})
update_interval = CONFIGS['update_interval']
print "Start monitoring (CTRL-c to stop)..."
try:
while True:
check_now()
time.sleep(update_interval)
except:
pass
print "Monitoring stopped."
开发者ID:thpark,项目名称:indiegogo-to-ifttt,代码行数:35,代码来源:igg.py
示例19: match
def match(self, field, table_name=None, regex=None, test=None):
"""Find records where `field` matches `regex` or `test`.
Either `regex` or `test` may be specified, not both.
If `regex` is given, then all records with `field` matching the regular expression are returned.
If test is given then all records with `field` set to a value that caues `test` to return True are returned.
If neither is given, return all records where `field` is set to any value.
Args:
table_name (str): Name of the table to operate on. See :any:`AbstractDatabase.table`.
field (string): Name of the data field to match.
regex (string): Regular expression string.
test: Callable returning a boolean value.
Returns:
list: Matching data records.
Raises:
ValueError: Invalid value for `keys`.
"""
table = self.table(table_name)
if test is not None:
LOGGER.debug("%s: search(where(%s).test(%r))", table_name, field, test)
return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).test(test))]
elif regex is not None:
LOGGER.debug("%s: search(where(%s).matches(%r))", table_name, field, regex)
return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).matches(regex))]
else:
LOGGER.debug("%s: search(where(%s).matches('.*'))", table_name, field)
return [self.Record(self, element=elem) for elem in table.search(tinydb.where(field).matches(".*"))]
开发者ID:linearregression,项目名称:taucmdr,代码行数:30,代码来源:local_file.py
示例20: test_update
def test_update(db):
eid = db.insert({'x': 1})
with transaction(db) as tr:
tr.update({'x': 2}, where('x') == 1)
tr.update({'x': 3}, eids=[eid])
assert db.get(where('x') == 3).eid == eid
开发者ID:carriercomm,项目名称:tinyrecord,代码行数:8,代码来源:tests.py
注:本文中的tinydb.where函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论