I have a set of python objects (I am giving only one case: x in the code) that I want to process using dask bag. The resulting value of the computation will be assigned as attribute (x.test in the code bellow) to the objects.
import dask.bag as db
class Test():
pass
x = Test()
def dask_test(x):
somevalue = someprocess(x)
setattr(x, "test", somevalue)
b = db.from_sequence([x], npartitions = 1)
b.map(dask_test).compute()
x.test
The above gives an error: AttributeError: 'Test' object has no attribute 'test'
The bellow here works fine.
setattr(x, "test", 'somevalue')
x.test
You should return a value from the dask_test function:
def dask_test(x):
setattr(x, "test", True)
return x
Related
I'm trying to make a class that contains an array and then name the columns of the array with instance variables and return the value of the cell in that row/column externally by filling in the row value from calling the method index_value.
However I get this error every time I try to call it.
AttributeError: 'function' object has no attribute 'value'
I've tried
import numpy as np
class stuff:
array = np.zeros((5,5), dtype = float)
def index_value(self, arr_index_number = 0):
self.value = self.array[arr_index_number,0]
self.value_2 = self.array[arr_index_number,1]
def index_number(self, n = 0):
return n
stuff = stuff()
stuff_index_value = stuff.index_value
print(stuff_index_value.value(1))
and with an init
import numpy as np
class stuff:
def __init__(self):
self.array = np.zeros((5,5), dtype = float)
def index_value(self, arr_index_number = 0):
self.value = self.array[arr_index_number,0]
self.value_2 = self.array[arr_index_number,1]
stuff = stuff()
stuff_index_value = stuff.index_value
print(stuff_index_value.value(1))
I've tried
print(stuff_index_value.value(1))
and
print(stuff.value(1))
What am I doing wrong? :(
To clarify what I want to do, I want to store every column in the array as its own variable. Each column represents a different category of data so I need them to be saved to their own variable.
Then I want to be able to call the value of the row/column by using the method and inputting the row number.
so in
self.value_2 = self.array[self.arr_index_number,1]
if arr_index_number == 1 then the value that would be returned would be the value of self.array[1,1].
In order to change the value of arr_index_number I need to call it from the method 'index_value'.
So if self.array[1,1] = 5 then I would need to call it with the equivalent of
stuff.index_value.value_2(1)
where (1) is the arr_index_number in the method in order to get that value.
The trouble here is I can't just call the method and be done it with, I need to call the variables within the method and their transformed values.
I can't figure out the correct syntax to do this.
class Swimmers:
""" Creates objects for each swimmer with unique details"""
instances = []
def __init__(self, fName = "None", lName = "None", house = "None", time = "None"):
self.fName = getfName()
self.lName = getlName()
self.house = getHouse()
self.time = getTime()
self.__class__.instances.append(self)
#classmethod
def printInstances(cls):
for instance in cls.instances:
print(instance)
def test():
style, swimmerNumber = raceDetails()
for x in range(int(swimmerNumber)):
y = re.sub(".0", "", str(x))
string = "swimmer" + y
print("\n" + string + "\n")
string = Swimmers()
x -= 1
I need to create a module that takes various inputs and saves each iteration as a class object. The function raceDetails() simply gets the type of race and the number of swimmers, nothing wrong with that part. The functions getX() are simply input functions with some error checking. The issue is that trying to call the objects or any of their variables after everything has been entered simply gives me:
>>> swimmer0.fName
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
swimmer0.fName
NameError: name 'swimmer0' is not defined
I've added a list of every object created by the class ('instances') which prints:
<__main__.Swimmers object at 0x04182F88>
<__main__.Swimmers object at 0x04182E50>
and so on, which, combined with the working getX() functions, means the objects are being instantiated perfectly fine. I've tried everything I can think of, including nonlocals, changing scopes, adding intermediary functions, but none of it seems to work. The only thing I can think of is an issue with reference generation in the module namespace.
It's not essential that I use classes for this, and I could very easily use dictionaries or the like, but I want to try and learn classes as best as I can.
Using Windows 10, Python 3.9.2 32-bit
The problem is you're setting the string variable equal to the variable name you want ('swimmer0', 'swimmer1'...), but then you set string equal to the Swimmers class. Dynamically setting variables names is possible in python, but typically you'll want to use a dictionary (or another collections object) to store the objects.
def test():
style, swimmerNumber = raceDetails()
swimmers_dict = {}
for x in range(int(swimmerNumber)):
y = re.sub(".0", "", str(x))
string = "swimmer" + y
print("\n" + string + "\n")
swimmers_dict[x] = Swimmers()
x -= 1
return swimmers_dict
I have code like this:
def options = JsonPath.read(prev.getResponseDataAsString(), '$.options')
def randomOption = options.get(RandomUtils.nextInt(0, options.size()))
def code = randomOption.get("code")
vars.put('code1', code)
def values = randomOption.get('values')
def randomValue = values.get(RandomUtils.nextInt(0, values.size())) as
String
def val = randomValue['value']
vars.put('randomValue', randomValue)
vars.put('ValueF', val).
In Random Variable i am getting value as [label:Red, value:8] . I need to fetch the value of Value=8
Youre trying to invoke
vars.put('ValueF', [label:Red, value:8])
which is put(String, Map)
JMeterVariables have no such method https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterVariables.html
you can use putObject() which accepts String as key and Object as value:
vars.putObject('ValueF', val)
I am trying to retrieve data from oracle db but getting No such property: expected for class: Script1343 (in groovy script); error
import java.util.Properties;
import java.io.InputStream;
import groovy.sql.Sql;
def url = 'jdbc:oracle:thin:#//localhost:1521/TEST'
def user = 'DB'
def password = 'DB'
def driver = 'oracle.jdbc.driver.OracleDriver'
def sql = Sql.newInstance('url', 'User', 'password','oracle.jdbc.driver.OracleDriver')
sql.withStatement {
stmt -> stmt.queryTimeout = 30
print "Request TimeOut"
}
def rowNum = 0
sql.eachRow("SELECT DISTINCT CST_START_DT_PF,CST_ITEM_NUM_PF FROM COST "){ row ->
def first = row[0]
def middle = row.CST_START_DT_PF
def one = row.CST_ITEM_NUM_PF
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
}
There are several things wrong. The specific error you asked about is the result of the following:
assert expected[rowNum] == "$CST_START_DT_PF, $CST_ITEM_NUM_PF"
You are referencing a variable expected which doesn't exist.
You didn't ask about the things below but other problems you are going to run into...
Referencing $CST_START_DT_PF and $CST_ITEM_NUM_PF is going to be a problem because they also don't exist, at least not in a way that your code will work.
You also are probably going to get unexpected results related to the fact that you are never incrementing rowNum.
I am trying to retrieve a list of all instances of 'search' from a json response and set it so that any values that contains 'null' is changed to 0. However I am getting an error stating no such property: it for class. How can I fix this to ensure I get the code working so any instance of 'null' changes to 0?
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def resultItems = json.xxx.xxx.items
def resultSearchCostGroup = json.xxx.xxx.xxx.search
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect(it ?:0 ).sum()
Your last line should read
int totalSearchCostGroup = resultSearchCostGroup.flatten().collect { it ?:0 }.sum()