I have narrowed down my problem in the following code. I am trying to convert a string into equivalent z3 expression. The problem is that when the variable name is big, the 'eval' puts extra \n in between the expression but if I use a smaller variable name the extra \n is not there. I need to have a bigger variable name because that is not under my control. Please suggest how can I make the code working correctly with bigger variable names
EXTRA \n PRODUCING CODE
from z3 import BitVec, Solver ##UnresolvedImport
z3sig_dict = {}
z3sig_dict['v__DOT__process_1_reg3'] = {"z3name":BitVec('v__DOT__process_1_reg3', 32), "bits":32}
z3sig_dict['v__DOT__process_1_reg3_1'] = {"z3name":BitVec('v__DOT__process_1_reg3_1', 32), "bits":32}
string = "(z3sig_dict['v__DOT__process_1_reg3']['z3name'] == (8 + (z3sig_dict['v__DOT__process_1_reg3_1']['z3name'] % 0x20000000)))"
s = Solver()
print(string)
clause = eval(string)
print(str(clause))
s.add(clause)
The output of this code is
(z3sig_dict['v__DOT__process_1_reg3']['z3name'] == (8 + (z3sig_dict['v__DOT__process_1_reg3_1']['z3name'] % 0x20000000)))
v__DOT__process_1_reg3 ==
8 + v__DOT__process_1_reg3_1%536870912
CORRECTLY WORKING CODE
from z3 import BitVec, Solver ##UnresolvedImport
z3sig_dict = {}
z3sig_dict['reg3'] = {"z3name":BitVec('reg3', 32), "bits":32}
z3sig_dict['reg3_1'] = {"z3name":BitVec('reg3_1', 32), "bits":32}
string = "(z3sig_dict['reg3']['z3name'] == (8 + (z3sig_dict['reg3_1']['z3name'] % 0x20000000)))"
s = Solver()
print(string)
clause = eval(string)
print(str(clause))
s.add(clause)
The output of this code is
(z3sig_dict['reg3']['z3name'] == (8 + (z3sig_dict['reg3_1']['z3name'] % 0x20000000)))
reg3 == 8 + reg3_1%536870912
SOME OBSERVATIONS
If I reduce the % 0x20000000 to % 0x2000, then also the code works correctly, but incorrectly if I add one more zero i.e 0x20000
Z3 adds the \n because it thinks the output is too wide for the shell to print. By default, it assumes that only 80 characters fit into one line, but it's easy to tell Z3 to use more space:
from z3 import *
set_param(max_lines=1, max_width=1000000)
print(str(clause))
Related
I'm trying to increment the video file names every time they get into my folder. I tried the + and the join() method but I can't seem to figure it out. I tried integers without quotation marks but the join method wont let me use an integer so I tried with quotation marks but now it won't increment
Here is my code
VideoNumber += "99"
folderLocation = ("C:/Users/someone/Documents", VideoNumber, ".mp4")
x = "/".join(folderLocation)
print(x)
You can format integers into a string using an f-string or the format() method on strings.
video_number += 99
video_path = f"C:/Users/someone/Documents/{video_number}.mp4"
print(video_path)
Just as an example of how to make your original code work, you could keep your number as an integer and then convert it to a string using str() (though note this has a bug because you will have an extra / between the number and .mp4).
VideoNumber += 99
folderLocation = ("C:/Users/someone/Documents", str(VideoNumber), ".mp4")
x = "/".join(folderLocation)
print(x)
You can cast the integer into string, so your code will be like this
folderLocation = ("C:/Users/someone/Documents", str(VideoNumber), ".mp4")
How can I save string s got in this way:
f = open("a.jpg", "rb")
b = f.read()
s = str(b)[2:-1]
as .jpg file? In other program I have only s like form of this image, so it is: "\\xff\\xd8\\xff\\xe0...".
My recommendation would be to change the code, that creates the string in this strange way.
If not possible:
Where is this string coming from? Is this a trusted source or is it coming from a web server or a person who might want to hack / break your computer?
Is the string really created with str(b)[2:-1] or is this just an approximation of the real problem?
I am asking, as this is making things a little more complicated then necessary. (It requires adding a try / except)
Following code should work:
from ast import literal_eval
def stripped_str_b_to_bytes(s):
try:
return literal_eval("b'" + s + "'")
except SyntaxError:
return literal_eval('b"' + s + '"')
testvalues = [
b"A'B",
b'A"B',
bytes([v for v in range(256)]),
]
for b in testvalues:
print("testing with ", b)
s = b[2:-1]
print("S =", s)
c = stripped_str_b_to_bytes(s)
assert b == c
It tries to prepend b' and append ' to s and evaluate that string as a python expression.
If this doesn't work, then it tries to prepend b" and append " to s and evaluate it.
I have a folder with about 50 .txt files containing data in the following format.
=== Predictions on test data ===
inst# actual predicted error distribution (OFTd1_OF_Latency)
1 1:S 2:R + 0.125,*0.875 (73.84)
I need to write a program that combines the following: my index number (i), the letter of the true class (R or S), the letter of the predicted class, and each of the distribution predictions (the decimals less than 1.0).
I would like it to look like the following when finished, but preferably as a .csv file.
ID True Pred S R
1 S R 0.125 0.875
2 R R 0.105 0.895
3 S S 0.945 0.055
. . . . .
. . . . .
. . . . .
n S S 0.900 0.100
I'm a beginner and a bit fuzzy on how to get all of that parsed and then concatenated and appended. Here's what I was thinking, but feel free to suggest another direction if that would be easier.
for i in range(1, n):
s = str(i)
readin = open('mydata/output/output'+s+'out','r')
#The files are all named the same but with different numbers associated
output = open("mydata/summary.csv", "a")
storage = []
for line in readin:
#data extraction/concatenation here
if line.startswith('1'):
id = i
true = # split at the ':' and take the letter after it
pred = # split at the second ':' and take the letter after it
#some have error '+'s and some don't so I'm not exactly sure what to do to get the distributions
ds = # split at the ',' and take the string of 5 digits before it
if pred == 'R':
dr = #skip the character after the comma but take the have characters after
else:
#take the five characters after the comma
lineholder = id+' , '+true+' , '+pred+' , '+ds+' , '+dr
else: continue
output.write(lineholder)
I think using the indexes would be another option, but it might complicate things if the spacing is off in any of the files and I haven't checked this for sure.
Thank you for your help!
Well first of all, if you want to use CSV, you should use CSV module that comes with python. More about this module here: https://docs.python.org/2.7/library/csv.html I won't demonstrate how to use it, because it's pretty simple.
As for reading the input data, here's my suggestion how to break down every line of the data itself. I assume that lines of data in the input file have their values separated by spaces, and each value cannot contain a space:
def process_line(id_, line):
pieces = line.split() # Now we have an array of values
true = pieces[1].split(':')[1] # split at the ':' and take the letter after it
pred = pieces[2].split(':')[1] # split at the second ':' and take the letter after it
if len(pieces) == 6: # There was an error, the + is there
p4 = pieces[4]
else: # There was no '+' only spaces
p4 = pieces[3]
ds = p4.split(',')[0] # split at the ',' and take the string of 5 digits before it
if pred == 'R':
dr = p4.split(',')[0][1:] #skip the character after the comma but take the have??? characters after
else:
dr = p4.split(',')[0]
return id_+' , '+true+' , '+pred+' , '+ds+' , '+dr
What I mainly used here was split function of strings: https://docs.python.org/2/library/stdtypes.html#str.split and in one place this simple syntax of str[1:] to skip the first character of the string (strings are arrays after all, we can use this slicing syntax).
Keep in mind that my function won't handle any errors or lines formated differently than the one you posted as an example. If the values in every line are separated by tabs and not spaces you should replace this line: pieces = line.split() with pieces = line.split('\t').
i think u can separte floats and then combine it with the strings with the help of re module as follows:
import re
file = open('sample.txt','r')
strings=[[num for num in re.findall(r'\d+\.+\d+',i) for i in file.readlines()]]
print (strings)
file.close()
file = open('sample.txt','r')
num=[[num for num in re.findall(r'\w+\:+\w+',i) for i in file.readlines()]]
print (num)
s= num+strings
print s #[['1:S','2:R'],['0.125','0.875','73.84']] output of the code
this prog is written for one line u can use it for multiple line as well but u need to use a loop for that
contents of sample.txt:
1 1:S 2:R + 0.125,*0.875 (73.84)
2 1:S 2:R + 0.15,*0.85 (69.4)
when you run the prog the result will be:
[['1:S,'2:R'],['1:S','2:R'],['0.125','0.875','73.84'],['0.15,'0.85,'69.4']]
simply concatenate them
This uses regular expressions and the CSV module.
import re
import csv
matcher = re.compile(r'[[:blank:]]*1.*:(.).*:(.).* ([^ ]*),[^0-9]?(.*) ')
filenametemplate = 'mydata/output/output%iout'
output = csv.writer(open('mydata/summary.csv', 'w'))
for i in range(1, n):
for line in open(filenametemplate % i):
m = matcher.match(line)
if m:
output.write([i] + list(m.groups()))
I am trying to create a code that takes number from output and create a generate a text file
with that number , then write some lines in that file with that number in use ..
I tried to use the code :
for i in Nums:
sh1 = '%d.txt' %i
target = open (sh1, 'w') ## a will append, w will over-write
text = '%d * 0\n %d *1'
target.write(text %(i))
target.close()
but i face this error TypeError: not enough arguments for format string .
I do not understand this error why shows for me . I searched but solutions did not work with my code .
What i need from the code is to create the text file Like if i entered the number 1 . creates txt file name 1.txt and write these lines to it .
1 * 0
1 * 1
1 * 2
1 * 3
Any help ?
Thanks in advance
The problem is with the expression
text %(i)
text refers to the format string '%d * 0\n %d *1', which contains two %d placeholders, but you’re only passing one argument, i. You need to do something like
text % (i, j)
For example, text % (4, 5) would give you
4 * 0\n 5 *1
By the way, it’s standard to include spaces both before and after the % operator used for formatting. And if you’re passing just one argument to a formatting operation and you want to use a tuple, you need to use syntax like (i,) instead of just (i). You can read more about that rule here.
Why don't you use str.format?
for i in Nums:
target = open('{}.txt'.format(i), 'w')
target.write('{0} * 0\n{0} * 1\n{0} * 2\n{0} * 3\n'.format(i))
target.close()
The use of '%d.txt' %i string format is slowly becoming less used, perhaps due it's slightly confusing usability. str.format is a bit more concise and provides you bit the same functionality. You only need to specify the {} to signify where the parameter will go. You can further specify the index of the parameter inside the brackets, {0}, or {1}.
This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 9 years ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
I was wondering if it was possible to remove items you have printed in Python - not from the Python GUI, but from the command prompt.
e.g.
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
print (a)
so it prints
>>>Loading
>>>Loading.
>>>Loading..
>>>Loading...
But, my problem is I want this all on one line, and for it it remove it self when something else comes along. So instead of printing "Loading", "Loading.", "Loading... I want it to print "Loading.", then it removes what is on the line and replaces it with "Loading.." and then removes "Loading.." and replaces it (on the same line) with "Loading...". It's kind of hard to describe.
p.s I have tried to use the Backspace character but it doesn't seem to work ("\b")
Just use CR to go to beginning of the line.
import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
import sys
import time
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
# \r prints a carriage return first, so `b` is printed on top of the previous line.
sys.stdout.write('\r'+b)
time.sleep(0.5)
print (a)
Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.