def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
python类getcontext()的实例源码
def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
if self.decimal_places is None:
return value
context = decimal.getcontext().copy()
if self.max_digits is not None:
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context
)
# Date & time fields...
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
if self.decimal_places is None:
return value
context = decimal.getcontext().copy()
if self.max_digits is not None:
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context
)
# Date & time fields...
def KDJ_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
#sma target round2
precision = 40
high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
if np.isnan(close[-1]):
return np.array([np.nan]),np.array([np.nan]),np.array([np.nan])
#K_V, D_V, J_V = self.KDJ_CN(high, low, close)
K_V, D_V, J_V = self.KDJ_COM(high, low, close)
if len(K_V) > precision:
K_V = K_V[precision:]
D_V = D_V[precision:]
J_V = J_V[precision:]
else:
#print "security:%s no len data precison %s" %(str(security), len(K_V))
pass
decimal.getcontext().rounding=decimal.ROUND_HALF_UP
K_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in K_V])
D_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in D_V])
J_V = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in J_V])
return K_V, D_V, J_V
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def decimal2dms(decimal_degrees):
""" Converts a floating point number of degrees to the equivalent
number of degrees, minutes, and seconds, which are returned
as a 3-element tuple of decimals. If 'decimal_degrees' is negative,
only degrees (1st element of returned tuple) will be negative,
minutes (2nd element) and seconds (3rd element) will always be positive.
Example:
>>> decimal2dms(121.135)
(Decimal('121'), Decimal('8'), Decimal('6.000'))
>>> decimal2dms(-121.135)
(Decimal('-121'), Decimal('8'), Decimal('6.000'))
"""
degrees = D(int(decimal_degrees))
decimal_minutes = libdecimal.getcontext().multiply(
(D(str(decimal_degrees)) - degrees).copy_abs(), D(60))
minutes = D(int(decimal_minutes))
seconds = libdecimal.getcontext().multiply(
(decimal_minutes - minutes), D(60))
return (degrees, minutes, seconds)
def decimal2dm(decimal_degrees):
"""
Converts a floating point number of degrees to the degress & minutes.
Returns a 2-element tuple of decimals.
If 'decimal_degrees' is negative, only degrees (1st element of returned
tuple) will be negative, minutes (2nd element) will always be positive.
Example:
>>> decimal2dm(121.135)
(Decimal('121'), Decimal('8.100'))
>>> decimal2dm(-121.135)
(Decimal('-121'), Decimal('8.100'))
"""
degrees = D(int(decimal_degrees))
minutes = libdecimal.getcontext().multiply(
(D(str(decimal_degrees)) - degrees).copy_abs(), D(60))
return (degrees, minutes)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if decimal_places is not None:
value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
else:
context.traps[decimal.Rounded] = 1
value = context.create_decimal(value)
return "{:f}".format(value)
if decimal_places is not None:
return "%.*f" % (decimal_places, value)
return "{:f}".format(value)
def cube_root(x):
"""Required because the usual x ^ 1/3 does not work with big integers."""
decimal.getcontext().prec = 2 * len(str(x))
power = decimal.Decimal(1) / decimal.Decimal(3)
x = decimal.Decimal(str(x))
root = x ** power
integer_root = root.quantize(decimal.Decimal('1.'), rounding=decimal.ROUND_DOWN)
return int(integer_root)
# Taken from Hal Finney's summary at https://www.ietf.org/mail-archive/web/openpgp/current/msg00999.html,
def run(self):
c = decimal.getcontext().copy()
c.prec = self.prec
decimal.setcontext(c)
self.q.put((self.prec, a * b))
def dt_to_decimal(utc):
"""Datetime to Decimal.
Some databases don't store microseconds in datetime
so we always store as Decimal unixtime.
"""
if utc is None:
return None
decimal.getcontext().prec = 30
return (decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) +
(decimal.Decimal(str(utc.microsecond)) /
decimal.Decimal("1000000.0")))
def opacity(self, value):
try:
cleaned_opacity = Decimal(value)
except (TypeError, ValueError):
raise ValueError('Invalid opacity')
if cleaned_opacity < 0:
cleaned_opacity = Decimal()
elif cleaned_opacity > 1:
cleaned_opacity = Decimal(1)
context = getcontext().copy()
context.prec = 3
self._opacity = cleaned_opacity.quantize(Decimal('0.01'), context=context)
def __init__(self, value='0', rounding=ROUND_CEILING):
# ????????? ??????????????
self._formatter = get_formatter()
# ?????????????? ?????
context = getcontext().copy()
context.prec = 18
context.rounding = rounding
value = Decimal(value)
self._value = value.quantize(Decimal('.1') ** self._formatter['decimal_places'], context=context)
# ????? ? ??????? ?????
self._int, self._frac = str(self._value).rsplit('.', 1)
def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
context = decimal.getcontext().copy()
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context)
# Date & time fields...
def cpu_total(self):
decimal.getcontext().rounding = decimal.ROUND_DOWN
return int(self.cpu * float(self.cpu_coef))
def ram_total(self):
decimal.getcontext().rounding = decimal.ROUND_DOWN
return int(self.ram * float(self.ram_coef))
def resources(self):
"""Return tuple with total (cpu, ram, disk) resources"""
# We are working with decimal objects and rounding everything down
decimal.getcontext().rounding = decimal.ROUND_DOWN
# The total local disk size should not include backups and snapshots
# TODO: fix ns.size_images and subtract it too
disk_size_total = self.storage.size_total
if self._ns:
disk_size_total -= self._ns.size_backups + self._ns.size_snapshots + self._ns.size_rep_snapshots
return self.cpu * float(self.cpu_coef), self.ram * float(self.ram_coef), disk_size_total
def size_total(self):
# We are working with decimal objects and rounding everything down
decimal.getcontext().rounding = decimal.ROUND_DOWN
return int(int(self.size) * float(self.size_coef))
def CCI_DATA(self, context, security, freq = 'D', data={}, dataCount=1):
#sma target round2
precision = 14
high, low, close = self.GET_PERIOD_DATA(context, security, freq, data, dataCount+precision)
if np.isnan(close[-1]):
return np.array([np.nan])
CCI = self.CCI_CN(high, low, close)
if len(CCI) > precision:
CCI = CCI[-dataCount:]
else:
#print "security:%s no len data precison %s" %(str(security), len(CCI))
pass
decimal.getcontext().rounding=decimal.ROUND_HALF_UP
CCI = np.array([float(decimal.Decimal(s).quantize(decimal.Decimal('0.00'))) for s in CCI])
return CCI
def _dt_to_decimal(utc):
"""Datetime to Decimal.
Some databases don't store microseconds in datetime
so we always store as Decimal unixtime.
"""
if utc is None:
return None
decimal.getcontext().prec = 30
return (decimal.Decimal(str(calendar.timegm(utc.utctimetuple()))) +
(decimal.Decimal(str(utc.microsecond)) /
decimal.Decimal("1000000.0")))
def __init__(self):
decimal.getcontext().prec = 5
self.config_file = ConfigurationFile.ConfigurationFile()
self.port = 8989
self.listen_address = "localhost"
self.server_socket = None
self.wallets = []
self.authority_wallet = None
self.clients = []
self.ca_name = "unnamed"
self.transactions = []
self.coins_per_challenge = 0
self.minutes_per_challenge = 0
self.ssl_on = True
self.ssl_cert = ""
self.available_challenges = []
self.prefix_length = 4
self.challenge_thread = None
self.max_requests_per_minutes = 30
self.initial_cooldown_length = 60
self.invalid_submission_allowed = 5 # within 5 minutes
self.supervisor_key = ''
self.emit_coins = False
self.min_transaction_amount = 0
self.submissions_allowed_ips = []
self.statistic = ServerStatistic.ServerStatistic()
self.read_vars_from_config()
self.database = ServerDatabase.ServerDatabase(self.config_file.get_string("db_user", "cacoins"), self.config_file.get_string("db_password", ""), self.config_file.get_string("db_name", "cacoins"))
# commands handler
self.commands_handler = []
self.fill_commands_handler()
self.ca_private_key = None
self.ca_public_key = None
self.ca_wallet_id = None
self.wallet_keys = {}
def dms2decimal(degrees, minutes, seconds):
""" Converts degrees, minutes, and seconds to the equivalent
number of decimal degrees. If parameter 'degrees' is negative,
then returned decimal-degrees will also be negative.
NOTE: this method returns a decimal.Decimal
Example:
>>> dms2decimal(121, 8, 6)
Decimal('121.135')
>>> dms2decimal(-121, 8, 6)
Decimal('-121.135')
"""
decimal = D(0)
degs = D(str(degrees))
mins = libdecimal.getcontext().divide(D(str(minutes)), D(60))
secs = libdecimal.getcontext().divide(D(str(seconds)), D(3600))
if degrees >= D(0):
decimal = degs + mins + secs
else:
decimal = degs - mins - secs
return libdecimal.getcontext().normalize(decimal)
def base_round(val, n):
if val is not None:
val = Decimal(val, getcontext())
return val.__round__(n)
return None
def base_round_zero(val, n):
if val is not None:
val = Decimal(val, getcontext())
else:
val = Decimal(0, getcontext())
return val.__round__(n)
def base_round(self, val, n):
if val is not None:
val = Decimal(val, getcontext())
return val.__round__(n)
return None