Exemple #1
0
    def test_order(self):
        s = "is2 Thi1s T4est 3a"
        self.assertEqual(order(s), "Thi1s is2 3a T4est")

        s = "4of Fo1r pe6ople g3ood th5e the2"
        self.assertEqual(order(s), "Fo1r the2 g3ood 4of th5e pe6ople")

        s = "d4o dru7nken sh2all w5ith s8ailor wha1t 3we a6"
        result = "wha1t sh2all 3we d4o w5ith a6 dru7nken s8ailor"
        self.assertEqual(order(s), result)

        self.assertEqual(order(""), "")

        self.assertEqual(order("3 6 4 2 8 7 5 1 9"), "1 2 3 4 5 6 7 8 9")
Exemple #2
0
def initialize(context):  # 初始化函数,设定要操作的股票、基准等等.
    # 定义一个全局变量, 保存要操作的股票.
    g.security = '600218.XSHG'
    # 加载统计模块
    g.order = order.order()
    # 设定沪深300作为基准
    set_benchmark('000001.XSHG')
Exemple #3
0
def extract(tripleset, template, entitymap, corenlp):
    sentences = []
    try:
        out = corenlp.annotate(template.strip(), properties=props)
        out = json.loads(out)

        for snt in out['sentences']:
            sentence = ' '.join(map(lambda w: w['originalText'], snt['tokens']))
            sentences.append(sentence)
    except:
        print('Parsing error...')

    templates = []
    for i in range(len(sentences)):
        idx = i+1

        for j, snt in enumerate(sentences):
            snts = sentences[j:j+idx]
            if len(snts) == idx:
                template_ = ' '.join(snts)
                orderedset = order.order(copy.deepcopy(tripleset), template_, entitymap)

                orderedset_, template_ = format(orderedset, template_, entitymap)
                templates.append((orderedset_, template_))

    return templates
Exemple #4
0
 def test_order(self):
     test = [[False, False, False, False, False],
             [False, False, True, False, True],
             [True, False, False, False, True],
             [False, False, True, False, False],
             [True, False, False, False, False]]
     self.assertEqual(order(test), [0, 4, 2, 1, 3])
    def test_stripOrder(self):
        """
        tests if the stripOrder function correctly strips order and returns correct list
        """
        orderCheck = order()
        decodedOrder = orderCheck.stripOrder("3 1,2 3,2")

        orderList = [1, 2, 3, 2]
        self.assertEquals(orderList, decodedOrder)
Exemple #6
0
 def create_order(self,customer_id):
     try:
         check_customer(customer_id)
     except OrderingError as error:
         return error.errors
     cus = customer(customer_id)
     self._orderid = self._orderid + 1
     self._totalorder.append(order(customer_id))
     self._customer.append(cus)
     return {}
Exemple #7
0
def start():
    print(qs.greet1)
    q1 = str(input(qs.greet2))
    if q1 in qs.greet2_p:
        print(qs.qs2_good)
    elif q1 in qs.greet2_n:
        print(qs.qs2_bad)
    global q2
    q2 = int(input(qs.greet3))
    if (q2 == 0):
        print(qs.greet5)
    elif (0 < q2 <= 12):
        print(qs.qs3)
        print(qs.greet4)
        print(mn.menu)
        order.order()
    else:
        print(qs.greet6[0:23], q2, qs.greet6[23:])
        print(qs.greet5)
Exemple #8
0
def send_buy(message):
    words = message.text.split()
    if (valid_order(words)):
        user = message.from_user.username  ##get @username of the sender
        amount = float(words[1])  ##string to float
        price = float(words[2])
        myorder = order(user, amount, price, 'b')  ## b is buy order category
        tauorderbook.add_bid(myorder)
        tbot.reply_to(
            message,
            "user {} added order n~{} for {}TAU with price {}$ total {}$".
            format(user, myorder.id, amount, price, myorder.total))
Exemple #9
0
def send_sell(message):
    words = message.text.split()
    if (valid_order(words)):
        user = message.from_user.username
        amount = float(words[1])
        price = float(words[2])
        myorder = order(user, amount, price, 'a')
        tauorderbook.add_ask(myorder)
        tbot.reply_to(
            message,
            "user {} added sell order n~{} for {}TAU with price {}$ total {}$".
            format(user, myorder.id, amount, price, myorder.total))
 def test_orderFormatCheck(self):
     """
     tests if the format check function returns the correct bool value
     """
     orderCheck = order()
     boolean = orderCheck.orderFormatCheck("3 1,2 3,2")
     self.assertEquals(boolean, True)
     boolean = orderCheck.orderFormatCheck("3 1,2 3,2 4,3,")
     self.assertEquals(boolean, False)
     boolean = orderCheck.orderFormatCheck("3 1")
     self.assertEquals(boolean, False)
     boolean = orderCheck.orderFormatCheck("3 1,,")
     self.assertEquals(boolean, False)
Exemple #11
0
def send_add(message):
    words = message.text.split()
    if (valid_add(words) and is_sender_admin(message)):
        amount = float(words[1])
        price = float(words[2])
        mode = str(words[3])
        name = str(words[4])
        myorder = order(name, amount, price, mode)
        tauorderbook.add_order(myorder)
        tbot.reply_to(
            message,
            "admin added order for {} with n~{} for {}TAU with price {}$ total {}$"
            .format(name, myorder.id, amount, price, myorder.total))
Exemple #12
0
def login():
    n = input('Username: '******'Password: '******'SELECT * FROM customers WHERE name = %s AND password = %s', (n, p))
    data = mycursor.fetchone()
    if data:
        print("Welcome to eShop !")
        from order import order
        order(n)

    else:
        print('Invalid id or password')
        e = input('Press y to register: ')
        if e == 'y':
            mycursor.execute(
                'insert into customers(name,password) values(%s,%s)', (n, p))
            mydb.commit()
            print('Your Id and password is registered !')
            from order import order
            order(n)
        else:
            print('Have a nice day!')
def run_test_location():
    #Step 1) Load restaurant:
    example_restaurant_json_path = data_dir + "restaurant_json/resaurant_id_1_in_n_out.json"
    data_as_dict = load_json_file_as_dict(example_restaurant_json_path)
    sample_restaurant = restaurant(data_as_dict)

    #Step 2) Load order:
    example_order_json_path = data_dir + "order_json/order_id_1.json"
    data_as_dict = load_json_file_as_dict(example_order_json_path)
    sample_order = order(data_as_dict)

    #Step 3) Calculate distance:
    sample_restaurant_location = sample_restaurant.info.location
    sample_order_location = sample_order.info.location
    distance = sample_order_location.caluclate_distance_to_location(sample_restaurant_location)
    print("Distance = {}".format(distance))
def run_eample_three():
    #example 3: load json file of order as order class object, edit data, and write back to json file

    #Step 1) Load json file as dict:
    example_order_json_path = data_dir + "order_json/order_id_1.json"
    data_as_dict = load_json_file_as_dict(example_order_json_path)

    #Step 2) Create restraunt object and read in dict:
    sample_order = order(data_as_dict)

    #Step 3) *optional* update restraunt data:

    #Step 4) Write restraunt to json file:
    sample_order_dict = sample_order.convert_to_dict()
    ##json_pretty_print(sample_order_dict)

    example_order_json_output_path = data_dir + "order_json/sample_order_output.json"
    write_dict_to_json_file(sample_order_dict, example_order_json_output_path)
Exemple #15
0
 def do_order(self,c,user,msg):
     """
     Set order
     format
     """
     bd = self.core.menu.getBandon(msg)
     if len(bd) == 0:
         self.bot.sayTo(c,user,'No bandon on menu')
         return
     else:
         userOrder = self.core.findUserOrder(user)
         if len(userOrder)>0:
             userOrder[0].bandon=bd[0]
             self.bot.sayTo(c,user,'Order Updated')
         else:
             o = order.order(user,bd[0])
             self.core.order.append(o)
             self.bot.sayTo(c,user,'Order Done')
     pass
Exemple #16
0
def main():
    filename = sys.argv[1]
    matrix = parse_file(filename)
    ordering = order(matrix)
    print(' '.join([str(x + 1) for x in ordering]))
Exemple #17
0
def main():
    #Obstacles=[ [ [5,20,25,20,15,5,10,10] , [ 0,0,20,30,30,25,20,5] ] , [ [15,25,20] , [45,45,65]] ,
    #[ [35,40,45,50,45,35,30] , [20,30,20,30,45,45,30]] ]
    Obstacles = [[[5, 10, 15, 13, 10, 8], [15, 20, 15, 25, 30, 25]],
                 [[14, 30, 30, 20, 14], [30, 30, 60, 50, 70]],
                 [[35, 45, 40, 35], [15, 15, 30, 25]]]
    #Obstacles= [ ]
    o = len(Obstacles)
    global origin
    s = [0, 0]
    d = [60, 60]
    x = []
    y = []
    #n=int(input("enter no of points:"))
    convexhull = [[] for i in range(o)]
    print('Convex polygons of the obstacles : ')
    for i in range(o):
        x = Obstacles[i][0]
        y = Obstacles[i][1]
        convexhull[i] = quickhull(x, y)
        #print(convexhull[i])
        order.origin = convexhull[i][0]
        convexhull[i] = order.order(convexhull[i], order.origin)
        print(convexhull[i])

    l = convexhull
    #G=makegraph(convexhull)
    v, e = 0, 0
    S = (0, 0)
    D = (60, 60)
    for i in range(len(l)):
        for j in range(len(l[i])):
            l[i][j] = tuple(l[i][j])
    VG = vgraph()
    VG.findEdges(l, S, D)
    for i in VG.adj:
        v += 1
        for j in VG.adj[i]:
            e += 1
    #print(v,e)
    L = AdjLst(v, e)
    d = {}
    c = 0
    for i in VG.adj:
        d[i] = c
        c += 1
    #l=[[None,None] for i in range(v)]
    c = 0
    #d=sorted(d,key=lambda x :x[1])
    #for i in d:
    #print(d[i])
    for i in d:
        #l[c][0]=i[0]
        #l[c][1]=i[1]
        L.head[d[i]].x = i[0]
        L.head[d[i]].y = i[1]

    for i in d:
        for j in VG.adj[i]:
            L.form(d[i], d[j])

    for i in range(len(L.head)):
        if (L.head[i].x == S[0] and L.head[i].y == S[1]):
            s = L.head[i].value

    for i in range(len(L.head)):
        if (L.head[i].x == D[0] and L.head[i].y == D[1]):
            d = L.head[i].value

    if s < v:
        L.head[s].dist = 0
        L.Dijkstra(s)
        L.printlst(d)
    else:
        print("vertex doesnot exist in given graph")
Exemple #18
0
import threading
import time
import random
import urllib
import urllib2
import re
import time
import ConfigParser
import order

myOrder = order.order()

class mythread(threading.Thread):
	def __init__(self, threadname):
		threading.Thread.__init__(self, name = threadname)

	def run(self):
		myOrder.submit()

def func1():
	num = 0
	while num < 150:
		print num
		t = mythread('t1'+str(num))
		t.start()
		num+=1


func1()
Exemple #19
0
from order import order
from file_manager2 import FileManager

#주문내역 불러오고, 출력하자
file_manager = FileManager("history.bin")
history = file_manager.load()
# if len(history)==0:
#     print("주문내역이 없습니다.")
# else:
sum = 0
for h in history:  #들여쓰기 앞으로 댕기기 (shift+Tab)
    print(h)
    sum += h.price
print("내가 아마스빈에 갖다 바친 돈: " + str(sum) + "원")

#지금 주문하자
o = order()
o.order_drink()

#주문내역 저장하자
file_manager.save(history + o.order_menu)
Exemple #20
0
def main(args):
    initiate(args)
    order(sys.argv)
    Repository.repo.get_conn().commit()
    def shop(self):
        list = []
        mycursor = mydb.cursor()
        mycursor.execute("SELECT * FROM cart")
        myresult = mycursor.fetchall()
        for rows in myresult:
            list.append(rows)

        if not list:
            add_cart.add_cart(self)

            upd_cart.upd_cart(self)

            cart_total.cart_total(self)

            order.order(self)

        else:

            show_cart.show_cart(self)

            cond = int(
                input(
                    "Do you want to review your cart(give input '1') or do you want to clear cart(give input '2'): "
                ))
            if cond == 1:
                review = True
                while review:
                    cond1 = int(
                        input(
                            "Do you want to add an item(give '1' as input) or \n"
                            "Do You want to review/delete any item(give '2' as input) or\n"
                            "Do you want place the order(give '3' as input): ")
                    )
                    if cond1 == 1:
                        add_cart.add_cart(self)
                    elif cond1 == 2:
                        upd_cart.upd_cart(self)
                    else:
                        cart_total.cart_total(self)

                        order.order(self)
                        break
            else:
                mycursor = mydb.cursor()
                mycursor.execute("SELECT Pro_Id FROM cart")
                myresult = mycursor.fetchall()
                for i in myresult:
                    val = i
                    mycursor.execute(
                        "SELECT Quantity FROM cart where Pro_ID = %s", val)
                    myresult1 = mycursor.fetchone()
                    for quant in myresult1:
                        pre = int(quant)
                    mycursor.execute(
                        "SELECT Quantity FROM products where Pro_ID = %s", val)
                    myresult2 = mycursor.fetchone()
                    for proquant in myresult2:
                        ini = int(proquant)

                    post = pre + ini
                    mycursor.execute(
                        "UPDATE products SET Quantity = %s WHERE Pro_ID = %s",
                        (post, val))

                mycursor.execute("TRUNCATE TABLE cart")
                mydb.commit()
                print("your cart has been cleared.\nStart shopping. \n")
                add_cart.add_cart(self)

                upd_cart.upd_cart(self)

                cart_total.cart_total(self)

                order.order(self)
Exemple #22
0
import order

# メールを送信するサンプルコード2
if __name__ == '__main__':
	
	order.order('param', 'Please wait [Run PARAM]...')
def readFile(fileName):
    f = ""

    with open(fileName) as file:
        f = file.read()

    f = f.split("\n")

    firstLine = f[0]
    firstLine = firstLine.split(" ")

    gridx = int(firstLine[0])
    gridy = int(firstLine[1])
    droneCount = int(firstLine[2])
    maxCommands = int(firstLine[3])
    maxPayload = int(firstLine[4])

    secLine = f[1]

    productCount = int(secLine)

    thLine = f[2]
    thLine = thLine.split(" ")

    for i in thLine:
        i = int(i)

    productWeights = thLine

    warehouseCount = int(f[3])
    
    newF = f[4:]

    listofwarehouseobjects = []

    for i in xrange(0, warehouseCount):
        print "loading warehouse: " + str(i)
        flin = newF[0]
        flin = flin.split(" ")

        location = [int(flin[0]), int(flin[1])]

        flin2 = newF[1]
        flin2 = flin2.split(" ")

        wobj = Warehouse.warehouse(location, flin2)

        listofwarehouseobjects.append(wobj)

        newF = newF[2:]

    """print productWeights

    print "Gridx " + str(gridx)
    print "Gridy " + str(gridy)
    print "dronecount " + str(droneCount)
    print "maxcommands " + str(maxCommands)
    print "maxpayload " + str(maxPayload)
    print "product count " + str(productCount)
    print "warehouseCount " + str(warehouseCount)"""

    nOrders = newF[0]
    newF = newF[1:]

    orderList = []

    for i in xrange(0, len(nOrders)):
        line = newF[0]
        line = line.split(" ")
        line[0] = int(line[0])
        line[1] = int(line[1])
        olocation = line
        oquan = int(newF[1])
        line = newF[2]
        line = line.split(" ")
        for j in xrange(0, len(line)):
            line[j] = int(line[j])
        oids = line
        obj = order.order(i, olocation, oquan, oids)

        newF = newF[3:]

    return gridx, gridy, listofwarehouseobjects, droneCount, maxCommands, maxPayload, orderList, productWeights
Exemple #24
0
import order

# メールを送信するサンプルコード3
if __name__ == '__main__':

    order.order('record', 'Please wait [Run RECORD]...')
Exemple #25
0
for line in sys.stdin:
    # remove leading and trailing whitespace

    line = line.strip()
    json_file_paths = line.split()

    for json_file_path in json_file_paths:
        current_json_path = parent_dir + json_file_path
        data_as_dict = load_json_file_as_dict(current_json_path)

        if "order_id" in data_as_dict.keys():
            if current_order is not None:
                confirm_order_with_current_lowest_waiting_time_restaurant()
                current_lowest_waiting_time = 999999999999

            current_order = order(data_as_dict)
            current_order_info = get_order_info(current_order.order_id)
        else:
            current_restaurant = restaurant(data_as_dict)
            current_restaurant_estimated_waiting_time = get_estimated_waiting_time(current_order_info, current_restaurant.id)
            current_restaurant_estimated_drive_time = calculate_driving_time(current_order.info.location, current_restaurant.info.location) * 60
            # print("current_restaurant_estimated_waiting_time:", current_restaurant_estimated_waiting_time, ", current_restaurant_estimated_drive_time:", current_restaurant_estimated_drive_time)
            current_restaurant_estimated_waiting_time = max(current_restaurant_estimated_waiting_time, current_restaurant_estimated_drive_time)
            if current_lowest_waiting_time > current_restaurant_estimated_waiting_time:
                current_lowest_waiting_time = current_restaurant_estimated_waiting_time
                current_lowest_waiting_time_restaurant = current_restaurant

# TO-DO: Make some backup restaurants options...

confirm_order_with_current_lowest_waiting_time_restaurant()
Exemple #26
0
import order

# メールを送信するサンプルコード1
if __name__ == '__main__':

    order.order('confirm', 'Please wait [Run CONFIRM]...')
Exemple #27
0
def readFile(fileName):
    f = ""

    with open(fileName) as file:
        f = file.read()

    f = f.split("\n")

    firstLine = f[0]
    firstLine = firstLine.split(" ")

    gridx = int(firstLine[0])
    gridy = int(firstLine[1])
    droneCount = int(firstLine[2])
    maxCommands = int(firstLine[3])
    maxPayload = int(firstLine[4])

    secLine = f[1]

    productCount = int(secLine)

    thLine = f[2]
    thLine = thLine.split(" ")

    for i in thLine:
        i = int(i)

    productWeights = thLine

    warehouseCount = int(f[3])

    newF = f[4:]

    listofwarehouseobjects = []

    for i in xrange(0, warehouseCount):
        print "loading warehouse: " + str(i)
        flin = newF[0]
        flin = flin.split(" ")

        location = [int(flin[0]), int(flin[1])]

        flin2 = newF[1]
        flin2 = flin2.split(" ")

        wobj = Warehouse.warehouse(location, flin2)

        listofwarehouseobjects.append(wobj)

        newF = newF[2:]
    """print productWeights

    print "Gridx " + str(gridx)
    print "Gridy " + str(gridy)
    print "dronecount " + str(droneCount)
    print "maxcommands " + str(maxCommands)
    print "maxpayload " + str(maxPayload)
    print "product count " + str(productCount)
    print "warehouseCount " + str(warehouseCount)"""

    nOrders = newF[0]
    newF = newF[1:]

    orderList = []

    for i in xrange(0, len(nOrders)):
        line = newF[0]
        line = line.split(" ")
        line[0] = int(line[0])
        line[1] = int(line[1])
        olocation = line
        oquan = int(newF[1])
        line = newF[2]
        line = line.split(" ")
        for j in xrange(0, len(line)):
            line[j] = int(line[j])
        oids = line
        obj = order.order(i, olocation, oquan, oids)

        newF = newF[3:]

    return gridx, gridy, listofwarehouseobjects, droneCount, maxCommands, maxPayload, orderList, productWeights
import order
import saving

order.show()
order.add('Cup noodle', 2)
order.add('Cup noodle', 1)
order.add('Fish cake bar', 1)
order.order()
saving.start()
def pow_orders(d, n):
    fs = [1, d] + factor(d)
    for x in range(1, n):
        if order(x, n) in fs:
            print(x)
Exemple #30
0
 def test_1(self):
     result = order("is2 Thi1s T4est 3a")
     self.assertEqual(result, "Thi1s is2 3a T4est")
Exemple #31
0
 def newRec(self, code=0, customer=None, good=None, cost=''):
     self.appendList(order(code, customer, good, cost))
Exemple #32
0
import threading
import time
from cf import *
from showping import showping
from order import order
from memberinfo import member
from time import ctime
from business import Business
import requests
membertoken = shopkeeper_token
businesstoken = supplier_token
admin_token = operation_token
order = order()
memberinfo = member()


class MyThread(threading.Thread):
    a = 0

    def __init__(self):
        super(MyThread, self).__init__()  # 重构run函数必须要写

    def run(self):
        bulidorder = order.bulidorder(membertoken, 1, 2)  # 创建订单
        # trade_no = bulidorder[0]
        # short_no = bulidorder[1]
        # nun = bulidorder[2]
        # pyorder = order.payorder(membertoken, trade_no)  # 余额购买
        #
        # # qxzhifuorder=order.qxzhifuorder(membertoken,short_no) # 取消已支付订单
        # # s=order.nopayquxiao(membertoken,trade_no)
Exemple #33
0
    def algo_1(self, risk, profit, starting_capital=500, testing=False):
        '''Generate buy and sell signals using the SuperTrend Indicator'''

        self.capital = starting_capital
        for stock in self.results.keys():
            all_orders = []
            current_order = None
            trade_profit = 0
            max_drawdown = 0
            max_profit = 0
            capital = self.capital
            current_shares = 0

            data = self.results[stock]
            cash = capital
            stock = stock.upper()
            data = data[[
                stock + "_date", stock + "_average", stock + "_ST",
                stock + "_ST_BUYSELL"
            ]].copy(deep=True)
            data.rename(columns={
                stock + "_date": "date",
                stock + "_average": "price",
                stock + "_ST_BUYSELL": "signal",
                stock + "_ST": "st"
            },
                        inplace=True)
            data = data.dropna()
            stopPrice = -1
            profitPrice = -1

            for i, row in data.iterrows():
                signal = data.loc[i, "signal"]
                price = data.loc[i, "price"]
                date = data.loc[i, "date"]

                # Check to see if signal matches buy conditions
                if equals(signal, "buy") and current_order == None:
                    if capital < price:
                        continue
                    else:
                        current_shares = floor(capital / price)

                    stopPrice = price * (1 - risk)
                    profitPrice = price * (1 + profit)
                    newOrder = order(self.id_counter,
                                     stock,
                                     date,
                                     price,
                                     profitPrice,
                                     stopPrice,
                                     shares=current_shares)
                    current_order = newOrder
                    self.id_counter += 1
                    capital -= (price * current_shares)

                    if testing:
                        print("Bought ", current_shares, " stock at ",
                              current_order.buyPrice)
                        print("Profit: ", trade_profit, "Capital: ", capital,
                              "\n")
                    continue

                # Check for sell conditons and threshold contions - use the new features.
                sell = self.check_sell(date,
                                       price,
                                       current_order,
                                       trade_profit,
                                       max_drawdown,
                                       all_orders,
                                       capital,
                                       max_profit,
                                       testing=testing,
                                       shares=current_shares)
                if sell != None:
                    current_order = sell[0]
                    trade_profit = sell[1]
                    max_drawdown = sell[2]
                    all_orders = sell[3]
                    capital = sell[4]
                    max_profit = sell[5]

                # Check and sell if signal falls below threshold
                if current_order != None and equals(signal, "Sell"):
                    checker = self.threshold(date,
                                             price,
                                             current_order,
                                             trade_profit,
                                             max_drawdown,
                                             all_orders,
                                             capital,
                                             max_profit,
                                             shares=current_shares)
                    current_order = checker[0]
                    trade_profit = checker[1]
                    max_drawdown = checker[2]
                    all_orders = checker[3]
                    capital = checker[4]
                    max_profit = checker[5]

                    if testing:
                        print("Sold ", current_shares,
                              " stock due to siganl threshold at ",
                              current_order.soldPrice)
                        print("Profit: ", trade_profit, "Capital: ", capital,
                              "\n")

                    current_order = None
                    current_shares = 0

            # Resolution of Open Shares
            if current_order != None:
                capital += current_order.get_balance()
                current_order = None
                if all_orders[0] == None:
                    all_orders = all_orders[:-1]
            self.totalProfit[stock] = [
                all_orders, trade_profit, max_profit, max_drawdown, capital
            ]

        self.log()