The following are code examples for showing how to use math.radians(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
 Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    Apache License 2.0 7 votes
```def distance(origin, destination):
"""Determine distance between 2 sets of [lat,lon] in km"""

lat1, lon1 = origin
lat2, lon2 = destination

a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

return d ```
Example 2
```def distance(pointA, pointB):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)

http://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [pointA[1], pointA[0], pointB[1], pointB[0]])

# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
r = 3956  # Radius of earth in miles. Use 6371 for kilometers
return c * r ```
Example 3
```def _startImageCapturingAtGraphNode(self):
amntY = 0.3
xdir = [-0.5, 0, 0.5]
cameraId = 0

for idx,amntX in enumerate(xdir):
time.sleep(0.1)
self._checkIfAsthamaInEnvironment(cameraId)
if self.pumpFound :
# Setting rotation angle of body towards head
theta = 0
if idx == 0: # LEFT
if idx == 2: # RIGHT
self.pumpAngleRotation = theta

return "KILLING GRAPH SEARCH : PUMP FOUND"

self._moveHead(0, 0) # Bringing to initial view

return ```
Example 4
```def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
m = 6367000. * c
return m

# calculating the intersection  point between two rays (specified each by camera position and depth-estimated object location) ```
Example 5
 Project: airqdata   Author: dr-1   File: utils.py    GNU General Public License v3.0 6 votes
```def haversine(lat1, lon1, lat2, lon2):
"""Calculate the great circle distance between two points on earth.

Args:
lat1, lon1, lat2, lon2: coordinates of point 1 and point 2 in
decimal degrees

Returns:
Distance in kilometers
"""

# Convert decimal degrees to radians
lat1, lon1, lat2, lon2 = (radians(val) for val in (lat1, lon1, lat2, lon2))

# Haversine formula
d_lat = lat2 - lat1
d_lon = lon2 - lon1
a = sin(d_lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(d_lon / 2) ** 2
c = 2 * asin(sqrt(a))

return distance ```
Example 6
```def rotate_bbox(box, a):
'''Rotate a bounding box 4-tuple by an angle in degrees'''
corners = ( (box[0], box[1]), (box[0], box[3]), (box[2], box[3]), (box[2], box[1]) )
sa = math.sin(a)
ca = math.cos(a)

rot = []
for p in corners:
rx = p[0]*ca + p[1]*sa
ry = -p[0]*sa + p[1]*ca
rot.append((rx,ry))

# Find the extrema of the rotated points
rot = list(zip(*rot))
rx0 = min(rot[0])
rx1 = max(rot[0])
ry0 = min(rot[1])
ry1 = max(rot[1])

#print('## RBB:', box, rot)

return (rx0, ry0, rx1, ry1) ```
Example 7
```def draw_marker(self, name, mp, tp, weight, c):
if name in self.markers:
m_shape, ref, orient, units = self.markers[name]

c.save()
c.translate(*mp)
if orient == 'auto':
angle = math.atan2(tp[1]-mp[1], tp[0]-mp[0])
c.rotate(angle)
elif isinstance(orient, int):
c.rotate(angle)

if units == 'stroke':
c.scale(weight, weight)

c.translate(-ref[0], -ref[1])

self.draw_shape(m_shape)
c.restore() ```
Example 8
```def mergeRotatedScaledPage(self, page2, rotation, scale):
rotating = [[math.cos(rotation), math.sin(rotation),0],
[-math.sin(rotation),math.cos(rotation), 0],
[0,                  0,                  1]]
scaling = [[scale,0,    0],
[0,    scale,0],
[0,    0,    1]]
ctm = utils.matrixMultiply(rotating, scaling)

return self.mergeTransformedPage(page2,
[ctm[0][0], ctm[0][1],
ctm[1][0], ctm[1][1],
ctm[2][0], ctm[2][1]])

##
# This is similar to mergePage, but the stream to be merged is translated
# and scaled by appling a transformation matrix.
#
# @param page2 An instance of {@link #PageObject PageObject} to be merged.
# @param scale The scaling factor
# @param tx    The translation on X axis
# @param tx    The translation on Y axis ```
Example 9
```def mergeRotatedScaledTranslatedPage(self, page2, rotation, scale, tx, ty):
translation = [[1, 0, 0],
[0, 1, 0],
[tx,ty,1]]
rotating = [[math.cos(rotation), math.sin(rotation),0],
[-math.sin(rotation),math.cos(rotation), 0],
[0,                  0,                  1]]
scaling = [[scale,0,    0],
[0,    scale,0],
[0,    0,    1]]
ctm = utils.matrixMultiply(rotating, scaling)
ctm = utils.matrixMultiply(ctm, translation)

return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
ctm[1][0], ctm[1][1],
ctm[2][0], ctm[2][1]])

##
# Applys a transformation matrix the page.
#
# @param ctm   A 6 elements tuple containing the operands of the
#              transformation matrix ```
Example 10
```def update(self):

# Update ball position
self.rect.x = self.x
self.rect.y = self.y

if self.y <= self.top_edge:
self.direction = (180-self.direction) % 360
self.sound.edge_sound.play()
if self.y > self.bottom_edge - 1*self.height:
self.direction = (180-self.direction) % 360
self.sound.edge_sound.play() ```
Example 11
```def haversine(lon1, lat1, lon2, lat2, unit='mi'):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = list(map(radians, [lon1, lat1, lon2, lat2]))
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
# print "dlat=%r,dlon=%r" % (dlat, dlon)
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))

distance = {'km': 6367,
'mi': 3956,
'ft': 20889110}[unit] * c
return distance

# brought in from context.py r23462 ```
Example 12
```def great_circle_dist(a, b, unit="kilometers"):
"""
compute great circle distance between two latitude/longitude coordinate pairs.
Returns great cirlce distance in kilometers (default) or meters.
https://en.wikipedia.org/wiki/Great-circle_distance
"""
lat1, lon1 = a
lat2, lon2 = b
if (lat1==92) or (lat2==92):
return -1 # invalid location gives invalid distance
a = (math.sin(dlat / 2.0) * math.sin(dlat / 2.0) +
math.sin(dlon / 2.0) * math.sin(dlon / 2.0))
c = 2.0 * math.asin(math.sqrt(a))
if unit == "kilometers":
return dist_km
elif unit == "meters":
return dist_km * 1000
else:
raise ValueError("Unknown unit: %s" % unit) ```
Example 13
 Project: ssrspeed_backup   Author: mazhenting   File: speedtestnet.py    GNU General Public License v3.0 6 votes
```def distance(origin, destination):
"""Determine distance between 2 sets of [lat,lon] in km"""

lat1, lon1 = origin
lat2, lon2 = destination

a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

return d ```
Example 14
```def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
"""
Check if a target object is within a certain distance in front of a reference object.

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:param max_distance: maximum allowed distance
:return: True if target object is within max_distance ahead of the reference object
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

# If the vector is too short, we can simply stop here
if norm_target < 0.001:
return True

if norm_target > max_distance:
return False

forward_vector = np.array(
d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return d_angle < 90.0 ```
Example 15
```def compute_magnitude_angle(target_location, current_location, orientation):
"""
Compute relative angle and distance between a target_location and a current_location

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:return: a tuple composed by the distance to the object and the angle between both objects
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return (norm_target, d_angle) ```
Example 16
```def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
"""
Check if a target object is within a certain distance in front of a reference object.

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:param max_distance: maximum allowed distance
:return: True if target object is within max_distance ahead of the reference object
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

# If the vector is too short, we can simply stop here
if norm_target < 0.001:
return True

if norm_target > max_distance:
return False

forward_vector = np.array(
d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return d_angle < 90.0 ```
Example 17
```def compute_magnitude_angle(target_location, current_location, orientation):
"""
Compute relative angle and distance between a target_location and a current_location

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:return: a tuple composed by the distance to the object and the angle between both objects
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return (norm_target, d_angle) ```
Example 18
```def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
"""
Check if a target object is within a certain distance in front of a reference object.

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:param max_distance: maximum allowed distance
:return: True if target object is within max_distance ahead of the reference object
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

# If the vector is too short, we can simply stop here
if norm_target < 0.001:
return True

if norm_target > max_distance:
return False

forward_vector = np.array(
d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return d_angle < 90.0 ```
Example 19
```def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
"""
Check if a target object is within a certain distance in front of a reference object.

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:param max_distance: maximum allowed distance
:return: True if target object is within max_distance ahead of the reference object
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

# If the vector is too short, we can simply stop here
if norm_target < 0.001:
return True

if norm_target > max_distance:
return False

forward_vector = np.array(
d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return d_angle < 90.0 ```
Example 20
```def compute_magnitude_angle(target_location, current_location, orientation):
"""
Compute relative angle and distance between a target_location and a current_location

:param target_location: location of the target object
:param current_location: location of the reference object
:param orientation: orientation of the reference object
:return: a tuple composed by the distance to the object and the angle between both objects
"""
target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
norm_target = np.linalg.norm(target_vector)

d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

return (norm_target, d_angle) ```
Example 21
```def __init__(self, name=None, origin=(0, 0, 0), width=3.0, depth=6.0, height=3.2,
rotation_angle=0):
"""Init room."""
self._width = float(width) or 3.0
self._depth = float(depth) or 6.0
self._height = float(height) or 3.2
self._rotation_angle = float(rotation_angle) or 0.0

self._z_axis = Vector3(0, 0, 1)
self._x_axis = Vector3(1, 0, 0).rotate_around(
self._y_axis = Vector3(0, 1, 0).rotate_around(

name = name or 'room'
origin = Point3(*tuple(origin)) if origin else Point3(0, 0, 0)
# setting up origin will initiate recalculation of room
HBZone.__init__(self, name, origin) ```
Example 22
 Project: toolbox   Author: aschaller   File: gui.py    GNU General Public License v3.0 6 votes
```def OnChamferAngleUnit(self, event):
oldUnit = self.chamferCfgSettings.angleUnit
newUnit = str(self.chamferUnitwxChoice.GetSelection())

if oldUnit == '0' and newUnit == '1':
self.chamferAngleSpinCtrlDouble.SetMax(1.5708)
self.chamferAngleSpinCtrlDouble.SetIncrement(0.01)
self.chamferCfgSettings.angleUnit = '1'
elif oldUnit == '1' and newUnit == '0':
self.chamferAngleSpinCtrlDouble.SetMax(90)
self.chamferAngleSpinCtrlDouble.SetValue(round(m.degrees(self.chamferAngleSpinCtrlDouble.GetValue()), 2))
self.chamferAngleSpinCtrlDouble.SetIncrement(1)
self.chamferCfgSettings.angleUnit = '0'

self.OnChamferSpinCtrlDouble(None) ```
Example 23
```def _get_affine_matrix(center, angle, translate, scale, shear):
# Helper method to compute matrix for affine transformation
# We need compute affine transformation matrix: M = T * C * RSS * C^-1
# where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
#       C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
#       RSS is rotation with scale and shear matrix
#       RSS(a, scale, shear) = [ cos(a)*scale    -sin(a + shear)*scale     0]
#                              [ sin(a)*scale    cos(a + shear)*scale     0]
#                              [     0                  0          1]

# scale = 1.0 / scale

T = np.array([[1, 0, translate[0]], [0, 1, translate[1]], [0,0,1]])
C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0,0,1]])
[math.sin(angle)*scale, math.cos(angle+shear)*scale, 0],
[0,0,1]])
matrix = T @ C @ RSS @ np.linalg.inv(C)

return matrix[:2,:] ```
Example 24
```def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
# todo, handle props, angle, origins
size = prop.get_size_in_points()

texmanager = self.get_texmanager()

Z = texmanager.get_grey(s, size, self.dpi)
Z = np.array(Z * 255.0, np.uint8)

w, h, d = self.get_text_width_height_descent(s, prop, ismath)
x = np.round(x + xd)
y = np.round(y + yd)

self._renderer.draw_text_image(Z, x, y, angle, gc) ```
Example 25
```def rotation_matrix(degrees):
return numpy.array((
(math.cos(angle), -math.sin(angle), 0.0, 0.0),
(math.sin(angle), math.cos(angle), 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, 0.0, 0.0, 1.0)
)) ```
Example 26
```def vector_from_angle(degrees):
"""Returns a unit vector in the xy-plane rotated by the given degrees from
the positive x-axis"""
z_rot_matrix = numpy.identity(4)

return tuple(numpy.dot(z_rot_matrix, (1, 0, 0, 0))[:3]) ```
Example 27
```def _transformTheta(self, theta):
# CONVERTING THETA { THETA' % 360}
theta = 0.0

theta = 0.0

theta = -math.pi/2

theta = math.pi/2

return theta ```
Example 28
 Project: client   Author: Scorched-Moon   File: ani.py    GNU General Public License v3.0 5 votes
```def image_rotate(tv,name,img,shape,angles,diff=0):
"""Rotate an image and put it into tv.images

Arguments:
tv -- vid to load into
name -- prefix name to give the images
image -- image to load anis from
shape -- shape fimage (usually a subset of 0,0,w,h) used for collision detection
angles -- a list of angles to render in degrees
diff -- a number to add to the angles, to correct for source image not actually being at 0 degrees

"""
w1,h1 = img.get_width(),img.get_height()
shape = pygame.Rect(shape)
ps = shape.topleft,shape.topright,shape.bottomleft,shape.bottomright
for a in angles:
img2 = pygame.transform.rotate(img,a+diff)
w2,h2 = img2.get_width(),img2.get_height()
minx,miny,maxx,maxy = 1024,1024,0,0
for x,y in ps:
x,y = x-w1/2,y-h1/2
#NOTE: the + and - are switched from the normal formula because of
#the weird way that pygame does the angle...
x2 = x*math.cos(a2) + y*math.sin(a2)
y2 = y*math.cos(a2) - x*math.sin(a2)
x2,y2 = x2+w2/2,y2+h2/2
minx = min(minx,x2)
miny = min(miny,y2)
maxx = max(maxx,x2)
maxy = max(maxy,y2)
r = pygame.Rect(minx,miny,maxx-minx,maxy-miny)
#((ww-w)/2,(hh-h)/2,w,h)
tv.images["%s.%d"%(name,a)] = img2,r ```
Example 29
 Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes
```def testRadians(self):
Example 30
```def draw(self, context):
pie.separator()
pie.separator()
pie.operator("mesh.customdata_custom_splitnormals_clear", text="Clear Custom Normals")
pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 60").angle = math.radians(60)
pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 30").angle = math.radians(30)
pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 180").angle = math.radians(180)
Example 31
 Project: kuaa   Author: rafaelwerneck   File: application.py    GNU General Public License v3.0 5 votes
```def show_block_wheel(self):
"""Shows the block wheel for the user to choose a block to add in the
experiment."""
# If first time showing the wheel, simply remove the background guide
# text
if self._textID:
self.canvas.delete(self._textID)
self._textID = None

self._afterjob = None
self._wheel_visible = True

# Gray out everything else
for block in self._experiment_blocks:
block.gray_out()
if block._context_visible:
block._context_box.set_invisible()
block._context_visible = False

self.canvas.configure(bg='#444444')

# Display the wheel
total_blocks = len(config.APPLICATION_BLOCKS)
for i in xrange(total_blocks):
teta = math.radians(i * (float(360) / total_blocks))
self._wheel_blocks[i].set_visible()
self._wheel_blocks[i].position(self._button_press_position['x'] -
(config.BLOCK_SIZE / 2) +
math.sin(teta)),
self._button_press_position['y'] -
(config.BLOCK_SIZE / 2) -
math.cos(teta)))
tk.Misc.lift(self._wheel_blocks[i]._frame) ```
Example 32
```def distance(origin, destination):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, origin + destination)

# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371  # Radius of earth in kilometers. Use 3956 for miles
return c * r ```
Example 33
```def _makeJointDict(motors, use_radians = True):
pose = {}
for p in motors.findall(NS + "Motor"):
name = p.find(NS + 'name').text
value = float(p.find(NS + 'value').text)

pose[name] = value

return pose ```
Example 34
```def getpostures(xap_file):
""" Parses a Aldebaran Choregraphe posture library (.xap files)
into a Python dictionary of postures.
"""

if not os.path.exists(xap_file):
raise RuntimeError("The XAP file %s does not exist." % xap_file)

try:
tree = ET.parse(xap_file)
except ET.ParseError:
raise RuntimeError("The XAP file %s is not a valid XML file." % xap_file)

root=tree.getroot()

postures = {}

positions = [p for p in root.iter(NS + 'position')]

if not positions:
raise RuntimeError("The XAP file %s does not contain any pose." % xap_file)

for p in positions:
name = p.find(NS + 'name').text
version = p.find(NS + 'version') # it *seems* that the 'version' 2 indicates joints stored in radians
pose = _makeJointDict(p.find(NS + "Motors"), version is not None and version.text=='2')

postures[name] = pose

return postures ```
Example 35
```def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two
points on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * asin(sqrt(a))
r = 6371  # Radius of earth in kilometers. Use 3956 for miles
return c * r ```
Example 36
```def getGroundPointDistance(self,x,y,pitchang):
xdist=0
ydist=0
h=45+5*math.sin(-pitchang)
ydist=h/math.tan(angle)
if ydist<100:ydist-=3 #修正系数，测试出来的数据
if self._robotip=="192.168.1.103": #两个机器人部分参数不同，修正,nao y值加6cm
ydist+=5
xdist=math.sqrt(ydist*ydist+h**2)*math.tan(wangle) #下摄像头高度45+修正值
xdist=round(xdist,2)
ydist=round(ydist,2)
return xdist,ydist ```
Example 37
```def getSpaceBallDistance(self):
thresh=self._threshBall.copy() #保护
(x,y),r=self.getMinCircle(thresh)
dist=0
if r>0: #缩放转换函数
if dist>50:dist*=1.1
return dist ```
Example 38
```def do(self,nv,nm):
print "modify."
nm.poseInit()
time.sleep(0.5)
print x,y
if y>0:
nm._motion.walkTo((y-10)/100.0,-x/100.0,0,\
[["MaxStepFrequency", 0.2]])
if self.ballLocation==0:
print "mid turn"
self.__class__=self.nextstate ```
Example 39
```def do(self,nv,nm):
"finding gate."
time.sleep(1)
x,y,w,h=nv._gateBounding
print x,w
if x<5 and w<200:
elif x>30 and w<200:
else:
self.__class__=self.nextstate ```
Example 40
```def updatePositionAndHeading(self,deltaX,deltaTheta):
if (deltaX>0.0):
self.totalDistanceCovered = deltaX + self.totalDistanceCovered
Example 41
```def vertical_section_calc(northing: float, easting: float,
vertical_section_difference: float
) -> Tuple[float, float, float, float]:
'''
using northing, easting and vertical section direction as inputs
and return directional difference, closure distance, closure azimuth
, vertical section difference (vsd).
'''

# Calculation for closure distance
closure_distance = (northing**2 + easting**2)**.5

# Calculation for closure azimuth
if northing == 0:
closure_azimuth = 0
else:
closure_azimuth = math.degrees(np.arctan(easting / northing))

# Calculation for directional difference
directional_difference = closure_azimuth - vertical_section_difference

# Calculation for vertical section
vertical_section = (closure_distance * (np.cos(

return directional_difference, closure_distance, closure_azimuth, vertical_section ```
Example 42
```def distanceBetweenCoords(lat1, lon1, lat2, lon2):
"""
This uses the haversine formula to calculate the great-circle distance
between two points.

Parameters
----------
lat1 : float
The latitude of the first point
lon1 : float
The longitude of the first point
lat2 : float
The latitude of the second point
lon2 : float
The longitude of the second point
"""

a = math.sin(deltaPhi/2.0)**2 + \
math.cos(phi1)*math.cos(phi2)*(math.sin(deltaLambda/2.0)**2)

c = 2.0*math.atan2(math.sqrt(a), math.sqrt(1 - a))

return d ```
Example 43
```def can_dodge(agent, target):
bot_to_target = target - agent.info.my_car.pos
local_bot_to_target = dot(bot_to_target, agent.info.my_car.theta)
angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
distance_bot_to_target = norm(vec2(bot_to_target))
on_ground = agent.info.my_car.on_ground and agent.info.my_car.pos[2] < 100
going_fast = velocity_2d(agent.info.my_car.vel) > 1250
target_not_in_goal = not agent.info.my_goal.inside(target)
return good_angle and distance_bot_to_target > 2000 and on_ground and going_fast and target_not_in_goal ```
Example 44
```def should_dodge(agent):
car = agent.info.my_car
their_goal = agent.info.their_goal
close_to_goal = distance_2d(car.pos, their_goal.center) < 4000
aiming_for_goal = abs(line_backline_intersect(their_goal.center[1], vec2(car.pos), vec2(car.forward()))) < 850
bot_to_target = agent.info.ball.pos - car.pos
local_bot_to_target = dot(bot_to_target, agent.info.my_car.theta)
angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
close_to_ball = norm(vec2(bot_to_target)) < 850
return close_to_ball and close_to_goal and aiming_for_goal and good_angle ```
Example 45
```def pointOnCircle(radius, angle):

return (x, y) ```
Example 46
 Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes
```def __init__(self, **kwargs):
# setting default values
self.lat = 0. # in degrees
self.lon = 0. # in degrees
self.k = 1. # scale factor

for attr in kwargs:
setattr(self, attr, kwargs[attr])
Example 47
 Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes
```def fromGeographic(self, lat, lon):
B = math.sin(lon) * math.cos(lat)
x = 0.5 * self.k * self.radius * math.log((1.+B)/(1.-B))
return (x,y) ```
Example 48
 Project: torch-toolbox   Author: PistonY   File: functional.py    BSD 3-Clause "New" or "Revised" License 5 votes
```def _get_inverse_affine_matrix(center, angle, translate, scale, shear):
# Helper method to compute inverse matrix for affine transformation

M00 = math.cos(angle) * scale
M01 = -math.sin(angle + shear) * scale
M10 = math.sin(angle) * scale
M11 = math.cos(angle + shear) * scale
M02 = center[0] - center[0] * M00 - center[1] * M01 + translate[0]
M12 = center[1] - center[0] * M10 - center[1] * M11 + translate[1]
matrix = np.array([[M00, M01, M02], [M10, M11, M12]], dtype=np.float32)
return matrix ```
Example 49
```def mergeRotatedPage(self, page2, rotation):
return self.mergeTransformedPage(page2,
[math.cos(rotation),  math.sin(rotation),
-math.sin(rotation), math.cos(rotation),
0,                   0])

##
# This is similar to mergePage, but the stream to be merged is translated
# by appling a transformation matrix.
#
# @param page2 An instance of {@link #PageObject PageObject} to be merged.
# @param tx    The translation on X axis
# @param tx    The translation on Y axis ```
Example 50
```def rotate_x(self, deg):
"""Rotate mesh around x-axis

:param float deg: Rotation angle (degree)
:return:
"""
mat = numpy.array([
[1, 0, 0, 0],
[0, 0, 0, 1]
])
self.vectors = self.vectors.dot(mat)
return self ```
Example 51
```def rotate_y(self, deg):
"""Rotate mesh around y-axis

:param float deg: Rotation angle (degree)
"""
mat = numpy.array([
[0, 1, 0, 0],
[0, 0, 0, 1]
])
self.vectors = self.vectors.dot(mat)
return self ```
Example 52
```def rotate_z(self, deg):
"""Rotate mesh around z-axis

:param float deg: Rotation angle (degree)
"""
mat = numpy.array([
[0, 0, 1, 0],
[0, 0, 0, 1]
])
self.vectors = self.vectors.dot(mat)
return self ```
Example 53
```def rotated(self,
verts,
deg,
cam=None,
axis='y',
img=None,
do_alpha=True,
far=None,
near=None,
color_id=0,
img_size=None):
import math
if axis == 'y':
elif axis == 'x':
else:
center = verts.mean(axis=0)
new_v = np.dot((verts - center), around) + center

return self.__call__(
new_v,
cam,
img=img,
do_alpha=do_alpha,
far=far,
near=near,
img_size=img_size,
color_id=color_id) ```
Example 54
```def simple_renderer(rn,
verts,
faces,
color=colors['light_pink']):
# Rendered model color
rn.set(v=verts, f=faces, vc=color, bgcolor=np.ones(3))
albedo = rn.vc

# Construct Back Light (on back right corner)
rn.vc = LambertianPointLight(
f=rn.f,
v=rn.v,
num_verts=len(rn.v),
light_pos=_rotateY(np.array([-200, -100, -100]), yrot),
vc=albedo,
light_color=np.array([1, 1, 1]))

# Construct Left Light
rn.vc += LambertianPointLight(
f=rn.f,
v=rn.v,
num_verts=len(rn.v),
light_pos=_rotateY(np.array([800, 10, 300]), yrot),
vc=albedo,
light_color=np.array([1, 1, 1]))

# Construct Right Light
rn.vc += LambertianPointLight(
f=rn.f,
v=rn.v,
num_verts=len(rn.v),
light_pos=_rotateY(np.array([-500, 500, 1000]), yrot),
vc=albedo,
light_color=np.array([.7, .7, .7]))

return rn.r ```
Example 55
 Project: openrocketdoc   Author: open-aerospace   File: document.py    GNU General Public License v3.0 5 votes
```def sweep(self):
"""**[m]** The Distance from the start of the fin to the beginning of
the tip.
"""
if self._sweep is not None:
return self._sweep
Example 56
```def distance_on_earth(lat1, lon1, lat2, lon2):
#print "starting distance comp ",lat1,lon1,lat2,lon2
if lat1==lat2 and lon1==lon2:
return 0.0

# Convert latitude and longitude to

# phi = 90 - latitude

# theta = longitude
# Compute spherical distance from spherical coordinates.

# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
#    sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length

cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
#print type(cos)
try:
arc = math.acos( cos )
except ValueError:
arc = 1.0/6371/1000
#print arc
# Distance in meters
return arc*6371*1000 ```
Example 57
```def largest_rotated_rect(w, h, angle):
"""
Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle within the rotated rectangle.

Original JS code by 'Andri' and Magnus Hoff from Stack Overflow

Converted to Python by Aaron Snoswell
"""

quadrant = int(math.floor(angle / (math.pi / 2))) & 3
sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle
alpha = (sign_alpha % math.pi + math.pi) % math.pi

bb_w = w * math.cos(alpha) + h * math.sin(alpha)
bb_h = w * math.sin(alpha) + h * math.cos(alpha)

gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w)

delta = math.pi - alpha - gamma

length = h if (w < h) else w

d = length * math.cos(alpha)
a = d * math.sin(alpha) / math.sin(delta)

y = a * math.cos(gamma)
x = y * math.tan(gamma)

return (bb_w - 2 * x, bb_h - 2 * y) ```
Example 58
```def rotate_and_crop(image, angle):
image_width, image_height = image.shape[:2]
image_rotated = rotate_image(image, angle)
image_rotated_cropped = crop_around_center(image_rotated,
*largest_rotated_rect(
image_width, image_height,
return image_rotated_cropped ```
Example 59
```def draw_waypoints(world, waypoints, z=0.5):
"""
Draw a list of waypoints at a certain height given in z.

:param world: carla.world object
:param waypoints: list or iterable container with the waypoints to draw
:param z: height in meters
:return:
"""
for w in waypoints:
t = w.transform
begin = t.location + carla.Location(z=z)
end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) ```
Example 60
```def draw_waypoints(world, waypoints, z=0.5):
"""
Draw a list of waypoints at a certain height given in z.

:param world: carla.world object
:param waypoints: list or iterable container with the waypoints to draw
:param z: height in meters
:return:
"""
for w in waypoints:
t = w.transform
begin = t.location + carla.Location(z=z)
end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) ```
Example 61
```def draw_waypoints(world, waypoints, z=0.5):
"""
Draw a list of waypoints at a certain height given in z.

:param world: carla.world object
:param waypoints: list or iterable container with the waypoints to draw
:param z: height in meters
:return:
"""
for w in waypoints:
t = w.transform
begin = t.location + carla.Location(z=z)
end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) ```
Example 62
```def __init__(self,rmajor,rminor,lon1,lat1,lon2,lat2):
"""
Define a great circle by specifying:
rmajor - radius of major axis of ellipsoid
rminor - radius of minor axis of ellipsoid.
lon1 - starting longitude of great circle
lat1 - starting latitude
lon2 - ending longitude
lat2 - ending latitude
All must be given in degrees.

Instance variables:
distance - distance along great circle in radians.
lon1,lat1,lon2,lat2 - start and end points (in radians).
"""
# convert to radians from degrees.
self.a = rmajor
self.f = (rmajor-rminor)/rmajor
self.lat1 = lat1
self.lat2 = lat2
self.lon1 = lon1
self.lon2 = lon2
# distance along geodesic in meters.
d,a12,a21 = vinc_dist(self.f,  self.a,  lat1,  lon1,  lat2,  lon2 )
self.distance = d
self.azimuth12 = a12
self.azimuth21 = a21
# great circle arc-length distance (in radians).
self.gcarclen = 2.*math.asin(math.sqrt((math.sin((lat1-lat2)/2))**2+\
math.cos(lat1)*math.cos(lat2)*(math.sin((lon1-lon2)/2))**2))
# check to see if points are antipodal (if so, route is undefined).
if self.gcarclen == math.pi:
self.antipodal = True
else:
self.antipodal = False ```
Example 63
```def fromNaviDegree(degrees):
return math.pi / 2. - math.radians(degrees) ```
Example 64
```def test_frompyfunc_endian(self, level=rlevel):
# Ticket #503
big_endian = np.array([83.4, 83.5], dtype='>f8')
little_endian = np.array([83.4, 83.5], dtype='<f8')
Example 65
```def draw_mathtext(self, gc, x, y, s, prop, angle):
"""
Draw the math text using matplotlib.mathtext
"""
if __debug__: verbose.report('RendererAgg.draw_mathtext',
'debug-annoying')
ox, oy, width, height, descent, font_image, used_characters = \
self.mathtext_parser.parse(s, self.dpi, prop)

x = np.round(x + ox + xd)
y = np.round(y - oy + yd)
self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) ```
Example 66
```def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
"""
Render the text
"""
if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying')

if ismath:
return self.draw_mathtext(gc, x, y, s, prop, angle)

flags = get_hinting_flag()
font = self._get_agg_font(prop)

if font is None: return None
if len(s) == 1 and ord(s) > 127:
else:
# We pass '0' for angle here, since it will be rotated (in raster
# space) in the following call to draw_text_image).
font.set_text(s, 0, flags=flags)
font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
d = font.get_descent() / 64.0
# The descent needs to be adjusted for the angle
xo, yo = font.get_bitmap_offset()
xo /= 64.0
yo /= 64.0

#print x, y, int(x), int(y), s
self._renderer.draw_text_image(
font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc) ```
Example 67
```def bearing(pointA, pointB):
"""
Calculates the bearing between two points.

Found here: https://gist.github.com/jeromer/2005586

The formulae used is the following:
θ = atan2(sin(Δlong).cos(lat2),
cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))

:Parameters:
- `pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees
- `pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees

:Returns:
The bearing in degrees

:Returns Type:
float
"""
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")

x = math.sin(diffLong) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
* math.cos(lat2) * math.cos(diffLong))

initial_bearing = math.atan2(x, y)

# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = math.degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360

return compass_bearing ```
Example 68
```def return_the_instructions(var):
if var == 'v0':
return ['v0x / cos_a', 'v0y / sin_a', '( x - x0 ) / ( cos_a * t ) ', '( L - x0 ) / ( cos_a * t_all )', '( y - y0 + g * t * t / 2 ) / ( sin_a * t )', '( t_all * g ) / ( 2 * sin_a )', 'math.sqrt( ( 2 * g ) / cmath.sin( 2 * alpha ) )', '( vy + g * t ) / sin_a', 'math.sqrt( vy * vy + 2 * g * y ) / sin_a', 'math.sqrt( h_max * 2 * g ) / sin_a']

if var == 'alpha':
return ['math.radians( cmath.acos ( cos_a ) )', 'math.radians( cmath.asin ( sin_a ))', 'math.radians( cmath.asin( ( ( L * g ) / ( v0 * v0 )) / 2 )', 'math.radians( math.sqrt( cmath.asin( ( h_max * 2 * g ) / ( v0 * v0 ) ) ))']

if var == 'g':
return ['M * G / ( r * r )']

if var == 'v0x':
return ['v0 * cos_a', '( x - x0 ) / t', '( L - x0 ) / t_all']

if var == 'v0y':
return ['v0 * sin_a', '( y - y0 + g * t * t / 2 ) / t', 't_all * g / 2', 'vy + g * t', 'math.sqrt( vy * vy + 2 * g * y )', 'math.sqrt( h_max * 2 * g )']

if var == 'vy':
return ['v0y - g * t', 'v0 * sin_a - g * t', 'math.sqrt( v0y * v0y - 2 * g * y )']

if var == 't_all':
return ['( L - x0 ) / ( v0 * cos_a )', '( L - x0 ) / v0x']

if var == 't':
return ['( v0y - vy ) / g', '( v0y - v0 * sin_a ) / g', '( x - x0 ) / v0x', '( x - x0 )  / v0 * cos_a']

if var == 'h_max':
return ['y0 + v0 * sin_a * 0.5 * t_all - 0.25 * g * t_all * t_all / 2', 'y0 + v0y * 0.5 * t_all - 0.25 * g * t_all * t_all / 2']

if var == 'x0':
return ['x - vox * t', 'x - v0 * cos_a * t', 'L - v0 * cos_a * t_all', 'L - v0x * t_all']

if var == 'x':
return ['x0 + v0x * t', 'x0 + v0 * cos_a * t']

if var == 'y0':
return ['y - v0y * t + g * t * t / 2', 'y - v0 * sin_a * t + g * t * t / 2', 'h_max - v0y * 0.5 * t_all + 0.25 * g * t_all * t_all / 2', 'h_max - v0 * sin_a * 0.5 * t_all + g * t_all * 0.25 * t_all / 2']

if var == 'y':
return ['y0 + v0y * t - g * t * t / 2', 'y0 + v0 * sin_a * t - g * t * t / 2', '( vy * vy - v0y * v0y ) / ( -2 * g )', '( vy * vy - v0 * sin_a * v0 * sin_a ) / ( -2 * g )']

if var == 'L':
return ['x0 + v0 * cos_a * t_all', 'x0 + v0x * t_all', 'v0 * v0 * math.sin( alpha * 2 ) / g']

if var == 'F':
return ['test', 'test']

if var == 'm':
return ['test', 'test']

if var == 'sin_a':
return ['cmath.sin( alpha )', 'v0y / v0', '( y - y0 + g * t * t / 2 ) / ( v0 * t )', 't_all * g / ( 2 * v0 )', '( t * g + vy ) / v0', 'math.sqrt( h_max * 2 * g ) / v0']

if var == 'cos_a':
return ['v0x / v0', '( L - x0 ) / ( v0 * t_all )', '( x - x0 ) / ( v0 * t )', 'cmath.cos( alpha )']

######

# функция берет массив инструкций и словарь переменных
# и ищет инстукцию в которой все переменные известны ```
Example 69
```def minimum_curvature_calc(
distance_between_stations: float,
azimuth_survey_station_1: float,
dip_survey_station_1: float,
azimuth_survey_station_2: float,
dip_survey_station_2: float,
convergence: float = 0) -> Tuple[float, float, float, float]:
'''
Using the length between two surveys, an initial azimuth, an initial dip,
a secondary azimuth, a secondary dip and an optional grid convergence argument
, return the tvd difference, northing difference, easting difference and
dogleg severity in (°/30m).
See https://www.onepetro.org/journal-paper/SPE-3362-PA for detail on calculations.
'''

# Set variables for the inclination and azimuth of the first two survey points

# Set variables for the inclination and azimuth of the second two survey points

# Calculate the DogLeg
dogleg = np.arccos(
np.cos(inclination_2 - inclination_1) - np.sin(inclination_1) *
np.sin(inclination_2) * (1 - np.cos(azimuth_2 - azimuth_1)))

# Warn if length is zero, prevent divison by zero.
if distance_between_stations == 0:
print('''ERROR: Cannot perform calculation on zero length between
survey stations. Return values set to 'None' ''')
return None, None, None, None

# Calculate the dogleg severity in (°/30m)
dogleg_severity = math.degrees(dogleg * (30 / distance_between_stations))

# Calculate ratio factor.  If there's no dogleg, calculate with balanced tangential instead of minimum curvature.
if dogleg != 0.0:
ratio_factor = 2 * np.tan(dogleg / 2) / dogleg  # minimum curvature
else:
ratio_factor = 1  # balanced tangential

# Calculation for TVD depth difference between first and second survey stations
tvd_difference = (0.5 * distance_between_stations * (
np.cos(inclination_1) + np.cos(inclination_2)) * ratio_factor)

# Calculation for northing difference between first and second survey stations
northing_difference = 0.5 * distance_between_stations * (
np.sin(inclination_1) * np.cos(azimuth_1) +
np.sin(inclination_2) * np.cos(azimuth_2)) * ratio_factor

# Calculation for easting difference between first and second survey stations
easting_difference = 0.5 * distance_between_stations * (
np.sin(inclination_1) * np.sin(azimuth_1) +
np.sin(inclination_2) * np.sin(azimuth_2)) * ratio_factor

return tvd_difference, northing_difference, easting_difference, dogleg_severity ```
Example 70
```def haversine_distance(origin, destination):
"""
Calculate the Haversine distance.

Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)

Returns
-------
distance_in_km : float

Examples
--------
>>> munich = (48.1372, 11.5756)
>>> berlin = (52.5186, 13.4083)
>>> round(haversine_distance(munich, berlin), 1)
504.2

>>> new_york_city = (40.712777777778, -74.005833333333)  # NYC
>>> round(haversine_distance(berlin, new_york_city), 1)
6385.3
"""
lat1, lon1 = origin
lat2, lon2 = destination
if not (-90.0 <= lat1 <= 90):
raise ValueError("lat1={:2.2f}, but must be in [-90,+90]".format(lat1))
if not (-90.0 <= lat2 <= 90):
raise ValueError("lat2={:2.2f}, but must be in [-90,+90]".format(lat2))
if not (-180.0 <= lon1 <= 180):
raise ValueError("lon1={:2.2f}, but must be in [-180,+180]"
.format(lat1))
if not (-180.0 <= lon2 <= 180):
raise ValueError("lon1={:2.2f}, but must be in [-180,+180]"
.format(lat1))

a = (math_stl.sin(dlat / 2) * math_stl.sin(dlat / 2)
* math_stl.sin(dlon / 2) * math_stl.sin(dlon / 2))
c = 2 * math_stl.atan2(math_stl.sqrt(a), math_stl.sqrt(1 - a))

return d ```
Example 71
```def step(self, dt):

max_throttle_speed = 1410
max_boost_speed = 2300

# get the local coordinates of where the ball is, relative to the car
# delta_local[0]: how far in front
# delta_local[1]: how far to the left
# delta_local[2]: how far above
delta_local = dot(self.target_pos - self.car.pos, self.car.theta)

# angle between car's forward direction and target position
phi = math.atan2(delta_local[1], delta_local[0])

# If the target is more than 10 degrees right from the centre, steer left
self.controls.steer = -1
# If the target is more than 10 degrees left from the centre, steer right
self.controls.steer = 1
else:
# If the target is less than 10 degrees from the centre, steer straight

if abs(phi) < math.radians(3) and not self.car.supersonic:
self.controls.boost = True
else:
self.controls.boost = False

if abs(phi) > 1.75:
self.controls.handbrake = 1
else:
self.controls.handbrake = 0

# forward velocity
vf = dot(self.car.vel, self.car.forward())

if vf < self.target_speed:
self.controls.throttle = 1.0
if self.target_speed > max_throttle_speed:
self.controls.boost = 1
else:
self.controls.boost = 0
else:
self.controls.throttle = -1
self.controls.boost = 0
if norm(delta_local) < 20:
self.controls.throttle = -norm(delta_local) / 20
if norm(delta_local) < 10:
self.controls.throttle = -norm(delta_local) / 10

if self.car.supersonic:
self.controls.boost = False

if norm(self.car.pos - self.target_pos) < 100:
self.finished = True ```
Example 72
```def get_controls(self):
if self.step == "Steer" or self.step == "Dodge2":
self.step = "Catching"
if self.step == "Catching":
target = get_bounce(self)
if target is None:
self.step = "Defending"
else:
self.catching.target_pos = target[0]
self.catching.target_speed = (distance_2d(self.info.my_car.pos, target[0]) + 50) / target[1]
self.catching.step(self.FPS)
self.controls = self.catching.controls
ball = self.info.ball
car = self.info.my_car
if distance_2d(ball.pos, car.pos) < 150 and 65 < abs(ball.pos[2] - car.pos[2]) < 127:
self.step = "Dribbling"
self.dribble = Dribbling(self.info.my_car, self.info.ball, self.info.their_goal)
if self.defending:
self.step = "Defending"
if not self.info.my_car.on_ground:
self.step = "Recovery"
ball = self.info.ball
if abs(ball.vel[2]) < 100 and sign(self.team) * ball.vel[1] < 0 and sign(self.team) * ball.pos[1] < 0:
self.step = "Shooting"
elif self.step == "Dribbling":
self.dribble.step(self.FPS)
self.controls = self.dribble.controls
ball = self.info.ball
car = self.info.my_car
bot_to_opponent = self.info.opponents[0].pos - self.info.my_car.pos
local_bot_to_target = dot(bot_to_opponent, self.info.my_car.theta)
angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
opponent_is_near = norm(vec2(bot_to_opponent)) < 2000
if not (distance_2d(ball.pos, car.pos) < 150 and 65 < abs(ball.pos[2] - car.pos[2]) < 127):
self.step = "Catching"
if self.defending:
self.step = "Defending"
if opponent_is_near and opponent_is_in_the_way:
self.step = "Dodge"
self.dodge = AirDodge(self.info.my_car, 0.25, self.info.their_goal.center)
if not self.info.my_car.on_ground:
self.step = "Recovery"
elif self.step == "Defending":
defending(self)
elif self.step == "Dodge":
self.dodge.step(self.FPS)
self.controls = self.dodge.controls
self.controls.boost = 0
if self.dodge.finished and self.info.my_car.on_ground:
self.step = "Catching"
elif self.step == "Recovery":
self.recovery.step(self.FPS)
self.controls = self.recovery.controls
if self.info.my_car.on_ground:
self.step = "Catching"
elif self.step == "Shooting":
shooting(self) ```
Example 73
```def rounded_corner(start, apex, end, rad):

# Translate all points with apex at origin
start = (start[0] - apex[0], start[1] - apex[1])
end = (end[0] - apex[0], end[1] - apex[1])

# Get angles of each line segment
enter_a = math.atan2(start[1], start[0]) % math.radians(360)
leave_a = math.atan2(end[1], end[0]) % math.radians(360)

#print('## enter, leave', math.degrees(enter_a), math.degrees(leave_a))

# Determine bisector angle
ea2 = abs(enter_a - leave_a)
bisect = ea2 / 2.0

return (apex, apex, apex, -1)

# Check that q is no more than half the shortest leg
enter_leg = math.sqrt(start[0]**2 + start[1]**2)
leave_leg = math.sqrt(end[0]**2 + end[1]**2)
short_leg = min(enter_leg, leave_leg)
if q > short_leg / 2:
q = short_leg / 2

# Center of circle

# Determine which direction is the smallest angle to the leave point
# Determine direction of arc
# Rotate whole system so that enter_a is on x-axis
delta = (leave_a - enter_a) % math.radians(360)
if delta < math.radians(180): # CW
bisect = enter_a + bisect
else: # CCW
bisect = enter_a - bisect

#print('## Bisect2', math.degrees(bisect))
center = (h * math.cos(bisect) + apex[0], h * math.sin(bisect) + apex[1])

# Find start and end point of arcs
start_p = (q * math.cos(enter_a) + apex[0], q * math.sin(enter_a) + apex[1])
end_p = (q * math.cos(leave_a) + apex[0], q * math.sin(leave_a) + apex[1])

return (center, start_p, end_p, rad) ```
Example 74
```def bbox(self):
lw = self.param('weight')
if lw is None:
lw = 0

lw /= 2.0

# Calculate bounding box for arc segment
x0, y0, x1, y1 = self.points
xc = (x0 + x1) / 2.0
yc = (y0 + y1) / 2.0
hw = abs(x1 - x0) / 2.0
hh = abs(y1 - y0) / 2.0

start = self.options['start'] % 360
extent = self.options['extent']
stop = (start + extent) % 360

if extent < 0:
start, stop = stop, start  # Swap points so we can rotate CCW

if stop < start:
stop += 360 # Make stop greater than start

angles = [start, stop]

# Find the extrema of the circle included in the arc
ortho = (start // 90) * 90 + 90
while ortho < stop:
angles.append(ortho)
ortho += 90 # Rotate CCW

# Convert all extrema points to cartesian
points = [(hw * math.cos(math.radians(a)), -hh * math.sin(math.radians(a))) for a in angles]

points = list(zip(*points))
x0 = min(points[0]) + xc - lw
y0 = min(points[1]) + yc - lw
x1 = max(points[0]) + xc + lw
y1 = max(points[1]) + yc + lw

if 'weight' in self.options:
w = self.options['weight'] / 2.0
# FIXME: This doesn't properly compensate for the true extrema of the stroked outline
x0 -= w
x1 += w
y0 -= w
y1 += w

#print('@@ ARC BB:', (bx0,by0,bx1,by1), hw, hh, angles, start, extent)
return (x0,y0,x1,y1) ```
Example 75
 Project: captivox   Author: expectocode   File: captivox.py    GNU General Public License v3.0 4 votes
```def paintEvent(self, *_):
"""
This is called on self.update() and on resize - makes resizes a bit ugly.
This method draws every frame and forms the core of the program.
"""
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
painter.translate(self.width() / 2, self.height() / 2)  # Make (0,0) centre

if self.draw_axes:
painter.setPen(QPen(QColor(0, 0, 0, 64), 1))
# Line(x1,y2,x2,y2)
painter.drawLine(QLineF(0, self.height() / 2, 0, -self.height() / 2))
painter.drawLine(QLineF(self.width() / 2, 0, -self.width() / 2, 0))

colours = interpolate_hsv(self.col1, self.col2, self.num_dots - 2)
# self.num_dots slider minimum is 2, so middle num minimum 0 which is ok
last = None

for cur_dot_num in range(self.num_dots):
if self.join_end_dots:
frame_no = self.frame_no + cur_dot_num*(180/(self.num_dots-1))/self.speedmult
else:
frame_no = self.frame_no + cur_dot_num*(180/self.num_dots)/self.speedmult
# green = (240/self.num_dots) * (self.num_dots - cur_dot_num)
# blue = (240/self.num_dots) * cur_dot_num
# colour = QColor(0, green, blue)
colour = next(colours).toRgb()
painter.setPen(QPen(colour))
painter.setBrush(QBrush(colour))
# progress = (cos(radians(SPEED_MULT * frame_no)) + 1)/2 * 180
progress = abs((frame_no * self.speedmult) % (2*self.halfmax)-self.halfmax)
# Progress oscillates every 360/speed_mult frames
# Progress dictates the range of values of x later fed into cos(x)
# frame_no multiplier dictates frequency of oscillations
# Progress ranges between 0 and 180 which later gives us a
# cos(progress) ranging between # 1 and -1, which combines with
# sometimes-neg wid * hei to give a full range
# print(self.frame_no,progress)
height = sin(angle_off) * (self.height() - 100)
width = cos(angle_off) * (self.width() - 100)
# (0,0) is the centre
x = cos(radians(self.x_multiplier * progress)) * width / 2
y = cos(radians(self.y_multiplier * progress)) * height / 2

if self.draw_lines:
painter.setPen(QPen(colour, self.dot_size))
painter.drawLine(QPointF(x, y), QPointF(0,0))
if self.connect_lines:
if last:
painter.drawLine(QPointF(x, y), last)
last = QPointF(x,y)
else:
painter.drawEllipse(QPointF(x, y), self.dot_size, self.dot_size) ```
Example 76
```def _turn_decision(self, index, route, threshold=math.radians(5)):
"""
This method returns the turn decision (RoadOption) for pair of edges
around current index of route list
"""

decision = None
previous_node = route[index-1]
current_node = route[index]
next_node = route[index+1]
next_edge = self._graph.edges[current_node, next_node]
if index > 0:
current_edge = self._graph.edges[previous_node, current_node]
calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
not current_edge['intersection'] and \
next_edge['intersection']
if calculate_turn:
cv, nv = current_edge['exit_vector'], next_edge['net_vector']
cross_list = []
for neighbor in self._graph.successors(current_node):
select_edge = self._graph.edges[current_node, neighbor]
if neighbor != route[index+1]:
sv = select_edge['net_vector']
cross_list.append(np.cross(cv, sv)[2])
next_cross = np.cross(cv, nv)[2]
deviation = math.acos(np.dot(cv, nv) /\
(np.linalg.norm(cv)*np.linalg.norm(nv)))
if not cross_list:
cross_list.append(0)
if deviation < threshold:
elif cross_list and next_cross < min(cross_list):
elif cross_list and next_cross > max(cross_list):
else:
decision = next_edge['type']
else:
decision = next_edge['type']

return decision ```
Example 77
```def _turn_decision(self, index, route, threshold=math.radians(5)):
"""
This method returns the turn decision (RoadOption) for pair of edges
around current index of route list
"""

decision = None
previous_node = route[index-1]
current_node = route[index]
next_node = route[index+1]
next_edge = self._graph.edges[current_node, next_node]
if index > 0:
current_edge = self._graph.edges[previous_node, current_node]
calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
not current_edge['intersection'] and \
next_edge['intersection']
if calculate_turn:
cv, nv = current_edge['exit_vector'], next_edge['net_vector']
cross_list = []
for neighbor in self._graph.successors(current_node):
select_edge = self._graph.edges[current_node, neighbor]
if neighbor != route[index+1]:
sv = select_edge['net_vector']
cross_list.append(np.cross(cv, sv)[2])
next_cross = np.cross(cv, nv)[2]
deviation = math.acos(np.dot(cv, nv) /\
(np.linalg.norm(cv)*np.linalg.norm(nv)))
if not cross_list:
cross_list.append(0)
if deviation < threshold:
elif cross_list and next_cross < min(cross_list):
elif cross_list and next_cross > max(cross_list):
else:
decision = next_edge['type']
else:
decision = next_edge['type']

return decision ```
Example 78
```def _turn_decision(self, index, route, threshold=math.radians(5)):
"""
This method returns the turn decision (RoadOption) for pair of edges
around current index of route list
"""

decision = None
previous_node = route[index-1]
current_node = route[index]
next_node = route[index+1]
next_edge = self._graph.edges[current_node, next_node]
if index > 0:
current_edge = self._graph.edges[previous_node, current_node]
calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
not current_edge['intersection'] and \
next_edge['intersection']
if calculate_turn:
cv, nv = current_edge['exit_vector'], next_edge['net_vector']
cross_list = []
for neighbor in self._graph.successors(current_node):
select_edge = self._graph.edges[current_node, neighbor]
if neighbor != route[index+1]:
sv = select_edge['net_vector']
cross_list.append(np.cross(cv, sv)[2])
next_cross = np.cross(cv, nv)[2]
deviation = math.acos(np.dot(cv, nv) /\
(np.linalg.norm(cv)*np.linalg.norm(nv)))
if not cross_list:
cross_list.append(0)
if deviation < threshold:
elif cross_list and next_cross < min(cross_list):
elif cross_list and next_cross > max(cross_list):
else:
decision = next_edge['type']
else:
decision = next_edge['type']

return decision ```
Example 79
```def _turn_decision(self, index, route, threshold=math.radians(5)):
"""
This method returns the turn decision (RoadOption) for pair of edges
around current index of route list
"""

decision = None
previous_node = route[index-1]
current_node = route[index]
next_node = route[index+1]
next_edge = self._graph.edges[current_node, next_node]
if index > 0:
current_edge = self._graph.edges[previous_node, current_node]
calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
not current_edge['intersection'] and \
next_edge['intersection']
if calculate_turn:
cv, nv = current_edge['exit_vector'], next_edge['net_vector']
cross_list = []
for neighbor in self._graph.successors(current_node):
select_edge = self._graph.edges[current_node, neighbor]
if neighbor != route[index+1]:
sv = select_edge['net_vector']
cross_list.append(np.cross(cv, sv)[2])
next_cross = np.cross(cv, nv)[2]
deviation = math.acos(np.dot(cv, nv) /\
(np.linalg.norm(cv)*np.linalg.norm(nv)))
if not cross_list:
cross_list.append(0)
if deviation < threshold:
elif cross_list and next_cross < min(cross_list):
elif cross_list and next_cross > max(cross_list):
else:
decision = next_edge['type']
else:
decision = next_edge['type']

return decision ```
Example 80
```def generate_interior_view(self, u=0.5, v=0.5, z=0.5, angle=0,
view_up_vector=(0, 0, 1), view_type=0, view_h_size=60,
view_v_size=60, x_resolution=64, y_resolution=64,
view_shift=0, view_lift=0):
u"""Generate an inetrior view.

Args:
u: u value between 0 and 1.
v: v value between 0 and 1.
z: z value between 0 and 1.
angle: Rotation angle from back wall.
view_up_vector: Set the view up (-vu) vector (vertical direction) to
(x, y, z).cDefault: (0, 0, 1)
view_type: Set view type (-vt) to one of the choices below.
0: Perspective (v)
1: Hemispherical fisheye (h)
2: Parallel (l)
3: Cylindrical panorma (c)
4: Angular fisheye (a)
5: Planisphere [stereographic] projection (s)
For more detailed description about view types check rpict manual
view_h_size: Set the view horizontal size (-vs). For a perspective
projection (including fisheye views), val is the horizontal field
of view (in degrees). For a parallel projection, val is the view
width in world coordinates.
view_v_size: Set the view vertical size (-vv). For a perspective
projection (including fisheye views), val is the horizontal field
of view (in degrees). For a parallel projection, val is the view
width in world coordinates.
x_resolution: Set the maximum x resolution (-x) to an integer.
y_resolution: Set the maximum y resolution (-y) to an integer.
view_shift: Set the view shift (-vs). This is the amount the actual
image will be shifted to the right of the specified view. This
option is useful for generating skewed perspectives or rendering
an image a piece at a time. A value of 1 means that the rendered
image starts just to the right of the normal view. A value of −1
would be to the left. Larger or fractional values are permitted
as well.
view_lift: Set the view lift (-vl) to a value. This is the amount the
actual image will be lifted up from the specified view.
"""
v = View(self.get_location(u, v, z),