Revit Python have problem with isinstance() - python

I use if isinstance(ins,list): to check . but it returned false Although ins is the List[Object]
def getname(ins):
name=[]
if isinstance(ins,list):
for i in ins:
name.append(i.Name)
else:
name.append(ins.Name)
return name
Levels = FilteredElementCollector(doc).OfClass(Level).ToElements()
ULevels = UnwrapElement(Levels)
Levelsname = getname(ULevels)
Error message is:
AttributeError: 'List[object]' object has no attribute 'Name'

You can do it in a single line of code like this:
[UnwrapElement(x).Name for x in FilteredElementCollector(doc).OfClass(Level).ToElements()]
Since I can see you are using Dynamo you can also do it like this:

Related

Why is a filter throwing a not callable error on the parent

I have a python class named MyFilter. In one of the methods I filter a list:
def __gatherCommits(self, head, count=2, commits=[]):
next_commits = self.repo.iter_commits(head, max_count=count)
filtered_commits = list(filter(lambda x: x.committed_date == self.current_day, next_commits))
That last line is causing an error to be thrown:
File "MyFilter.py", line 22, in __gatherCommits
filtered_commits = list(filter(lambda x: x.committed_date == self.current_day, next_commits))
TypeError: 'MyFilter' object is not callable
When I remove the offending line it runs as expected.
That was it exactly. Thanks folks. I was testing the class by instantiating an instance of the class with the variable filter. :face-palm:

AttributeError: 'str' object has no attribute 'json'

I wrote little script on python 3.7 to receive actual browser version
Here is it:
import json
def json_open():
file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
return json.load(file_json)
def get_last_version(browser_name):
f = json_open()
res = (f['global']['link_to_latest_browser_version'])
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
#print(last_version[1:-1])
return last_version[1:-1]
Also, json file exists, but it does not matter now.
Received:
AttributeError: 'str' object has no attribute 'json'.
In row
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
Please, tell me what is my mistake?
If you are trying to convert res as a json object try json.loads(res) instead of res.json()
Try this:
import json
FILEJSON = '/Users/user/PycharmProjects/Test/configuration.json'
def get_last_version(browser_name):
with open(FILEJSON, 'r') as fson:
res = json.load(fson)
last_version = res['global']['link_to_latest_browser_version']\
['latest']['client'][browser_name]['version'][1:-1]
return last_version
I think that the json_open function is unnecessary. Also take into account that the behavior of the json.load() method depends on the type of file you are reading.
Ok, the problem is here:
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
A JSON object is basically a dictionary. So when you do json['key'] it returns the content, not a json object.
Here res is a string, not a json object and thus does not have the .json() attribute.
Edit:
If you want a string to be return in your situation:
res = json.loads(f['global']['link_to_latest_browser_version'])
last_version = res['latest']['client'][browser_name]['version']
return last_version
Your "res" variable is of type string.
Strings do not have an attribute called json.
So res.json() is invalid.

AttributeError: 'tuple' object has no attribute 'status_code'

I'm a beginner in python. I'm not able to understand what the problem is?
the runtime process for the instance running on port 43421 has unexpectedly quit
ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/
Traceback (most recent call last):
File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response
response = middleware_method(request, response)
File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response
if response.status_code == 404:
AttributeError: 'tuple' object has no attribute 'status_code'
Whatever middleware_method returns is a tuple, so in the form ('a', 1, []) or something.
The error is telling you that you can't access members of the tuple by name, because they don't have names.
Maybe you created a tuple like this:
status_code = 404
name = 'Not found'
response = (name, status_code)
Once you declare the tuple, the names that went into it are lost. You have a couple of options for getting things out.
Direct access
You can get the objects by index, like you would with a list:
assert response[1] == 404
If you don't know what the tuple looks like, just print it, and calculate the index.
Named tuple
If you're determined to use names, you can create a namedtuple, provided that the tuple is going to be in the same format every time.
from collections import namedtuple
Response = namedtuple('Response', ('name', 'status_code')
response = Response('Not found', 404)
assert response.status_code == 404
Alternatively there may be a mistake in your code, where you are inadvertently returning a tuple, but one part of it is a requests.Response object. In that case, you can just extract the object as in "Direct access", and then use as you are already.
Would have to see the code to be of more help, but it might be something like:
response[2].status_code
I will try to explain how this error comes with a simple example
def example_error():
a1 = "I am here"
b1 = "you are there"
c1 = "This is error"
return a1, b1, c1
def call_function():
strings = example_error()
s1 = strings.a1
s2 = strings.b1
s3 = strings.c1
print(s1, s2, s3)
call_function()
This will return the error
AttributeError: 'tuple' object has no attribute 'a1'
Because I have returned three variables a1, b1, c1 in example_error function and trying to get them by using single variable strings.
I can get rid of this by using the following modified call_function
def call_function():
strings = example_error()
s1 = strings[0]
s2 = strings[1]
s3 = strings[2]
print(s1, s2, s3)
call_function()
As you did not show your code, I assume you have done something similar as here in the first case.

TypeError: String indices must be integers, not str. What am I not seeing?

I am testing some code and want to test to see if the API is properly formatted. Below is the dictionary that I am using to test.
self.test_query_values_positive = {
'DriverAge' : 33,
'PickUpCity' : 'Tampa',
'CarType' : 'luxury'
}
Here is the unit test in question:
def testQueryCreationPositive(self):
test_query = self.testDBM.create_http_query(self.test_query_values_positive)
self.assertEqual("some.api/findCar?city=Tampa&class=luxury",
self.testDBM.create_http_query(test_query))
And here is the function I am calling from the testDBM object
def create_http_query(self, slots):
base_url = 'some.api/findCar?'
query = None
if self.verify_age(slots['DriverAge']):
pickup = slots['PickUpCity'].title()
car_type = slots['CarType'].lower()
query = '{0}city={1}&class={2}'.format(base_url, pickup, car_type)
else:
query = None
return query
From this, I am getting a TypeError as shown below:
TypeError: string indices must be integers, not str
What am I not seeing? I have a negative test right below it that runs perfectly fine, but this one doesn't. Why is that?
EDIT: I forgot to say that the line in question is:
if self.verify_age(slots['DriverAge']):
It seems to run fine other than that.
def testQueryCreationPositive(self):
test_query = self.testDBM.create_http_query(self.test_query_values_positive)
self.assertEqual("some.api/findCar?city=Tampa&class=luxury",
self.testDBM.create_http_query(test_query)) # this line is bad
This is what you want:
self.assertEqual("some.api/findCar?city=Tampa&class=luxury", test_query)

TypeError: 'type' object has no attribute '__getitem__' in pandas DataFrame

I was trying to analyse the play-by-play data of a basketball team
What I did was to read a csv file into a DataFrame object.
I want to preserve the functionality of the DataFrame object while adding in new attributes to the existing object. Thus I wrote a class called Basketball:
from data_math import *
import pandas as pd
class Basketball(pd.DataFrame):
def __init__(self,*args,**kargs):
pd.DataFrame.__init__(self,*args,**kargs)
self.FGM = calculate_FGM(pd.DataFrame)
self.FGA = calculate_FGA(pd.DateFrame)
self.FGP = self.FGM / self.FGA
self.M3 = calculate_3M(pd.DataFrame)
self.A3 = calcualte_3A(pd.DataFrame)
self.P3 = self.M3 / self.A3
self.FTM = calcualte_FTM(pd.DataFrame)
self.FTA = calculate_FTA(pd.DataFrame)
self.FTP = self.FTM / self.FTA
# self.P = score_calculate(pd.DataFrame)
I wrote another data_math.py file to help calculate the different attributes I wanted to include into the Basketball class.
from pandas import DataFrame
def score_calculate(df):
df_pt_scored = df[((df['etype']=='shot') & (df['result']=='made'))]
df_ft_scored = df[((df['etype']=='free throw') & (df['result']=='made'))]
return df_pt_scored['points'].sum()+len(df_ft_scored.index)
def calculate_FGM(df):
cond_pt = (df['etype']=='shots') & (df['results']=='made')
cond_ft = (df['etype']=='freethrow') & (df['results']=='made')
return len(df[cond_pt].index)+len(df[cond_ft].index)
def calculate_FGA(df):
shot_cond= df['etype']=='shot'
free_throw_cond = df['etype']=='free throw'
return len(df[shot_cond].index)+len(df[free_throw_cond].index)
def calculate_3M(df):
cond_3M= (df['etype']=='shot')&(df['type']=='3pt')&(df['result']=='made')
return len(df[cond_3M].index)
def calcualte_3A(df):
cond_3A = (df['etype']=='shot')&(df['type']=='3pt')
return len(df[cond_3A].index)
def calculate_FTM(df):
cond_FTM =(df['etype']=='free throw') & (df['result']=='made')
return len(df[cond_FTM].index)
def calcualte_FTA(df):
cond_FTA =(df['etype']=='free throw')
return len(df[cond_FTA].index)
In the end I start my program from main.py which I hope would give me the correct output. However while executing on this line:
team1= Basketball(tm1)
I received the following Traceback
Traceback (most recent call last):
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/main.py", line 20, in <module>
team1= Basketball(tm1)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/Basketball.py", line 6, in __init__
self.FGM = calculate_FGM(pd.DataFrame)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/data_math.py", line 9, in calculate_FGM
cond_pt = (df['etype']=='shots') & (df['results']=='made')
TypeError: 'type' object has no attribute '__getitem__'
I am new to python programming and could not figure out why this error has occurred. To my understanding, this error means I am unable to use indexing feature of the DataFrame. However, if I try to code in my main function similar things I am able to get the output I want. I am also not clear of how to extend the existing DataFrame class so that I can still access the methods in the DataFrame class while extending the team1 object to have attributes such as FGM, FGA, etc.
The idea of extending this class is to allow me to pass any DataFrame object in the Basketball() so that I can have an object with extending attributes and methods. I think I also lack an understanding of the use of init and self.
Please don't blame for not describing the problem clearly as I am not familiar with all the terminology in OOP.
Thank you so much!
You're passing each function pd.DataFrame which is of type type:
In [11]: type(pd.DataFrame)
Out[11]: type
Hence the exception message.
You mean to be passing self (which is of type DataFrame):
self.FGM = calculate_FGM(pd.DataFrame)
...
should read:
self.FGM = calculate_FGM(self)
...

Categories