def print_event_stream():
"""Print event stream"""
controllers = discover()
# for now only care about one controller
controller = next(controllers, None) or exit('no tellstick devices found')
if argv[-1] == "raw":
stream = map(prepend_timestamp, controller.packets())
else:
stream = controller.events()
for packet in stream:
print(packet)
try:
stdout.flush()
except IOError:
# broken pipe
pass
python类flush()的实例源码
def test_pos(model, sentences, display=False):
from sys import stdout
count = correct = 0
for sentence in sentences:
sentence = [(token[0], None) for token in sentence]
pts = model.best_path(sentence)
if display:
print sentence
print 'HMM >>>'
print pts
print model.entropy(sentences)
print '-' * 60
else:
print '\b.',
stdout.flush()
for token, tag in zip(sentence, pts):
count += 1
if tag == token[TAG]:
correct += 1
print 'accuracy over', count, 'tokens %.1f' % (100.0 * correct / count)
def test_pos(model, sentences, display=False):
from sys import stdout
count = correct = 0
for sentence in sentences:
sentence = [(token[0], None) for token in sentence]
pts = model.best_path(sentence)
if display:
print sentence
print 'HMM >>>'
print pts
print model.entropy(sentences)
print '-' * 60
else:
print '\b.',
stdout.flush()
for token, tag in zip(sentence, pts):
count += 1
if tag == token[TAG]:
correct += 1
print 'accuracy over', count, 'tokens %.1f' % (100.0 * correct / count)
def test_pos(model, sentences, display=False):
from sys import stdout
count = correct = 0
for sentence in sentences:
sentence = [(token[0], None) for token in sentence]
pts = model.best_path(sentence)
if display:
print sentence
print 'HMM >>>'
print pts
print model.entropy(sentences)
print '-' * 60
else:
print '\b.',
stdout.flush()
for token, tag in zip(sentence, pts):
count += 1
if tag == token[TAG]:
correct += 1
print 'accuracy over', count, 'tokens %.1f' % (100.0 * correct / count)
linux-soft-exploit-suggester.py 文件源码
项目:linux-soft-exploit-suggester
作者: belane
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def updateDB():
""" Download latest exploits DB """
update_url = 'https://raw.githubusercontent.com/offensive-security/exploit-database/master/files.csv'
try:
print 'Updating exploits db',
from sys import stdout
stdout.flush()
import urllib
urllib.urlretrieve(update_url, 'files.csv')
print 'DONE.'
except:
print 'ERROR. Unable to download.'
def main():
timings = False
start = time.time()
initialize()
if timings: print('initialize {} s'.format(time.time() - start), file=stderr)
start = time.time()
command_table = load_command_table()
if timings: print('load_command_table {} s'.format(time.time() - start), file=stderr)
start = time.time()
group_index = get_group_index(command_table)
if timings: print('get_group_index {} s'.format(time.time() - start), file=stderr)
start = time.time()
snippets = get_snippets(command_table) if AUTOMATIC_SNIPPETS_ENABLED else []
if timings: print('get_snippets {} s'.format(time.time() - start), file=stderr)
while True:
line = stdin.readline()
start = time.time()
request = json.loads(line)
response_data = None
if request['data'].get('request') == 'status':
response_data = get_status()
if timings: print('get_status {} s'.format(time.time() - start), file=stderr)
elif request['data'].get('request') == 'hover':
response_data = get_hover_text(group_index, command_table, request['data']['command'])
if timings: print('get_hover_text {} s'.format(time.time() - start), file=stderr)
else:
response_data = get_completions(group_index, command_table, snippets, request['data'], True)
if timings: print('get_completions {} s'.format(time.time() - start), file=stderr)
response = {
'sequence': request['sequence'],
'data': response_data
}
output = json.dumps(response)
stdout.write(output + '\n')
stdout.flush()
stderr.flush()
def __next__(self):
"""
next overload. If display is true the latest stetistics are displayed
:return: The next number in iterator
"""
if self.display:
self.__restart_line()
stdout.write(str(self))
stdout.flush()
if self.current >= self.end:
raise StopIteration
self.current += self.step
return self.current - self.step
def __restart_line():
"""
Writes return carriage to stdout and flushes. This allows writing to the same line.
:return: None
"""
stdout.write('\r')
stdout.flush()
def __next__(self):
"""
next overload. If display is true the latest stetistics are displayed
:return: The next number in iterator
"""
if self.display:
self.__restart_line()
stdout.write(str(self))
stdout.flush()
if self.current >= self.end:
raise StopIteration
self.current += self.step
return self.current - self.step
def __restart_line():
"""
Writes return carriage to stdout and flushes. This allows writing to the same line.
:return: None
"""
stdout.write('\r')
stdout.flush()
jira_confluence_backup.py 文件源码
项目:jira-confluence-backup
作者: MyMedsAndMe
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def monitor(s):
r = s.get(url=progress_url)
try:
progress_data = json.loads(r.text)
except ValueError:
print """No JSON object could be decoded.
Get progress failed to return expected data.
Return code: %s """ % (r.status_code)
result = ['No JSON object could be decoded\
- get progress failed to return expected data\
Return code: %s """ % (r.status_code)', False]
# Timeout waiting for remote backup to complete
# (since it sometimes fails) in 5s multiples
global timeout
timeout_count = timeout*12 # timeout x 12 = number of iterations of 5s
time_left = timeout
while 'fileName' not in progress_data or timeout_count > 0:
# Clears the line before re-writing to avoid artifacts
stdout.write("\r\x1b[2k")
stdout.write("\r\x1b[2K%s. Timeout remaining: %sm"
% (progress_data['alternativePercentage'],
str(time_left)))
stdout.flush()
r = s.get(url=progress_url)
progress_data = json.loads(r.text)
time.sleep(5)
timeout_count = timeout_count - 5
if timeout_count % 12 == 0:
time_left = time_left - 1
if 'fileName' in progress_data:
result = [progress_data['fileName'], True]
return result
jira_confluence_backup.py 文件源码
项目:jira-confluence-backup
作者: MyMedsAndMe
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def download(s, l):
filename = get_filename(s)
if not filename:
return False
print "Filename found: %s" % filename
print "Checking if url is valid"
r = s.get(url=download_url + filename, stream=True)
print "Status code: %s" % str(r.status_code)
if int(r.status_code) == 200:
print "Url returned '200', downloading file"
if not create_backup_location(l):
result = ['Failed to create backup location', False]
return result
date_time = datetime.datetime.now().strftime("%Y%m%d")
with open(l + '/' + application + '-' + date_time + '.zip', 'wb') as f:
file_total = 0
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
file_total = file_total + 1024
file_total_m = float(file_total)/1048576
# Clears the line before re-writing to avoid artifacts
stdout.write("\r\x1b[2k")
stdout.write("\r\x1b[2K%.2fMB downloaded" % file_total_m)
stdout.flush()
stdout.write("\n")
result = ['Backup downloaded successfully', True]
return result
else:
print "Download file not found on remote server - response code %s" % \
str(r.status_code)
print "Download url: %s" % download_url + filename
result = ['Download file not found on remote server', False]
return result
def LoadingCallBack(j,k):
stdout.write("\r [+] Files: [{}] (strings: [{}])".format(j,k))
stdout.flush()
def run_inversion(self):
try: self.clear()
except: pass
self.sel_files = [str(self.open_files[i]) for i in self.text_files.curselection()]
if len(self.sel_files) == 0:
tkinter.messagebox.showwarning("Inversion error",
"No data selected for inversion \nSelect at least one data file in the left panel", parent=self.master)
if len(self.sel_files) >= 1:
try:
self.Inversion()
stdout.flush()
except:
tkinter.messagebox.showerror("Inversion error", "Error\nMake sure all fields are OK\nMake sure data file is correctly formatted",
parent=self.master)
return
def merge_csv_files(self):
if len(self.files) > 1:
self.sol.merge_results(self.files)
print("=====================")
else:
print("Can't merge csv files: Only 1 file inverted in last batch")
print("=====================")
stdout.flush()
def set_plot_par(self): # Setting up plotting parameters
try:
print("\nLoading plot parameters")
rcParams.update(iR.plot_par())
print("Plot parameters successfully loaded")
except:
print("Plot parameters not found, using default values")
stdout.flush()
def plot_diagnostic(self, which):
f_n = self.var_review.get()
sol = self.all_results[f_n]["sol"]
try:
if which == "traces":
trace_plot = sol.plot_traces(save=False)
self.plot_window(trace_plot, "Parameter traces: "+f_n)
if which == "histo":
histo_plot = sol.plot_histograms(save=False)
self.plot_window(histo_plot, "Parameter histograms: "+f_n)
if which == "autocorr":
autocorr_plot = sol.plot_autocorrelation(save=False)
self.plot_window(autocorr_plot, "Parameter autocorrelation: "+f_n)
if which == "geweke":
geweke_plot = sol.plot_scores(save=False)
self.plot_window(geweke_plot, "Geweke scores: "+f_n)
if which == "summary":
summa_plot = sol.plot_summary(save=False)
self.plot_window(summa_plot, "Parameter summary: "+f_n)
if which == "deviance":
devi_plot = sol.plot_model_deviance(save=False)
self.plot_window(devi_plot, "Model deviance: "+f_n)
if which == "logp":
logp_plot = sol.plot_log_likelihood(save=False)
self.plot_window(logp_plot, "Log-likelihood: "+f_n)
if which == "hexbin":
try: self.top_bivar.destroy()
except: pass
hex_plot = sol.plot_hexbin(self.biv1.get(), self.biv2.get(), save=False)
self.plot_window(hex_plot, "Hexagonal binning: "+f_n)
if which == "KDE":
try: self.top_bivar.destroy()
except: pass
kde_plot = sol.plot_KDE(self.biv1.get(), self.biv2.get(), save=False)
self.plot_window(kde_plot, "Bivariate KDE: "+f_n)
stdout.flush()
except:
tkinter.messagebox.showwarning("Error analyzing results", "Error\nProblem with inversion results\nTry adding iterations",
parent=self.master)
def load(self):
print("\nLoading root_ini from:\n", self.working_path)
try:
with open(self.working_path+'root_ini') as f:
self.root_ini = jload(f)
print("root_ini successfully loaded")
except:
print("root_ini not found, using default values")
self.root_ini = self.use_default_root_ini()
stdout.flush()
def merge_csv_files(self):
if len(self.files) > 1:
self.sol.merge_results(self.files)
print("=====================")
else:
print("Can't merge csv files: Only 1 file inverted in last batch")
print("=====================")
stdout.flush()
def set_plot_par(self): # Setting up plotting parameters
try:
print("\nLoading plot parameters")
rcParams.update(iR.plot_par())
print("Plot parameters successfully loaded")
except:
print("Plot parameters not found, using default values")
stdout.flush()