I have this code:
static def parseString(String inputRow, Particle particle) {
//input row is:
//static final inputRow = "1 -5.2 3.8"
def map = inputRow.split()
particle.mass = Integer.parseInt(map[0])
particle.x = Integer.parseInt(map[1])
particle.y = Integer.parseInt(map[2])
}
This code is throwing this error:
java.lang.NumberFormatException: For input string: "-5.2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.valueOf(Integer.java:582)
at RepulsionForce.parseString(RepulsionForce.groovy:13)
at RepulsionForceTest.string should be parsed into particles(RepulsionForceTest.groovy:27)
How do I avoid this exception?
You can cut down redundant lines as shown below where particle is a map:
def arr = inputRow.split()
def mass, x, y
(mass, x, y) = arr*.toDouble()
def particle = [:] << [mass: mass, x: x, y: y]
Missed the part where Particle class has been referred instead.
Whoops, figured this out... 5.2 is not an integer.
static def parseString(String inputRow, Particle particle) {
def map = inputRow.split()
particle.mass = Double.parseDouble(map[0])
particle.x = Double.parseDouble(map[1])
particle.y = Double.parseDouble(map[2])
}
Here is one way to do it... Answer within a full solution:
// setup
class Particle {
def mass
def x
def y
}
def particle = new Particle()
def inputRow = "1 -5.2 3.8"
def fieldsByIndex = [0: "mass", 1: "x", 2: "y"]
// answer
inputRow.split().eachWithIndex { val, index ->
def field = fieldsByIndex.get(index)
particle."${field}" = val.toDouble()
}
// output
println "mass : " + particle.mass
println "x : " + particle.x
println "y : " + particle.y
Explanation: You Mistakenly trying to parse Double number to Integer number and it's not applicable, not sharing the same type ( integer != double) , and not gonna work - Therefore you getting java.lang.NumberFormatException: For input string exception which explicitly inform you for the type issue.
Solution: Convert it to to double using Double Class.
Double.parseDouble(map[i])
Related
I am trying to get my code to work, where I have the different #Enigma Rotors and reflectors defined however would like to be able to look from left to right and right to left for a specific character entered. Then returning the same alphabetical character in the position of the selected rotor.
In the code below you will see I added the different rotors and reflectors in the bottom section. The "rotor_from_name" is to select the specific rotor and the other functions should search for the letter and return the ALPHABETIC letter. The rotor variable has the selector however I am not sure how I can get this selector to return the full 26 letters linked to this?
import string
# Getting the uppercase alphabet
ALPHABET = string.ascii_uppercase
class Rotor:
TURN_FREQUENCY = len(ALPHABET)
def __init__(self):
pass
def encode_right_to_left(self, x):
self.alphabet = ALPHABET
j = rotor.find(x)
return j
def encode_left_to_right(self, x):
self.alphabet = ALPHABET
j = self.alphabet.rfind(x)
return j
#classmethod
def rotor_from_name(self, y):
self.y = y
return y
if __name__=='__main__':
instance = Rotor()
#Enigma Rotors and reflectors
Beta = "LEYJVCNIXWPBQMDRTAKZGFUHOS"
Gamma = "FSOKANUERHMBTIYCWLQPZXVGJD"
I = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"
II = "AJDKSIRUXBLHWTMCQGZNPYFVOE"
III = "BDFHJLCPRTXVZNYEIWGAKMUSQO"
IV = "ESOVPZJAYQUIRHXLNFTGKDCMWB"
V = "VZBRGITYUPSDNHLXAWMJQOFECK"
The expected results are the following:
rotor = rotor_from_name("I")
assert(rotor.encode_right_to_left("A") == "E")
assert(rotor.encode_left_to_right("A") == "U")
Thank you for any support and/or guidance on how I can achieve this.
I fixed some bugs
TURN_FREQUENCY never used, you should remove it.
If you dont need __init__, just remove it, no need to add a __init__ only have one line pass.
You need set a proper name to the variable self.y, such as self.rotor.self.y is really confusing.
You create a instance to Rotor, then you need use it, not to use the lowercase rotor, which is never defined.
When you need to assign the rotor to the instance, you need assign the varible, not a stirng like "I"
I think you may need a IDE to debug your code, such as VSCode, PyCharm.
code:
import string
class Rotor:
def encode_right_to_left(self, x):
return self.rotor[ALPHABET.index(x)]
def encode_left_to_right(self, x):
return ALPHABET[self.rotor.index(x)]
def rotor_from_name(self, rotor):
self.rotor = rotor
ALPHABET = string.ascii_uppercase
instance = Rotor()
Beta = "LEYJVCNIXWPBQMDRTAKZGFUHOS"
Gamma = "FSOKANUERHMBTIYCWLQPZXVGJD"
I = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"
II = "AJDKSIRUXBLHWTMCQGZNPYFVOE"
III = "BDFHJLCPRTXVZNYEIWGAKMUSQO"
IV = "ESOVPZJAYQUIRHXLNFTGKDCMWB"
V = "VZBRGITYUPSDNHLXAWMJQOFECK"
instance.rotor_from_name(I)
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "E")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "U")
instance.rotor_from_name(Beta)
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "L")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "R")
result:
E
U
L
R
EDIT: If you want to use varibale name to select router, you can use loacls()
code:
instance.rotor_from_name(locals()["I"])
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "E")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "U")
instance.rotor_from_name(locals()["Beta"])
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "L")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "R")
result:
E
U
L
R
Or, you can write a dict to translate name key to chart value.
code:
def rotor_from_name(name):
rotor_dic = {
"Beta" : "LEYJVCNIXWPBQMDRTAKZGFUHOS",
"Gamma" : "FSOKANUERHMBTIYCWLQPZXVGJD",
"I" : "EKMFLGDQVZNTOWYHXUSPAIBRCJ",
"II" : "AJDKSIRUXBLHWTMCQGZNPYFVOE",
"III" : "BDFHJLCPRTXVZNYEIWGAKMUSQO",
"IV" : "ESOVPZJAYQUIRHXLNFTGKDCMWB",
"V" : "VZBRGITYUPSDNHLXAWMJQOFECK"}
return rotor_dic[name]
ALPHABET = string.ascii_uppercase
instance = Rotor()
rotor = rotor_from_name("I")
instance.rotor_from_name(rotor)
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "E")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "U")
rotor = rotor_from_name("Beta")
instance.rotor_from_name(rotor)
print(instance.encode_right_to_left("A"))
assert(instance.encode_right_to_left("A") == "L")
print(instance.encode_left_to_right("A"))
assert(instance.encode_left_to_right("A") == "R")
result:
E
U
L
R
I get this error from the following Pytorch code:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.DoubleTensor [3]] is at version 10; expected version 9 instead.
As it is seen the code does not have inplace operations.
import torch
device = torch.device('cpu')
class MesNet(torch.nn.Module):
def __init__(self):
super(MesNet, self).__init__()
self.cov_lin = torch.nn.Sequential(torch.nn.Linear(6, 5)).double()
def forward(self, u):
z_cov = self.cov_lin(u.transpose(0, 2).squeeze(-1))
return z_cov
class UpdateModel(torch.nn.Module):
def __init__(self):
torch.nn.Module.__init__(self)
self.P_dim = 18
self.Id3 = torch.eye(3).double()
def run_KF(self):
N = 10
u = torch.randn(N, 6).double()
v = torch.zeros(N, 3).double()
model = MesNet()
measurements_covs_l = model(u.t().unsqueeze(0))
# remember to remove this afterwards
torch.autograd.set_detect_anomaly(True)
for i in range(1, N):
v[i] = self.update_pos(v[i].detach(), measurements_covs_l[i-1])
criterion = torch.nn.MSELoss(reduction="sum")
targ = torch.rand(10, 3).double()
loss = criterion(v, targ)
loss = torch.mean(loss)
loss.backward()
return v, p
def update_pos(self, v, measurement_cov):
Omega = torch.eye(3).double()
H = torch.ones((5, self.P_dim)).double()
R = torch.diag(measurement_cov)
Kt = H.t().mm(torch.inverse(R))
# it is indicating inplace error even with this:
# Kt = H.t().mm(R)
dx = Kt.mv(torch.ones(5).double())
dR = self.trans(dx[:9].clone())
v_up = dR.mv(v)
return v_up
def trans(self, xi):
phi = xi[:3].clone()
angle = torch.norm(phi.clone())
if angle.abs().lt(1e-10):
skew_phi = torch.eye(3).double()
J = self.Id3 + 0.5 * skew_phi
Rot = self.Id3 + skew_phi
else:
axis = phi / angle
skew_axis = torch.eye(3).double()
s = torch.sin(angle)
c = torch.cos(angle)
Rot = c * self.Id3
return Rot
net = UpdateModel()
net.run_KF()
I think the issue is that you are overwriting v[i] elements.
You could instead construct an auxiliary list v_ from the loop, then convert it tensor:
v_ = [v[0]]
for i in range(1, N):
v_.append(self.update_pos(v[i].detach(), measurements_covs_l[i-1]))
v = torch.stack(v_)
all the examples shown just explain how to create a singleton of a class without the instantiation of any members.
But how can I produce a singleton of the following class in Python 3:
class NotOneOnly:
def __init__(self, a, b):
print("Instatiation of objects.")
self.a = a
self.b = b
def run(self):
print("Variable a = " + str(self.a) + " and variable b = " +
str(self.b))
In the main program, the use would be:
not_one_only = NotOneOnly(5, 10)
not_one_only.run()
Thanks 4 help.
After investigating a little bit, I've discovered this. So my conclusion is:
class OneOnly:
_singleton = None
a = None
b = None
def __new__(cls, a, b):
if not cls._singleton:
print("Object is created and the variables are instantiated.")
cls._singleton = super(OneOnly, cls).__new__(cls)
cls.a = a
cls.b = b
else:
print("Sorry, byt object is already made.")
return cls._singleton
def run(self):
print("Variable a = " + str(self.a) + " and variable b = " + str(self.b))
Now in the mainfile I made the following experiments showing that the singleton was created in the right way:
print("Singleton Experiment:")
a = 10
b = 5
one_only1 = OneOnly(a, b)
print(one_only1)
one_only1.run()
one_only2 = OneOnly(1, 2)
print(one_only2)
one_only2.run()
one_only1.a = 100
one_only1.run()
one_only2.run()
Now the output is:
Singleton Experiment:
Object is created and the variables are instantiated.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Sorry, byt object is already made.
<__main__.OneOnly object at 0x7fa4295cbcc0>
Variable a = 10 and variable b = 5
Variable a = 100 and variable b = 5
Variable a = 100 and variable b = 5
I have a string like the following:
def slurper = new JsonSlurper()
def request = slurper.parseText(dataRequest)
def response1 = slurper.parseText(dataResponse)
Eval.me('request.variable1 = request.variable2')
But I got an error: javax.script.ScriptException: ReferenceError: "request" is not defined in at line number 1
Use groovy expression like
def a = 2
def b = 3
Eval.me("$a == $b")
or use the xy method instead
Eval.xy(a, b, 'x == y')
http://docs.groovy-lang.org/latest/html/api/groovy/util/Eval.html
I was trying to make an Image Captioning model in a similar fashion as in here
I used ResNet50 instead off VGG16 and also had to use progressive loading via model.fit_generator() method.
I used ResNet50 from here and when I imported it by setting include_top = False, It gave me features of photo in shape of {'key': [[[[value1, value2, .... value 2048]]]]}, where "key" is the image id.
Here's my code of captionGenerator function:-
def createCaptions(tokenizer, photoData, MaxLength, model):
for key, feature in photoData.items():
inSeq = "START"
for i in range(MaxLength):
sequence = tokenizer.texts_to_sequences([inSeq])[0]
sequence = pad_sequences([sequence], maxlen = MaxLength)
ID = model.predict([np.array(feature[0][0][0]), sequence])
ID = np.argmax(ID)
ID = word_for_id(ID)
if ID is None:
break
inSeq += " " + ID
if ID == "END":
break
print(inSeq)
The function word_for_id is :-
def word_for_id(integer, tokenizer):
for word, index in tokenizer.word_index.items():
if index == integer:
return word
return None
I had generated photoData via:-
features = {}
for images in os.listdir(args["image"]):
filename = args["image"] + '/' + images
image = load_img(filename, target_size = inputShape)
image = img_to_array(image)
image = np.expand_dims(image, axis = 0)
image = preprocess(image)
pred = resnet.predict(image)
image_id = images.split('.')[0]
features[image_id] = pred
print('>{}'.format(images))
features is my photoData dictionary.
The problem is, in training data photos descriptions which I generate through:-
def train_test_data(filename):
DataFile = open(filename, 'r')
Data = DataFile.read()
DataFile.close()
ImageID = []
textDataFile = pickle.load(open('descriptions.pkl', 'rb'))
for line in Data.split('\n'):
if len(line) < 1:
continue
ImageID.append(line.split('.')[0])
Data = {}
for key in textDataFile:
if key in ImageID:
Data[key] = textDataFile[key]
for ID in Data:
for i in range(len(Data[ID])):
l = Data[ID][i]
l = "START " + " ".join(l) + " END"
Data[ID][i] = l
return Data
Here, I added "START" and "END" at the begginning and end of each sentences of description respectively. But in tokenizer.word_index, "START" and "END" are not found as keys. That is:-
k = pickle.load(open('word_index.pkl', 'rb'))
print("START" in k)
This gives result as False.
Please explain to me why this is happening.
If I do:-
k = pickle.load(open('word_index.pkl', 'rb'))
print("start" in k)
The answer comes out True.
That is because by default the Tokenizer lowers the words when fitting based on the lower=True parameter. You can either use the lower case or pass lower=False when creating the tokenizer, documentation.