def train(self, training_set_inputs, training_set_outputs,
              number_of_training_iterations):
        for iteration in xrange(number_of_training_iterations):
            # Pass the training set through our neural network (a single neuron).
            output = self.think(training_set_inputs)

            # Calculate the error (The difference between the desired output
            # and the predicted output).
            error = training_set_outputs - output

            # Multiply the error by the input and again by the gradient of the Sigmoid curve.
            # This means less confident weights are adjusted more.
            # This means inputs, which are zero, do not cause changes to the weights.
            adjustment = dot(training_set_inputs.T,
                             error * self.__sigmoid_derivative(output))

            # Adjust the weights.
            self.synaptic_weights += adjustment
Exemplo n.º 2
0
def read_partitions(fp, header, lba_size=512):
    fp.seek(header.part_entry_start_lba * lba_size)
    fmt, GPTPartition = _make_fmt('GPTPartition',
                                  GPT_PARTITION_FORMAT,
                                  extras=['index'])
    for idx in xrange(1, 1 + header.num_part_entries):
        data = fp.read(header.part_entry_size)
        if len(data) < struct.calcsize(fmt):
            raise GPTError('Short partition entry')
        part = GPTPartition._make(struct.unpack(fmt, data) + (idx, ))
        if part.type == 16 * '\x00':
            continue
        part = part._replace(
            type=str(uuid.UUID(bytes_le=part.type)),
            unique=str(uuid.UUID(bytes_le=part.unique)),
            # do C-style string termination; otherwise you'll see a
            # long row of NILs for most names
            name=part.name.decode('utf-16').split('\0', 1)[0],
        )
        yield part
Exemplo n.º 3
0
    def insertionSort(self, array, model):
        counter = 0
        shift = 0
        unsortedArray = array
        model.append(str("Изначальный массив:"))
        model.append(str(unsortedArray))
        model.append(str("Сортировка:"))

        for i in xrange(1, len(array)):
            j = i - 1
            value = array.pop(i)
            model.append(str(array))
            shift += 1
            while (j >= 0) and (array[j] > value):
                j -= 1
                counter += 1
            array.insert(j + 1, value)
            counter += 1
        array.insert(len(array), counter)
        array.insert(len(array), shift)
        return array
Exemplo n.º 4
0
def arePermutation(str1, str2):
    len_str1 = len(str1)
    len_str2 = len(str2)

    if len_str1 != len_str2:
        return 0

    count1 = [0] * NO_CHARS
    count2 = [0] * NO_CHARS

    for i in str1:
        count1[ord(
            i
        )] += 1  # return an integer representing the Unicode code point of the character

    for i in str2:
        count2[ord(i)] += 1

    for i in xrange(NO_CHARS):
        if count1[i] != count2[i]:
            return 0
    return 1
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        nodes = []

        def getNodes(node):
            if node:
                nodes.append(node)
                if node.left:
                    getNodes(node.left)
                if node.right:
                    getNodes(node.right)

        getNodes(root)

        for i in xrange(len(nodes) - 1):
            node = nodes[i]
            node.right = nodes[i + 1]
            node.left = None
        """
Exemplo n.º 6
0
def middle_cod(geneList, genLength):
    onestr = ''.join(geneList)
    amount = (genLength - 6) / 3
    codons = (onestr[n:n + 3]
              for n in xrange(3,
                              len(onestr) - 3, 3))  # creates generator
    dict_codons = {}
    for i in codons:
        if dict_codons.get(i) is not None:
            dict_codons[i] += 1
        else:
            dict_codons[i] = 1
    # sum = 0
    for i in dict_codons:
        dict_codons[i] /= amount
        dict_codons['TAA'] = dict_codons['TGA'] = dict_codons['TAG'] = 0
        dict_codons[i] = round(dict_codons[i], 3)
        # sum += dict_codons[i]
    # print("total sum of frequency=: " + str(sumfre))
    pd.reset_option('display.max_rows')
    df = pd.DataFrame(dict_codons.items(), columns=["codon", "frequency"])
    return df
Exemplo n.º 7
0
def delete_entry(entry_id):
    user = mongo.db.users.find_one({'username': session["user"]})
    entry = mongo.db.entries.find_one({"_id": ObjectId(entry_id)})
    # Deduct from Vacation days if Regular Vacation
    if entry['entry_type'] == "Regular Vacation":
        start_date_from_entry = datetime.strptime(entry["start_date"], '%d %b, %Y')
        end_date_from_entry = datetime.strptime(entry["end_date"], '%d %b, %Y')

        day_generator = (start_date_from_entry + timedelta(x + 1) for x in xrange(
            (end_date_from_entry - start_date_from_entry).days))
        how_many_days_to_add = sum(1 for day in day_generator if day.weekday() < 5) + 1

        update_user_days_before_new_deduction = user['vacation_days'] + how_many_days_to_add
        mongo.db.users.update_one({
            "username": user['username']}, {
            "$set": {
                "vacation_days": update_user_days_before_new_deduction
            }})

    # Next Lets delete the user entry
    mongo.db.entries.remove({"_id": ObjectId(entry_id)})
    flash("Task Successfully Deleted!")
    return redirect(url_for("manage_entries"))
def parseData(log_file_path, export_file, regex, read_line=True):
    with open(log_file_path, "r") as file:
        match_list = []
        if read_line == True:
            for line in file:
                for match in re.finditer(regex, line, re.S):
                    match_text = match.group()
                    match_list.append(match_text)
                    print(match_text)
        else:
            data = file.read()
            for match in re.finditer(regex, data, re.S):
                match_text = match.group();
                match_list.append(match_text)
    file.close()

    with open("output", "w+") as file:
        file.write("EXPORTED DATA:\n")
        match_list_clean = list(set(match_list))
        for item in xrange(0, len(match_list_clean)):
            print(match_list_clean[item])
            file.write(match_list_clean[item] + "\n")
    file.close()
Exemplo n.º 9
0
def rev():
    if len(i) == 0:
        return 0
    else:
        if len(sc) > 0:
            if i[0] != sc[0]:
                r.append(i[0])
                i.pop(0)
            else:
                while len(sc) > 0:
                    for m in xrange(len(sc)):
                        if i[int(m)] == sc[int(m)]:
                            mp = True
                    if mp:
                        i.pop(0)
                        sc.pop(0)
                    else:
                        i.pop(0)
        else:
            r.append(i[0])
            i.pop(0)

        rev()
def frames_per_second(location):
    """
    Calculate FPS
    Inout: Path of the Video
    Output: return list of fps(size 2).
    """

    # video from path
    video = cv2.VideoCapture(location)

    # getting fps
    fps1 = video.get(cv2.CAP_PROP_FPS)

    # Number of frames to capture
    num_frames = 100
    start = time.time()
    # Grab a few frames
    for i in xrange(0, num_frames):
        ret, frame = video.read()
    end = time.time()
    seconds = end - start  # Time elapsed
    fps = num_frames / seconds  # Calculate frames per second
    return [fps1, fps]
Exemplo n.º 11
0
def markPlaceses(board, column, row):

    # check row & columns
    i = -1
    while i > -n:
        board[row][i] = 1
        board[i][column] = 1
        i -= 1

    # check row
    for i in xrange(n):
        board[row][i] = 1

    i = 1
    # check diagonal
    while 0 <= column + i <= n - 1 and 0 <= row + i <= n - 1:
        board[row + i][column + i] = 1
        i += 1

    i = 1
    # check other diagonal
    while 0 <= column + i <= n - 1 and 0 <= row - i <= n - 1:
        board[row - i][column + i] = 1
        i += 1
Exemplo n.º 12
0
def print_hi(name):
    # Configure depth and color streams
    pipeline = rs.pipeline()
    colorizer = rs.colorizer()
    threshold_distance = 0.4
    tr1 = rs.threshold_filter(min_dist=0.15, max_dist=threshold_distance)
    config = rs.config()
    # Get device product line for setting a supporting resolution
    pipeline_wrapper = rs.pipeline_wrapper(pipeline)
    pipeline_profile = config.resolve(pipeline_wrapper)
    device = pipeline_profile.get_device()
    device_product_line = str(device.get_info(rs.camera_info.product_line))

    depth_sensor = pipeline_profile.get_device().first_depth_sensor()
    depth_scale = depth_sensor.get_depth_scale()

    config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)

    if device_product_line == 'L500':
        config.enable_stream(rs.stream.color, 960, 540, rs.format.bgr8, 30)
    else:
        config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
    # Start streaming
    clipping_distance_in_meters = 0.9
    clipping_distance = clipping_distance_in_meters / depth_scale
    align_to = rs.stream.color
    align = rs.align(align_to)
    pipeline.start(config)
    #thresholds for detect skins
    lower = np.array([0, 48, 80], dtype="uint8")
    upper = np.array([20, 255, 255], dtype="uint8")

    try:
        while True:
            frames = pipeline.wait_for_frames()
            # Align the depth frame to color frame
            aligned_frames = align.process(frames)
            # Get aligned frames
            aligned_depth_frame = aligned_frames.get_depth_frame(
            )  # aligned_depth_frame is a 640x480 depth image
            color_frame = aligned_frames.get_color_frame()
            # Validate that both frames are valid
            if not aligned_depth_frame or not color_frame:
                continue
            depth_image = np.asanyarray(aligned_depth_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data())
            # Remove background - Set pixels further than clipping_distance to grey
            grey_color = 153
            depth_image_3d = np.dstack(
                (depth_image, depth_image,
                 depth_image))  # depth image is 1 channel, color is 3 channels
            bg_removed = np.where(
                (depth_image_3d > clipping_distance) | (depth_image_3d <= 0),
                grey_color, color_image)

            # Render images
            depth_colormap = cv2.applyColorMap(
                cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
            images = np.hstack((bg_removed, depth_colormap))
            # cv2.namedWindow('Background Removed', cv2.WINDOW_AUTOSIZE)
            cv2.imshow('Color+depth', images)

            # images[270:, :] = [0, 0, 0]
            # images[0:240,:] = [0,0,0]
            # images[:, 0:50] = [0, 0, 0]
            # images[:, 630:] = [0, 0, 0]

            img_hsv = cv2.cvtColor(bg_removed, cv2.COLOR_BGR2HSV)
            ## Gen lower mask (0-5) and upper mask (175-180) of RED
            lower_red = np.array([94, 80, 2], dtype="uint8")
            upper_red = np.array([126, 255, 255], dtype="uint8")
            mask = cv2.inRange(img_hsv, lower_red, upper_red)
            bluepen = cv2.bitwise_and(bg_removed, bg_removed, mask=mask)

            cv2.imshow('BluePen', bluepen)
            bgModel = cv2.createBackgroundSubtractorMOG2(0, 50)
            fgmask = bgModel.apply(bluepen)
            kernel = np.ones((3, 3), np.uint8)
            fgmask = cv2.erode(fgmask, kernel, iterations=1)
            img = cv2.bitwise_and(bluepen, bluepen, mask=fgmask)

            # Skin detect and thresholding
            hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            lower = np.array([94, 80, 2], dtype="uint8")
            upper = np.array([126, 255, 255], dtype="uint8")
            skinMask = cv2.inRange(hsv, lower, upper)
            kernel = np.ones((3, 3), np.uint8)
            skinMask = cv2.erode(skinMask, kernel, iterations=2)
            skinMask = cv2.dilate(skinMask, kernel, iterations=1)

            cv2.imshow('Threshold Hands', skinMask)
            contours, hierarchy = cv2.findContours(skinMask, cv2.RETR_TREE,
                                                   cv2.CHAIN_APPROX_SIMPLE)

            length = len(contours)
            maxArea = -1
            drawing = np.zeros(img.shape, np.uint8)
            if length > 0:
                for i in xrange(length):
                    temp = contours[i]
                    area = cv2.contourArea(temp)
                    if area > maxArea:
                        maxArea = area
                        ci = i
                        res = contours[ci]
                hull = cv2.convexHull(res)
                # drawing = np.zeros(img.shape, np.uint8)
                cx, cy = centroid(res)

                print(aligned_depth_frame.get_distance(cx, cy))
                cv2.drawContours(drawing, [res], 0, (0, 255, 0), 2)
            else:
                drawing = np.zeros(img.shape, np.uint8)
            cv2.imshow('DRAWING', drawing)

            # bluepen_gray = cv2.cvtColor(bluepen, cv2.COLOR_BGR2HSV)
            # contours, hierarchy = cv2.findContours(bluepen_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            # length = len(contours)
            # drawing = np.zeros(bluepen_gray.shape, np.uint8)
            # maxArea = -1
            # if length > 0:
            #     for i in xrange(length):
            #         temp = contours[i]
            #         area = cv2.contourArea(temp)
            #         if area > maxArea:
            #             maxArea = area
            #             ci = i
            #             res1 = contours[ci]
            #
            #     hull = cv2.convexHull(res1)
            #
            #     cv2.drawContours(drawing, [res1], 0, (0, 255, 0), 2)
            #     cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3)
            # cv2.imshow('',drawing)
            # length = len(contours)
            # print(length)
            # drawing = np.zeros(res.shape, np.uint8)
            # maxArea = -1
            # if length > 0:
            #     for i in xrange(length):
            #         temp = contours[i]
            #         area = cv2.contourArea(temp)
            #         if area > maxArea:
            #             maxArea = area
            #             ci = i
            #             res = contours[ci]
            #
            #     hull = cv2.convexHull(res)
            #
            #
            #     cv2.drawContours(drawing, [res], 0, (0, 255, 0), 2)
            #     cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3)
            # cv2.imshow('Only contour for calibration', drawing)

            # cv2.imshow('BluePen', res)

            # converted = cv2.cvtColor(images, cv2.COLOR_BGR2HSV)
            # skinMask = cv2.inRange(converted, lower, upper)
            # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
            # skinMask = cv2.erode(skinMask, kernel, iterations=2)
            # skinMask = cv2.dilate(skinMask, kernel, iterations=1)
            #
            # skinMask = cv2.GaussianBlur(skinMask, (5, 5), 0)
            # skin = cv2.bitwise_and(images, images, mask=skinMask)

            cv2.waitKey(1)

            # img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            # ## Gen lower mask (0-5) and upper mask (175-180) of RED
            # mask1 = cv2.inRange(img_hsv, (0, 50, 20), (5, 255, 255))
            # mask2 = cv2.inRange(img_hsv, (175, 50, 20), (180, 255, 255))
            #
            # ## Merge the mask and crop the red regions
            # mask = cv2.bitwise_or(mask1, mask2)
            # croped = cv2.bitwise_and(img, img, mask=mask)

    finally:

        # Stop streaming
        pipeline.stop()

    # threshold_filter = rs.threshold_filter()
    # threshold_filter.set_option(rs.option.max_distance, 1)
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
                                         'haarcascade_frontalface_default.xml')
Exemplo n.º 13
0
from pip._vendor.msgpack.fallback import xrange

f = open('./dist/2.txt', 'r').readlines()
stringsArr = [line.rstrip() for line in f]
position = 0
string = []

for stringItemFirst in stringsArr:
    for j in range(1, len(stringsArr)):
        positions = [
            i for i in xrange(len(stringsArr[j]))
            if stringsArr[j][i] != stringItemFirst[i]
        ]
        print(positions)
        if len(positions) == 1:
            position = positions.pop()
            string = stringItemFirst

print(string[:position] + string[(position + 1):])
Exemplo n.º 14
0
 def double_click(self, pos=(-1, -1), button_name="left"):
     """Double click at the specifed placed"""
     for i in xrange(2):
         self.click(pos, button_name)
def result_plot(x,y,w_min):
     x1 = p.arange(0, 0.8, 0.01)
     y1 = [-(w_min[2] + w_min[0] * x1[k]) / w_min[1] for k in xrange(len(x1))]
     color = ['r'] * y.count(1.) + ['b'] * y.count(0.)
     plt.scatter(x[0], x[1], c=color)
     plt.plot(x1, y1)
def dfunc(x, y, w):
    # 一阶导数
    df = p.zeros(len(x))
    for i in xrange(len(x[0])):
        df += x[:, i] * (y[i] - p1(x[:, i], w))
    return -df
def p1(x, w):
    # 后验概率估计
    wx = 0
    for i in xrange(len(x)):
        wx += w[i] * x[i]
    return p.exp(wx) / (1 + p.exp(wx))
Exemplo n.º 18
0
def edit_entry(entry_id):
    if request.method == "POST":
        user = mongo.db.users.find_one({'username': session["user"]})
        entry = mongo.db.entries.find_one({"_id": ObjectId(entry_id)})

        username = user["username"]
        entry_username = entry["created_by"]
        if username != entry_username:
            flash("""This is not your entry. You can edit only your own!
                        Please select only your entry!""")
            return redirect(url_for("calendar_home"))

        print("User: {} and Created By: {}".format(username, entry_username))

        add_entry_department = request.form.get("category_name")
        user_department = user["department"]
        if user["department"] == "":
            mongo.db.users.update_one(
                {"username": user['username']},
                {"$set": {
                    "department": request.form["category_name"]
                }})
        else:
            if add_entry_department != user_department:
                print(
                    "Add entry department: {} is not the same as user department: {}"
                    .format(add_entry_department, user_department))
                flash("""Departments doesn't match. 
                        If you want to select different department, update your department in Profile"""
                      )
                return redirect(url_for("manage_entries"))

        # Deduct from Vacation days if Regular Vacation
        if entry['entry_type'] == "Regular Vacation":
            start_date_from_entry = datetime.strptime(entry["start_date"],
                                                      '%d %b, %Y')
            end_date_from_entry = datetime.strptime(entry["end_date"],
                                                    '%d %b, %Y')

            day_generator = (start_date_from_entry + timedelta(x + 1)
                             for x in xrange((end_date_from_entry -
                                              start_date_from_entry).days))
            how_many_days_to_add = sum(
                1 for day in day_generator if day.weekday() < 5) + 1

            update_user_days_before_new_deduction = user[
                'vacation_days'] + how_many_days_to_add
            mongo.db.users.update_one({"username": user['username']}, {
                "$set": {
                    "vacation_days": update_user_days_before_new_deduction
                }
            })

            user = mongo.db.users.find_one({'username': session["user"]})

            # Next we deduct new amount of vacation days
            start_date = datetime.strptime(request.form.get("start_date"),
                                           '%d %b, %Y')
            end_date = datetime.strptime(request.form.get("end_date"),
                                         '%d %b, %Y')

            day_generator = (start_date + timedelta(x + 1)
                             for x in xrange((end_date - start_date).days))
            how_many_days = sum(
                1 for day in day_generator if day.weekday() < 5) + 1

            update_user_days = user['vacation_days'] - how_many_days
            mongo.db.users.update_one(
                {"username": user['username']},
                {"$set": {
                    "vacation_days": update_user_days
                }})

        # Check if End Date is Before Start Date
        start_date = datetime.strptime(request.form.get("start_date"),
                                       '%d %b, %Y')
        end_date = datetime.strptime(request.form.get("end_date"), '%d %b, %Y')
        if end_date < start_date:
            flash("End Date is before start date. Please correct date entry")
            return redirect(url_for("manage_entries"))

        update = {
            "category_name": request.form.get("category_name"),
            "entry_type": request.form.get("entry_type"),
            "entry_description": request.form.get("entry_description"),
            "start_date": request.form.get("start_date"),
            "end_date": request.form.get("end_date"),
            "created_by": session["user"]
        }

        mongo.db.entries.update({"_id": ObjectId(entry_id)}, update)
        flash("Entry successfully Updated!")

    entry = mongo.db.entries.find_one({"_id": ObjectId(entry_id)})
    categories = mongo.db.categories.find().sort("category_name", 1)
    vacation_types = mongo.db.vacation_types.find().sort("entry_type", 1)
    return render_template("edit_entry.html",
                           categories=categories,
                           vacation_types=vacation_types,
                           entry=entry)
Exemplo n.º 19
0
from __future__ import division, print_function, unicode_literals
import math
import numpy as np
import matplotlib.pyplot as plt
from pip._vendor.msgpack.fallback import xrange

N = 100
d0 = 2
C = 3
X = np.zeros((d0, N * C))
y = np.zeros(N * C, dtype='uint8')

for j in xrange(C):
    ix = range(N * j, N * (j + 1))
    r = np.linspace(0.0, 1, N)

    t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2  # theta

    X[:, ix] = np.c_[r * np.sin(t), r * np.cos(t)].T

    y[ix] = j
    #print(y[ix])
    #print("==============")
# lets visualize the data:
# plt.scatter(X[:N, 0], X[:N, 1], c=y[:N], s=40, cmap=plt.cm.Spectral)

plt.plot(X[0, :N], X[1, :N], 'bs', markersize=5)
plt.plot(X[0, N:2 * N], X[1, N:2 * N], 'ro', markersize=5)
plt.plot(X[0, 2 * N:], X[1, 2 * N:], 'g^', markersize=5)
# plt.axis('off')
plt.xlim([-1.5, 1.5])
    while not questionmark:  # Checks to see if there is a question mark
        question = input("Please ask a question:\n"
                         )  # Allow the user to input their question.
        if "?" in question:
            questionmark = True
        else:
            print("This is not a question.")
    # Show an in progress message
    toolbar_width = 40
    print("Magic 8 Balling in progress, do not disturb.")
    sys.stdout.write("[%s]" % (" " * toolbar_width))  # setup toolbar
    sys.stdout.flush()
    sys.stdout.write("\b" *
                     (toolbar_width + 1))  # return to start of line, after '['

    for i in xrange(toolbar_width):
        time.sleep(0.2)  # Amount of pause between update
        # Updates the bar
        sys.stdout.write("-")
        sys.stdout.flush()

    sys.stdout.write("]\n")  # This ends the progress bar
    print(choice(responses))  # Randomizes responses
    while not quitresponse:  # Allow the user to ask another question/advice or quit the game
        quitinput = input(
            'Would you like to ask the Magic 8 Ball again?\n [Yes] \n [No] \n')
        if str(quitinput.lower()) in ('yes', 'no'):
            if str(quitinput.lower()) in 'yes':
                quit = False
                quitresponse = True
            else:
Exemplo n.º 21
0
from pip._vendor.msgpack.fallback import xrange

n = int(input())
for i in xrange(n):
    print(i + 1, end="")
Exemplo n.º 22
0
import sys
from itertools import product
from pip._vendor.msgpack.fallback import xrange

width, height = 10, 5
coordinates = list(product(xrange(width), xrange(height)))
coordinates[0] = "Godzilla"
print(coordinates)

#second
counter = 0
for line in sys.stdin:
    counter += 1
    ab = line.split()
    itemsCount = len(ab)
    finalExpression = []
    nextCounter = 0
    for index in range(len(ab)):
        if (index == nextCounter):

            item = ab[index]
            if item in ['+', '-', '*'] and index <= (itemsCount - 3):
                if ab[index +
                      1].isnumeric() and ab[index + 2].isnumeric() and int(
                          ab[index + 1]) in range(-10, 10) and int(
                              ab[index + 2]) in range(-10, 10):
                    result = 0
                    if (item == '+'):
                        result = int(ab[index + 1]) + int(ab[index + 2])
                    elif (item == '-'):
                        result = int(ab[index + 1]) - int(ab[index + 2])
X = np.array([[0, 0, 1],
              [0, 1, 1],
              [1, 0, 1],
              [1, 1, 1]])

# output dataset
y = np.array([[0, 0, 1, 1]]).T

# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)

# initialize weights randomly with mean 0
syn0 = 2 * np.random.random((3, 1)) - 1

for iter in xrange(10000):
    # forward propagation
    l0 = X
    l1 = nonlin(np.dot(l0, syn0))

    # how much did we miss?
    l1_error = y - l1

    # multiply how much we missed by the
    # slope of the sigmoid at the values in l1
    l1_delta = l1_error * nonlin(l1, True)

    # update weights
    syn0 += np.dot(l0.T, l1_delta)

    sleep(0.001)
Exemplo n.º 24
0
from PIL import Image
from pytesseract import *

img = cv2.imread('img/c1.jpg')  #이미지 파일에서 영상을 읽어들인다. 각 픽셀정보
img = cv2.resize(img, (600, 420))  #img를 크기를 600*420으로 재조정

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #흑백처리
blur = cv2.GaussianBlur(gray, (3, 3), 0)  #잡음제거
#threshold
canny = cv2.Canny(blur, 75, 200)  #윤곽추축

#컨투어 작업
contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)

for i in xrange(len(contours)):
    cnt = contours[i]
    print(i)

    area = cv2.contourArea(cnt)  #컨투어 영역의 넓이
    rect = cv2.minAreaRect(cnt)  #컨투어 영역을 포함한 최소의 사각형을 추출
    box = cv2.boxPoints(rect)  #위에서 추출한 사각형의 4개 좌표를 반환(좌표타입은 float)
    box = np.int0(box)  #위에서 추출한 4좌표의 타입을 int로 변환 == int()
    h = box[0][1] - box[1][1]
    w = box[2][0] - box[1][0]
    if w == 0:
        continue
    if 1 / 6 <= h / w <= 1 / 4 and area >= 500:  #번호판 추출 조건
        img = cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
        roi = img[box[1][1]:box[0][1],
                  box[1][0]:box[2][0]]  #조건에 맞는 컨투어 영역을 잘라서 roi에 저장
Exemplo n.º 25
0
@author: Jacky
'''
from collections import OrderedDict
from time import time
from random import randint
from pip._vendor.distlib.compat import raw_input
from pip._vendor.msgpack.fallback import xrange

d = OrderedDict()
d['Jacky']=(1,20)
d['Tracy']=(1,22)
d['Dora']=(2,20)
for k in d:
    print(k)

players = list('ABCDEFGH')
d = OrderedDict()
start = time()

for i in xrange(8):
    raw_input()
    p = players.pop(randint(0,7-i))
    end = time()
    print(i+1,p,end - start)
    d[p]=(i+1,end - start)

print()
print('='*20)
for k in d:
    print(k,d[k])
Exemplo n.º 26
0
def add_entry():
    if request.method == "POST":
        user = mongo.db.users.find_one({'username': session["user"]})
        start_date = datetime.strptime(request.form.get("start_date"),
                                       '%d %b, %Y')
        end_date = datetime.strptime(request.form.get("end_date"), '%d %b, %Y')
        if end_date < start_date:
            flash("End Date is before start date. Please correct date entry")
            return redirect(url_for("add_entry"))

        add_entry_department = request.form.get("category_name")
        user_department = user["department"]
        if user["department"] == "":
            mongo.db.users.update_one(
                {"username": user['username']},
                {"$set": {
                    "department": request.form["category_name"]
                }})
        else:
            if add_entry_department != user_department:
                print(
                    "Add entry department: {} is not the same as user department: {}"
                    .format(add_entry_department, user_department))
                flash("""Departments doesn't match. 
                    If you want to select different department, update your department in Profile"""
                      )
                return redirect(url_for("add_entry"))

        # Deduct from Vacation days if Regular Vacation
        entry_type = request.form.get("entry_type")
        if entry_type == "Regular Vacation":
            day_generator = (start_date + timedelta(x + 1)
                             for x in xrange((end_date - start_date).days))
            how_many_days = sum(
                1 for day in day_generator if day.weekday() < 5) + 1
            update_user_days = user['vacation_days'] - how_many_days

            if update_user_days <= 0:
                flash(
                    "Current status of days left {}! You don't have enough days!"
                    .format(user['vacation_days']))
                return redirect(url_for("manage_entries"))
            else:
                mongo.db.users.update_one(
                    {"username": user['username']},
                    {"$set": {
                        "vacation_days": update_user_days
                    }})

        entry = {
            "category_name": request.form.get("category_name"),
            "entry_type": request.form.get("entry_type"),
            "entry_description": request.form.get("entry_description"),
            "start_date": request.form.get("start_date"),
            "end_date": request.form.get("end_date"),
            "created_by": session["user"]
        }
        mongo.db.entries.insert_one(entry)
        flash("Entry successfully added")

    categories = mongo.db.categories.find().sort("category_name", 1)
    vacation_types = mongo.db.vacation_types.find().sort("entry_type", 1)
    return render_template("add_entry.html",
                           categories=categories,
                           vacation_types=vacation_types)
Exemplo n.º 27
0
    if S['speedX']<10:
       R['accel']+= 1/(S['speedX']+.1)

    # Traction Control System
    if ((S['wheelSpinVel'][2]+S['wheelSpinVel'][3]) -
       (S['wheelSpinVel'][0]+S['wheelSpinVel'][1]) > 5):
       R['accel']-= .2
    R['accel']= clip(R['accel'], 0 ,1)

    # Automatic Transmission
    R['gear']=1
    if S['speedX']>50:
        R['gear']=2
    if S['speedX']>80:
        R['gear']=3
    if S['speedX']>110:
        R['gear']=4
    if S['speedX']>140:
        R['gear']=5
    if S['speedX']>170:
        R['gear']=6
    return

# ================ MAIN ================
if __name__ == "__main__":
    C= Client()
    for step in xrange(C.maxSteps, 0, -1):
        C.get_servers_input()
        drive_example(C)
        C.respond_to_server()
    C.shutdown()
Exemplo n.º 28
0
def largeSum(num):
    listOf50 = []
    for i in xrange(50, len(str(num))+1,50):
        listOf50.append(long(str(num)[i-50:i]))
    totalSum = reduce(lambda x , y : x + y, listOf50)
    return int(str(totalSum)[0:10])
Exemplo n.º 29
0
#  |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
#  |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
#  |  These are exactly the valid indices for a list of 4 elements.
#  |  When step is given, it specifies the increment (or decrement).
# print(help(range(10)))
from pip._vendor.msgpack.fallback import xrange

for item in range(0, 10, 2):
    print(item)

#result 0 2 4 6 8

#the xrange() is quit similar to range() except that xrange() releases or frees the memory when not in use .
#whereas range() doesn't release the memory .
x = 0
for item in xrange(20):
    print("hello world !")

for char in "this is a sentence !!! ":
    print(char)

list = [char for char in "this is a sentence ! "]
print(list)

#indefinite Loop

#try to get from user a valid integer
#
test = True
while test:
    test = False
Exemplo n.º 30
0
# Importamo modul random
import random
# Iz knjižnice pip._vendor.msgpack.fallback importamo xrange
from pip._vendor.msgpack.fallback import xrange
# Programu sporočimo naj izbere 10 števil od 1 do 100
array = random.sample(xrange(101),10)
# Vpeljemo spremenljivko total in s funkcijo sum() seštejemo elemente "tabele"
total = sum(array)
# Izpišemo element
print(array)
# Izpišemo seštevek vsem elementov.
print(total)