Monkeyrunner Opening Settings Programmatically - android-testing

I know MonkeyRunner is kind of deprecated, but I still have a weird question.
If I open Settings via touch events from Monkeyrunner Users option is not there,
If I do it as follows same thing.
FLAG_ACTIVITY_NEW_TASK = 0x10000000
package = 'com.android.settings'
activity='.Settings'
runComponent = package + '/' + activity
device.startActivity(component=runComponent, flags=FLAG_ACTIVITY_NEW_TASK)
Does anyone know why, or how to get Users to display or open using MonkeyRunner?
Running Android v6.0.1.
Thanks,
Eugene

You can use AndroidViewClient/culebra to do it.
This is a culebra script slightly modified to check for Users while scrolling, but most of it is generated using Culebra GUI:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014 Diego Torres Milano
Created on 2016-01-11 by Culebra v11.0.8
__ __ __ __
/ \ / \ / \ / \
____________________/ __\/ __\/ __\/ __\_____________________________
___________________/ /__/ /__/ /__/ /________________________________
| / \ / \ / \ / \ \___
|/ \_/ \_/ \_/ \ o \
\_____/--<
#author: Diego Torres Milano
#author: Jennifer E. Swofford (ascii art snake)
'''
import re
import sys
import os
import unittest
from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase
TAG = 'CULEBRA'
class CulebraTests(CulebraTestCase):
#classmethod
def setUpClass(cls):
cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
cls.kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
cls.options = {'start-activity': None, 'concertina': False, 'device-art': None, 'use-jar': False, 'multi-device': False, 'unit-test-class': True, 'save-screenshot': None, 'use-dictionary': False, 'glare': False, 'dictionary-keys-from': 'id', 'scale': 0.5, 'find-views-with-content-description': True, 'window': -1, 'orientation-locked': None, 'save-view-screenshots': None, 'find-views-by-id': True, 'log-actions': False, 'use-regexps': False, 'null-back-end': False, 'auto-regexps': None, 'do-not-verify-screen-dump': True, 'verbose-comments': False, 'gui': True, 'find-views-with-text': True, 'prepend-to-sys-path': False, 'install-apk': None, 'drop-shadow': False, 'output': None, 'unit-test-method': None, 'interactive': False}
cls.sleep = 5
def setUp(self):
super(CulebraTests, self).setUp()
def tearDown(self):
super(CulebraTests, self).tearDown()
def preconditions(self):
if not super(CulebraTests, self).preconditions():
return False
return True
def testSomething(self):
if not self.preconditions():
self.fail('Preconditions failed')
_s = CulebraTests.sleep
_v = CulebraTests.verbose
self.vc.dump(window=-1)
self.vc.uiDevice.openQuickSettings()
self.vc.sleep(_s)
self.vc.dump(window=-1)
self.vc.findViewWithContentDescriptionOrRaise(u'''Settings''').touch()
self.vc.sleep(_s)
self.vc.dump(window=-1)
users = None
com_android_settings___id_dashboard = self.vc.findViewByIdOrRaise("com.android.settings:id/dashboard")
com_android_settings___id_dashboard.uiScrollable.flingToBeginning()
attempts = 10
while attempts > 0:
users = self.vc.findViewWithText(u'Users')
if users:
break
com_android_settings___id_dashboard.uiScrollable.flingForward()
self.vc.dump(window=-1)
self.vc.sleep(_s)
com_android_settings___id_dashboard = self.vc.findViewByIdOrRaise("com.android.settings:id/dashboard")
attempts -= 1
if not users:
self.fail("Users not found")
if __name__ == '__main__':
CulebraTests.main()

Related

Part of requested market data is not subscribed-ib_insync

I have a problem with getting option parameters using the library ib_insync.
import time
from ib_insync import *
import pandas as pd
from configparser import ConfigParser
from ibapi.common import TickerId, SetOfFloat, SetOfString, MarketDataTypeEnum
config = ConfigParser()
# TWs 7497, IBGW 4001
def get_chain(ib,ticker, exp_list):
exps = {}
df = pd.DataFrame(columns=['strike', 'kind', 'close', 'last'])
for i in exp_list:
ib.sleep()
cds = ib.reqContractDetails(Option(ticker, i, exchange='SMART'))
options = [cd.contract for cd in cds]
tickers = [t for i in range(0, len(options), 100)
for t in ib.reqTickers(*options[i:i + 100])]
for x in tickers:
df = df.append(
{'strike': x.contract.strike, 'kind': x.contract.right, 'close': x.close, 'last': x.last, 'bid': x.bid,
'ask': x.ask, 'mid': (x.bid + x.ask) / 2, 'volume': x.volume}, ignore_index=True)
exps[i] = df
return exps
def get_individual(ib,ticker, exp, strike, kind):
cds = ib.reqContractDetails(Option(ticker, exp, strike, kind, exchange='SMART'))
options = [cd.contract for cd in cds]
tickers = [t for i in range(0, len(options), 100) for t in ib.reqTickers(*options[i:i + 100])]
con = {'strike': tickers[0].contract.strike, 'kind': tickers[0].contract.right, 'close': tickers[0].close,
'last': tickers[0].last, 'bid': tickers[0].bid, 'ask': tickers[0].ask, 'volume': tickers[0].volume}
return con
def main():
with IB().connect('127.0.0.1', 7497) as ib:
ib.reqMarketDataType(3)
time.sleep(1)
print(get_chain(ib,"AAPL", ["20220211"]))
if __name__ == '__main__':
main()
Output: "Error 10090, reqId 4: Part of requested market data is not subscribed. Subscription-independent ticks are still active.Delayed market data is available.AAPL NASDAQ.NMS/TOP/ALL"
My solution was to implement ib.sleep because I thought maybe the calls are overlapping. As you can see the MarketDataType is set to 3.
In the end a table with strikes and all other parameters are NaN. Sometimes the first row gets some values, because of this I think it is some kind of overlapping problem.
Sorry if my question is to long.

Superset 1.0 Reports not running (docker)

having trouble getting reports to run on superset, running latest from /docker
I can set reports from the ui, but nothing happens afterwards.
I see the beat worker is running and waking up every 5 minutes, I also see in the main worker logs:
[2021-02-07 20:01:00,071: DEBUG/MainProcess] TaskPool: Apply <function _fast_trace_task at 0x7f03c6533830> (args:('email_reports.schedule_hourly', 'f1a887b8-4cb6-4d99-aba2-d571f56fcf1c', {'lang': None, 'task': 'email_reports.schedule_hourly', 'id': 'f1a887b8-4cb6-4d99-aba2-d571f56fcf1c', 'root_id': None, 'parent_id': None, 'group': None, 'meth': None, 'shadow': None, 'eta': None, 'expires': None, 'retries': 0, 'timelimit': [None, None], 'argsrepr': None, 'kwargsrepr': None, 'origin': None, 'reply_to': 'feca0569-95f8-39e2-893e-f2f29b904c06', 'correlation_id': 'f1a887b8-4cb6-4d99-aba2-d571f56fcf1c', 'hostname': 'celery#ebb95abd0849', 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}, 'args': [], 'kwargs': {}}, ([], {}, {'callbacks': None, 'errbacks': None, 'chord': None, 'chain': None}), None, None) kwargs:{})
[2021-02-07 20:01:00,097: DEBUG/MainProcess] Task accepted: email_reports.schedule_hourly[f1a887b8-4cb6-4d99-aba2-d571f56fcf1c] pid:17
[2021-02-07 20:01:00,221: INFO/ForkPoolWorker-1] Task email_reports.schedule_hourly[f1a887b8-4cb6-4d99-aba2-d571f56fcf1c] succeeded in 0.1267093000060413s: None
my config:
docker-compose.yaml
added:
superset-beat:
image: *superset-image
container_name: superset_beat
command: ["/app/docker/docker-bootstrap.sh", "beat"]
env_file: docker/.env
restart: unless-stopped
depends_on: *superset-depends-on
user: "root"
volumes: *superset-volumes
docker-bootstrap.sh
modified to:
if [[ "${1}" == "worker" ]]; then
echo "Starting Celery worker..."
celery worker --app=superset.tasks.celery_app:app --pool=prefork -O fair -c 4 -l DEBUG
elif [[ "${1}" == "beat" ]]; then
echo "Starting Celery beat..."
celery beat --app=superset.tasks.celery_app:app -l DEBUG
elif [[ "${1}" == "app" ]]; then
echo "Starting web app..."
flask run -p 8088 --with-threads --reload --debugger --host=0.0.0.0
fi
superset_config.py
modified to:
RESULTS_BACKEND = RedisCache(
host=REDIS_HOST, port=REDIS_PORT)
FEATURE_FLAGS = {
"ALERT_REPORTS": True,
}
class CeleryConfig(object):
BROKER_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_CELERY_DB}"
CELERY_IMPORTS = (
"superset.sql_lab",
"superset.tasks",
)
CELERY_RESULT_BACKEND = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_RESULTS_DB}"
CELERY_ANNOTATIONS = {
"tasks.add": {
"rate_limit": "10/s",
},
"sql_lab.get_sql_results": {
"rate_limit": "100/s",
},
"email_reports.send": {
"rate_limit": "1/s",
"time_limit": 120,
"soft_time_limit": 150,
"ignore_result": True,
},
}
CELERYBEAT_SCHEDULE = {
"email_reports.schedule_hourly": {
"task": "email_reports.schedule_hourly",
"schedule": crontab(minute=1, hour="*"),
},
}
CELERY_TASK_PROTOCOL = 1
CACHE_CONFIG = {
"CACHE_TYPE": "redis",
"CACHE_DEFAULT_TIMEOUT": 60 * 60 * 24, # 1 day default (in secs)
"CACHE_KEY_PREFIX": "superset_results",
"CACHE_REDIS_URL": f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_RESULTS_DB}",
}
CELERY_CONFIG = CeleryConfig
SQLLAB_CTAS_NO_LIMIT = True
ENABLE_SCHEDULED_EMAIL_REPORTS = True
EMAIL_NOTIFICATIONS = True
SMTP_HOST = "smtp.gmail.com"
SMTP_STARTTLS = True
SMTP_SSL = True
SMTP_USER = "df.team.test#gmail.com"
SMTP_PORT = 465
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD")
SMTP_MAIL_FROM = "df.team.test#gmail.com"
You should have the alerts and reports (in case you want both alerts and reports functionality) scheduler set in the CELERYBEAT_SCHEDULE . Here is an example config :
CELERYBEAT_SCHEDULE = {
'email_reports.schedule_hourly': {
'task': 'email_reports.schedule_hourly',
'schedule': crontab(minute=1, hour='*'),
},
'alerts.schedule_check': {
'task': 'alerts.schedule_check',
'schedule': crontab(minute='*', hour='*'),
},
'reports.scheduler': {
'task': 'reports.scheduler',
'schedule': crontab(minute='*', hour='*'),
},
'reports.prune_log': {
'task': 'reports.prune_log',
'schedule': crontab(minute=0, hour=0),
},
'cache-warmup-hourly': {
'task': 'cache-warmup',
'schedule': crontab(minute='*/30', hour='*'),
'kwargs': {
'strategy_name': 'top_n_dashboards',
'top_n': 10,
'since': '7 days ago',
},
},
}

hf-tikz and sphinx are not playing well together

I am trying to add some color to my matrices in sphinx. I was using hf-tikz for it before. However, when I add it to Sphinx, it renders it incorrectly.
The result that I am trying to get is
The result I am getting is
Here is the code that I have.
main.rst:
.. math::
\left(\begin{array}{cc}
\tikzmarkin[style red]{a}a\tikzmarkend{a}
& \tikzmarkin[style green]{b}b\tikzmarkend{b} \\
\tikzmarkin[style blue]{c}c\tikzmarkend{c}
& \tikzmarkin[style orange]{d}d\tikzmarkend{d} \\
\end{array}\right)
\star
\left(\begin{array}{cc}
\tikzmarkin[style red]{w}w\tikzmarkend{w}
& \tikzmarkin[style green]{x}x\tikzmarkend{x} \\
\tikzmarkin[style blue]{y}y\tikzmarkend{y}
& \tikzmarkin[style orange]{z}z\tikzmarkend{z} \\
\end{array}\right)
=
\left(\begin{array}{cc}
\tikzmarkin[hor=style red]{aw}{a\star w}\tikzmarkend{aw}
& \tikzmarkin[hor=style green]{bx}b\star x\tikzmarkend{bx} \\
\tikzmarkin[hor=style blue]{cy}c\star y\tikzmarkend{cy}
& \tikzmarkin[hor=style orange]{dz}d\star z\tikzmarkend{dz} \\
\end{array}\right)
conf.py
extensions = [
'sphinx.ext.imgmath',
]
# Math configurations (https://tex.stackexchange.com/a/69770/51173)
imgmath_image_format = 'svg'
imgmath_use_preview = True
imgmath_latex_preamble = r'''
\usepackage{xcolor}
\usepackage[customcolors]{hf-tikz}
\colorlet{myred}{red!50!purple!30}
\colorlet{mygreen}{green!50!lime!60}
\colorlet{myblue}{blue!50!white!50}
\colorlet{myorange}{orange!80!red!60}
\colorlet{mycyan}{cyan!90!blue!60}
\colorlet{mymagenta}{magenta!90!red!60}
\tikzset{
style red/.style={
set fill color=myred,
set border color=white,
},
style green/.style={
set fill color=mygreen,
set border color=white,
},
style blue/.style={
set fill color=myblue,
set border color=white,
},
style orange/.style={
set fill color=myorange,
set border color=white,
},
style cyan/.style={
set fill color=mycyan,
set border color=white,
},
style magenta/.style={
set fill color=mymagenta,
set border color=white,
},
%
hor/.style={
above left offset={-0.15,0.31},
below right offset={0.15,-0.125},
#1
},
ver/.style={
above left offset={-0.1,0.3},
below right offset={0.15,-0.15},
#1
}
}
'''
Makefile
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
#$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
#$(SPHINXBUILD) -M $# "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
make.bat
#ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
EDIT: Added makefile used to build the rst's
I think I found why this was happening: the problem was in the sphinx.ext.imgmath extension + hf-tikz not working well with the DVI files.
When converting the math equations, sphinx creates a very basic latex document, and compiles it using latexpdf into a DVI file. After that the file is converted into an SVG, and the resulting svg file is copied to the sphinx's _build directory. The problem is that dvisvgm (used by imgmath) cannot convert tikz stuff. Alternative would be using extended DVI, but that doesn't work well either.
The solution is to compile everything into PDF, and convert that pdf into SVG. This is slightly problematic, and the only way I found is to use pdf2svg + pdfcrop. I ended up modifying the imgmath.py into a custom extension. Below are the changes that I put in the imgmath.py. The changes require the use of external applications, so I don't think there is a merit in creating a pull request (at least not with a more scalable solution).
Changes in the imgmath.py:
Create a new method:
def convert_pdf_to_svg(pdfpath, builder):
# type: (str, Builder) -> Tuple[str, int]
"""Convert DVI file to SVG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.svg')
name = 'pdfcrop'
command = [name, pdfpath, pdfpath]
run_external_command(command, name)
name = 'pdf2svg'
command = [name, pdfpath, filename]
run_external_command(command, name)
return filename, None
In the compile_math function, inside the try block, replace the return statement with the following
if builder.config.imgmath_pdf2svg:
return path.join(tempdir, 'math.pdf')
else:
return path.join(tempdir, 'math.dvi')
Inside the render_math method, in the block titles # .dvi -> .png/svg, replace the try block with the following
try:
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
if self.builder.config.imgmath_pdf2svg:
imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
else:
imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
Finally, add a new configuration entry in the very end of the imgmath.py:
app.add_config_value('imgmath_pdf2svg', False, 'html')
After that, you can write in the conf.py to enable the tikz images.
imgmath_image_format = 'svg'
imgmath_latex = 'latexmk'
imgmath_latex_args = ['-pdf']
imgmath_pdf2svg = True # Available only in the custom `imgmath.py`
patch for imgmath extension. Includes some other stuff :)
The patch goes a->b.
--- a/imgmath.py
+++ b/imgmath.py
## -15,7 +15,7 ##
import sys
import tempfile
from hashlib import sha1
-from os import path
+from os import path, symlink
from subprocess import CalledProcessError, PIPE
from typing import Any, Dict, List, Tuple
## -157,6 +157,11 ##
with open(filename, 'w', encoding='utf-8') as f:
f.write(latex)
+ for add_file in builder.config.imgmath_latex_additional_files:
+ filename = path.join(tempdir, path.basename(add_file))
+ if not path.exists(filename):
+ symlink(path.join(builder.confdir, add_file), filename)
+
# build latex command; old versions of latex don't have the
# --output-directory option, so we have to manually chdir to the
# temp dir to run it.
## -165,9 +170,15 ##
command.extend(builder.config.imgmath_latex_args)
command.append('math.tex')
+ output_extension = 'dvi'
+ if builder.config.imgmath_latex == 'xelatex':
+ output_extension = 'xdv'
+ if builder.config.imgmath_pdf2svg:
+ output_extension = 'pdf'
+
try:
subprocess.run(command, stdout=PIPE, stderr=PIPE, cwd=tempdir, check=True)
- return path.join(tempdir, 'math.dvi')
+ return path.join(tempdir, 'math.' + output_extension)
except OSError:
logger.warning(__('LaTeX command %r cannot be run (needed for math '
'display), check the imgmath_latex setting'),
## -177,7 +188,7 ##
raise MathExtError('latex exited with error', exc.stderr, exc.stdout)
-def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
+def run_external_command(command: List[str], name: str) -> Tuple[bytes, bytes]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
## -203,7 +214,7 ##
command.append('--depth')
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -227,7 +238,7 ##
command.extend(builder.config.imgmath_dvisvgm_args)
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -239,6 +250,21 ##
break
return filename, depth
+
+def convert_pdf_to_svg(pdfpath, builder):
+ # type: (str, Builder) -> Tuple[str, int]
+ """Convert DVI file to SVG image."""
+ tempdir = ensure_tempdir(builder)
+ filename = path.join(tempdir, 'math.svg')
+
+ name = 'pdfcrop'
+ command = [name, pdfpath, pdfpath]
+ run_external_command(command, name)
+
+ name = 'pdf2svg'
+ command = [name, pdfpath, filename]
+ run_external_command(command, name)
+ return filename, None
def render_math(self: HTMLTranslator, math: str) -> Tuple[str, int]:
## -291,7 +317,10 ##
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
- imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
+ if self.builder.config.imgmath_pdf2svg:
+ imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
+ else:
+ imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
## -396,8 +425,10 ##
['-gamma', '1.5', '-D', '110', '-bg', 'Transparent'],
'html')
app.add_config_value('imgmath_dvisvgm_args', ['--no-fonts'], 'html')
+ app.add_config_value('imgmath_pdf2svg', False, 'html')
app.add_config_value('imgmath_latex_args', [], 'html')
app.add_config_value('imgmath_latex_preamble', '', 'html')
+ app.add_config_value('imgmath_latex_additional_files', [], 'html')
app.add_config_value('imgmath_add_tooltips', True, 'html')
app.add_config_value('imgmath_font_size', 12, 'html')
app.connect('build-finished', cleanup_tempdir)

Tcl Tk double click binding is blocked by another binding

I work with tcl 8.6
I've got two tablelists (by Nehmeti):
set pfd(frMain) [frame $fr.frMain]
set pfd(bottomFr) [frame $pfd(frMain).bfr]
set pfd(panWin) [panedwindow $pfd(bottomFr).pw -showhandle 1 -orient vertical -sashpad 0 -sashrelief raised -sashwidth 2]
set pfd(frKlaffNeupkt) [frame $pfd(panWin).frKlaffNeupkt]
pack $pfd(frMesswerte) -anchor nw -expand 0 -fill both
pack $pfd(frKlaffNeupkt) -anchor nw -expand 0 -fill both
pack $pfd(panWin) -anchor nw -expand 1 -fill both
$pfd(panWin) add $pfd(frMesswerte) $pfd(frKlaffNeupkt)
set pfd(tali_mw) [tablelist::tablelist $pfd(frMesswerte).li.tali_mw \
-columns {0 "oid" l \
0 "status" l \
0 "art" l \
0 "sollTyp" l \
0 "Nr" l \
0 "Typ" l \
0 "Gst" l \
0 "Hz" r \
0 "V" r \
0 "S" r \
0 "Q" r \
0 "L" r \
0 "AK" l\
0 "LSEX" l \
0 "lfdNrGes" l}\
-exportselection 0 \
-labelbackground #EEEEEE \
-background white \
-labelfont $tableheadfont\
-font $tableinhfont\
-stretch 12\
-selectbackground $vmVConfig::setVar(activeBG) \
-selectforeground $vmVConfig::setVar(activeFG) \
-selectmode single\
-borderwidth 1 \
-labelborderwidth 1 \
-selectborderwidth 0 \
-tooltipaddcommand [::itcl::code $this tooltipAddCmd] \
-tooltipdelcommand [::itcl::code $this tooltipDelCmd] \
-xscrollcommand [list vmTkTools::configSB "h" $pfd(mw_scrx)]\
-yscrollcommand [list vmTkTools::configSB "v" $pfd(mw_scry)]]
set pfd(noteb) [iwidgets::notebook $pfd(frKlaffNeupkt).noteb]
pack $pfd(noteb) -anchor nw -expand 1 -fill both
set pfd(frKlaffungen) [$pfd(noteb) add -label Klaffungen]
set pfd(tali_klaff) [tablelist::tablelist $pfd(frKlaffungen).li.tali_klaff \
-columns {0 "oid" l 0 "Nr" l 0 "dX" r 0 "dY" r 0 "GwX" r 0 "GwY" r 0 "Rdz" r 0 "lfdNrGes" r}\
-exportselection 0 \
-labelbackground #EEEEEE \
-background white \
-labelfont $tableheadfont\
-font $tableinhfont\
-stretch 7\
-selectbackground $vmVConfig::setVar(activeBG) \
-selectforeground $vmVConfig::setVar(activeFG) \
-selectmode single\
-labelrelief groove \
-borderwidth 1 \
-labelborderwidth 1 \
-selectborderwidth 0 \
-xscrollcommand [list vmTkTools::configSB "h" $pfd(klaff_scrx)]\
-yscrollcommand [list vmTkTools::configSB "v" $pfd(klaff_scry)]]
Both tablelist have Bindings:
set body [$pfd(tali_mw) bodypath]
bind $body <Button-1> +[::itcl::code $this klickZeile %x %y %W]
bind $body <Double-1> +[::itcl::code $this doubleKlickMesswerte %x %y %W]
set body [$pfd(tali_klaff) bodypath]
bind $body <Button-1> [::itcl::code $this klickZeile %x %y %W]
The method klickZeile looks like this
itcl::body vmMaskHelmert::klickZeile {x y W} {
puts "klickZeile"
delCommonKreuz
foreach {pfad xC yC} [tablelist::convEventFields $W $x $y] {}
set row [$pfad containing $yC]
if {$row == -1} {
set row end
}
if {[string first "tali_mw" $W] != -1} {
# select the row
$pfd(tali_mw) activate $row
$pfd(tali_mw) selection clear 0 end
$pfd(tali_mw) selection set $row $row
anzeigePpMp
} else {
$pfd(tali_klaff) activate $row
$pfd(tali_klaff) selection clear 0 end
$pfd(tali_klaff) selection set $row $row
anzeigePpMp4Klaff
}
return
}
It seems, that the method klickZeile blocks my double click binding, the method doubleKlickMesswerte is not being called.
In klickZeile two corresponding rows in both tablelists are selected.
I tried to comment out the two blocks with "activate $row, selection clear 0 end and selection set $row $row". In that case, doubleKlickMesswerte is being called but unfortunately the method klickZeile doesn't work correctly. It seems that in that case the method selects the corresponding row for the row selected before.
So I've got two questions:
How can I prevent the method klickZeile from blocking the double click binding?
Or, if there is no way for this, what can I do, to make the method "klickZeile" work correctly without extra selection and activation?
Thanks for your help!
Mouse click events (at least single/double/triple) without modifiers (like Control) will all trigger when a bind to triple is set up and the user triple-clicks on the target element. The GUI cannot predict that another click is coming. It has to dispatch the single-click event first, followed by the double, then the triple.
Your best alternative is to use a modifier, such as a , because this is unique and does not depend on sequence, as long as the Control button is pressed first ;)
proc doClick { widget } {
puts "You clicked [$widget cget -text]"
}
proc doControlClick { widget } {
puts "You control-clicked [$widget cget -text]"
}
set label_1 [label .l1 -text "This is label 1"]
pack $label_1 -side top -fill both
bind $label_1 <Control-Button-1> { doControlClick %W }
bind $label_1 <Button-1> { doClick %W }

tensorflow cifar-10 evaluation example softmax outputs

I want to view the probabilities of each test image, so I modified the code(cifar10_eval.py) like this
def eval_once(saver, summary_writer, logits, labels, top_k_op, summary_op):
...............
while step < num_iter and not coord.should_stop():
result1, result2 = sess.run([logits, labels])
print('Step:', step, 'result',result1, 'Label:', result2)
...............
and I run the python code like this.
# python cifar10_eval.py --batch_size=1 --run_once=True
The screen results are like this
Step: 0 result [[ 0.01539493 -0.00109618 -0.00364288 -0.00898853 -0.00086198 0.00587899 0.00981337 -0.00785329 -0.00282823 -0.00171288]] Label: [4]
Step: 1 result [[ 0.01539471 -0.00109601 -0.00364273 -0.00898863 -0.00086192 0.005879 0.00981339 -0.00785322 -0.00282811 -0.00171296]] Label: [7]
Step: 2 result [[ 0.01539475 -0.00109617 -0.00364274 -0.00898876 -0.00086183 0.00587886 0.00981328 -0.00785333 -0.00282814 -0.00171295]] Label: [8]
Step: 3 result [[ 0.01539472 -0.00109597 -0.00364275 -0.0089886 -0.00086183 0.00587902 0.00981344 -0.00785326 -0.00282817 -0.00171299]] Label: [4]
Step: 4 result [[ 0.01539488 -0.00109631 -0.00364294 -0.00898863 -0.00086199 0.00587896 0.00981327 -0.00785329 -0.00282809 -0.00171307]] Label: [0]
Step: 5 result [[ 0.01539478 -0.00109607 -0.00364292 -0.00898858 -0.00086194 0.00587904 0.00981335 -0.0078533 -0.00282818 -0.00171321]] Label: [4]
Step: 6 result [[ 0.01539493 -0.00109627 -0.00364277 -0.00898873 -0.0008618 0.00587892 0.00981339 -0.00785325 -0.00282807 -0.00171289]] Label: [9]
Step: 7 result [[ 0.01539504 -0.00109619 -0.0036429 -0.00898865 -0.00086194 0.00587894 0.0098133 -0.00785331 -0.00282818 -0.00171294]] Label: [4]
Step: 8 result [[ 0.01539493 -0.00109627 -0.00364286 -0.00898867 -0.00086183 0.00587899 0.00981332 -0.00785329 -0.00282825 -0.00171283]] Label: [8]
Step: 9 result [[ 0.01539495 -0.00109617 -0.00364286 -0.00898852 -0.00086186 0.0058789 0.00981337 -0.00785326 -0.00282827 -0.00171287]] Label: [9]
The Label values seem to be good, but the logits outputs seem to be same values!
Why?
Anyone can tell me the reason?
This is new cifar10_eval.py source code.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import math
import time
import numpy as np
import tensorflow as tf
#from tensorflow.models.image.cifar10 import cifar10
import cifar10
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('eval_dir', '/tmp/cifar10_eval',
"""Directory where to write event logs.""")
tf.app.flags.DEFINE_string('eval_data', 'test',
"""Either 'test' or 'train_eval'.""")
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train',
"""Directory where to read model checkpoints.""")
tf.app.flags.DEFINE_integer('eval_interval_secs', 60 * 5,
"""How often to run the eval.""")
tf.app.flags.DEFINE_integer('num_examples', 10000,
"""Number of examples to run.""")
tf.app.flags.DEFINE_boolean('run_once', True,
"""Whether to run eval only once.""")
def eval_once(saver, summary_writer, logits, labels, top_k_op, summary_op):
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
else:
print('No checkpoint file found')
return
# Start the queue runners.
coord = tf.train.Coordinator()
try:
threads = []
for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
threads.extend(qr.create_threads(sess, coord=coord, daemon=True,
start=True))
#num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size))
#total_sample_count = num_iter * FLAGS.batch_size
num_iter = FLAGS.num_examples
total_sample_count = FLAGS.num_examples
print (num_iter, FLAGS.batch_size, total_sample_count)
true_count = 0 # Counts the number of correct predictions.
step = 0
time.sleep(1)
while step < num_iter and not coord.should_stop():
result1, result2 = sess.run([logits, labels])
#label = sess.run(labels)
print('Step:', step, 'result',result1, 'Label:', result2)
step += 1
precision = true_count / step
print('Summary -- Step:', step, 'Accurcy:',true_count * 100.0 / step * 1.0, )
print('%s: total:%d true:%d precision # 1 = %.3f' % (datetime.now(), total_sample_count, true_count, precision))
except Exception as e: # pylint: disable=broad-except
coord.request_stop(e)
coord.request_stop()
coord.join(threads, stop_grace_period_secs=10)
def evaluate():
"""Eval CIFAR-10 for a number of steps."""
with tf.Graph().as_default():
# Get images and labels for CIFAR-10.
eval_data = FLAGS.eval_data == 'test'
images, labels = cifar10.inputs(eval_data=eval_data, )
# Build a Graph that computes the logits predictions from the
# inference model. logits is softmax
logits = cifar10.inference(images)
# Calculate predictions.
top_k_op = tf.nn.in_top_k(logits, labels, 1)
# Restore the moving average version of the learned variables for eval.
variable_averages = tf.train.ExponentialMovingAverage(
cifar10.MOVING_AVERAGE_DECAY)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
# Build the summary operation based on the TF collection of Summaries.
summary_op = tf.merge_all_summaries()
graph_def = tf.get_default_graph().as_graph_def()
summary_writer = tf.train.SummaryWriter(FLAGS.eval_dir,
graph_def=graph_def)
while True:
eval_once(saver, summary_writer, logits, labels,top_k_op, summary_op)
if FLAGS.run_once:
break
time.sleep(FLAGS.eval_interval_secs)
def main(argv=None): # pylint: disable=unused-argument
cifar10.maybe_download_and_extract()
if tf.gfile.Exists(FLAGS.eval_dir):
tf.gfile.DeleteRecursively(FLAGS.eval_dir)
tf.gfile.MakeDirs(FLAGS.eval_dir)
print('Evaluate Start')
evaluate()
if __name__ == '__main__':
tf.app.run()
I have trained with 1k steps(accuracy 10% or so).
But after I trained with 100k steps(accuracy 86% or so), the result is very good
.................
Step: 9991 result: [[ 1.30259633 0.71064955 -2.6035285 -1.30183697 -4.1291523 -3.00246906 0.30873945 -4.02916574 13.05054665 -0.42556083]] Label: 8
Step: 9992 result: [[-1.05670786 -1.86572766 0.28350741 1.78929067 0.03841069 1.23079467 2.97172165 -1.18722486 -1.17184007 -1.02505279]] Label: 6
Step: 9993 result: [[ 1.50454926 2.34122658 -3.45632267 -0.55308843 -4.35214806 -2.28931832 -1.74908364 -4.71527719 11.44062901 1.72015083]] Label: 8
Step: 9994 result: [[ 1.96891284 -2.57139373 0.29864013 1.30923986 1.72708285 0.95571399 -0.49331608 0.49454236 -2.26134181 -1.39561605]] Label: 0
Step: 9995 result: [[-0.65523863 1.58577776 0.13226865 1.43122363 -2.34669352 0.18927786 -2.51019335 -1.70729315 -0.21297894 4.06098557]] Label: 9
Step: 9996 result: [[-2.17944765 -3.22895575 2.29571438 2.63287306 0.46685112 4.42715979 -0.76104468 2.39603662 -3.21783161 -2.8433671 ]] Label: 2
Step: 9997 result: [[ 4.26957560e+00 1.95574760e-03 1.91038296e-01 -8.00723195e-01 -2.36319876e+00 -2.12906289e+00 -3.35138845e+00 7.97132492e-01 6.60009801e-01 2.73786736e+00]] Label: 0
Step: 9998 result: [[ 0.42694128 -2.07150149 0.47749567 2.62247086 1.11608386 3.05186462 -0.19805858 0.03386561 -2.87092948 -2.59781456]] Label: 5
Step: 9999 result: [[ 0.23629765 -3.21540785 1.01075113 0.46802399 3.44423246 0.25743011 4.71304989 -1.12128389 -3.07727337 -2.7076664 ]] Label: 6
2016-04-09 00:32:49.861650 Total:10000 True:8631: precision # 1 = 0.863

Resources