I am trying to give arguments to my function by adding URL parameter.
import json
import flask
def location_sort(request):
request_json = request.get_json()
location = json.dumps(request_json)
location = json.loads(location)
reverse_location = {v: k for k, v in location.items()}
x = location.keys()
harf_x = (float(max(x)) + float(min(x))) / 2
y_right = []
y_left = []
sorted_location = []
for i in location:
if float(i) < harf_x:
y_left.append(location[i])
else:
y_right.append(location[i])
y_left.sort()
y_right.sort(reverse=True)
sorted_input = y_left + y_right
for i in sorted_input:
sorted_location.append([reverse_location[i], i])
for i in sorted_location:
i[0],i[1] = float(i[0]),float(i[1])
return sorted_location
def cal_centroid(location):
area = 0 # 면적
centroid_x = 0
centroid_y = 0
temp = 0
for i in range(len(location)):
if i == len(location)-1:
temp = location[i][0]*location[0][1] - location[0][0]*location[i][1]
area += temp*0.5
centroid_x += (location[i][0] + location[0][0]) * temp
centroid_y += (location[i][1] + location[0][1]) * temp
else:
temp = location[i][0]*location[i+1][1] - location[i+1][0]*location[i][1]
area += temp*0.5
centroid_x += (location[i][0] + location[i+1][0]) * temp
centroid_y += (location[i][1] + location[i+1][1]) * temp
centroid_x = round(centroid_x / (6*area), 6)
centroid_y = round(centroid_y / (6*area), 6)
x = [centroid_x, centroid_y]
return json.dumps(x)
def main(request):
request_args = request.args
if request_args and "location" in request_args:
request = request["location"]
request = json.dumps(request)
a = location_sort(request)
return cal_centroid(a)
This is my code for Cloud Function and i run main function. And i tried the URL as
https://<REGION>-<GOOGLE_CLOUD_PROJECT>.cloudfunctions.net/FUNCTION_NAME?location={"37.284213":"127.006481","37.562045":"127.034809","37.528694":"126.907483","37.411124":"127.124356"}
And it returns
Error: could not handle the request
What could be the problem to my code? I am very beginner for GCF and i would be very thankful for your help:)
Related
I am trying to build a simple form which calculates which machine would run a film width the quickest, the parameters and capabilities of each machine are held in a django model.
The width of the film and how much of it will be entered in the form and the quantity needed. The function should work out which machine(s) can run it, what the max speed is and the average speed over the machines that are capable.
I want to return the values of the calculation and maybe run a for loop and display the values for each machine in a results.html template in a table. I also want to display average times across machines capable of running the widths of film.
I had some success with lists but would like to use a class that I can use in the template and do away with the lists.
Any help with this would be much appreciated as I am getting pretty lost in it!
I have only started on the 'Layflat Tubing' function in the hope that I can get it right and just copy down to the other functions.
from django.views.generic.base import TemplateView
from django.shortcuts import render
import math, datetime
from settings.models import Extruder
class Result:
def __init__(self, ext_no, width, speed=0, ):
self.ext_no = ext_no
self.width = width
self.speed = speed
def __str__(self):
return self.ext_no
extruders = Extruder.objects.all()
class FilmSpeedView(TemplateView):
template_name = 'calculations/film-speed.html'
class BagWeightView(TemplateView):
template_name = 'calculations/bag-weight.html'
class CalculatorsView(TemplateView):
template_name = 'calculations/calculators.html'
def result(request):
film_type=''
film_width=''
measure=''
speeds = [0]
quantity = 0
max_speed = 0
ave_speed = 0
ave_time = 0
max_time = 0
a=[]
b=[]
c=[]
d=[]
e=[]
if request.method=="GET":
film_type = str(request.GET["film_type"])
film_width = int(request.GET["film_width"])
edge_trim = int(request.GET["edge_trim"])
quantity =int(request.GET["quantity"])
measure = str(request.GET["measure"])
if measure == "metric":
film_width = int(film_width)
else:
film_width = film_width * 25.4
if edge_trim is None:
edge_trim = 0
else:
edge_trim = int(edge_trim)
if str(film_type) == 'Layflat Tubing':
film_type = "LFT"
for extruder in extruders:
bur = film_width / extruder.die_size
if film_width < extruder.min_width:
b.append(extruder.name + ' : Film too narrow')
extruder = Result(ext_no = extruder.ext_no, width = 'too narrow')
elif film_width > extruder.max_width:
b.append(extruder.name + ' : Film too wide')
extruder = Result(ext_no = extruder.ext_no, width = 'too wide')
else:
percentage = film_width / extruder.max_width
speed = extruder.max_kgs_hr * percentage
extruder = Result(ext_no = extruder.ext_no, speed = round(extruder.max_kgs_hr * percentage, 2), width = 'ok')
speeds.append(speed)
max_speed = max(speeds)
ave_speed = sum(speeds) / len(speeds)
ave_time = float(quantity) / ave_speed * 60.0
max_time = float(quantity) / max_speed * 60.0
else:
film_type = "Invalid Film Type"
m = a
n = b
o = c
g = str(round(ave_speed, 2)) + 'kg\'s/h'
h = str(datetime.timedelta(minutes=ave_time))
i = str(datetime.timedelta(minutes=30))
j = str(round(max_speed, 2)) + 'kg\'s/h'
k = str(datetime.timedelta(minutes=max_time))
return render(request, 'calculations/result.html', {'a':a, 'b':b, 'c':c, 'd':d, 'e':e, 'g':g, 'h':h, 'i':i, 'j':j, 'k':k, 'm':m, 'n':n, 'o':o, 'bur':bur,})
I want to use boost.python to use multi-index columns dataframe in c++.
※multi-index columns dataframe is like
I changed the type of multi-index columns dataframe into csv.
My csv file looks like this on spreadsheet
The reason why I want to use this data is for backtest. This is my backtest code in python that I want to translate to c++.
import pandas as pd
import numpy as np
from utils import load_data, load_list_csv, to_int
class No_Strategy():
def __init__(self, codes, unit, cash, position):
self.codes = codes
self.unit = unit
self.cash = cash
self.buy_signal = [0]*len(codes)
self.sell_signal = [0]*len(codes)
self.valid = 0
self.position = position
self.pass_st = 0 # 전략에 들어가지도 못한 경우
def set_data(self, prev_fs_row, fs_row, indi_row):
self.prev_fs = prev_fs_row
self.fs = fs_row # multi dimensional df
self.indi = indi_row
def _strat(self, prev_fs, curr_fs, curr_indi):
curr_rev = prev_rev = curr_ni = prev_ni = ni_growth = curr_asset = noncurr_asset = curr_asset_rat = 0
try:
prev_rev = int(prev_fs['매출액'].replace(",",""))
curr_rev = int(curr_fs['매출액'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
rev_growth=(curr_rev-prev_rev)/prev_rev
try:
prev_ni = int(prev_fs['당기순이익'].replace(",",""))
curr_ni = int(curr_fs['당기순이익'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
ni_growth=(curr_ni-prev_ni)/prev_ni
try:
curr_asset = int(curr_fs['유동자산'].replace(",",""))
noncurr_asset = int(curr_fs['비유동자산'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
curr_asset_rat = curr_asset / noncurr_asset
#### this is the buy strategy! You can change the below ####
if (curr_indi.golden_cross) or (curr_indi.rsi_k < 0.65) :
return 1, 0
#### ************************************************** ####
#### this is the sell strategy! You can change the below ####
if (curr_indi.dead_cross):
return 0, 1
#### ************************************************** ####
return 0, 0
def run(self):
for i, code in enumerate(self.codes):
self.valid = 0
prev_fs = self.prev_fs[code]
curr_fs = self.fs[code]
curr_indi = self.indi[code]
prev_fs_cell = None
curr_fs_cell = None
try:
prev_fs_cell = prev_fs.iloc[0].replace(",","")
try:
curr_fs_cell = curr_fs.iloc[0].replace(",","")
except:
self.pass_st += 1
pass
except:
self.pass_st += 1
pass
if (curr_fs_cell != None) & (prev_fs_cell != None):
self.valid = 1
buy, sell = self._strat(prev_fs, curr_fs, curr_indi)
if self.valid == 0:
self.pass_st += 1
continue
else: # buy or sell signal get
price = curr_indi['close']
if buy:
if self.cash >= self.unit * price:
self.buy_signal[i] = self.unit
self.position[i] += self.unit
self.cash -= price * self.unit
elif sell:
if self.position[i] > 0 :
sell_num = self.position[i] - int(self.position[i]/2)
self.sell_signal[i] = sell_num
self.position[i] = int(self.position[i]/2) # 1-> 1 sell, 4 -> 2 sell ....
self.cash += price * sell_num
##title
class Broker():
def __init__(self, codes):
self.cash = 200000000 #2억
self.cash_df = None #pd.DataFrame(columns=['cash'])
self.position = [0]*len(codes)
self.position_df = None #pd.DataFrame(columns=codes) # for accumulated profit calculation
self.buy_signal = None #pd.DataFrame(columns=codes) # codes = KOSPI_stock_names
self.sell_signal = None #pd.DataFrame(columns=codes)
self.codes = codes # 012934, 3281, ...
self.unit = 1 # 주식 매매 단위
self.pass_st = 0
def set_strat(self, strategy):
self.strategy = strategy # class
def set_time(self, time_index): # time_index type: pd.Index / time range for indi df
self.buy_signal = pd.DataFrame(columns = self.codes, index = time_index) #set_index(time_index)
self.sell_signal = pd.DataFrame(columns = self.codes, index = time_index) #.set_index(time_index)
self.position_df = pd.DataFrame(columns = self.codes, index = time_index)
self.cash_df = pd.DataFrame(columns = ['cash'], index = time_index)#.set_index(time_index)
self.time_index = time_index
def set_data(self, fs, indi, price):
self.fs = fs # multi dimensional df / start: 0th - nth
self.indi = indi # multi dimensional df / start : 1th - nth
self.price = price # 2 dimensional (date X codes : close price)
def update_data(self, strategy, date):
self.cash = strategy.cash
self.cash_df.loc[date] = strategy.cash
self.position = strategy.position
self.position_df.loc[date] = strategy.position #list
self.buy_signal.loc[date] = strategy.buy_signal #list
self.sell_signal.loc[date] = strategy.sell_signal #list
self.pass_st += strategy.pass_st
def run(self):
for date in self.time_index: #아마 수정해야 할 확률 높음
if date.year == 2021:
break
else:
prev_fs_row = self.fs.loc[date.year-1] # ex: 2014
fs_row = self.fs.loc[date.year] # 2015
indi_row = self.indi.loc[date] # 2015
strategy = self.strategy(self.codes, self.unit, self.cash, self.position)
strategy.set_data(prev_fs_row, fs_row, indi_row)
strategy.run()
self.update_data(strategy, date)
def performance(self):
# !!!! 2020년까지의 결과만 성능 평가 ####
cash_df = self.cash_df[self.cash_df.index < '2021']
position_df = self.position_df[self.position_df.index < '2021']
price = self.price[self.price.index < '2021']
buy_signal = self.buy_signal[self.buy_signal.index < '2021']
sell_signal = self.sell_signal[self.sell_signal.index < '2021']
last_price = price.iloc[-1]
total_remain_num = self.position # last(2020) position data
total_buy = (price * buy_signal).sum(axis=1).sum()
total_sell = (price * sell_signal).sum(axis=1).sum()
total_remain = (last_price * total_remain_num).sum()
print(f'remain 개수: {total_remain_num}, total_remain: {total_remain} total_buy: {total_buy}, total_sell={total_sell}')
profit = total_sell + total_remain - total_buy
try:
return_mean = profit / total_buy
except:
print("no buy")
return
accum_df = (cash_df['cash'] + ((price.fillna(0) * position_df).sum(axis=1))).to_frame() # row sum
daily_return_df = (accum_df - accum_df.shift(1))/accum_df.shift(1)-1
SSE = ((daily_return_df - return_mean)**2).sum().item()
std = np.sqrt(SSE/(accum_df.shape[0]-1)) # route(sigma(x-x_bar)^2 / (n-1))
sharp = return_mean / std
self.return_mean = return_mean
self.sharp = sharp
print(f'return_mean: {return_mean}, sharp: {sharp}')
code_path = GDRIVE_DATA_PATH + 'codes.csv'
fs_path = GDRIVE_DATA_PATH + 'fs_total.csv'
indi_path = GDRIVE_DATA_PATH + 'indi_total.csv'
price_path = GDRIVE_DATA_PATH + 'prices.csv'
fs_total = load_data("fs_total.csv")
indi_total = load_data("indi_total.csv") # stock price and indicator(Golden cross, RSI, etc.)
prices = load_data("prices.csv") # stock close price data rows:date, cols: stock code.
time_index = indi_total.index # time index of indi_total multi-index columns
broker = Broker(codes)
broker.set_strat(No_Strategy)
broker.set_time(time_index)
broker.set_data(fs_total, indi_total, prices)
broker.run()
broker.performance()
I want to translate it not changing much in flow of the code.
But I cannot find how to get multi-index columns dataframe in c++, and transfer its row data to No_Strategy to decide whether invest into the stock.
※ I uploaded similar question before and get thankful answer, but it is too complicated for me so I question one more time with detail information.
look at https://github.com/hosseinmoein/DataFrame. It has about 95% of Pandas functionality in a much faster framework
model = ConcreteModel()
model.time = Set(initialize = range(24*3))
model.option = Set(initialize = range(4))
model.time_soc = Var(model.time, bounds = (0.1,0.9), domain=PositiveReals)
model.time_option = Var(model.time, model.option, domain = Binary)
model.soc_param = Param(model.option, initialize={0:0, 1:-0.025, 2:-0.05, 3:0.125})
model.soc_ini = Param(initialize = 0.5)
def cons_time_opt(model, i):
total_choice = sum(model.time_option[i,j] for j in model.option)
return total_choice == 1
model.opt = Constraint(model.time, rule = cons_time_opt)
model.soc_con0 = Constraint(0.5 + model.time_option[0,j]*model.soc_param[j] == model.time_soc[0] for j in model.option)
I got the following error:
ERROR: Constructing component 'soc_con0_index' from data=None failed:
TypeError: Problem inserting time_soc[0] == 0.5 into set soc_con0_index
I'm guessing the soc_con0 constraint is meant to be an indexed constraint in which case you are missing a constraint rule. It should be:
def soc_con0_rule(model, j):
return 0.5 + model.time_option[0,j]*model.soc_param[j] == model.time_soc[0]
model.soc_con0 = Constraint(model.option, rule=soc_con0_rule)
I am using below code snippet to get the red reduced price from amazon but simehow I am always getting the old price and not the reduced red one.
enter code here`def getSignedUrlAmazon(searchvalue):
params = {'ResponseGroup':'Medium',
'AssociateTag':'',
'Operation':'ItemSearch',
'SearchIndex':'All',
'Keywords':searchvalue}
action = 'GET'`enter code here`
server = "webservices.amazon.in"
path = "/onca/xml"
params['Version'] = '2011-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# Now sort by keys and make the param string
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
# Combine key value pairs into a string.
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
# Add the method and path (always the same, how RESTy!) and get it ready to sign
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
# Sign it up and make the url string
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
forgot the price grabbing part:
def getDataAmazon(searchvalue,PRICE, lock):
try:
searchvalue = removeStopWord(searchvalue)
url = getSignedUrlAmazon(searchvalue)
data = etree.parse(url)
root = objectify.fromstring(etree.tostring(data, pretty_print=True))
gd=[]
gd1=[]
counter = 0
if hasattr(root, 'Items') and hasattr(root.Items, 'Item'):
for item in root.Items.Item:
cd={}
priceCheckFlag = False
try :
if hasattr(item.ItemAttributes, 'EAN'):
cd['EAN'] = str(item.ItemAttributes.EAN)
elif hasattr(item, 'ASIN'):
cd['ASIN'] = str(item.ASIN)
cd['productName'] = str(item.ItemAttributes.Title)
if hasattr(item, 'SmallImage'):
cd['imgLink'] = str(item.SmallImage.URL)
elif hasattr(item, 'MediumImage'):
cd['imgLink'] = str(item.MediumImage.URL)
cd['numstar'] = "0"
cd['productdiv'] = '1'
cd['sellername'] = 'Amazon'
if hasattr(item, 'DetailPageURL'):
cd['visitstore'] = str(item.DetailPageURL)
if hasattr(item.ItemAttributes, 'ListPrice') and hasattr(item.ItemAttributes.ListPrice, 'Amount'):
cd['price'] = item.ItemAttributes.ListPrice.Amount/100.0
elif hasattr(item, 'OfferSummary') and hasattr(item.OfferSummary, 'LowestNewPrice'):
cd['price'] = item.OfferSummary.LowestNewPrice.Amount/100.0
I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes)
Am I over-thinking this?
Code:
def lindexsplit(List,*lindex):
index = list(lindex)
index.sort()
templist1 = []
templist2 = []
templist3 = []
breakcounter = 0
itemcounter = 0
finalcounter = 0
numberofbreaks = len(index)
totalitems = len(List)
lastindexval = index[(len(index)-1)]
finalcounttrigger = (totalitems-(lastindexval+1))
for item in List:
itemcounter += 1
indexofitem = itemcounter - 1
nextbreakindex = index[breakcounter]
#Less than the last cut
if breakcounter <= numberofbreaks:
if indexofitem < nextbreakindex:
templist1.append(item)
elif breakcounter < (numberofbreaks - 1):
templist1.append(item)
templist2.append(templist1)
templist1 = []
breakcounter +=1
else:
if indexofitem <= lastindexval and indexofitem <= totalitems:
templist1.append(item)
templist2.append(templist1)
templist1 = []
else:
if indexofitem >= lastindexval and indexofitem < totalitems + 1:
finalcounter += 1
templist3.append(item)
if finalcounter == finalcounttrigger:
templist2.append(templist3)
return templist2