def verify_xrp_value(xrp_value: str) -> None: """ Validates the format of an XRP amount. Raises if value is invalid. Args: xrp_value: A string representing an amount of XRP. Returns: None, but raises if xrp_value is not a valid XRP amount. Raises: XRPLBinaryCodecException: If xrp_value is not a valid XRP amount. """ # Contains no decimal point if not _contains_decimal(xrp_value): raise XRPLBinaryCodecException( f"{xrp_value} is an invalid XRP amount.") # Within valid range decimal = Decimal(xrp_value) # Zero is less than both the min and max XRP amounts but is valid. if decimal.is_zero(): return if (decimal.compare(_MIN_XRP) == -1) or (decimal.compare(_MAX_DROPS) == 1): raise XRPLBinaryCodecException( f"{xrp_value} is an invalid XRP amount.")
def normalize(self): t = self.text.strip() if self.name == "einsatzstelle": lc = t.lower() lcLen = len(lc) if lcLen >= 2: for grund in self.gründe: if lcLen <= len(grund) and lc == grund[0:lcLen].lower(): self.text = grund break if self.fam.fnr == 1: # and t.lower() in utils.extras: self.fam.fillinStdBegEnd(app.menu.wtag2Stunden) elif self.name == "fahrtzeit": if t != "" and t != "0,5": toast("Fahrtzeit 0,5 oder nichts") self.text = "" return elif self.name == "mvv_euro": try: d = Decimal(t.replace(",", ".")) if int(d.compare(Decimal("5"))) < 0 or int( d.compare(Decimal(15))) > 0: toast("MVV Kosten von 5 bis 15 €") self.text = "" else: self.text = utils.moneyfmt(d, sep='.', dp=',') except: toast("MVV Kosten von 5 bis 15 €") self.text = "" elif self.name == "wochenstunden": if t != "20" and t != "30" and t != "35" and t != "38,5": toast("Wochenstunden: 20, 30, 35, 38,5)") t = "" self.text = t
def SaveAssetAddress(asset, address): #print "Asset:", asset,"Address:", address i = 0 value = Decimal("0") txid_set = set() txid_list = [] results = collection_coins.find({ "asset": asset, "address": address }).sort("height", -1) for result in results: #print "coinsHeight: " + str(result['height']) if i == 0: first_tx_time = GetTimeByBlockHeight(result['height']) # Check if spent if int(result['state']) & CoinState.Spent == CoinState.Spent: value = Decimal(value) - Decimal(result['value']) print "value -", Decimal(result['value']), "value:", value if result['spent_txid'] not in txid_set: txid_set.add(result['spent_txid']) txid_list.append({ 'txid': result['spent_txid'], 'height': str(GetHeightByTxid(result['spent_txid'])) }) else: value = Decimal(value) + Decimal(result['value']) print "value +", Decimal(result['value']), "value:", value if result['txid'] not in txid_set: txid_set.add(result['txid']) txid_list.append({ 'txid': result['txid'], 'height': str(result['height']) }) i = i + 1 if value.compare(Decimal("0")) == Decimal("0"): value = Decimal("0") if value.compare(Decimal("0")) == Decimal('-1'): raise Exception("[SaveAddress] value < 0") last_tx_time = GetTimeByBlockHeight(result['height']) ads_dict = {} ads_dict['asset'] = asset ads_dict['address'] = address ads_dict['value'] = str(value) ads_dict['first_tx_time'] = first_tx_time ads_dict['last_tx_time'] = last_tx_time ads_dict['txid_list'] = txid_list SaveAds(ads_dict)
def SaveAssetAddress(asset, address): #print "Asset:", asset,"Address:", address i = 0 value = Decimal("0") txid_set = set() txid_str = "" results = collection_coins.find({ "asset": asset, "address": address }).sort("height", -1) for result in results: #print "coinsHeight: " + str(result['height']) if i == 0: first_tx_time = GetTimeByBlockHeight(result['height']) # Check if spent if int(result['state']) & CoinState.Spent == CoinState.Spent: value = Decimal(value) - Decimal(result['value']) print "value -", Decimal(result['value']), "value:", value if result['spent_txid'] not in txid_set: txid_set.add(result['spent_txid']) if i == 0: txid_str = txid_str + '{"txid":"' + result[ 'spent_txid'] + '","height":' + str( GetHeightByTxid(result['spent_txid'])) + '}' else: txid_str = txid_str + ',{"txid":"' + result[ 'spent_txid'] + '","height":' + str( GetHeightByTxid(result['spent_txid'])) + '}' else: value = Decimal(value) + Decimal(result['value']) print "value +", Decimal(result['value']), "value:", value if result['txid'] not in txid_set: txid_set.add(result['txid']) if i == 0: txid_str = txid_str + '{"txid":"' + result[ 'txid'] + '","height":' + str(result['height']) + '}' else: txid_str = txid_str + ',{"txid":"' + result[ 'txid'] + '","height":' + str(result['height']) + '}' i = i + 1 if value.compare(Decimal("0")) == Decimal("0"): value = Decimal("0") if value.compare(Decimal("0")) == Decimal('-1'): raise Exception("[SaveAddress] value < 0") last_tx_time = GetTimeByBlockHeight(result['height']) json_str = '{"asset":"%s", "address":"%s", "value":"%s", "first_tx_time":%d, "last_tx_time":%d, "txid_list":[%s]}' % ( asset, address, value, first_tx_time, last_tx_time, txid_str) ads = json.loads(json_str) SaveAds(ads)
def _format_time(hours: Decimal, minutes: Decimal, seconds: Decimal) -> str: if hours.compare(0) == 1 and minutes.compare(0) == 1 and seconds.compare(0) == 1: return f'{hours}h {minutes}m {seconds}s' if hours.compare(0) == 0 and minutes.compare(0) == 1 and seconds.compare(0) == 1: return f'{minutes}m {seconds}s' if hours.compare(0) == 0 and minutes.compare(0) == 0 and seconds.compare(0) == 1: return f'{seconds}s' return f'{hours}h {minutes}m {seconds}s'
def post(self, request, format=None): invoice_row = get_object_from_query_params('invoice_row', request.query_params) amount = request.data.get('amount', None) if amount is not None: try: amount = Decimal(amount) except InvalidOperation: raise APIException(_('Invalid amount')) if amount.compare(Decimal(0)) != Decimal(1): raise APIException(_('Amount must be bigger than zero')) try: credit_invoice = invoice_row.invoice.create_credit_invoice( row_ids=[invoice_row.id], amount=amount) except RuntimeError as e: raise APIException(e) credit_invoice_serializer = InvoiceSerializer(credit_invoice) result = { 'invoice': credit_invoice_serializer.data, } return Response(result)
def post(self, request, format=None): invoice_row = get_object_from_query_params( "land_use_agreement_invoice_row", request.query_params) amount = request.data.get("amount", None) if amount is not None: try: amount = Decimal(amount) except InvalidOperation: raise ValidationError(_("Invalid amount")) if amount.compare(Decimal(0)) != Decimal(1): raise ValidationError(_("Amount must be bigger than zero")) try: credit_invoice = invoice_row.invoice.create_credit_invoice( row_ids=[invoice_row.id], amount=amount) except RuntimeError as e: raise APIException(str(e)) credit_invoice_serializer = LandUseAgreementInvoiceSerializer( credit_invoice) result = {"invoice": credit_invoice_serializer.data} return Response(result)
def update_amounts(self): for row in self.rows.all(): row.update_amount() rows_sum = self.rows.aggregate(sum=Sum("amount"))["sum"] if not rows_sum: rows_sum = Decimal(0) self.billed_amount = rows_sum self.total_amount = rows_sum payments_total = self.payments.aggregate(sum=Sum("paid_amount"))["sum"] if not payments_total: payments_total = Decimal(0) # Aggregating like this ignores the manager (i.e. includes deleted rows which we don't want): # total_credited_amount = self.credit_invoices.aggregate(sum=Sum("rows__amount"))["sum"] # ... so we have to iterate the rows and tally the sum by hand total_credited_amount = Decimal(0) for credit_inv in self.credit_invoices.all(): for row in credit_inv.rows.all(): total_credited_amount += row.amount self.outstanding_amount = max( Decimal(0), self.billed_amount - payments_total - total_credited_amount, ) # Don't mark as refunded unless credited amount is nonzero if total_credited_amount != Decimal(0) and total_credited_amount.compare( self.billed_amount ) != Decimal(-1): self.state = InvoiceState.REFUNDED elif self.type == InvoiceType.CHARGE and self.outstanding_amount == Decimal(0): self.state = InvoiceState.PAID self.save()
def get_values_from_credit_request(data): amount = data.get('amount', None) receivable_type_id = data.get('receivable_type') notes = data.get('notes') receivable_type = None if amount is not None and not receivable_type_id: raise APIException( 'receivable_type is required if amount is provided.') if amount is not None: try: amount = Decimal(amount) except InvalidOperation: raise APIException(_('Invalid amount')) if amount.compare(Decimal(0)) != Decimal(1): raise APIException(_('Amount must be bigger than zero')) if receivable_type_id: try: receivable_type = ReceivableType.objects.get(pk=receivable_type_id) except ReceivableType.DoesNotExist: raise APIException( 'Receivable_type "{}" not found'.format(receivable_type_id)) return amount, receivable_type, notes
def get_values_from_credit_request(data): amount = data.get("amount", None) receivable_type_id = data.get("receivable_type") notes = data.get("notes", "") receivable_type = None if amount is not None and not receivable_type_id: raise ValidationError( "receivable_type is required if amount is provided.") if amount is not None: try: amount = Decimal(amount) except InvalidOperation: raise ValidationError(_("Invalid amount")) if amount.compare(Decimal(0)) != Decimal(1): raise ValidationError(_("Amount must be bigger than zero")) if receivable_type_id: try: receivable_type = ReceivableType.objects.get(pk=receivable_type_id) except ReceivableType.DoesNotExist: raise ValidationError( 'Receivable_type "{}" not found'.format(receivable_type_id)) return amount, receivable_type, notes
def test_generic_data_container_decimal_with_no_validator_and_valid_decimal( self): gdc = GenericDataContainer(result_set_name='Test', data_type=Decimal) l = Decimal(1001.01) result = gdc.store(data=l) self.assertEqual(1, result) self.assertEqual(0, l.compare(gdc.data))
def test_sort_by_rating(all_courses): courses = list(Course.sort_by_rating(all_courses)) for index in range(len(courses) - 1): if courses[index].avg_rating is None: assert courses[index + 1].avg_rating is None elif courses[index + 1].avg_rating is not None: assert Decimal.compare(courses[index].avg_rating, courses[index + 1].avg_rating) > -1
def on_message(ws, message, drop=drop, pair=pair, high=high, deal=deal): dictionary = json.loads(message) percentoff = Decimal(drop) sessionmax = Decimal(high.getvalue()) # Uncomment this statement to debug messages: logger.debug(dictionary) # Process "type": "update" messages with events only. if 'update' in dictionary['type']: if dictionary['events'] != []: events = dictionary['events'] # Process "type": "trade" events for latest price. for event in events: if event['type'] == 'trade': last = Decimal(event["price"]) if last.compare(Decimal(sessionmax)) == 1: sessionmax = last high.setvalue(last) # Calculate movement away from high [if any]. move = 100 * (sessionmax - last) / sessionmax # Display impact of event information received. logger.info( f'{move:.2f}% off highs [{sessionmax}] : {pair} is {last} presently : [Message ID: {dictionary["socket_sequence"]}].' ) # Define bargain (sale) price. sale = Decimal(sessionmax * (1 - percentoff)) # Exit loop if there's a sale. if sale.compare(last) == 1: logger.info( f'{pair} [now {last:.2f}] just went on sale [dropped below {sale:.2f}].' ) smsalert( f'There was a {percentoff*100}% drop in the price of the {pair} pair on Gemini.' ) # Update deal price. deal.setvalue(last) ws.close()
def test_generic_data_container_decimal_with_validator_and_valid_decimal( self): gdc = GenericDataContainer(result_set_name='Test', data_type=Decimal, data_validator=NumberDataValidator()) l = Decimal(1001.01) result = gdc.store(data=l, min_value=Decimal(0.0), max_value=Decimal(9999.0)) self.assertEqual(1, result) self.assertEqual(0, l.compare(gdc.data))
def update_amounts(self): rows_sum = self.rows.aggregate(sum=Sum('amount'))['sum'] if not rows_sum: rows_sum = Decimal(0) self.billed_amount = rows_sum if not self.invoiceset: self.total_amount = rows_sum else: # Sum amounts from all of the rows in the same type of invoices in this invoiceset invoiceset_rows_sum = InvoiceRow.objects.filter( invoice__invoiceset=self.invoiceset, invoice__type=self.type, invoice__deleted__isnull=True, deleted__isnull=True).aggregate(sum=Sum('amount'))['sum'] if not invoiceset_rows_sum: invoiceset_rows_sum = Decimal(0) # Update sum to all of the same type invoices in this invoiceset self.invoiceset.invoices.filter( type=self.type, deleted__isnull=True).exclude( id=self.id).update(total_amount=invoiceset_rows_sum) # Need to set self total_amount separately because the # total_amount is not automatically refreshed from the # database self.total_amount = invoiceset_rows_sum payments_total = self.payments.aggregate(sum=Sum('paid_amount'))['sum'] if not payments_total: payments_total = Decimal(0) total_credited_amount = self.credit_invoices.aggregate( sum=Sum('rows__amount'))['sum'] if not total_credited_amount: total_credited_amount = Decimal(0) collection_charge = Decimal(0) if self.collection_charge: collection_charge = self.collection_charge self.outstanding_amount = max( Decimal(0), self.billed_amount + collection_charge - payments_total - total_credited_amount) if total_credited_amount.compare(self.billed_amount) != Decimal(-1): self.state = InvoiceState.REFUNDED elif self.type == InvoiceType.CHARGE and self.outstanding_amount == Decimal( 0): self.state = InvoiceState.PAID self.save()
def get_shipping_cost(shipping_id, customer_id, total_amount): print('get_shipping_cost') shipping_cost = Decimal('0') shipping_extra = Decimal('0') if shipping_id: shipping_method = ShippingMethod.objects.get(id=shipping_id) if shipping_method.name == 'Store Pickup': shipping_cost = Decimal(shipping_method.price) else: if total_amount.compare(Decimal('50')) < 0: shipping_cost = Decimal(shipping_method.price) shipping_address = ShippingAddress.objects.get( customer_id=customer_id) destination = shipping_address.address + ' ' + shipping_address.house_number + ', ' + \ shipping_address.city + ', ' + shipping_address.country + ', ' + shipping_address.zip store = Store.objects.get(store_id=shipping_method.store_id) origin = store.address + ', ' + store.city + ', ' + \ store.country + ', ' + store.zip resp = requests.get( 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + origin + '&destinations=' + destination + '&mode=car&units=imperial&key=' + settings.API_KEY) print(resp.status_code) if resp.status_code != 200: print('dist response ' + resp.text) raise ValidationError( 'Google distance API failed to retrieve distance to calculate shipping' ) distance_resp = json.loads(resp.text) distance = distance_resp.get('rows')[0].get('elements')[0].get( 'distance').get('text') distance = distance.replace(',', '') distance = distance.replace(' mi', '') distance = round(float(distance)) print('distance', distance) if distance > settings.DELIVERY_FREE_MILES: shipping_extra = (distance - settings.DELIVERY_FREE_MILES ) * settings.DELIVERY_PER_MILE shipping_cost = Decimal(shipping_cost) + Decimal(shipping_extra) if shipping_cost.compare(Decimal('50')) > 0: shipping_cost = Decimal('50') cents = Decimal('.01') shipping_cost = shipping_cost.quantize(cents, decimal.ROUND_HALF_UP) return shipping_cost
def calculateCompoundRank(compound): decimalCompound = Decimal(compound) if(decimalCompound.compare(Decimal(0.75)) == 1): return 4 elif(decimalCompound.compare(Decimal(0.5)) == 1): return 3 elif(decimalCompound.compare(Decimal(0.25)) == 1): return 2 elif(decimalCompound.compare(Decimal(0)) == 1): return 1 elif(decimalCompound.compare(Decimal(0)) == 0): return 0 elif(decimalCompound.compare(Decimal(-0.25)) == 1): return -1 elif(decimalCompound.compare(Decimal(-0.5)) == 1): return -2 elif(decimalCompound.compare(Decimal(-0.75)) == 1): return -3 return -4
def is_after(*, timestamp: Decimal, after: Decimal, inclusive: bool, verbose: bool, debug: bool, ): acceptable_results = [Decimal('1')] if inclusive: acceptable_results.append(Decimal('0')) if debug: ic(acceptable_results) result = timestamp.compare(after) if debug: ic(result) if result not in acceptable_results: return False return True
def nice_size(size, include_bytes=False): """Returns a readably formatted string with the size""" niced = False nice_string = "%s bytes" % size try: nsize = Decimal(size) for x in ['bytes', 'KB', 'MB', 'GB']: if nsize.compare(Decimal("1024.0")) == Decimal("-1"): nice_string = "%3.1f %s" % (nsize, x) niced = True break nsize /= Decimal("1024.0") if not niced: nice_string = "%3.1f %s" % (nsize, 'TB') niced = True if include_bytes and x != 'bytes': nice_string = "%s (%s bytes)" % (nice_string, size) except Exception: pass return nice_string
def nice_size(size, include_bytes=False): """Returns a readably formatted string with the size""" niced = False nice_string = f"{size} bytes" try: nsize = Decimal(size) for x in ['bytes', 'KB', 'MB', 'GB']: if nsize.compare(Decimal("1024.0")) == Decimal("-1"): nice_string = f"{nsize:3.1f} {x}" niced = True break nsize /= Decimal("1024.0") if not niced: nice_string = f"{nsize:3.1f} TB" niced = True if include_bytes and x != 'bytes': nice_string = f"{nice_string} ({size} bytes)" except Exception: pass return nice_string
class CryptoMonitor(CryptoWorker): def __init__(self, client, product_id, granularity): super().__init__(client) self.product_id = product_id self.granularity = granularity self.last_time = datetime.fromtimestamp(0, tz=timezone.utc) self.historical_df = None self.state = STATE_DEFAULT self.owned_crypto_balance = Decimal(0) def __str__(self): return f"CryptoMonitor({self.get_thread_name()},{self.product_id},{self.granularity})" def round_down_time(self, t): return t.replace(microsecond=0, second=0, minute=0, tzinfo=timezone.utc) def get_expected_last_time(self): return self.round_down_time(datetime.utcnow()) def request_data(self): if self.get_expected_last_time() > self.last_time: history_request_msg = HistoricalDataRequestMessage( self, self.client, self.product_id, granularity=self.granularity, ) self.client.add_message_to_queue(history_request_msg) product_ticker_msg = ProductTickerRequestMessage( self, self.client, self.product_id) self.client.add_message_to_queue(product_ticker_msg) def process_message(self, msg): if msg is not None: if isinstance(msg, HistoricalDataResponseMessage): # Check if the most recent time is from after our last most recent # If it is, build a new dataframe and save it. If not, we'll keep # trying until it is if datetime.fromtimestamp(msg.data[0][0], tz=timezone.utc) > self.last_time: self.historical_df = list_to_dataframe(msg.data) self.last_time = datetime.fromtimestamp(msg.data[0][0], tz=timezone.utc) elif isinstance(msg, ProductTickerResponseMessage): # Shouldn't ever get a response for this before a response for # overall historical data if self.historical_df is None: return 1 fresh_df = self.historical_df.copy(deep=True) dt = dateutil.parser.isoparse(msg.data['time']) d = "{:.2f}".format(float(msg.data['price'])) fresh_df.loc[len(fresh_df)] = [dt, 0, 0, 0, Decimal(d), 0] df = gather_all_crypto_data(fresh_df) z = np.polyfit(df.index, [float(x) for x in df.close], 1) if Decimal(z[0]) / Decimal(d) < Decimal(-0.0005): logger.warning( f"{self} has a significantly negative trend, " f"avoiding this market for now") return next_state = determine_next_state(df, self.state) if next_state == STATE_BUY: if self.owned_crypto_balance.compare( Decimal(0)) == Decimal(1): logger.info( f"{self} already has a outstanding balance " f"of {self.owned_crypto_balance}") else: logger.info(f"{self} is issuing a buy order") buy_order = BuyOrderRequestMessage( self, self.client, self.product_id) self.client.add_message_to_priority_queue(buy_order) self.state = STATE_DEFAULT elif next_state == STATE_SELL: if self.owned_crypto_balance.compare( Decimal(0)) == Decimal(0): logger.info(f"{self} does not have any outstanding " f"crypto to sell") else: logger.info(f"{self} is issuing a sell order") sell_order = SellOrderRequestMessage( self, self.client, self.product_id) self.client.add_message_to_priority_queue(sell_order) self.state = STATE_DEFAULT else: if next_state != STATE_DEFAULT and next_state != self.state: logger.info( f"{self} has just entered state {next_state}") self.state = next_state elif isinstance(msg, BuyOrderResponseMessage): self.owned_crypto_balance = Decimal(msg['size']) elif isinstance(msg, SellOrderResponseMessage): self.owned_crypto_balance = Decimal(0) else: return def process_messages(self): while self.get_remaining_message_count() > 0: msg = self.get_next_message_from_queue() self.process_message(msg) def run(self): logger.info(f"{self} starting") while not self.is_shutdown(): self.request_data() for i in range(int(SLEEP_TIME / SLEEP_INTERVAL)): self.process_messages() sleep(SLEEP_INTERVAL) logger.info(f"{self} terminating")
def test_sort_by_load(all_courses): courses = list(Course.sort_by_load(all_courses)) for index in range(len(courses) - 1): if courses[index].avg_load is not None: assert Decimal.compare(courses[index].avg_load, courses[index + 1].avg_load) < 1
def load(): #f=request.files['imagefile'] imagefile = request.files['imagefile'] filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ werkzeug.secure_filename(imagefile.filename) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.save(filename) image = exifutil.open_oriented_im(filename) plt.rcParams['figure.figsize'] = (10, 10) # large images plt.rcParams[ 'image.interpolation'] = 'nearest' # don't interpolate: show square pixels plt.rcParams[ 'image.cmap'] = 'gray' # use grayscale output rather than a (potentially misleading) color heatmap # The caffe module needs to be on the Python path; # we'll add it here explicitly. caffe_root = '/home/speech/.local/install/caffe/' # this file should be run from {caffe_root}/examples (otherwise change this line) sys.path.insert(0, caffe_root + 'python') # If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path. if os.path.isfile(caffe_root + 'models/placesCNN/places205CNN_iter_300000.caffemodel'): print('CaffeNet found') else: print('Downloading pre-trained CaffeNet model...') caffe.set_mode_cpu() model_def = caffe_root + 'models/placesCNN/places205CNN_deploy.prototxt' model_weights = caffe_root + 'models/placesCNN/places205CNN_iter_300000.caffemodel' net = caffe.Net( model_def, # defines the structure of the model model_weights, # contains the trained weights caffe.TEST) # use test mode (e.g., don't perform dropout) # load the mean ImageNet image (as distributed with Caffe) for subtraction mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy') mu = mu.mean(1).mean( 1) # average over pixels to obtain the mean (BGR) pixel values print('mean-subtracted values:', zip('BGR', mu)) # create transformer for the input called 'data' transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) transformer.set_transpose( 'data', (2, 0, 1)) # move image channels to outermost dimension transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255] transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR # set the size of the input (we can skip this if we're happy # with the default; we can also change it later, e.g., for different batch sizes) net.blobs['data'].reshape( 50, # batch size 3, # 3-channel (BGR) images 227, 227) # image size is 227x227 img = caffe.io.load_image(filename) transformed_image = transformer.preprocess('data', img) plt.imshow(img) # copy the image data into the memory allocated for the net net.blobs['data'].data[...] = transformed_image ### perform classification output = net.forward() output_prob = output['prob'][ 0] # the output probability vector for the first image in the batch print('predicted class is:', output_prob.argmax()) # load ImageNet labels labels_file = caffe_root + 'data/place/categoryIndex_places205.csv' labels = np.loadtxt(labels_file, str, delimiter='\t') #thresh = raw_input("Enter input: ") thresh = 0.1 top_inds = output_prob.argsort()[::-1] items = [] for i in top_inds: a = Decimal(str(output_prob[i])).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN) b = Decimal(str(thresh)).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN) if a.compare(b) >= 0: an_item = dict(a1=output_prob[i], a2=labels[i]) items.append(an_item) options = { "model": "/home/speech/darkflow-master/cfg/tiny-yolo.cfg", "load": "/home/speech/darkflow-master/bin/tiny-yolo.weights", "threshold": 0.1 } tfnet = TFNet(options) imgcv = cv2.imread(filename) result = tfnet.return_predict(imgcv) font = cv2.FONT_HERSHEY_SIMPLEX for r in result: cv2.rectangle(imgcv, (r['topleft']['x'], r['topleft']['y']), (r['bottomright']['x'], r['bottomright']['y']), (0, 255, 0), 1) cv2.putText(imgcv, r['label'], (r['topleft']['x'], r['topleft']['y'] + 12), font, 0.47, (255, 0, 0), 1) cv2.imwrite('outfile.jpg', imgcv) files = '/home/speech/.local/install/caffe/outfile.jpg' i = exifutil.open_oriented_im(files) return render_template('2.html', imagesrc=embed_image_html(image), items=items, result=result, isrc=embed_image_html(i))
def create_credit_invoiceset_for_amount(self, amount=None, receivable_type=None, notes=""): if amount and not receivable_type: raise RuntimeError( "receivable_type is required if amount is provided.") all_invoices = self.invoices.filter(type=InvoiceType.CHARGE) if not all_invoices: raise RuntimeError( 'No refundable invoices found (no invoices with the type "{}" found)' .format(InvoiceType.CHARGE.value)) shares = {} all_shares = Fraction() total_row_count = InvoiceRow.objects.filter( invoice__in=all_invoices, receivable_type=receivable_type).count() has_tenants = (InvoiceRow.objects.filter( invoice__in=all_invoices, receivable_type=receivable_type, tenant__isnull=False, ).count() == total_row_count) total_row_amount = InvoiceRow.objects.filter( invoice__in=all_invoices, receivable_type=receivable_type).aggregate( total_row_amount=Sum("amount"))["total_row_amount"] if amount > total_row_amount: raise RuntimeError( 'Credit amount "{}" is more that total row amount "{}"!'. format(amount, total_row_amount)) for invoice in all_invoices: if has_tenants: shares[invoice] = invoice.get_fraction_for_receivable_type( receivable_type) else: shares[invoice] = Fraction( invoice.rows.filter( receivable_type=receivable_type).count(), total_row_count, ) all_shares += shares[invoice] if all_shares != 1: raise RuntimeError("Shares together do not equal 1/1") credit_invoiceset = InvoiceSet.objects.create( lease=self.lease, billing_period_start_date=self.billing_period_start_date, billing_period_end_date=self.billing_period_end_date, ) total_credited_amount = Decimal(0) for i, (invoice, fraction) in enumerate(shares.items()): invoice_credit_amount = Decimal( amount * Decimal(fraction.numerator / fraction.denominator)).quantize( Decimal(".01"), rounding=ROUND_HALF_UP) total_credited_amount += invoice_credit_amount # If this is the last share, check if we need to round if i == len(shares) - 1 and total_credited_amount.compare( amount) != Decimal("0"): invoice_credit_amount += amount - total_credited_amount credit_invoice = invoice.create_credit_invoice( amount=invoice_credit_amount, receivable_type=receivable_type, notes=notes, ) credit_invoiceset.invoices.add(credit_invoice) return credit_invoiceset
def create_credit_invoice( # noqa C901 TODO self, row_ids=None, amount=None, receivable_type=None, notes=""): """Create a credit note for this invoice""" if self.type != InvoiceType.CHARGE: raise RuntimeError( 'Can not credit invoice with the type "{}". Only type "{}" allowed.' .format( self.type.value if self.type else self.type, InvoiceType.CHARGE.value, )) row_queryset = self.rows.all() if row_ids: row_queryset = row_queryset.filter(id__in=row_ids) if receivable_type: row_queryset = row_queryset.filter(receivable_type=receivable_type) row_count = row_queryset.count() if not row_count: raise RuntimeError("No rows to credit") total_row_amount = row_queryset.aggregate(sum=Sum("amount"))["sum"] previously_credited_amount = InvoiceRow.objects.filter( invoice__in=self.credit_invoices.all(), receivable_type_id__in=[ r.receivable_type for r in row_queryset.all() ], ).aggregate(sum=Sum("amount"))["sum"] if not previously_credited_amount: previously_credited_amount = Decimal(0) if amount: if total_row_amount.compare(amount) == Decimal(-1): raise RuntimeError( "Cannot credit more than invoice row amount") non_credited_amount = total_row_amount - previously_credited_amount if non_credited_amount.compare(amount) == Decimal(-1): raise RuntimeError( "Cannot credit more than total amount minus already credited amount" ) elif previously_credited_amount: # If crediting fully but there are previous credits, use the remaining amount amount = total_row_amount - previously_credited_amount has_tenants = row_queryset.filter( tenant__isnull=False).count() == row_count new_denominator = None if has_tenants: new_denominator = row_queryset.aggregate(new_denominator=Sum( "tenant__share_numerator"))["new_denominator"] today = timezone.now().date() credit_note = Invoice.objects.create( lease=self.lease, type=InvoiceType.CREDIT_NOTE, recipient=self.recipient, due_date=self.due_date, invoicing_date=today, state=InvoiceState.PAID, total_amount=Decimal(0), billed_amount=Decimal(0), billing_period_start_date=self.billing_period_start_date, billing_period_end_date=self.billing_period_end_date, credited_invoice=self, notes=notes, ) total_credited_amount = Decimal(0) row_count = row_queryset.count() for i, invoice_row in enumerate(row_queryset): if amount: if has_tenants: invoice_row_amount = Decimal( amount * Decimal(invoice_row.tenant.share_numerator / new_denominator)).quantize( Decimal(".01"), rounding=ROUND_HALF_UP) else: invoice_row_amount = Decimal(amount) / row_count else: invoice_row_amount = invoice_row.amount total_credited_amount += invoice_row_amount # If this is the last row, check if we need to round if (amount and i == row_count - 1 and total_credited_amount.compare(amount) != Decimal("0")): difference = amount - total_credited_amount invoice_row_amount += difference total_credited_amount += difference InvoiceRow.objects.create( invoice=credit_note, tenant=invoice_row.tenant, receivable_type=invoice_row.receivable_type, billing_period_start_date=invoice_row. billing_period_start_date, billing_period_end_date=invoice_row.billing_period_end_date, amount=invoice_row_amount, ) credit_note.total_amount = total_credited_amount credit_note.save() self.update_amounts() return credit_note
def update_amounts(self): rows_sum = self.rows.aggregate(sum=Sum("amount"))["sum"] if not rows_sum: rows_sum = Decimal(0) self.billed_amount = rows_sum if not self.invoiceset: self.total_amount = rows_sum else: # Sum amounts from all of the rows in the same type of invoices in this invoiceset invoiceset_rows_sum = InvoiceRow.objects.filter( invoice__invoiceset=self.invoiceset, invoice__type=self.type, invoice__deleted__isnull=True, deleted__isnull=True, ).aggregate(sum=Sum("amount"))["sum"] if not invoiceset_rows_sum: invoiceset_rows_sum = Decimal(0) # Update sum to all of the same type invoices in this invoiceset self.invoiceset.invoices.filter( type=self.type, deleted__isnull=True).exclude( id=self.id).update(total_amount=invoiceset_rows_sum) # Need to set self total_amount separately because the # total_amount is not automatically refreshed from the # database self.total_amount = invoiceset_rows_sum payments_total = self.payments.aggregate(sum=Sum("paid_amount"))["sum"] if not payments_total: payments_total = Decimal(0) # Aggregating like this ignores the manager (i.e. includes deleted rows which we don't want): # total_credited_amount = self.credit_invoices.aggregate(sum=Sum("rows__amount"))["sum"] # ... so we have to iterate the rows and tally the sum by hand total_credited_amount = Decimal(0) for credit_inv in self.credit_invoices.all(): for row in credit_inv.rows.all(): total_credited_amount += row.amount collection_charge = Decimal(0) if self.collection_charge: collection_charge = self.collection_charge self.outstanding_amount = max( Decimal(0), self.billed_amount + collection_charge - payments_total - total_credited_amount, ) # Don't mark as refunded unless credited amount is nonzero if total_credited_amount != Decimal( 0) and total_credited_amount.compare( self.billed_amount) != Decimal(-1): self.state = InvoiceState.REFUNDED elif self.type == InvoiceType.CHARGE and self.outstanding_amount == Decimal( 0): self.state = InvoiceState.PAID self.save()
def price_order(old_entry, update_entry, sideOrder): old_price = Decimal(old_entry['price']) update_price = Decimal(update_entry['price']) order = old_price.compare(update_price) if sideOrder == SideOrder.ASCENDING: return order return -order
def zero_size(entry): size = Decimal(entry['size']) return size.compare(Decimal('0.00')) == 0
def actualizar(self): #estado = evento.wait() # aqui el wait y nal final de la funcion activamos con set self.root.evento.set() dato = str.encode("B") print("Enviando B") s.send(dato) #cambiamos la imagen de actualizar self.img_update.source= 'update1.png' data= s.recv(1024) print(data) datas=data.decode() if data != b'A': with open('update.txt', "w") as f: f.write(datas) #for ch in data: #f.write(datas) sleep(0.5) with open('update.txt', "r") as f: strin=str(datas) dataa=f.read() print(dataa) print(type(dataa)) JSON = json.loads(dataa) print(JSON) print(type(JSON)) if "c1" in JSON: print("La corriente 1 es:", JSON["c1"]) #convertimo esto en decimal para usar la libreria corriente1=eval(JSON.get("c1")) co_decimal=Decimal(corriente1) if co_decimal.compare(Decimal(0.1)) <= Decimal(0.1): #NO hay corriente, por lo tanto no hay voltaje #para solventar esto, hayq eu colocar un sensor de voltaje corriente1=0 else: print ("Si Hay corriente") #print(corriente1) potencia1= str(float(corriente1)*120) #setiamos la potencia self.p1.text=potencia1 print(type(corriente1)) #setiamos la corriente self.i1.text=str(corriente1) #setiamos la corriente IRMS corrienteRMS=str(float(corriente1)*.707) #corriente*sqrt(2) self.i1rms.text=corrienteRMS elif "i_alerta" in JSON: print("Corriente ALERTA:", JSON["i_alerta"]) corrientem=str(eval(JSON.get("i_alerta"))) ################################################################################################ NOTIFICACIONES #Generamos la notificacion con vibracion title = b"Alerta".decode('utf8') message = f" Alerta de corriente" ticker = "La corriente tiene un valor de:" + corrientem + "superando el valor maximo" app_name = "conexion" app_icon = "plyer-icon.png" toast = True notification.notify(title=title, message=message, app_name=app_name, app_icon=app_icon, timeout=10, ticker=ticker, toast=toast ) #ponemos a vibrar el telefono vibrator.vibrate(10) else: print ("No se encuentra") #evento.set() return corriente1
def calculate(): first_number = ((request.form['first number']).replace(',', '.')) second_number = ((request.form['second number']).replace(',', '.')) exp_form = "^([0-9]+[.]?[0-9]*|[0-9]*[.][0-9]+)[eE][+-]?[0-9]+$" comp = re.compile(exp_form) if comp.match(first_number) or comp.match(second_number): return render_template('error_exp.html', first_number=first_number, second_number=second_number) if not check_format(first_number) or not check_format(second_number): return render_template('error_res_range.html', error_message='INVALID FORMAT!', result='Error') else: first_number = first_number.replace(' ', '') second_number = second_number.replace(' ', '') try: first_number = Decimal(first_number) second_number = Decimal(second_number) except InvalidOperation: return render_template('error_res_range.html', error_message='You need to enter numbers!', result='Error') # check format with spaces! if (first_number.compare(LOWER_BOUND) == Decimal('-1') or first_number.compare(UPPER_BOUND) == Decimal('1')) \ or (second_number.compare(LOWER_BOUND) == Decimal('-1') or second_number.compare(UPPER_BOUND) == Decimal('1')): return render_template('error_exp.html', first_number=first_number, second_number=second_number) if request.form.get('sum') is not None: result = first_number + second_number if request.form.get('diff') is not None: result = first_number - second_number if request.form.get('composition') is not None: result = first_number * second_number if request.form.get('division') is not None: try: result = first_number / second_number except ZeroDivisionError: return render_template('error_res_range.html', error_message='You cannot divide by zero!', result='Error') if result.compare(LOWER_BOUND) == Decimal('-1') or result.compare( UPPER_BOUND) == Decimal('1'): return render_template( 'error_res_range.html', error_message= 'Error! Result must be between 1 000 000 000 000 000.00 and -1 000 000 ' '000 000 000.00', result=result) # result = "%.6f" % result result = ceil(result * 1000000) / 1000000.0 result = f'{result:,}'.replace(',', ' ') # result = re.sub(r'((\d)[ ]*(\d))*', r'\1\2', result) return render_template('result.html', first_number=first_number, second_number=second_number, result=result)