Esempio n. 1
0
def main():
    rate = int(input("Введите процентную ставку: "))
    money = int(input("Введите сумму: "))
    period = int(input("Введите период ведения счета в месяцах: "))

    result = account.calculate_income(rate, money, period)
    for i in range(len(conv.v)):
        m = conv.convert(money, i)
        r = conv.convert(result, i)
        print("Параметры счета ({0}):\n".format(m[0]),
              "Сумма ({0}): {1}".format(m[0], m[1]), "\n", "Ставка: ", rate,
              "\n", "Период: ", period, "\n",
              "Сумма на счете в конце периода ({0}): {1}".format(r[0], r[1]))
Esempio n. 2
0
def main(argv):
    fromCurrency, toCurrency, amount = loadInput(argv)
    output = convert(fromCurrency, toCurrency, amount)
    if output is None:
        sys.exit("Something went wrong. Please try later or contact IT support.")
    with open("outputFile.json", "w") as file:
        json.dump(output, file, indent=4, sort_keys=True)
Esempio n. 3
0
def convert_value(request):
    """Convert and return json response.
    
    """
    res = conv.convert(request)
    return HttpResponse(json.dumps({
                                    "result": res
                                    }), content_type="application/json")
Esempio n. 4
0
def index():
    fromCurrency = request.args.get('input_currency', '')
    toCurrency = request.args.get('output_currency', '')
    try:
        amount = float(request.args.get('amount', ''))
    except ValueError:
        return "Cannot convert amount to float.", status.HTTP_400_BAD_REQUEST
    if fromCurrency == "":
        return "Input currency is missing.", status.HTTP_400_BAD_REQUEST

    return jsonify(convert(fromCurrency, toCurrency, amount))
Esempio n. 5
0
 def run(self):
     #线程执行的代码
     for (root, dirs, files) in os.walk(self.srcDir):
         for filename in files:
             fpath = os.path.join(root, filename)
             if fpath.endswith(self.extTuple):
                 res = conv.convert(os.path.join(root, filename),
                                    self.outEncode)
                 wx.CallAfter(pub.sendMessage, "updatelogs", msg=res)
             else:
                 pass
     wx.CallAfter(pub.sendMessage, "updatelogs", msg=u'All files done')
Esempio n. 6
0
def test_image(img_name, model):

    classes = [
        "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal",
        "Shirt", "Sneaker", "Bag", "Ankle boot"
    ]
    img = io.imread(img_name)
    print("img.shape", img.shape)

    # Pre-process
    converted = conv.convert(img)

    # write this for debug only
    cv2.imwrite("converted.png", converted)

    # Normalize data
    x = converted.reshape((28, 28, 1))

    x = x.astype('float32')
    x /= 255
    x = np.expand_dims(x, axis=0)

    # load model and predict

    predicted_x = model.predict(x)

    pred_class = np.argmax(predicted_x)
    print('Class:', pred_class, classes[pred_class])

    #NEW: sort and pick the best five
    pairs = list(enumerate(predicted_x[0]))
    pairs.sort(key=lambda x: -x[1])
    top5 = pairs[:5]
    array_top5 = []
    for i, res in enumerate(top5):
        msg = "{}: {}({}) {:.2f}%".format(i, classes[res[0]], res[0],
                                          res[1] * 100)
        array_top5.append(msg)

    return array_top5
Esempio n. 7
0
def test_image(img_name, model_name):

    global model

    img = io.imread(img_name)
    print("img.shape", img.shape)

    converted = conv.convert(img)

    x = converted.reshape((28, 28, 1))

    x = x.astype('float32')
    x /= 255
    x = np.expand_dims(x, axis=0)

    if not model:

        model = load_model(model_name)

    predicted_x = model.predict(x)

    print('!!prediction-x!!', predicted_x)

    pred_class = np.argmax(predicted_x)
    print('Class:', pred_class, classes[pred_class])

    pairs = list(enumerate(predicted_x[0]))
    pairs.sort(key=lambda x: -x[1])
    top5 = pairs[:5]
    print(top5)

    expected_num, expected_class = class_from_filename(img_name)
    print("Expected:", expected_class)

    pred_class_num = top5[0][0]
    if expected_num == pred_class_num:
        print("Match ok:", expected_class, img_name)
    else:
        perc = top5[0][1] * 100
        msg = "Match failed: expected {}({}) was {}({})({:.2f}%) for file {}".format(
            classes[expected_num], expected_num, classes[pred_class_num],
            pred_class_num, perc, img_name)
        print(msg)

        basename = os.path.basename(img_name)
        no_ext_name, ext = os.path.splitext(basename)

        err_name = "errors/" + no_ext_name + "_as_" + classes[
            pred_class_num] + "-" + str(int(perc)) + ext
        shutil.copy(img_name, err_name)

        conv_err_name = "errors/" + no_ext_name + "_as_" + classes[
            pred_class_num] + "-" + str(int(perc)) + "_converted.png"
        #shutil.copy("converted.png", conv_err_name)
        cv2.imwrite(conv_err_name, converted)

    for i, res in enumerate(top5):
        msg = "{}: {}({}) {:.2f}%".format(i, classes[res[0]], res[0],
                                          res[1] * 100)
        print(msg)

    return expected_num, pred_class_num
Esempio n. 8
0
def Parse_all(data):
    dataframe = []
    for unique_match in data:
        r = requests.get(unique_match)
        soup = BeautifulSoup(r.content, "html5lib")
        temp_list = []
        temp_df = []
        try:
            temp_list.append(soup.time.attrs['datetime'])
        except:
            temp_list.append(np.nan)
        try:
            temp_list.append(soup.find("span", attrs={"class": "match__region"}).text)
        except:
            temp_list.append(np.nan)
        try:
            temp_list.append(soup.find("span", attrs={"class": "match__season-number"}).text)
        except:
            temp_list.append(np.nan)
        bans = soup.select("li[class*='list-group-item op']")
        try:
            temp_list.append(bans[0].span.find("span").text)
        except:
            temp_list.append(np.nan)
        try:
            temp_list.append(bans[1].span.find("span").text)
        except:
            temp_list.append(np.nan)
        for ban in bans:
            try:
                temp_list.append(ban.span.find("strong").text)
            except:
                temp_list.append(np.nan)
        ATK = soup.select("td[class*='sp__atk js-heatmap-ignore py-0']")
        DEF = soup.select("td[class*='sp__def js-heatmap-ignore py-0']")
        for operator in range(10):
            try:
                temp_list.append(ATK[operator].span.text)
            except:
                temp_list.append(np.nan)
            try:
                temp_list.append(DEF[operator].span.text)
            except:
                temp_list.append(np.nan)
        match = soup.select("li[class*='log__line']")
        try:
            temp_list.append(" ".join(conv.convert([match[-1].find("strong").next_sibling])[1:]))
        except:
            temp_list.append(np.nan)
        for round in range(len(match) - 1):
            new_list = temp_list.copy()
            temp_text = conv.convert([match[round].find("strong").next_sibling])
            try:
                new_list.append(round + 1)
            except:
                new_list.append(np.nan)
            try:
                new_list.append(match[round].find("strong").text)
            except:
                new_list.append(np.nan)
            try:
                if (temp_text[1] == "Aviator/Game"):
                    new_list.append("Aviator/Game Room")
                elif (temp_text[1] == "Open"):
                    new_list.append("Open Area/Kitchen")
                elif (temp_text[1] == "Armory/Throne"):
                    new_list.append("Armory/Throne Room")
                elif (temp_text[1] == "Bunk/Day"):
                    new_list.append("Bunk/Day Care")
                elif (temp_text[1] == "Initiatiom"):
                    new_list.append("Initiation Room/Office")
                else:
                    new_list.append(temp_text[1])
            except:
                new_list.append(np.nan)
            try:
                if temp_text[2] != "attack" and temp_text[2] != "defense":
                    new_list.append(temp_text[3])
                else:
                    new_list.append(temp_text[2])
            except:
                new_list.append(np.nan)
            try:
                new_list.append(" ".join(temp_text[4:]))
            except:
                new_list.append(np.nan)
            dataframe.append(new_list)
        time.sleep(5)
    return pd.DataFrame(dataframe, columns=["date of game", "region of game", "season", "Team 1", "Team 2", "1st ban", "2nd ban", "3rd ban", "4th ban", "Operator on ATK1", "Operator on DEF1", "Operator on ATK2", "Operator on DEF2", "Operator on ATK3", "Operator on DEF3", "Operator on ATK4", "Operator on DEF4", "Operator on ATK5", "Operator on DEF5", "Operator on ATK6", "Operator on DEF6", "Operator on ATK7", "Operator on DEF7", "Operator on ATK8", "Operator on DEF8", "Operator on ATK9", "Operator on DEF9", "Operator on ATK10", "Operator on DEF10", "Map name", "round number", "Round winner", "Site location", "Which side won", "How they won"])
Esempio n. 9
0
        files.append(get_pdf_url(args['year'], period))

pdfs = []
print('Downloading PDFs...')
print(files)
for f in files:
    overwrite = True
    filename = f.split('/')[-1]
    if os.path.exists(filename):
        print(f'File exists: {f}')
        overwrite = query_yes_no('Overwrite?', default='no')
    if overwrite:
        wget.download(f)
    pdfs.append(filename)
print('Downloaded PDFs.')

import conv

print('Parsing PDFs ...')
for pdf in pdfs:
    print(f'======== {pdf} ========')
    text = pdfminer.high_level.extract_text(pdf)
    schedule = conv.convert(text)
    if args['json']:
        print(conv.schedule_to_json(schedule))
    else:
        conv.print_schedule(schedule)
    print(f'=======================')

print('Done! Have a nice day.')
Esempio n. 10
0
def callback2():
    e4.configure(state='normal')
    e4.delete(1.0,"end")
    e4.insert(1.0,"".join(convert([temp+"\n" for temp in e3.get(1.0,'end-1c').split("\n") if temp],[0,1,2,3,6],[6])))
    e4.configure(state='disabled')
Esempio n. 11
0
def callback():
    e2.configure(state='normal')
    
    e2.delete(1.0,"end")
    e2.insert(1.0,"".join(convert([temp+"\n" for temp in e.get(1.0,'end-1c').split("\n") if temp],[4],[])))
    e2.configure(state='disabled')
Esempio n. 12
0
import xmlutils
import control
from persistant import get
import position

substitutes = {
     "W":"West","N":"North","S":"South","E":"East",
     "km/h":"kilometers per hour","C":"Celsius","mph":"miles per hours", "kts": "knots",
     "Mon":"Monday","Tue":"Tuesday","Wed":"Wednesday","Thu":"Thursday","Fri":"Friday","Sat":"Saturday","Sun":"Sunday",
     "NNE":"Nor Nor East","NE":"Nor East","ENE":"East Nor East","ESE":"East Sow East",
     "SE":"Sow East" ,"SSE" :"Sow Sow East", "SSW":"Sow Sow West","SW":"Sow West","WSW":"West Sow West",
     "WNW":"West Nor West","NW":"Nor West","NNW":"Nor Nor West",
     "%":"percent"
     }


control.Control("speed",step=10,initial=60)

while True :
   if get("speed").on :
      position = get("gps")
      speed = round(conv.convert(position.speedOverGround,"kt","mph"),1)
      course = int(position.courseOverGround)
      points = conv.degree_to_compass_point(course)
      text = points + " at " + str(speed) + " mph " 
      mtext = speak.expand(text,substitutes)
      speak.say(mtext)
      print(text)

   time.sleep(get("speed").value)