Using folium new version map.save and getting a syntax error - python-3.x

I am trying the new version of folium so I am using map.save instead of map.create_map. It was working with the older version but when I am using the new code, I am getting an error again and again saying SyntaxError: Invalid syntax. But I think I ma using the right code:
I am running this script:
import pandas, folium
df = pandas.read_csv(".....txt")
map = folium.Map(location= [df["LAT"].mean(), df["LON"].mean()], zoom_start = 6, tiles = "Stamen Terrain")
def color(elev):
minimum= int(min(df["ELEV"]))
step= int((max(df["ELEV"])-min(df["ELEV"]))/3 )
if elev in range(minimum,minimum+step):
col= "blue"
elif elev in range(minimum+step,(minimum+step)*2):
col= "orange"
else:
col = "red"
return col
for lat,lon,name,elev in zip(df['LAT'], df['LON'], df['NAME'], df['ELEV']):
map.add_child(folium.Marker(location=[lat, lon], popup = name, icon= folium.Icon(color= color(elev)))
map.save(outfile= "test.html")
and I am getting this error:
...:
File "<ipython-input-2-02945dfe5a14>", line 27
map.save(outfile= "test.html")
^
SyntaxError: invalid syntax
Am I doing something wrong?

Related

Why is the webcolors library giving me an atribute error when the function is specified in the documentation

I am trying to create a color mixer-calculator type thing that will tell you the color name based on the RGB code you input. As in the webcolor database there are no 256^3 color names (niether in real life, I think) I included aproximations to the colors that didn't have names to the nearest similar color. The problem pops out when using the
webcolors.cc3_hex_to_name
It raises an atribute error:
AttributeError: module 'webcolors' has no attribute 'css3_hex_to_name'
This is very strange as the webcolor's documentation clearly includes this atribute:
Webcolors documentation extract
Here's the whole code for reference:
import webcolors
webcolors.css3_hex_to_name
def closest_colour(requested_colour):
min_colours = {}
for key, name in webcolors.css3_hex_to_names.items(): #Error line
r_c, g_c, b_c = webcolors.hex_to_rgb(key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1]) ** 2
bd = (b_c - requested_colour[2]) ** 2
min_colours[(rd + gd + bd)] = name
return min_colours[min(min_colours.keys())]
def get_colour_name(requested_colour):
try:
closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
except ValueError:
closest_name = closest_colour(requested_colour)
actual_name = None
return actual_name, closest_name
requested_colour = (119, 172, 152)
actual_name, closest_name = get_colour_name(requested_colour)
print ("Actual colour name:", actual_name, ", closest colour name:", closest_name)
try this webcolors.CSS3_HEX_TO_NAMES

SyntaxError: invalid syntax. Don't know what to do

I've been trying to get a fix and can't find why the error keeps appearing. Can somebody help me please?
Here is the code i am trying to fix:
import numpy as np
def nan_repl(x):
k = np.where(np.isnan(x))
x[k] = np.nanmean(x[:,k[1]],axis=0)
def pca(x,std = True, nlib = 0):
if std:
x_ = (x - np.mean(x,axis=0))/np.std(x,axis=0)
else:
x_ = x - np.mean(x, axis=0)
n,m = np.shape(x)
assert isinstance(x_,np.ndarray)
mat = (1/(n-nlib))*x_.T#x_
print(mat)
And the error is this:
"D:\Proiect Data Mining\venv\Scripts\python.exe" "D:/Proiect Data Mining/functii.py" File "D:/Proiect Data Mining/functii.py", line 14
mat = (1/(n-nlib))*x_.T#x_
^ SyntaxError: invalid syntax
Process finished with exit code 1
You can use np.matmul() to solve your error:
mat = (1/(n-nlib))*np.matmul(x_.T, x_)
You can refer to the documentation here: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
I assumed the operation you're trying to perform was a matrix multiplication with the '#' operator, which is only supported in python 3.

TypeError: 'headers' is an invalid keyword argument for print()

I recently installed tabulate onto conda and I am trying to tabulate my results with print syntax
Source: Printing Lists as Tabular Data
but I am getting "TypeError: 'headers' is an invalid keyword argument for print()"
I have tried "print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl'))"
from tabulate import tabulate
i: int
with open("incre.txt", "w") as file:
for i in range(1, 100,5):
mol = int((i*50)/(i+50))
file.write(str(i)+ " " +str(mol) + "\n")
print(tabulate([[i], [mol]]), headers=['i' , 'mol'], tablefmt='orgtbl')
file.close()
Expected Results would be on terms of
I am getting typeerror, what am I missing here?
There is a mistake in the way you wrote your parenthesis, try with that line:
print(tabulate([[i], [mol]], headers=['i' , 'mol'], tablefmt='orgtbl'))
What you were doing was like doing this:
x = tabulate([[i], [mol]]
print(x, headers=['i' , 'mol'], tablefmt='orgtbl')
As you can see there, you were trying to call the print method with headers and tablefmt keywords, wich caused the error: 'headers' is an invalid keyword argument for print()
Update:
I'm not sure, but i think what you try to achieve is:
from tabulate import tabulate
values = []
for i in range(1, 100,5):
mol = int((i*50)/(i+50))
values.append([i, mol])
print(tabulate(values, headers=['i' , 'mol'], tablefmt='orgtbl'))
in your code, you were printing i and mol after having exited from the while loop, then you would have only printed their last values...

Exception Handling Error: TypeError: can only concatenate list (not "odict_keys") to list

I was running pytest and using someone else's exception handling library. It supposed to run older version of python, not sure which one. However when I try to run it with python3, it spouted error that I didn't understand, also for some reason I have trouble finding the meaning of the keyword error (odict_keys) in the web.
The following was the result from the pytest. The exception handling inside test_analysis procedure was calling run_with_timeout(timeoutwrapper_analysis,max_seconds_per_call,(),{}) before the error occurred here. Inside run_with_timeout, the error happened when it raised e as an exception:
#pytest.mark.parametrize("inputs,outputs,description", portfolio_test_cases)
def test_analysis(inputs, outputs, description, grader):
"""Test get_portfolio_value() and get_portfolio_stats() return correct values.
Requires test inputs, expected outputs, description, and a grader fixture.
"""
points_earned = 0.0 # initialize points for this test case
try:
# Try to import student code (only once)
if not main_code in globals():
import importlib
# * Import module
mod = importlib.import_module(main_code)
globals()[main_code] = mod
# Unpack test case
start_date_str = inputs['start_date'].split('-')
start_date = datetime.datetime(int(start_date_str[0]),int(start_date_str[1]),int(start_date_str[2]))
end_date_str = inputs['end_date'].split('-')
end_date = datetime.datetime(int(end_date_str[0]),int(end_date_str[1]),int(end_date_str[2]))
symbols = inputs['symbol_allocs'].keys() # e.g.: ['GOOG', 'AAPL', 'GLD', 'XOM']
allocs = inputs['symbol_allocs'].values() # e.g.: [0.2, 0.3, 0.4, 0.1]
start_val = inputs['start_val']
risk_free_rate = inputs.get('risk_free_rate',0.0)
# the wonky unpacking here is so that we only pull out the values we say we'll test.
def timeoutwrapper_analysis():
student_rv = analysis.assess_portfolio(\
sd=start_date, ed=end_date,\
syms=symbols,\
allocs=allocs,\
sv=start_val, rfr=risk_free_rate, sf=252.0, \
gen_plot=False)
return student_rv
# Error happen in the following line:
result = run_with_timeout(timeoutwrapper_analysis,max_seconds_per_call,(),{})
grade_analysis.py:176:
func = .timeoutwrapper_analysis at 0x7f8c458347b8>, timeout_seconds = 5, pos_args = (), keyword_args = {}
def run_with_timeout(func,timeout_seconds,pos_args,keyword_args):
rv_dict = timeout_manager.dict()
p = multiprocessing.Process(target=proc_wrapper,args=(func,rv_dict,pos_args,keyword_args))
p.start()
p.join(timeout_seconds)
if p.is_alive():
p.terminate()
raise TimeoutException("Exceeded time limit!")
if not('output' in rv_dict):
if 'exception' in rv_dict:
e = rv_dict['exception']
e.grading_traceback=None
if 'traceback' in rv_dict:
e.grading_traceback = rv_dict['traceback']
# Error occurred after the following line:
raise e
E TypeError: can only concatenate list (not "odict_keys") to list
grading.py:134: TypeError
Looks the script didn't like
raise e
statement. What is that to do with odict_keys?
regards
two of the inputs of analysis.assess_portfolio, symbols and allocs are in the forms of odic_keys. Apparently, this worked in python 2.7, however when running with python 3, they need to be in the form of list, thus changing the input statement from
symbols = inputs['symbol_allocs'].keys()
allocs = inputs['symbol_allocs'].values()
to
symbols = list(inputs['symbol_allocs'].keys())
allocs = list(inputs['symbol_allocs'].values())
fixed it

Using sympy on strings

I have a file with some equations. I want to solve them using sympy. I can use open('problems.txt',mode='r') to open the file. But how to proceed with sympy?
I'm getting following error
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'x+x+x-x = 18 + 4'' failed, because of exception being raised:
SyntaxError: invalid syntax (, line 1)
I'm using Python 3.4.2
parse_expr should be able to get you going:
import sympy
from sympy.parsing.sympy_parser import (
parse_expr, standard_transformations,
implicit_multiplication_application
)
s = 'x+x+x-x = 18 + 4'
def my_parse(s, transfm=None):
lhs, rhs = s.split('=')
if transfm is None:
transfm = (standard_transformations +
(implicit_multiplication_application,))
return sympy.Eq(
parse_expr(lhs, transformations=transfm),
parse_expr(rhs, transformations=transfm))
expr = my_parse(s)
print(expr)
output:
2*x == 22
using sympy version 0.7.6

Resources