Python/Pyparsing Results when Cast as Float - python

I found the following example from another question:
Here
It has some pyparsing code like this:
from pyparsing import *
survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''
number = Word(nums+'.').setParseAction(lambda t: float(t[0]))
separator = Suppress(',')
latitude = Suppress('LA') + number
longitude = Suppress('LN') + number
elevation = Suppress('EL') + number
line = (Suppress('GPS,PN1,')
+ latitude
+ separator
+ longitude
+ separator
+ elevation)
print line.parseString(survey)
It says that the output is:
[52.125133215643, 21.031048525561, 116.898812]
However, I get the following output:
[W:(0123...), W:(0123...), W:(0123...)]
How can I get float outputs instead of these "W:(0123...)" values?
Thanks!

I upgraded my python and pyparsing version and it still did not work correctly. However, the next morning it suddenly worked just fine. I'm not sure why, maybe the restart overnight did something. Either way, it appears to work correctly now.

Related

Problem to get old series data (Python for Finance)

I've converted this formula (ZLEMA Moving Average)
But I have many issues with "Data(Lag Days Ago)", it seems that it cant go back to find the result. Here's the function but unfortunately it doesn't produce the desired result.
def fzlema(source,period):
zxLag = period / 2 if (period / 2) == np.round(period / 2) else (period - 1) / 2
zxLag = int(zxLag)
zxEMAData = source + (source - source.iloc[zxLag]) # Probably error is in this line
zlema = zxEMAData.ewm(span=period, adjust=False).mean()
zlema = np.round(zlema,2)
return zlema
zlema = fzlema(dataframe['close'], 50)
To be clear, the script runs perfectly but what I got is unmatched as it's been calculated on Tradingview.
I tried used iloc[..] and tail(..) but neither return exact results.
I can use the libraries pandas and numpy.
Any point of view?
SOLVED:
Simply using source.shift(zxLag)

Extracting correct characters from a string in Python

I have a BME280 environment sensor that returns a tuple in a variable called envi.
envi = bme.values
print(envi)
returns all three values of temp, pressure and humidity.
If I print(envi[1]) I get a string returned for pressure such as '1029.23hPa'
As this returned value needs calibrating ever so slightly, I simply need to add 3 to it, before publishing it via MQTT to Adafruit via...
c.publish(conf['user']+"/feeds/pres", env[1])
What would be the correct syntax to add 3 to env[1] please?
Is there a way I can do this?
Do you want to do this ?
# Python 3.6+
envi[1] = f"{float(envi[1].strip('hPa')) + 3:.2f}hPa"
# Python pre 3.6
envi[1] = "{:.2f}hPa".format(float(envi[1].strip('hPa')) + 3)
You can use:
s = '1029.23hPa'
f'{float(s[:-3]) + 3}hPa'
# 1032.23hPa
or
f"{float(s.rstrip('hPa')) + 3}hPa"

Number formatting not working with tabulate after printing text

I'm writing this little program learning Python and I have faced a problem. I use tabulate with number formatting set to 5 numbers after separator, to make everything look nice, and it works, until I print text in the table. After text is printed (stating that you cannot divide by 0), formatting on that column seems to be gone.
The code is:
if skaiciuoti == True:
while bp <= bg:
if (bp-a != 0):
y = float(a / (bp - a))
sk1.append(a)
sk2.append(bp)
sk3.append(y)
bp = bp + bz
elif (bp - a == 0):
sk1.append(a)
sk2.append(bp)
sk3.append('Veiksmas negalimas (dalyba is 0)')
bp = bp + bz
lentele = ['A reiksme', 'B reiksme', 'Y reiksme']
duomenys = zip(sk1, sk2, sk3)
print(tabulate (duomenys, headers=lentele, floatfmt=".5f", tablefmt="grid"))
Here are pictures to better illustrate my problem:
Working one
Broken one
I have tried formatting the number before appending it to the list, but it didn't work.
Any suggestions and ideas are welcome.
Okay, I've managed to fix it myself. It was really not that hard, I just didn't think about it.
The solution that worked for me was to format number when appending it to the list (not before the list) like so
sk3.append(format(y, '.5f'))
floatfmt must be a list or a tuple, specifying one format for each column.
In your case, use e.g.:
floatfmts = ('.5f', '.5f', '.5f')
print(tabulate (duomenys, headers=lentele, floatfmt=floatfmts, tablefmt="grid"))
(See e.g. https://bitbucket.org/astanin/python-tabulate/issues/96/floatfmt-option-is-ignored-in-python3)

Export out keyframe within object range

Is it possible to solely out export the keyframes of a given object within its own keyframed ranged?
Example, camA is keyframed in the range of Frame 1 to 10. But when I tried to export out this camera in another format, it is taking into account of the overall time slider instead. And hence exported_camA is keyframed in the range of Frame 1 to 24 (24 is the max range of my time slider)
Will this be possible? I tried out using cmds.playbackOptions but apparently it is also exporting out according to the time slider range
def __init__(self, transform, startAnimation, endAnimation, cameraObj):
self.fileExport = []
print ">>> Exported : %s" %self.fileExport
mayaGlobal = OpenMaya.MGlobal()
mayaGlobal.viewFrame(OpenMaya.MTime(1))
for i in range(startAnimation, endAnimation):
focalLength = cameraObj.focalLength()
vFilmApp = cameraObj.verticalFilmAperture()
focalOut = 2* math.degrees(math.atan(vFilmApp * 25.4/ (2* focalLength)))
myEuler = OpenMaya.MEulerRotation()
spc = OpenMaya.MSpace.kWorld
trans = transform.getTranslation(spc)
rotation = transform.getRotation(myEuler)
rotVector = OpenMaya.MVector(myEuler.asVector())
self.fileExport.append((str(i) + '\t' + str(trans[0]) + "\t" + str(trans[1]) + "\t" + str(trans[2]) + "\t" + str(math.degrees(rotVector[0])) + "\t" + str(math.degrees(rotVector[1])) + "\t" + str(math.degrees(rotVector[2])) + "\t" + str(focalOut) + "\n"))
mayaGlobal.viewFrame(OpenMaya.MTime(i+1))
in cmds you can get the maximum and minimum times for a given animation like this:
key_times = cmds.keyframe('pCube1', attribute = 'translate', q=True, tc=True)
first_key = key_times[0]
last_key = key_times[-1]
Note that this has to be applied to a particular attribute (in this case, I used 'translate'), otherwise you will get the keys from the first anim curve Maya finds on the object.
That said, it's usually considered best to export either the scene keyframe range or an explicitly set frame range. Otherwise you may have somebody working in a scene and scrubbing the time, then exporting and seeing fewer frames.
I have also found this command - cmds.findKeyframe so as to capture the keyframes of the selected object animation and it also aids in my code as well
Though I am not sure if this will generates any adverse effects later on, seeing that I have yet to encounter one :x
For example:
minTime = cmds.findKeyframe(which='first') # First keyframe
maxTime = cmds.findKeyframe(which='last') # Last keyframe

Struggling with a longitude/latitude SQL query I copied from PHP into our new Python backend. Need some second opinions

I'm moving the backend of a site to Django because it was originally coded in PHP and it's the biggest mess on Earth or Mars... anyway.. so I copied the PHP and Python that I've conjured up to copy it below. They both return IDENTICAL values, but for some reason, the Django/Python doesn't return anything from the query.
I'm up for suggestions, I'd consider installing GeoDjango, but I was hoping to get this going without having to do so.
So here's the code:
PHP:
$lat = $myrow['latitude'];
$lon = $myrow['longitude'];
// get the min/max latitudes and longitudes for the radius search
$lat_range = $miles / 69.172;
$lon_range = abs($miles / (cos($lon) * 69.172));
$min_lat = $lat - $lat_range;
$max_lat = $lat + $lat_range;
$min_lon = $lon - $lon_range;
$max_lon = $lon + $lon_range;
$sql = "SELECT * FROM zipcodes WHERE
(latitude >= $min_lat AND latitude <= $max_lat AND
longitude >= $min_lon AND longitude <= $max_lon)";
Python:
distance = float(distance)
orderloc = Zipcodes.objects.get(zip=order.zip)
orderloc.longitude = float(orderloc.longitude)
orderloc.latitude = float(orderloc.latitude)
latrange = distance/69.172
lonrange = math.fabs(distance/(math.cos(orderloc.longitude) * 69.172))
minlat = orderloc.latitude - latrange
maxlat = orderloc.latitude + latrange
minlon = orderloc.longitude - lonrange
maxlon = orderloc.longitude + lonrange
distanceresults = Zipcodes.objects.all().filter(longitude__gte=minlon,
longitude__lte=maxlon,latitude__gte=minlat,latitude__lte=maxlat)
P.S. This is the query that Django returns...
SELECT (a ton of stuff here) FROM `zipcodes` WHERE (`zipcodes`.`longitude` <= -74.489601513 AND `zipcodes`.`longitude` >= -75.957598487 AND `zipcodes`.`latitude` >= 39.8528641705 AND `zipcodes`.`latitude` <= 41.2985358295 )
I noticed that you're converting the latitude and longitude on orderloc to floats. What field type are they on your model in the first place? Django has a FloatField field type, so if you're dealing with floats, you should use that field type on your model. I'm thinking based on this that it might be an issue of comparing the actual true-blue float with something like a CHAR value, and it's not exactly matching.
Alternatively, floats in Python can be a little weird sometimes, returning numbers like 25.00000000001 instead of an even 25 after doing calculations. Since you're dealing with latitude and longitude, which typically have a fixed set of digits, you might also try using DecimalFields. These essentially function like floats, but limit stored data to a defined number of places. Again, just throwing out ideas.

Categories

Resources