本文整理汇总了Python中abs函数的典型用法代码示例。如果您正苦于以下问题:Python abs函数的具体用法?Python abs怎么用?Python abs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abs函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: getDist
def getDist(self):
mainCharX = self.mainChar.getPos().x
mainCharY = self.mainChar.getPos().y
pandaX = self.pandaActor2.getPos().x
pandaY = self.pandaActor2.getPos().y
dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2)
return dist
开发者ID:genusgant,项目名称:CS594-ThrottleThunder-GameClient,代码行数:7,代码来源:RRMain.py
示例2: get_ruler_distances
def get_ruler_distances(self, x1, y1, x2, y2):
mode = self.t_drawparams.get('units', 'arcmin')
try:
image = self.fitsimage.get_image()
if mode == 'arcmin':
# Calculate RA and DEC for the three points
# origination point
ra_org, dec_org = image.pixtoradec(x1, y1)
# destination point
ra_dst, dec_dst = image.pixtoradec(x2, y2)
# "heel" point making a right triangle
ra_heel, dec_heel = image.pixtoradec(x2, y1)
text_h = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_dst, dec_dst)
text_x = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_heel, dec_heel)
text_y = image.get_starsep_RaDecDeg(ra_heel, dec_heel, ra_dst, dec_dst)
else:
dx = abs(x2 - x1)
dy = abs(y2 - y1)
dh = math.sqrt(dx**2 + dy**2)
text_x = str(dx)
text_y = str(dy)
text_h = ("%.3f" % dh)
except Exception, e:
text_h = 'BAD WCS'
text_x = 'BAD WCS'
text_y = 'BAD WCS'
开发者ID:PaulPrice,项目名称:ginga,代码行数:30,代码来源:FitsImageCanvas.py
示例3: test_scal
def test_scal(vector_array):
v = vector_array
for ind in valid_inds(v):
if v.len_ind(ind) != v.len_ind_unique(ind):
with pytest.raises(Exception):
c = v.copy()
c[ind].scal(1.)
continue
ind_complement_ = ind_complement(v, ind)
c = v.copy()
c[ind].scal(1.)
assert len(c) == len(v)
assert np.all(almost_equal(c, v))
c = v.copy()
c[ind].scal(0.)
assert np.all(almost_equal(c[ind], v.zeros(v.len_ind(ind))))
assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))
for x in (1., 1.4, np.random.random(v.len_ind(ind))):
c = v.copy()
c[ind].scal(x)
assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))
assert np.allclose(c[ind].sup_norm(), v[ind].sup_norm() * abs(x))
assert np.allclose(c[ind].l2_norm(), v[ind].l2_norm() * abs(x))
if hasattr(v, 'data'):
y = v.data.copy()
if NUMPY_INDEX_QUIRK and len(y) == 0:
pass
else:
if isinstance(x, np.ndarray) and not isinstance(ind, Number):
x = x[:, np.newaxis]
y[ind] *= x
assert np.allclose(c.data, y)
开发者ID:renemilk,项目名称:pyMor,代码行数:34,代码来源:vectorarray.py
示例4: defaultGait
def defaultGait(self,leg):
# just walk forward for now
travelX = 50
travelY = 0
travelRotZ = 0
if abs(travelX)>5 or abs(travelY)>5 or abs(travelRotZ) > 0.05: # are we moving?
if(self.order[leg] == self.step):
# up, middle position
self[leg][0] = 0 # x
self[leg][1] = 0 # y
self[leg][2] = -20 # z
self[leg][3] = 0 # r
elif (self.order[leg]+1 == self.step) or (self.order[leg]-7 == self.step): # gaits in step -1
# leg down!
self[leg][0] = travelX/2
self[leg][1] = travelY/2
self[leg][2] = 0
self[leg][3] = travelRotZ/2
else:
# move body forward
self[leg][0] = self[leg][0] - travelX/6
self[leg][1] = self[leg][1] - travelY/6
self[leg][2] = 0
self[leg][3] = self[leg][3] - travelRotZ/6
return self[leg]
开发者ID:IanMHoffman,项目名称:pypose,代码行数:26,代码来源:lizard3.py
示例5: demoNoiseWS
def demoNoiseWS(iteration=11):
print("reading image...")
image = readImage('../samples/monsters.png', grayScale=True)
adj4 = AdjacencyNdRegular.getAdjacency2d4(image.embedding.size)
image = rescaleGray(image, 0, 1)
convolve = False
noiseInImage = True
sal0 = None
for i in range(iteration):
print("-> Iteration " + str(i))
print("Constructing gradient graph...")
if noiseInImage:
im2 = imageMap(image, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=False)
adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(im2[i] - im2[j]))
else:
adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(image[i] - image[j]))
adjacency = imageMap(adjacency, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=True)
print("Constructing area watershed...")
# wsh = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(adjacency))
# addAttributeArea(wsh)
# wsha= transformBPTtoAttributeHierarchy(wsh,"area")
wsha = constructExactRandomSeedsWatershed(adjacency)
sal = computeSaliencyMapFromAttribute(wsha, adj4)
print("Averaging and Drawing saliency...")
if convolve:
lineGraph = WeightedAdjacency.createLineGraph(sal)
adjLineGraph = WeightedAdjacency.createReflexiveRelation(lineGraph)
meanSal = spatialFilter(sal, adjLineGraph, BasicAccumulator.getMeanAccumulator())
else:
meanSal = sal
saveImage(normalizeToByte(
imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, meanSal), 0, 1), lambda x: x ** 0.33333)),
"Results/Random noise gradient " + str(i) + ".png")
if sal0 is None:
sal0 = meanSal
for j in range(len(sal0)):
sal0[j] = [sal0[j]]
else:
for j in range(len(sal0)):
sal0[j].append(meanSal[j])
print("Merging results...")
for i in range(len(sal0)):
sal0[i] = meanV(sal0[i])
saveImage(normalizeToByte(
imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, sal0), 0, 1), lambda x: x ** 0.33333)),
"Results/Random noise combined gradient.png")
print("Ultra metric opening...")
bpt = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(sal0))
addAttributeArea(bpt)
nbpt = filterBPTbyCriterion(bpt, lambda i: min(bpt.area[bpt.children[i][0]], bpt.area[bpt.children[i][1]]) < 10)
saveImage(drawSaliencyForVisualisation(bpt, image), "Results/Random noise WS bpt.png")
saveImage(drawSaliencyForVisualisation(nbpt, image), "Results/Random noise WS filteredbpt.png")
开发者ID:PerretB,项目名称:HiPy,代码行数:60,代码来源:DemoStochasticWatershed.py
示例6: test
def test():
'''Test the basic workings of `parse_slice`.'''
r1 = range(5)
r2 = range(2, 10)
r3 = range(100, 3, -7)
ranges = [r1, r2, r3]
slices = [slice(3), slice(5), slice(9), slice(1, 4), slice(4, 7),
slice(6, 2), slice(1, 4, 1), slice(1, 5, 3), slice(6, 2, 3),
slice(6, 2, -3), slice(8, 2, -1), slice(2, 5, -2),
slice(None, 5, -2), slice(6, None, -2), slice(8, 4, None),
slice(None, None, -2)]
for slice_ in slices:
(start, stop, step) = parse_slice(slice_)
# Replacing `infinity` with huge number cause Python's lists can't
# handle `infinity`:
if abs(start) == infinity: start = 10**10 * math_tools.get_sign(start)
if abs(stop) == infinity: stop = 10**10 * math_tools.get_sign(stop)
if abs(step) == infinity: step = 10**10 * math_tools.get_sign(step)
#######################################################################
assert [start, stop, step].count(None) == 0
parsed_slice = slice(start, stop, step)
for range_ in ranges:
assert range_[slice_] == range_[parsed_slice]
开发者ID:rfdiazpr,项目名称:python_toolbox,代码行数:29,代码来源:test_parse_slice.py
示例7: mouseInput
def mouseInput():
cont = logic.getCurrentController()
owner = cont.owner
centerX = (render.getWindowWidth()//2)/render.getWindowWidth()
centerY = (render.getWindowHeight()//2)/render.getWindowHeight()
global oldMouseVec
if oldMouseVec == None:
oldMouseVec = mathutils.Vector([0.0,0.0])
logic.mouse.position = (centerX,centerY)
return mathutils.Vector([0,0])
x = logic.mouse.position[0] - centerX
if abs(x) < abs(2/render.getWindowWidth()): x = 0
y = centerY - logic.mouse.position[1]
if abs(y) < abs(2/render.getWindowWidth()): y = 0
newMouseVec = mathutils.Vector([x, y])
global mouseSensitivity
newMouseVec *= mouseSensitivity
# Smooth movement
global mouseSmooth
oldMouseVec = oldMouseVec*mouseSmooth + newMouseVec*(1.0-mouseSmooth)
newMouseVec = oldMouseVec
# Center mouse in game window
logic.mouse.position = (centerX,centerY)
return mathutils.Vector(newMouseVec)
开发者ID:elfnor,项目名称:mazes,代码行数:34,代码来源:Input.py
示例8: getPartInfo
def getPartInfo( part ):
points = part['points']
n = len(points)
area = cx = cy = 0
xmin = ymin = 360
xmax = ymax = -360
pt = points[n-1]; xx = pt[0]; yy = pt[1]
for pt in points:
x = pt[0]; y = pt[1]
# bounds
xmin = min( x, xmin ); ymin = min( y, ymin )
xmax = max( x, xmax ); ymax = max( y, ymax )
# area and centroid
a = xx * y - x * yy
area += a
cx += ( x + xx ) * a
cy += ( y + yy ) * a
# next
xx = x; yy = y
area /= 2
if area:
centroid = [ cx / area / 6, cy / area / 6 ]
else:
centroid = None
part.update({
'area': abs(area),
'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ],
'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ],
'centroid': centroid,
'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ]
})
开发者ID:shangyian,项目名称:greatlakes-call-data,代码行数:31,代码来源:shpUtils.py
示例9: to_polynomial
def to_polynomial(self, c):
"""
Convert clause to :class:`sage.rings.polynomial.pbori.BooleanPolynomial`
INPUT:
- ``c`` - a clause
EXAMPLE::
sage: B.<a,b,c> = BooleanPolynomialRing()
sage: from sage.sat.converters.polybori import CNFEncoder
sage: from sage.sat.solvers.dimacs import DIMACS
sage: fn = tmp_filename()
sage: solver = DIMACS(filename=fn)
sage: e = CNFEncoder(solver, B, max_vars_sparse=2)
sage: _ = e([a*b + a + 1, a*b+ a + c])
sage: e.to_polynomial( (1,-2,3) )
a*b*c + a*b + b*c + b
"""
def product(l):
# order of these multiplications for performance
res = l[0]
for p in l[1:]:
res = res*p
return res
phi = self.phi
product = self.ring(1)
for v in c:
if phi[abs(v)] is None:
raise ValueError("Clause containst an XOR glueing variable.")
product *= phi[abs(v)] + int(v>0)
return product
开发者ID:DrXyzzy,项目名称:sage,代码行数:34,代码来源:polybori.py
示例10: fit_CSU_edges
def fit_CSU_edges(profile):
fitter = fitting.LevMarLSQFitter()
amp1_est = profile[profile == min(profile)][0]
mean1_est = np.argmin(profile)
amp2_est = profile[profile == max(profile)][0]
mean2_est = np.argmax(profile)
g_init1 = models.Gaussian1D(amplitude=amp1_est, mean=mean1_est, stddev=2.)
g_init1.amplitude.max = 0
g_init1.amplitude.min = amp1_est*0.9
g_init1.stddev.max = 3
g_init2 = models.Gaussian1D(amplitude=amp2_est, mean=mean2_est, stddev=2.)
g_init2.amplitude.min = 0
g_init2.amplitude.min = amp2_est*0.9
g_init2.stddev.max = 3
model = g_init1 + g_init2
fit = fitter(model, range(0,profile.shape[0]), profile)
# Check Validity of Fit
if abs(fit.stddev_0.value) <= 3 and abs(fit.stddev_1.value) <= 3\
and fit.amplitude_0.value < -1 and fit.amplitude_1.value > 1\
and fit.mean_0.value > fit.mean_1.value:
x = [fit.mean_0.value, fit.mean_1.value]
x1 = int(np.floor(min(x)-1))
x2 = int(np.ceil(max(x)+1))
else:
x1 = None
x2 = None
return x1, x2
开发者ID:joshwalawender,项目名称:KeckUtilities,代码行数:32,代码来源:slitAlign.py
示例11: karatsuba_multiply
def karatsuba_multiply(x, y):
if x == 0 or y == 0: return 0
sign = 1
if (x < 0 and y > 0) or (x > 0 and y < 0): sign = -1
x = abs(x)
y = abs(y)
max_digit = max(x.bit_length(), y.bit_length())
if max_digit == 1: return 1
half_digit = max_digit // 2
filter_mask = (1 << half_digit) - 1
x_upper_half = x >> half_digit
x_lower_half = x & filter_mask
y_upper_half = y >> half_digit
y_lower_half = y & filter_mask
z_0 = karatsuba_multiply(x_lower_half, y_lower_half)
z_2 = karatsuba_multiply(x_upper_half, y_upper_half)
z_1 = karatsuba_multiply((x_lower_half + x_upper_half), (y_lower_half + y_upper_half)) - z_0 - z_2
abs_res = ((z_2 << half_digit << half_digit) +
(z_1 << half_digit) +
z_0)
if sign == -1: return ~abs_res + 1
else: return abs_res
开发者ID:fikriauliya,项目名称:CS6.006,代码行数:27,代码来源:integer_arithmetic.py
示例12: test_translational_alignment
def test_translational_alignment(self):
""" Test the translational alignment in 2D routine """
random.seed()
name=self.get_input_file_name("1z5s-projection-2.spi")
srw = IMP.em2d.SpiderImageReaderWriter()
image=IMP.em2d.Image()
image.read(name,srw)
translated=IMP.em2d.Image()
# random translation
trans=IMP.algebra.Vector2D(random.random()*10,random.random()*10)
transformation = IMP.algebra.Transformation2D(trans)
IMP.em2d.get_transformed(image.get_data(),translated.get_data(),
transformation)
fn_translated = self.get_input_file_name("translated.spi")
# translated.write(fn_translated,srw)
result=IMP.em2d.get_translational_alignment(
image.get_data(),translated.get_data(),True)
fn_aligned = self.get_input_file_name("trans_aligned.spi")
# translated.write(fn_aligned,srw)
# -1 to get the translation applied to reference.
# Result contains the translation required for align the second matrix
determined_trans= (-1)*result[0].get_translation()
# Tolerate 1 pixel error
self.assertAlmostEqual(abs(determined_trans[0]-trans[0]),0, delta=1,
msg="1st coordinate is incorrect: Applied %f Determined %f" \
% (trans[0], determined_trans[0]))
self.assertAlmostEqual(abs(determined_trans[1]-trans[1]),0, delta=1,
msg="2nd coordinate is incorrect: Applied %f Determined %f" \
% (trans[1], determined_trans[1]))
开发者ID:andreyto,项目名称:imp-fork-proddl,代码行数:29,代码来源:test_align2d.py
示例13: test_rotational_alignment
def test_rotational_alignment(self):
""" Test the rotational alignment in 2D routine (new) """
random.seed()
name=self.get_input_file_name("1z5s-projection-2.spi")
srw = IMP.em2d.SpiderImageReaderWriter()
image=IMP.em2d.Image()
image.read(name,srw)
rotated=IMP.em2d.Image()
# random rotation
angle=random.random()*2*pi
rot=IMP.algebra.Rotation2D(angle)
transformation = IMP.algebra.Transformation2D(rot)
IMP.em2d.get_transformed(image.get_data(),rotated.get_data(),
transformation)
fn_rotated = self.get_input_file_name("rotated.spi")
# rotated.write(fn_rotated,srw)
result=IMP.em2d.get_rotational_alignment(
image.get_data(),rotated.get_data(),True)
fn_aligned = self.get_input_file_name("rot_aligned.spi")
# rotated.write(fn_aligned,srw)
determined_angle=result[0].get_rotation().get_angle()
# approximately 6 degrees tolerance, 0.1 rad.
x = angle+determined_angle
modulo = (abs(x % (2*pi)) < 0.1) or (abs(x % (2*pi)-2*pi) < 0.1)
self.assertEqual(modulo,True,msg="Angles applied %f and "
"determined %f are different, difference %f" % (angle
,determined_angle,x))
开发者ID:andreyto,项目名称:imp-fork-proddl,代码行数:28,代码来源:test_align2d.py
示例14: G
def G(x, k):
result = []
X = np.fft.fft(x, k)
for i in range(len(X)):
result.append(1/len(X) * (abs(X[i]) * abs(X[i])))
return result
开发者ID:elvslv,项目名称:PatternRecognition,代码行数:7,代码来源:Labs4.py
示例15: has_split_dividents
def has_split_dividents(mdata, from_date, to_date):
''' Verifies if market data interval has splits, dividends '''
from_diff = abs(mdata['close'][from_date] - mdata['adj_close'][from_date])
to_diff = abs(mdata['close'][to_date] - mdata['adj_close'][to_date])
if approx_equal(from_diff, to_diff, 0.0001):
return False
return not percent_equal(from_diff, to_diff, mdata['close'][to_date], 0.8)
开发者ID:dp0h,项目名称:candlesticks,代码行数:7,代码来源:mktdata.py
示例16: _str
def _str(self, i, x):
"""Handles string formatting of cell data
i - index of the cell datatype in self._dtype
x - cell data to format
"""
try:
f = float(x)
except:
return str(x)
n = self._precision
dtype = self._dtype[i]
if dtype == 'i':
return str(int(round(f)))
elif dtype == 'f':
return '%.*f' % (n, f)
elif dtype == 'e':
return '%.*e' % (n, f)
elif dtype == 't':
return str(x)
else:
if f - round(f) == 0:
if abs(f) > 1e8:
return '%.*e' % (n, f)
else:
return str(int(round(f)))
else:
if abs(f) > 1e8:
return '%.*e' % (n, f)
else:
return '%.*f' % (n, f)
开发者ID:AdrianBajdiuk,项目名称:PowerGridResillience,代码行数:33,代码来源:texttable.py
示例17: test_testUfuncs1
def test_testUfuncs1 (self):
"Test various functions such as sin, cos."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.assertTrue (eq(numpy.cos(x), cos(xm)))
self.assertTrue (eq(numpy.cosh(x), cosh(xm)))
self.assertTrue (eq(numpy.sin(x), sin(xm)))
self.assertTrue (eq(numpy.sinh(x), sinh(xm)))
self.assertTrue (eq(numpy.tan(x), tan(xm)))
self.assertTrue (eq(numpy.tanh(x), tanh(xm)))
olderr = numpy.seterr(divide='ignore', invalid='ignore')
try:
self.assertTrue (eq(numpy.sqrt(abs(x)), sqrt(xm)))
self.assertTrue (eq(numpy.log(abs(x)), log(xm)))
self.assertTrue (eq(numpy.log10(abs(x)), log10(xm)))
finally:
numpy.seterr(**olderr)
self.assertTrue (eq(numpy.exp(x), exp(xm)))
self.assertTrue (eq(numpy.arcsin(z), arcsin(zm)))
self.assertTrue (eq(numpy.arccos(z), arccos(zm)))
self.assertTrue (eq(numpy.arctan(z), arctan(zm)))
self.assertTrue (eq(numpy.arctan2(x, y), arctan2(xm, ym)))
self.assertTrue (eq(numpy.absolute(x), absolute(xm)))
self.assertTrue (eq(numpy.equal(x, y), equal(xm, ym)))
self.assertTrue (eq(numpy.not_equal(x, y), not_equal(xm, ym)))
self.assertTrue (eq(numpy.less(x, y), less(xm, ym)))
self.assertTrue (eq(numpy.greater(x, y), greater(xm, ym)))
self.assertTrue (eq(numpy.less_equal(x, y), less_equal(xm, ym)))
self.assertTrue (eq(numpy.greater_equal(x, y), greater_equal(xm, ym)))
self.assertTrue (eq(numpy.conjugate(x), conjugate(xm)))
self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, ym))))
self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((x, y))))
self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, y))))
self.assertTrue (eq(numpy.concatenate((x, y, x)), concatenate((x, ym, x))))
开发者ID:Sastria,项目名称:Sastria-Project,代码行数:33,代码来源:test_old_ma.py
示例18: genData
def genData():
c1 = 0.5
r1 = 0.4
r2 = 0.3
Ndat = 1000
# generate enough data to filter
N = 20* Ndat
X = array(random_sample(N))
Y = array(random_sample(N))
X1 = X[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1]
Y1 = Y[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1]
X2 = X1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2]
Y2 = Y1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2]
X3 = X2[ abs(X2-Y2)>0.05 ]
Y3 = Y2[ abs(X2-Y2)>0.05 ]
#X3 = X2[ X2-Y2>0.15 ]
#Y3 = Y2[ X2-Y2>0.15]
X4=zeros( Ndat, dtype=float32)
Y4=zeros( Ndat, dtype=float32)
for i in xrange(Ndat):
if (X3[i]-Y3[i]) >0.05:
X4[i] = X3[i] + 0.08
Y4[i] = Y3[i] + 0.18
else:
X4[i] = X3[i] - 0.08
Y4[i] = Y3[i] - 0.18
print "X", size(X3[0:Ndat]), "Y", size(Y3)
return vstack((X4[0:Ndat],Y4[0:Ndat])), vstack((array(random_sample(Ndat)),array(random_sample(Ndat))))
开发者ID:Paseam,项目名称:BackgroundSubtraction_by_GBRBM,代码行数:28,代码来源:testrealval.py
示例19: secant
def secant(func, x0, x1, eps, max_iter=50):
# Evaluate the function at the interval
f_l = func(x0)
f_x = func(x1)
# Set the initial x
if abs(f_l) < abs(f_x):
x = x0
xl = x1
f_l, f_x = f_x, f_l
else:
xl = x0
x = x1
# Iterate
for i in range(max_iter):
dx = (xl - x) * f_x / (f_x - f_l)
xl = x
f_l = f_x
x += dx
f_x = func(x)
# If we've reached the root, return
if abs(dx) < eps or f_x == 0.0:
return x
# Raise an exception if we reach maximum iterations
raise RuntimeError('Maximum iterations reached')
开发者ID:dials,项目名称:dials_scratch,代码行数:29,代码来源:find_roots.py
示例20: get_balance
def get_balance(self):
if not getlist(self.doclist,'entries'):
msgprint("Please enter atleast 1 entry in 'GL Entries' table")
else:
flag, self.doc.total_debit, self.doc.total_credit = 0, 0, 0
diff = flt(self.doc.difference, 2)
# If any row without amount, set the diff on that row
for d in getlist(self.doclist,'entries'):
if not d.credit and not d.debit and diff != 0:
if diff>0:
d.credit = diff
elif diff<0:
d.debit = diff
flag = 1
# Set the diff in a new row
if flag == 0 and diff != 0:
jd = addchild(self.doc, 'entries', 'Journal Voucher Detail', self.doclist)
if diff>0:
jd.credit = abs(diff)
elif diff<0:
jd.debit = abs(diff)
# Set the total debit, total credit and difference
for d in getlist(self.doclist,'entries'):
self.doc.total_debit += flt(d.debit, 2)
self.doc.total_credit += flt(d.credit, 2)
self.doc.difference = flt(self.doc.total_debit, 2) - flt(self.doc.total_credit, 2)
开发者ID:cocoy,项目名称:erpnext,代码行数:30,代码来源:journal_voucher.py
注:本文中的abs函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论