I am using headless chrome based on alpine:3.7 image under docker. However, when I take a screenshot using Chrome DevTools Protocol, I found alpine cannot show languages other than English like the screenshot below.
I have tried to copy font to docker image
COPY NotoSansCJKsc-Regular.otf /usr/share/fonts/
and tried to install font in alpine source:
RUN apk add --no-cache bash \
ttf-ubuntu-font-family \
font-adobe-100dpi \
font-noto \
ttf-dejavu \
But all methods failed. So my question is is Alpine support Chinese? And How can I use it using Docker?
python code to take the screenshot:
import threading
import pychrome
import time
import base64
class EventHandler(object):
screen_lock = threading.Lock()
def __init__(self, browser, tab):
self.browser = browser
self.tab = tab
self.start_frame = None
self.html_content = None
self.is_first_request = True
def frame_start_loading(self, frameId):
if not self.start_frame:
self.start_frame = frameId
def request_intercepted(self, interceptionId, request, **kwargs):
if self.is_first_request:
self.is_first_request = False
headers = request.get('headers', {})
self.tab.Network.continueInterceptedRequest(
interceptionId=interceptionId,
headers=headers,
method='POST',
postData="hello post data: %s" % time.time()
)
else:
self.tab.Network.continueInterceptedRequest(
interceptionId=interceptionId
)
def frame_stop_loading(self, frameId):
if self.start_frame == frameId:
self.tab.Page.stopLoading()
result = self.tab.Runtime.evaluate(expression="document.documentElement.outerHTML")
self.html_content = result.get('result', {}).get('value', "")
print self.html_content
self.tab.stop()
def close_all_tabs(browser):
if len(browser.list_tab()) == 0:
return
for tab in browser.list_tab():
try:
tab.stop()
except pychrome.RuntimeException:
pass
browser.close_tab(tab)
assert len(browser.list_tab()) == 0
if __name__ == '__main__':
# create a browser instance
browser = pychrome.Browser(url="http://127.0.0.1:9222")
print browser.version()
# create a tab
tab = browser.new_tab()
# register callback
def request_will_be_sent(**kwargs):
print("[start] start loading: %s" % kwargs.get('request').get('url'))
tab.set_listener("Network.requestWillBeSent", request_will_be_sent)
def received_callback(**kwargs):
print "[received] response type %s" % kwargs.get('type', '')
resp = kwargs.get('response', {})
resp_status = resp.get('status', '')
resp_headers = resp.get('headersText')
print "response status %s %s" % (resp_status, resp_headers)
tab.set_listener("Network.responseReceived", received_callback)
def frame_stop_loading():
print "frame stop loading"
tab.set_listener("Page.frameStoppedLoading", frame_stop_loading)
def loading_finished(**kwargs):
print "[loading finished]"
# when HTTP request has finished loading
tab.set_listener("Network.loadingFinished", loading_finished)
# start the tab
tab.start()
net = tab.call_method("Network.enable")
navi = tab.call_method("Page.navigate", url="https://www.douban.com", _timeout=5)
tab.wait(5)
screen_data = tab.call_method("Page.captureScreenshot")
image_data = screen_data.get('data', '')
with open("image.png", "wb") as file:
file.write(image_data.decode('base64'))
html = tab.Runtime.evaluate(expression="document.documentElement.outerHTML")
print html['result']['value']
all_cookies = tab.Network.getAllCookies()
print all_cookies
tab.stop()
browser.close_tab(tab)
Install wqy-zenhei package at testing channel will fix it.
echo #edge http://nl.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && apk add wqy-zenhei#edge
Related
I have this partial Lua Script which is working perfectly with Wireshark:
local function appl_rtt_dialog_menu()
local win = TextWindow.new("Application Latency");
local label = ""
local tot = 0
local i
i = 0
label = label .. "Server\t\tMin Application RTT\n"
for k,v in pairsByValues(min_appl_RRT, rev) do
label = label .. string.format("%-20s\t%.3f / %.3f msec\n", shortenString(k), v, max_appl_RRT[k])
if(i == max_num_entries) then break else i = i + 1 end
end
win:set(label)
win:add_button("Clear", function() win:clear() end)
end
I am trying to modify it for using in Tshark. since the script is written for GUI and Tshark has none, I change it in order to print to the console:
do
local function appl_rtt()
local label = ""
local i
i = 0
label = label .. "Server\t\tMin Application RTT\n"
for k,v in pairsByValues(min_appl_RRT, rev) do
label = label .. string.format("%-20s\t%.3f / %.3f msec\n", shortenString(k), v, max_appl_RRT[k])
print(label)
if(i == max_num_entries) then break else i = i + 1 end
end
end
appl_rtt()
end
but there is no output.
the full script: https://github.com/ntop/nDPI/blob/dev/wireshark/ndpi.lua
for execute in Tshark: tshark -r test.pcap -X lua_script:test.lua -q
does anyone know how to change the script?
I have fixed it with Listener() and draw() functions.
I am novice in python and on my way to completing my first desktop application. I have some reports but don't know how to send them to printer with the click of a button
Below is an example I got from PyQT's website. It helped me out quite a bit. You will have to install pip and PyQT5
from the command prompt type:
pip install PyQT5
import sys, os
from PyQt5 import QtCore, QtWidgets, QtPrintSupport
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.setWindowTitle('Document Printer')
self.editor = QtWidgets.QTextEdit(self)
self.editor.textChanged.connect(self.handleTextChanged)
self.buttonOpen = QtWidgets.QPushButton('Open', self)
self.buttonOpen.clicked.connect(self.handleOpen)
self.buttonPrint = QtWidgets.QPushButton('Print', self)
self.buttonPrint.clicked.connect(self.handlePrint)
self.buttonPreview = QtWidgets.QPushButton('Preview', self)
self.buttonPreview.clicked.connect(self.handlePreview)
layout = QtWidgets.QGridLayout(self)
layout.addWidget(self.editor, 0, 0, 1, 3)
layout.addWidget(self.buttonOpen, 1, 0)
layout.addWidget(self.buttonPrint, 1, 1)
layout.addWidget(self.buttonPreview, 1, 2)
self.handleTextChanged()
def handleOpen(self):
path = QtWidgets.QFileDialog.getOpenFileName(
self, 'Open file', '',
'HTML files (*.html);;Text files (*.txt)')[0]
if path:
file = QtCore.QFile(path)
if file.open(QtCore.QIODevice.ReadOnly):
stream = QtCore.QTextStream(file)
text = stream.readAll()
info = QtCore.QFileInfo(path)
if info.completeSuffix() == 'html':
self.editor.setHtml(text)
else:
self.editor.setPlainText(text)
file.close()
def handlePrint(self):
dialog = QtPrintSupport.QPrintDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.editor.document().print_(dialog.printer())
def handlePreview(self):
dialog = QtPrintSupport.QPrintPreviewDialog()
dialog.paintRequested.connect(self.editor.print_)
dialog.exec_()
def handleTextChanged(self):
enable = not self.editor.document().isEmpty()
self.buttonPrint.setEnabled(enable)
self.buttonPreview.setEnabled(enable)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
I tried to render a variable('predictions') in URL(/predict) on url('/hello'). I am beginner in the web development. If someone knows , please help.
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
def apicall(responses = None):
test_json = request.get_json()
test = pd.read_json(test_json, orient='records')
query_df = pd.DataFrame(test)
clf = 'kmeans__model.pkl'
print("Loading the model...")
lin_reg_model = None
with open(clf,'rb') as f:
lin_reg_model = joblib.load(f)
# lin_reg_model = joblib.load('/home/q/new_project/models/kmeans_model.pkl')
print("The model has been loaded...doing predictions now...")
predictions = lin_reg_model.predict(test)
print(predictions)
prediction_series = list(pd.Series(predictions))
final_predictions = pd.DataFrame(list(zip(prediction_series)))
responses = jsonify(predictions=final_predictions.to_json(orient="records"))
responses.status_code = 200
return (responses)
#app.route('/hello')
def hello():
**What should be used here to render *predictions*?**
return 'Hello, World '
You can return to template and show in html if you like. Create templates folder and create html file.
import requests
def hello():
response = requests.get(url_for('apicall'))
return render_template('<yourtemplate.html>', predictions=response.json())
HTML
{{ predictions }}
Note: Please follow this link for any problem with thread and deployment Handling multiple requests in Flask
We have a Windows based SPSS server say 10.20.30.40. We would like to kick off a SPSS Production job from another server 10.20.30.50.
Can we kick off the job using a batch file?
1.Create an SPJ file in production.
2.make a bat file to run spj
"C:\Program Files\IBM\SPSS\Statistics\21\stats.exe" -production "K:\Meinzer\Production\SPJ\DashBoardInsert.spj"
create a 'scheduled task' in windows.
The real issue is getting your output from the job. for that, i use python.
I use syntax like this
begin program.
AlertDays=4
Files=['k:\meinzer/Production\dashboarddatasets/aod_network_report.sps',
'k:\meinzer/Production\push/aod_network_reportpush.sps',
'k:\meinzer/Production\pushproduction/aod_network_reportpushP.sps']
end program.
insert file='k:/meinzer/production/ps/errorTestPickles.sps'.
to trigger this
*still needs error info passed.
set mprint=off /printback=on.
begin program.
#test files to observe - uncomment out 8 or 9
#Files=['k:\meinzer/Production\dashboarddatasets/test.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/testfail.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/clinfo.sps']
#Files=['k:\meinzer/Production\dashboarddatasets/CSOC_Consecutive_High_Level_Svcs.sps']
import shutil
import spss
import re, os, pickle
from datetime import datetime
def main(Files):
"""The parser and processor for Syntax Error Reporting """
try:
for FilePath in Files:
Start = datetime.now().replace( microsecond=0)
DBname, init_Syntax = init_Vars(FilePath)
cmds = init_cmds(init_Syntax)
cmd=''
cmd2=''
cmd3=''
try:
for cmd in cmds:
cmd=cmd.replace('\r\n','\n ')
cmd=cmd.replace('\t',' ')
print cmd
spss.Submit(cmd)
cmd3=cmd2
cmd2=cmd
# cmd, cmd2, cmd3=run_cmds(cmd,cmd2,cmd3,cmds)
Finish = datetime.now().replace( microsecond=0)
spss_Output(DBname)
SavedNewname=check_saved_new_name(DBname)
if SavedNewname==1:
send_result(DBname,'Failure',Start,Finish,0,cmd,cmd2,cmd3)
break
if SavedNewname==0:
send_result(DBname,'Success',Start,Finish,1,AlertDays)
except Exception,e:
Finish = datetime.now().replace( microsecond=0)
errorLevel, errorMsg = get_spss_error(e)
send_result(DBname,"Failure in code",Start,Finish,0,AlertDays,cmd,cmd2,cmd3,errorLevel, errorMsg )
spss_Output(DBname)
break
except IOError:
print "can't open file or difficulty initializing comands from spss"
send_result('Can not open File %s' % DBname,Start,Finish)
spss_Output(DBname)
def init_Vars(FilePath):
FilePath=FilePath.encode('string-escape')
#FilePath= map(os.path.normpath, FilePath)
FilePath=FilePath.replace('\\','/')
FilePath=FilePath.replace('/x07','/a')
FilePath=FilePath.replace('//','/')
FilePath=FilePath.replace('/x08','/b')
FilePath=FilePath.replace('/x0b','/v')
FilePath=FilePath.replace('/x0c','/v')
print 'this is the file path..................... '+FilePath
DBname = os.path.split(os.path.normpath(FilePath))[-1]
#if '\\' in FilePath:
# DBname=FilePath.rpartition('\\')[-1]
#if '/' in FilePath:
# DBname=FilePath.rpartition('/')[-1]
init_Syntax=FilePath
OutputClose="output close name=%s." % DBname
OutputNew="output new name=%s." % DBname
spss.Submit(OutputClose)
spss.Submit(OutputNew)
return (DBname, init_Syntax)
def init_cmds(init_Syntax):
with open(init_Syntax,'rb') as f:
BOM_UTF8 = "\xef\xbb\xbf"
code = f.read().lstrip(BOM_UTF8)
#r = re.compile('(?<=\.)\s*?^\s*',re.M)
r = re.compile('(?<=\.)\s*?^\s*|\s*\Z|\A\s*',re.M)
cmds = r.split(code)
#cmds = re.split("(?<=\\.)%s[ \t]*" % os.linesep, code, flags=re.M)
#cmds = re.split(r'(?<=\.)[ \t]*%s' % os.linesep, code, flags=re.M)
cmds = [cmdx.lstrip() for cmdx in cmds if not cmdx.startswith("*")]
return cmds
def run_cmds(cmd,cmd2,cmd3,cmds):
for cmd in cmds:
cmd=cmd.replace('\r\n','\n ')
cmd=cmd.replace('\t',' ')
print cmd
spss.Submit(cmd)
cmd3=cmd2
cmd2=cmd
return (cmd, cmd2, cmd3)
def send_result(DBname,result,Start,Finish,status,AlertDays,cmd='',cmd2='',cmd3='',errorLevel='', errorMsg=''):
""" """
print result + ' was sent for '+DBname
FinishText = Finish.strftime("%m-%d-%y %H:%M")
StartText = Start.strftime("%m-%d-%y %H:%M")
Runtimex = str(Finish-Start)[0:7]
error_result="""%s %s
Start Finish Runtime Hrs:Min:Sec
%s %s %s """ % (DBname,result,StartText,FinishText,Runtimex)
error_result_email="""%s <br>
%s <br> Runtime %s <br>\n""" % (result,DBname,Runtimex)
with open("k:/meinzer/production/output/Error Log.txt", "r+") as myfile:
old=myfile.read()
myfile.seek(0)
if status==1:
myfile.write(error_result+"\n\n"+ old)
if status==0:
myfile.write(error_result+'\n'+'This was the problem\n'+errorLevel+" "+ errorMsg+'\n'+cmd3+'\n'+cmd2+'\n'+cmd+"\n\n"+ old)
# with open("k:/meinzer/production/output/email Log.txt", "r+") as emailtext:
# olde=emailtext.read()
# emailtext.seek(0)
# emailtext.write(error_result_email+ olde)
with open("k:/meinzer/production/output/ErrorCSV.txt", "r+") as ErrorCSV:
oldcsv=ErrorCSV.read()
ErrorCSV.seek(0)
ErrorCSV.write(DBname+','+str(status)+','+FinishText+",0"+','+str(AlertDays)+"\n"+ oldcsv)
def check_saved_new_name(DBname):
""" check saved new name"""
with open("k:/meinzer/production/output/text/"+DBname+".txt", "r") as searchfile:
if 'Warning # 5334' in open("k:/meinzer/production/output/text/"+DBname+".txt", "r").read():
SavedNewname=True
else:
SavedNewname=False
return SavedNewname
def get_spss_error(e):
print 'Error', e
errorLevel=str(spss.GetLastErrorLevel())
errorMsg=spss.GetLastErrorMessage()
return (errorLevel, errorMsg)
def spss_Output(DBname):
""" """
outputtext="output export /text documentfile='k:/meinzer/production/output/text/%s.txt'." % DBname
outputspv="output save outfile='k:/meinzer/production/output/%s.spv'." % DBname
spss.Submit(outputspv)
spss.Submit(outputtext)
main(Files)
end program.
I am using UIAutomation scripts to test my iOS application. I've managed to get the scripts running from the command line but now I need to convert the output (pass/fails) in a format that Jenkins can understand, ideally JUnit style.
Has anyone written any scripts to do this before I try & write one?
Many thanks
Maybe you can have a look at : https://github.com/shaune/jasmine-ios-acceptance-tests
Edit :
I've also avoided to use jasmine. To 'listen' start, pass and fail test, I've simply replaced UIALogger.logStart, UIALogger.logFail and UIALogger.logPass :
(function () {
// An anonymous function wrapper helps you keep oldSomeFunction private
var oldSomeFunction = UIALogger.logStart;
UIALogger.logStart = function () {
//UIALogger.logDebug("intercepted a logStart : " + arguments);
OKJunitLogger.reportTestSuiteStarting(arguments[0]);
oldSomeFunction.apply(this, arguments);
}
})();
I bealive you will find what you need here:
https://github.com/shinetech/jenkins-ios-example
What you're interest in is the script call "ocunit2junit.rb"
I used it for a project, it work very well.
#!/usr/bin/ruby
#
# ocunit2junit.rb was written by Christian Hedin <christian.hedin#jayway.com>
# Version: 0.1 - 30/01 2010
# Usage:
# xcodebuild -yoursettings | ocunit2junit.rb
# All output is just passed through to stdout so you don't miss a thing!
# JUnit style XML-report are put in the folder specified below.
#
# Known problems:
# * "Errors" are not cought, only "warnings".
# * It's not possible to click links to failed test in Hudson
# * It's not possible to browse the source code in Hudson
#
# Acknowledgement:
# Big thanks to Steen Lehmann for prettifying this script.
################################################################
# Edit these variables to match your system
#
#
# Where to put the XML-files from your unit tests
TEST_REPORTS_FOLDER = "test-reports"
#
#
# Don't edit below this line
################################################################
require 'time'
require 'FileUtils'
require 'socket'
class ReportParser
attr_reader :exit_code
def initialize(piped_input)
#piped_input = piped_input
#exit_code = 0
FileUtils.rm_rf(TEST_REPORTS_FOLDER)
FileUtils.mkdir(TEST_REPORTS_FOLDER)
parse_input
end
private
def parse_input
#piped_input.each do |piped_row|
puts piped_row
case piped_row
when /Test Suite '(\S+)'.*started at\s+(.*)/
t = Time.parse($2.to_s)
handle_start_test_suite(t)
when /Test Suite '(\S+)'.*finished at\s+(.*)./
t = Time.parse($2.to_s)
handle_end_test_suite($1,t)
when /Test Case '-\[\S+\s+(\S+)\]' started./
test_case = $1
when /Test Case '-\[\S+\s+(\S+)\]' passed \((.*) seconds\)/
test_case = $1
test_case_duration = $2.to_f
handle_test_passed(test_case,test_case_duration)
when /(.*): error: -\[(\S+) (\S+)\] : (.*)/
error_location = $1
test_suite = $2
test_case = $3
error_message = $4
handle_test_error(test_suite,test_case,error_message,error_location)
when /Test Case '-\[\S+ (\S+)\]' failed \((\S+) seconds\)/
test_case = $1
test_case_duration = $2.to_f
handle_test_failed(test_case,test_case_duration)
when /failed with exit code (\d+)/
#exit_code = $1.to_i
when
/BUILD FAILED/
#exit_code = -1;
end
end
end
def handle_start_test_suite(start_time)
#total_failed_test_cases = 0
#total_passed_test_cases = 0
#tests_results = Hash.new # test_case -> duration
#errors = Hash.new # test_case -> error_msg
#ended_current_test_suite = false
#cur_start_time = start_time
end
def handle_end_test_suite(test_name,end_time)
unless #ended_current_test_suite
current_file = File.open("#{TEST_REPORTS_FOLDER}/TEST-#{test_name}.xml", 'w')
host_name = string_to_xml Socket.gethostname
test_name = string_to_xml test_name
test_duration = (end_time - #cur_start_time).to_s
total_tests = #total_failed_test_cases + #total_passed_test_cases
suite_info = '<testsuite errors="0" failures="'+#total_failed_test_cases.to_s+'" hostname="'+host_name+'" name="'+test_name+'" tests="'+total_tests.to_s+'" time="'+test_duration.to_s+'" timestamp="'+end_time.to_s+'">'
current_file << "<?xml version='1.0' encoding='UTF-8' ?>\n"
current_file << suite_info
#tests_results.each do |t|
test_case = string_to_xml t[0]
duration = #tests_results[test_case]
current_file << "<testcase classname='#{test_name}' name='#{test_case}' time='#{duration.to_s}'"
unless #errors[test_case].nil?
# uh oh we got a failure
puts "tests_errors[0]"
puts #errors[test_case][0]
puts "tests_errors[1]"
puts #errors[test_case][1]
message = string_to_xml #errors[test_case][0].to_s
location = string_to_xml #errors[test_case][1].to_s
current_file << ">\n"
current_file << "<failure message='#{message}' type='Failure'>#{location}</failure>\n"
current_file << "</testcase>\n"
else
current_file << " />\n"
end
end
current_file << "</testsuite>\n"
current_file.close
#ended_current_test_suite = true
end
end
def string_to_xml(s)
s.gsub(/&/, '&').gsub(/'/, '"').gsub(/</, '<')
end
def handle_test_passed(test_case,test_case_duration)
#total_passed_test_cases += 1
#tests_results[test_case] = test_case_duration
end
def handle_test_error(test_suite,test_case,error_message,error_location)
# error_message.tr!('<','').tr!('>','')
#errors[test_case] = [ error_message, error_location ]
end
def handle_test_failed(test_case,test_case_duration)
#total_failed_test_cases +=1
#tests_results[test_case] = test_case_duration
end
end
#Main
#piped_input = File.open("tests_fail.txt") # for debugging this script
piped_input = ARGF.read
report = ReportParser.new(piped_input)
exit report.exit_code
Maybe you can use this.
And in Jenkins execute shell:
sh setup.sh sh runTests.sh ./sample/alltests.js "/Users/komejun/Library/Application Support/iPhone Simulator/5.0/Applications/1622F505-8C07-47E0-B0F0-3A125A88B329/Recipes.app/"
And the report will be auto-created in ./ynmsk-report/test.xml
You can use the tuneupjs library. The library provides test runner that generates a xml report (jUnit style). It works with Xcode 6. For the xml report just provide -x param. Check it here: http://www.tuneupjs.org/running.html