def GetFh(self,code):#??????
try:
ret = urllib.urlopen("http://money.finance.sina.com.cn/corp/go.php/vISSUE_ShareBonus/stockid/" + code + ".phtml")
soup = BeautifulSoup(Tools().smartCode(ret.read()), "html.parser")
dict = {}
for x in soup.find_all('tbody'):
for e in str(x).split('_blank'):
if "type=1" in e:
td = re.findall(r'<td>(.+?)</td>', e)
dict.update({td[0]: {u"????".encode('gbk', 'ignore').decode('gbk'): td[0],
u"??".encode('gbk', 'ignore').decode('gbk'): td[1],
u"??".encode('gbk', 'ignore').decode('gbk'): td[2],
u"??".encode('gbk', 'ignore').decode('gbk'): td[3],
u"??".encode('gbk', 'ignore').decode('gbk'): td[4],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[5],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[6],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[7]
}})
return pandas.DataFrame.from_dict(dict, orient="index")
except:
return None
python类e()的实例源码
def GetPg(self,code):#??????
try:
ret = urllib.urlopen("http://money.finance.sina.com.cn/corp/go.php/vISSUE_ShareBonus/stockid/" + code + ".phtml")
soup = BeautifulSoup(Tools().smartCode(ret.read()), "html.parser")
dict = {}
for x in soup.find_all('tbody'):
for e in str(x).split('_blank'):
if "type=2" in e:
td = re.findall(r'<td>(.+?)</td>', e)
dict.update({td[0]: {u"????".encode('gbk', 'ignore').decode('gbk'): td[0],
u"????".encode('gbk', 'ignore').decode('gbk'): td[1],
u"????".encode('gbk', 'ignore').decode('gbk'): td[2],
u"????".encode('gbk', 'ignore').decode('gbk'): td[3],
u"???".encode('gbk', 'ignore').decode('gbk'): td[4],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[5],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[6],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[7],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[8],
}})
return pandas.DataFrame.from_dict(dict, orient="index")
except:
return None
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def evaluateStack( s ):
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
raise Exception("invalid identifier '%s'" % op)
else:
return float( op )
def evaluateStack( s ):
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
if op in variables:
return variables[op]
raise Exception("invalid identifier '%s'" % op)
else:
return float( op )
def test_Timing(self):
e = vu.ElapsedTime()
with vu.Timing(elapsed=e):
time.sleep(0.2)
self.assertAlmostEqual(e.value, 0.2, places=1)
# test some other modes of invocation
with vu.Timing() as t:
x = 1
loglvl = 10
class FakeLog:
def __init__(self, testclass):
self.tc = testclass
def log(self, lvl, msg):
self.tc.assertEqual(lvl, loglvl)
with vu.Timing(log=FakeLog(self), level=loglvl):
x = 1
def test_get_mongo(self):
"Test get_mongo() function"
import math
with self.assertRaises(ValueError):
for rec in [1, 2, 3], 'foo':
vv.mongo_get(rec, 'a')
for rec in {}, None, '':
self.assertEqual(vv.mongo_get(rec, 'a', 'dee-fault'), 'dee-fault')
rec = {'a': {
'apple': {
'red': 'delicious',
'green': 'grannysmith',
'blue': 'venutian'},
'anumber': 2, },
'e': math.e, }
default = 'mittens'
# these should be found
for key, expected in (('a.apple.green', 'grannysmith'), ('a.anumber', 2), ('e', math.e)):
self.assertEqual(vv.mongo_get(rec, key, default), expected)
# these should not
for key in 'a.apple.orange', 'x', '', 'z.zebra.', '.':
self.assertEqual(vv.mongo_get(rec, key, default), default)
def get_price_for_trade(prediction, trade):
"""Returns the price of a trade for a prediction."""
if trade.contract == 'CONTRACT_ONE':
old_quantity = prediction.contract_one
old_quantity_other = prediction.contract_two
else:
old_quantity = prediction.contract_two
old_quantity_other = prediction.contract_one
if trade.direction == 'BUY':
new_quantity = old_quantity + trade.quantity
else:
new_quantity = old_quantity - trade.quantity
price = (prediction.liquidity * math.log(
math.pow(math.e, (new_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity)))) - (
prediction.liquidity * math.log(
math.pow(math.e, (old_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity))))
return price
def getForegroundMask(self):
'''
@return: A mask image indicating which pixels are considered foreground.
Depending on whether soft-thresholding is used, this may be a binary image
with values of [0 or 255], or image of weights [0.0-255.0], which will
have to be divided by 255 to get weights [0.0-1.0].
@note: One may wish to perform additional morphological operations
on the foreground mask prior to use.
'''
diff = self._computeBGDiff()
if self._softThreshold:
mask = 1 - (math.e)**(-(1.0*diff)/self._threshold) #element-wise exp weighting
#mask = (diff > self._threshold)
else:
mask = (sp.absolute(diff) > self._threshold)
#mu = sp.mean(diff)
#sigma = sp.std(diff)
#mask = sp.absolute((diff-mu)/sigma) > self._threshold
return pv.Image(mask*255.0)
def _PrintResiduals(self, slope, intercept):
independent_dict = None
dependent_dict = None
if len(self._county_idata) > 0 and len(self._county_ddata) > 0:
independent_dict = self._county_idata
dependent_dict = self._county_ddata
else:
independent_dict = self._independent_data
dependent_dict = self._dependent_data
for precinct,logvotes in sorted(independent_dict.iteritems()):
if precinct not in dependent_dict:
continue
actual = int(math.e**dependent_dict[precinct])
predict_exponent = intercept + slope*logvotes
predict = int(math.e**predict_exponent)
diff = actual - predict
pct_error = (1.0 * diff) / predict
print('%-38s\t%7d\t%7d\t%7d\t%7.4f' % (precinct, actual, predict, diff, pct_error))
def get_theta():
import math
theta = [0.0, 0.0, 0.0]
step = 0.01
comments = Comment.query.all()[:100]
print "Comments gotten! Training..."
for m in range(1000):
for comment in comments:
if comment.emotion != -1:
x = [1, float(comment.pos_count), float(comment.neg_count)]
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
h = 1 / (1+math.e**-(feature_sum))
for i in range(3):
theta[i] = theta[i] + step*(comment.emotion-h)*x[i]
print "Theta Gotten: ", theta
def get_emotion():
print "Calculating thetas..."
get_theta()
print "Done!"
comments = Comment.query.filter_by(emotion=-1).all()
for comment in comments:
x = [1, float(comment.pos_count), float(comment.neg_count)]
hypothesis = 0
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
hypothesis = 1 / (1+math.e**-(feature_sum))
if 0 < hypothesis < 0.4:
comment.analysis_score = 0
elif 0.4 <= hypothesis < 0.6:
comment.analysis_score = 0.5
elif 0.6 <= hypothesis < 1:
comment.analysis_score = 1
def get_stats_and_update_occupancy(CG, sorted_nodes, tfile) :
"""
Update the occupancy in the Graph and the total simulation time
"""
# http://www.regular-expressions.info/floatingpoint.html
reg_flt = re.compile('[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?.')
lastlines = s.check_output(['tail', '-2', tfile]).strip().split("\n")
if not reg_flt.match(lastlines[0]):
raise ValueError('Cannot parse simulation output', tfile)
else :
time = float(lastlines[0].split()[0])
iterations = int(lastlines[-1].split()[-1])
tot_occ =sum(map(float, lastlines[0].split()[1:]))
for e, occu in enumerate(lastlines[0].split()[1:]) :
ss = sorted_nodes[e][0]
CG.node[ss]['occupancy'] = float(occu)/tot_occ
return time, iterations
def evaluateStack( s ):
try:
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
except:
return None
def test_use_decimal():
import math
from decimal import Decimal
dstr = "2.7182818284590452353602874713527"
d = Decimal(dstr)
with pytest.raises(TypeError):
rapidjson.dumps(d)
assert rapidjson.dumps(float(dstr)) == str(math.e)
assert rapidjson.dumps(d, use_decimal=True) == dstr
assert rapidjson.dumps({"foo": d}, use_decimal=True) == '{"foo":%s}' % dstr
assert rapidjson.loads(
rapidjson.dumps(d, use_decimal=True),
use_decimal=True) == d
assert rapidjson.loads(rapidjson.dumps(d, use_decimal=True)) == float(dstr)
def poisson_distribution(gamma):
"""Computes the probability of events for a Poisson distribution.
Args:
gamma: The average number of events to occur in an interval.
Returns:
The probability distribution of k events occuring.
This is a function taking one parameter (k) and returning the
probability of k events occuring.
"""
constant_factor = math.e ** (-gamma)
def probability(k):
"""The probability of k events occuring for a Poisson distribution.
Args:
k: The number of the events occuring in an interval.
Returns:
The probability of k events occuring in the given distribution.
"""
return (constant_factor * gamma ** k) / (math.factorial(k))
return probability
def _createGameFromData(self, gameData):
temp = int(gameData['Template'])
tempID, tempSettings, overrides = self._getTempSettings(temp)
teams = self._assembleTeams(gameData)
try:
wlID = self.handler.createGame(tempID, self._getGameName(gameData),
teams, settingsDict=tempSettings,
overridenBonuses=overrides,
teamless=self.teamless,
message=self._getGameMessage(gameData))
self._adjustTemplateGameCount(temp, 1)
createdStr = datetime.strftime(datetime.now(), self.TIMEFORMAT)
self._updateEntityValue(self.games, gameData['ID'],
WarlightID=wlID, Created=createdStr)
return gameData
except Exception as e:
sides = gameData['Sides']
self.parent.log("Failed to make game with %s on %d because of %s" %
(sides, temp, repr(e)), self.name, error=True)
self._deleteGame(gameData, False, False)
def _createBatch(self, batch):
currentID = self._getBatchStartingID()
for game in batch:
try:
self._addEntity(self.games,
{'ID': currentID, 'WarlightID': '', 'Created': '',
'Winners': '', 'Sides': game['Sides'], 'Vetos': 0,
'Vetoed': '', 'Finished': '',
'Template': game['Template']})
self._makeGame(currentID)
currentID += 1
except (SheetErrors.DataError, SheetErrors.SheetError) as e:
self.parent.log(("Failed to add game to sheet due to %s" %
str(e)), self.name, error=True)
except APIError as e:
self.parent.log(("Failed to create game with ID %d" %
(currentID)), self.name, error=True)
def test_nfloat_ops_binary():
# Signedness (nfloat + nfloat)
assert (nfloat( exponent=4 ) + nfloat( exponent=4 )).e == 4
assert (nfloat( exponent=4 ) + nfloat( exponent=8 )).e == 8
assert (nfloat( exponent=8 ) + nfloat( exponent=4 )).e == 8
assert (nfloat( exponent=8 ) + nfloat( exponent=8 )).e == 8
# Size (nfloat + nfloat)
assert (nfloat( mantissa=4 ) + nfloat( mantissa=4 )).m == 4
assert (nfloat( mantissa=4 ) + nfloat( mantissa=8 )).m == 8
assert (nfloat( mantissa=8 ) + nfloat( mantissa=4 )).m == 8
assert (nfloat( mantissa=8 ) + nfloat( mantissa=8 )).m == 8
# Signedness (nfloat + float)
assert (nfloat( exponent=4 ) + 0.0).e == 4
assert (nfloat( exponent=8 ) + 0.0).e == 8
# Size (nfloat + float)
assert (nfloat( mantissa=4 ) + 0.0).m == 4
assert (nfloat( mantissa=8 ) + 0.0).m == 8
# Arithmetic
assert float32(3.0) + float32(2.0) == float32(5.0)
assert float32(3.0) - float32(2.0) == float32(1.0)
assert float32(3.0) * float32(2.0) == float32(6.0)
assert float32(3.0) / float32(2.0) == float32(1.5)
assert float32(3.0) // float32(2.0) == float32(1.0)
assert float32(7.0) % float32(5.0) == float32(2.0)
assert float32(3.0) ** float32(4.0) == float32(81.0)
def test_nfloat_ops_reflected():
# Exponent size (float <op> nfloat)
assert (0.0 + nfloat( exponent=4 )).e == 4
assert (0.0 + nfloat( exponent=8 )).e == 8
assert (0.0 + nfloat( exponent=4 )).e == 4
assert (0.0 + nfloat( exponent=8 )).e == 8
# Mantissa size (float <op> nfloat)
assert (0.0 + nfloat( mantissa=4 )).m == 4
assert (0.0 + nfloat( mantissa=8 )).m == 8
assert (0.0 + nfloat( mantissa=4 )).m == 4
assert (0.0 + nfloat( mantissa=8 )).m == 8
# Arithmetic
assert 3.0 + float32(2.0) == float32(5.0)
assert 3.0 - float32(2.0) == float32(1.0)
assert 3.0 * float32(2.0) == float32(6.0)
assert 3.0 / float32(2.0) == float32(1.5)
assert 3.0 // float32(2.0) == float32(1.0)
assert 7.0 % float32(5.0) == float32(2.0)
assert 3.0 ** float32(4.0) == float32(81.0)
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def kullback_leibler_divergence(prob_dist1, prob_dist2, base=math.e):
# Calculate the Kullback-Leibler divergence
kl_divergence = 0
# To avoid zero in the numerator or denominator
pseudo_count = 0.000001
for index in range(len(prob_dist1)):
#print 'KL Divergence PD1[{0}]: {1} PD2[{0}]: {2}'.format(index, prob_dist1[index], prob_dist2[index])
#print "newdiv == {0}".format(newdiv(float(prob_dist1[index]) + pseudo_count, float(prob_dist2[index]) + pseudo_count))
#kl_divergence += prob_dist1[index] * math.log(newdiv(float(prob_dist1[index]) + pseudo_count, float(prob_dist2[index]) + pseudo_count), base)
kl_divergence += prob_dist1[index] * math.log((float(prob_dist1[index]) + pseudo_count) / (float(prob_dist2[index]) + pseudo_count), base)
return kl_divergence
def jensen_shannon_divergence(prob_dist1, prob_dist2, base=math.e):
# Calculate "M" == (prob_dist1 + prob_dist2) / 2
# m = []
len_pd1 = len(prob_dist1)
m = [0.5 * (prob_dist1[index] + prob_dist2[index]) for index in range(len_pd1)]
# for index in range(0, len(prob_dist1)):
# m.append(0.5 * (prob_dist1[index] + prob_dist2[index]))
#print 'M: {0}'.format(m)
# Return Jensen-Shannon Divergence
jsd = 0.5 * (kullback_leibler_divergence(prob_dist1, m, base) + kullback_leibler_divergence(prob_dist2, m, base))
#print 'Jensen-Shannon Divergence: {0}'.format(jsd)
return jsd
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4
def annealing_optimize(domain, cost_fuc, t=10000.0, cool=0.95, step=1):
vec = [float(random.randint(domain[i][0], domain[i][1])) for i in range(len(domain))]
while t > 0.1:
i = random.randint(0, len(domain)-1)
direction = random.randint(-step, step)
new_vec = vec[:]
new_vec[i] += direction
if new_vec[i] < domain[i][0]:
new_vec[i] = domain[i][0]
elif new_vec[i] > domain[i][1]:
new_vec[i] = domain[i][1]
cost = cost_fuc(vec)
new_cost = cost_fuc(new_vec)
# ?? pow(math.e, -(new_cost-cost)/t) ???????
# ?new_cost > cost ?????t????????new_cost
# ??t????????????new_cost
# ??t???????????new_cost
if new_cost < cost or random.random() < pow(math.e, -(new_cost+cost)/t):
vec = new_vec
t *= cool
return vec, cost_fuc(vec)
def run_cc(self, cmd, msg):
gid = str(msg.guild.id)
if self.ccs[gid][cmd]["locked"] and not msg.author.guild_permissions.manage_messages:
await respond(msg, f"**WARNING: Custom command {cmd} is locked.**")
else:
ccdat = self.ccs[gid][cmd]["content"]
try:
res = self._find_tags(ccdat, msg)
except CustomCommandSyntaxError as e:
err = e if e else "Syntax error."
await respond(msg, f"**WARNING: Author made syntax error: {err}**")
except CommandSyntaxError as e:
err = e if e else "Syntax error."
await respond(msg, f"**WARNING: {err}**")
except Exception:
self.logger.exception("Exception occurred in custom command: ", exc_info=True)
await respond(msg, "**WARNING: An error occurred while running the custom command.**")
else:
if res:
await respond(msg, res)
else:
self.logger.warning(f"CC {cmd} of {str(msg.guild)} returns nothing!")
self.ccvars = {}
self.ccs[gid][cmd]["times_run"] += 1
self._save_ccs()
def upper_incomplete_gamma(a,x,d=0,iterations=100):
if d == iterations:
if ((d % 2) == 1):
return 1.0 # end iterations
else:
m = d/2
return x + (m-a)
if d == 0:
result = ((x**a) * (e**(-x)))/upper_incomplete_gamma(a,x,d=d+1)
return result
elif ((d % 2) == 1):
m = 1.0+((d-1.0)/2.0)
return x+ ((m-a)/(upper_incomplete_gamma(a,x,d=d+1)))
else:
m = d/2
return 1+(m/(upper_incomplete_gamma(a,x,d=d+1)))
# 6.5.31 Handbook of Mathematical Functions, page 263
# Recursive implementation
def lower_incomplete_gamma(a,x,d=0,iterations=100):
if d == iterations:
if ((d % 2) == 1):
return 1.0 # end iterations
else:
m = d/2
return x + (m-a)
if d == 0:
result = ((x**a) * (e**(-x)))/lower_incomplete_gamma(a,x,d=d+1)
return result
elif ((d % 2) == 1):
m = d - 1
n = (d-1.0)/2.0
return a + m - (((a+n)*x)/lower_incomplete_gamma(a,x,d=d+1))
else:
m = d-1
n = d/2.0
return a+m+((n*x)/(lower_incomplete_gamma(a,x,d=d+1)))
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4