Example #1
0
    def diff_location(self, old_location, new_location):
        # Here we match up the children of the given locations. This is done in
        # three steps. First we use full tree equality to match up children
        # that are identical all the way down. Then, we use a heuristic
        # function to match up children that are similar, based on text
        # content. Lastly, we just use node tag types to match up elements. For
        # the text-similar matches and the tag-only matches, we still have more
        # work to do, so we recurse on these. The non-matching parts that
        # remain are used to output edit script entries.
        old_children = list(get_location(self.old_dom, old_location).childNodes)
        new_children = list(get_location(self.new_dom, new_location).childNodes)
        if not old_children and not new_children:
            return

        matching_blocks, recursion_indices = self.match_children(old_children, new_children)

        # Apply changes for this level.
        for tag, i1, i2, j1, j2 in adjusted_ops(get_opcodes(matching_blocks)):
            if tag == 'delete':
                assert j1 == j2
                # delete range from right to left
                for index, child in reversed(list(enumerate(old_children[i1:i2]))):
                    self.delete(old_location + [i1 + index], child)
                    old_children.pop(i1 + index)
            elif tag == 'insert':
                assert i1 == i2
                # insert range from left to right
                for index, child in enumerate(new_children[j1:j2]):
                    self.insert(new_location + [i1 + index], child)
                    old_children.insert(i1 + index, child)
            recursion_indices = list(adjust_indices(recursion_indices, i1, i2, j1, j2))

        # Recurse to deeper level.
        for old_index, new_index in recursion_indices:
            self.diff_location(old_location + [old_index], new_location + [new_index])
 def run_edit_script(self):
     """
     Run an xml edit script, and return the new html produced.
     """
     for action, location, properties in self.edit_script:
         if action == "delete":
             node = get_location(self.dom, location)
             self.action_delete(node)
         elif action == "insert":
             parent = get_location(self.dom, location[:-1])
             child_index = location[-1]
             self.action_insert(parent, child_index, **properties)
     return self.dom
 def run_edit_script(self):
     """
     Run an xml edit script, and return the new html produced.
     """
     for action, location, properties in self.edit_script:
         if action == 'delete':
             node = get_location(self.dom, location)
             self.action_delete(node)
         elif action == 'insert':
             parent = get_location(self.dom, location[:-1])
             child_index = location[-1]
             self.action_insert(parent, child_index, **properties)
     return self.dom
Example #4
0
    def begin(self):
        util.click_pos(self.hwnd, self.pos_x, self.pos_y)
        util.sleep(1000)
        util.screen_shot(self.hwnd, self.name)
        x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                                 'selectterm.png')
        while x < 1000:
            util.click_pos(self.hwnd, self.pos_x, self.pos_y)
            util.sleep(1000)
            util.screen_shot(self.hwnd, self.name)
            x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                                     'selectterm.png')

        util.click_pos(self.hwnd, 1002, 573)
def shifts():
    now = datetime.now()
    # get/post and cookie
    new_cookies = {}
    location_cookie, location = util.get_location()
    if not location_cookie:
        new_cookies = {"location": str(location)}
    month = int(request.args.get("month", now.month))
    year = int(request.args.get("year", now.year))
    # data
    base = CgBase(location)
    workers = base.get_workers()
    version = base.get_version()
    workdays, shift_totals = base.get_shift_stats(month, year)

    resp = make_response(render_template('shifts.html',
        title='Shifts',
        date=now,
        countries=util.country_list.items(),
        server=dbdetails.server,
        location=location,
        locations=util.locations,
        workers=workers,
        workdays=workdays,
        shift_totals=shift_totals,
        shown_month=month,
        shown_year=year,
        months=months,
        version=version
    ))
    for key, val in new_cookies.iteritems():
        resp.set_cookie(key, val)
    return resp
def purchases():
    # get/post and cookie
    showndate = request.args.get('date', None)
    location_cookie, location = util.get_location()

    # date
    if showndate is None:
        now = datetime.now()
    elif g.user.is_admin():
        now = datetime.strptime(showndate, '%Y-%m-%d')
    else:
        flash("Only admins can view past dates!", "danger")
        return redirect(url_for("home_page.home"))

    # data
    base = CgBase(location)
    purchases, total = util.calc_purchases_totals(
        base.get_purchases(onlydate=now))

    return render_template('purchases.html',
        purchases=purchases,
        total=total,
        server=dbdetails.server,
        location=location,
    )
Example #7
0
def edit_shift():
    base = CgBase(util.get_location()[1])
    shift = request.get_json()
    start = convert_date(shift["start"] + ":00")
    end = convert_date(shift["end"] + ":00")

    if start is None or end is None:
        message = {
            'status': 400,
            'message': "Not a valid datetime",
            'wrong-args': (shift["start"], shift["end"])
        }
        resp = jsonify(message)
        resp.status_code = 400
        return resp
    success = base.update_shift_times(shift["sync_id"], start, end)
    if success:
        return jsonify(shift)
    else:
        message = {
            'status': 500,
            'message': "Unknown start work error"
        }
        resp = jsonify(message)
        resp.status_code = 500
        return resp
Example #8
0
def delete_purchase(sync_id):
    base = CgBase(util.get_location()[1])
    success = base.mark_purchase_deleted(sync_id)
    if success:
        return jsonify({"purchase_deleted": sync_id})
    else:
        return abort_msg(404, "Not purchase with syncId: " + str(sync_id))
def show_login():
    if g.user.is_authenticated():
        return redirect(url_for('home_page.home'))
    # get/post and cookie
    new_cookies = {}
    location_cookie, location = util.get_location()
    if not location_cookie:
        new_cookies = {"location": str(location)}

    # data
    now = datetime.now()
    base = CgBase(location)
    version = base.get_version()
    workers = base.get_workers()

    resp = make_response(render_template('login.html',
        title='Login',
        date=now,
        server=dbdetails.server,
        workers=workers,
        location=location,
        locations=util.locations,
        version=version
    ))
    for key, val in new_cookies.iteritems():
        resp.set_cookie(key, val)
    return resp
def container_stock(container_id):
    # get/post and cookie
    new_cookies = {}
    location_cookie, location = util.get_location()
    if not location_cookie:
        new_cookies = {"location": str(location)}
    # data
    now = datetime.now()
    base = CgBase(location)
    stock = base.get_container_stock(container_id)
    container_name = util.containers[container_id]["title"]
    workers = base.get_workers()
    version = base.get_version()

    resp = make_response(render_template('container.html',
        title='Stock',
        date=now,
        countries=util.country_list.items(),
        server=dbdetails.server,
        location=location,
        locations=util.locations,
        workers=workers,
        containers=util.containers,
        stock=stock,
        container_name=container_name,
        version=version
    ))
    for key, val in new_cookies.iteritems():
        resp.set_cookie(key, val)
    return resp
Example #11
0
 def end(self):
     util.screen_shot(self.hwnd, self.name)
     x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                              'shen.png')
     if x == 156:
         return 1
     else:
         return 0
Example #12
0
 def end(self):
     util.screen_shot(self.hwnd, self.name)
     x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                              'meiri.png')
     if (x == 1220):
         return 1
     else:
         return 0
def stock_form():
    # get/post and cookie
    location_cookie, location = util.get_location()
    # data
    base = CgBase(location)
    stock = base.get_stock()

    return render_template('stock_form.html',
        containers=util.containers,
        stock=stock
    )
Example #14
0
    def step(self, amt=1):
        color_length = len(beam_state.colors)
        for x, y in self.grid():
            col_color = beam_state.colors[(beam_util.get_location(x, y) +
                                           self._step) % color_length]
            self.layout.set(x, y, col_color)

        if self._step + amt == color_length:
            self._step = 0
        else:
            self._step += amt
Example #15
0
    def step(self, amt=1):
        for x, y in self.grid():
            if beam_util.get_location(x, y) < self._step:
                self.layout.set(x, y, random.choice(beam_state.colors))
            else:
                self.layout.set(x, y, color_util.Off)

        if self._step == self.layout.width * self.layout.height:
            self._step = 0
        else:
            self._step += amt
Example #16
0
    def diff_location(self, old_location, new_location):
        # Here we match up the children of the given locations. This is done in
        # three steps. First we use full tree equality to match up children
        # that are identical all the way down. Then, we use a heuristic
        # function to match up children that are similar, based on text
        # content. Lastly, we just use node tag types to match up elements. For
        # the text-similar matches and the tag-only matches, we still have more
        # work to do, so we recurse on these. The non-matching parts that
        # remain are used to output edit script entries.
        old_children = list(
            get_location(self.old_dom, old_location).childNodes)
        new_children = list(
            get_location(self.new_dom, new_location).childNodes)
        if not old_children and not new_children:
            return

        matching_blocks, recursion_indices = self.match_children(
            old_children, new_children)

        # Apply changes for this level.
        for tag, i1, i2, j1, j2 in adjusted_ops(get_opcodes(matching_blocks)):
            if tag == 'delete':
                assert j1 == j2
                # delete range from right to left
                for index, child in reversed(
                        list(enumerate(old_children[i1:i2]))):
                    self.delete(old_location + [i1 + index], child)
                    old_children.pop(i1 + index)
            elif tag == 'insert':
                assert i1 == i2
                # insert range from left to right
                for index, child in enumerate(new_children[j1:j2]):
                    self.insert(new_location + [i1 + index], child)
                    old_children.insert(i1 + index, child)
            recursion_indices = list(
                adjust_indices(recursion_indices, i1, i2, j1, j2))

        # Recurse to deeper level.
        for old_index, new_index in recursion_indices:
            self.diff_location(old_location + [old_index],
                               new_location + [new_index])
Example #17
0
    def attack(self):
        util.screen_shot(self.hwnd, self.name)
        x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                                 'zhandouclick.png')

        if x > 1000 and y > 400:
            util.sleep(1000)
            util.click_pos(self.hwnd, x, y)
            self.sell()
            util.sleep(1000)
            util.click_pos(self.hwnd, 1194, 172)
        else:
            util.click_pos(self.hwnd, 516, 456)
Example #18
0
 def delete(self, location, node):
     # delete from the bottom up, children before parent, right to left
     for child_index, child in reversed(list(enumerate(node.childNodes))):
         self.delete(location + [child_index], child)
     # write deletion to the edit script
     self.edit_script.append((
         'delete',
         location,
         node_properties(node),
     ))
     # actually delete the node
     assert node.parentNode == get_location(self.old_dom, location[:-1])
     assert node.ownerDocument == self.old_dom
     remove_node(node)
Example #19
0
 def delete(self, location, node):
     # delete from the bottom up, children before parent, right to left
     for child_index, child in reversed(list(enumerate(node.childNodes))):
         self.delete(location + [child_index], child)
     # write deletion to the edit script
     self.edit_script.append((
         'delete',
         location,
         node_properties(node),
     ))
     # actually delete the node
     assert node.parentNode == get_location(self.old_dom, location[:-1])
     assert node.ownerDocument == self.old_dom
     remove_node(node)
Example #20
0
 def insert(self, location, node):
     # write insertion to the edit script
     self.edit_script.append((
         'insert',
         location,
         node_properties(node),
     ))
     # actually insert the node
     node_copy = node.cloneNode(deep=False)
     parent = get_location(self.old_dom, location[:-1])
     next_sibling = get_child(parent, location[-1])
     insert_or_append(parent, node_copy, next_sibling)
     # insert from the top down, parent before children, left to right
     for child_index, child in enumerate(node.childNodes):
         self.insert(location + [child_index], child)
Example #21
0
 def insert(self, location, node):
     # write insertion to the edit script
     self.edit_script.append((
         'insert',
         location,
         node_properties(node),
     ))
     # actually insert the node
     node_copy = node.cloneNode(deep=False)
     parent = get_location(self.old_dom, location[:-1])
     next_sibling = get_child(parent, location[-1])
     insert_or_append(parent, node_copy, next_sibling)
     # insert from the top down, parent before children, left to right
     for child_index, child in enumerate(node.childNodes):
         self.insert(location + [child_index], child)
Example #22
0
def end_shift(worker_id):
    base = CgBase(util.get_location()[1])
    workres = base.end_work(worker_id)
    if not workres:
        message = {
                'status': 404,
                'message': "Worker hasn't started: " + str(worker_id),
        }
        resp = jsonify(message)
        resp.status_code = 404
        return resp
    else:
        return jsonify({
            "worker_id": worker_id
        })
Example #23
0
def delete_shift():
    base = CgBase(util.get_location()[1])
    shift = request.get_json()
    success = base.mark_shift_deleted(shift["sync_id"])

    if success:
        return jsonify(shift)
    else:
        message = {
            'status': 500,
            'message': "Unknown delete_shift error"
        }
        resp = jsonify(message)
        resp.status_code = 500
        return resp
Example #24
0
def begin_shift(worker_id):
    base = CgBase(util.get_location()[1])
    workres = base.begin_work(worker_id)
    if workres:
        return jsonify({
            "worker_id": worker_id,
            "end": None
        })
    else:
        message = {
                'status': 500,
                'message': "Unknown start work error",
        }
        resp = jsonify(message)
        resp.status_code = 500
        return resp
Example #25
0
 def sell(self):
     util.screen_shot(self.hwnd, self.name)
     x, y = util.get_location('temp\\' + self.name + '\\screenshot.png',
                              'sell.png')
     if x == 760:
         util.click_pos(self.hwnd, x, y)
         util.sleep(1000)
         for i in range(0, 7):
             util.click_pos(self.hwnd, 109 + i * 177, 245)
             util.sleep(300)
         for i in range(0, 7):
             util.click_pos(self.hwnd, 109 + i * 177, 422)
             util.sleep(300)
         util.sleep(1000)
         util.click_pos(self.hwnd, 1176, 685)
         util.sleep(1000)
         util.click_pos(self.hwnd, 781, 540)
         util.sleep(1000)
         util.click_pos(self.hwnd, 516, 456)
Example #26
0
def save_purchase():
    purchase = request.get_json()
    base = CgBase(util.get_location()[1])
    if purchase['boxes']:
        date = convert_date(purchase['datetime'] + ":00")
        if date is None:
            return abort_msg(400, "Not a valid datetime")
        edited = datetime.now()
        insert_success = base.insert_purchase(
            purchase['country'], purchase['card'], purchase['datetime'],
            purchase['discount'], purchase['boxes'], edited,
            note=purchase['note'])
        if insert_success:
            resp = jsonify({"save_purchase": "Successful"})
            resp.status_code = 201
            return resp
    else:
        return abort_msg(400, "No cookies")
    return abort_msg(400, "Unknown save_purchase error")
def shifts_table():
    now = datetime.now()
    # get/post and cookie
    location_cookie, location = util.get_location()
    # data
    month = int(request.args.get("month", now.month))
    year = int(request.args.get("year", now.year))
    base = CgBase(location)
    workdays, shift_totals = base.get_shift_stats(month, year)

    return render_template('shifts_table.html',
        date=now,
        server=dbdetails.server,
        shift_totals=shift_totals,
        workdays=workdays,
        shown_month=month,
        shown_year=year,
        months=months
    )
Example #28
0
def home():
    # get/post and cookie
    showndate = request.args.get('date', None)
    new_cookies = {}
    location_cookie, location = util.get_location()
    if not location_cookie:
        new_cookies = {"location": str(location)}

    # date
    if showndate is None:
        now = datetime.now()
    elif g.user.is_admin():
        now = datetime.strptime(showndate, '%Y-%m-%d')
    else:
        flash("Only admins can view past dates!", "danger")
        return redirect(url_for("home_page.home"))
    # data
    base = CgBase(location)
    boxes = base.get_boxes()
    purchases, total = util.calc_purchases_totals(
        base.get_purchases(onlydate=now))
    workers = base.get_workers()
    version = base.get_version()

    resp = make_response(render_template('home.html',
        title='Herramienta',
        date=now,
        countries=util.country_list.items(),
        boxes=boxes.items(),
        purchases=purchases,
        total=total,
        server=dbdetails.server,
        workers=workers,
        location=location,
        locations=util.locations,
        version=version
    ))
    for key, val in new_cookies.iteritems():
        resp.set_cookie(key, val)
    return resp
Example #29
0
def update_stock():
    base = CgBase(util.get_location()[1])
    method = request.form.get('count-method', None)
    if method == "relative":
        absolute = False
    elif method == "absolute":
        absolute = True
    else:
        return abort_msg(400, "Wrong method for stock update")
    containers = {}
    for containerId in util.containers.keys():
        containerId = str(containerId)
        count = int(request.form.get('container_' + containerId, 0))
        if absolute or not count == 0:
            containers[containerId] = count
    success = base.update_stock(containers, absolute)
    if success:
        redirect_target = request.form.get('redirect', None)
        if redirect_target is not None:
            return redirect(url_for('stock_page.stock'))
        else:
            return jsonify({"updated_stock": containers})
    else:
        return abort_msg(500, "Some stock update error")
def stats():
    create_stats_file(util.get_location()[1])
    return send_from_directory('', 'estadisticas.xlsx')
Example #31
0
def sync():
    base = CgBase(util.get_location()[1])
    if not dbdetails.server:  # Clientside
        # get data to return
        up_data = {
            "data": {},
            "sync_time": util.datestring(datetime.now()),
            "last_sync": util.datestring(base.get_last_sync())
        }
        up_data['data']['purchase'] = base.get_purchases(
                getDeleted=True, datestring=True, notsynced=True,
                simplecart=True, allLocations=True)
        up_data['data']['shift'] = base.get_shifts(
                getDeleted=True, datestring=True, notsynced=True,
                allLocations=True)
        up_data['data']['stock'] = base.get_stock_items(
                datestring=True, notsynced=True, allLocations=True)
        r = requests.put(dbdetails.serverroot + "/api/v1.0/sync",
                        data=json.dumps(up_data),
                        headers={"Content-Type": "application/json"}
        )
        try:
            input = r.json()
            synced_up = input['synced']
            down_data = input['data']
        except ValueError:
            try:
                input = json.loads(r.text)
            except ValueError:
                return (
                    "ERROR ON SERVERSIDE!<br>\n"
                    + "For up_data:\n"
                    + json.dumps(up_data)
                    + "\nServerresponse:\n"
                    + r.text
                )
            except:
                raise
        except:
            raise
        sync_time = datetime.now()
    else: # Serverside
        input = request.get_json()
        try:
            sync_time = util.stringdate(input['sync_time'])
        except:
            return "JSON ERROR: " + str(input)

    # update based on submitted data
    existing = []
    purchase_items = input['data']['purchase']
    if purchase_items:
        extra = ("WHERE syncId IN (%s" + (",%s"*(len(purchase_items)-1)) + ")",
                tuple(item['syncId'] for item in purchase_items))
        existing += base.fetchall("purchases", ["syncId", "status", "edited"],
                                 extra)
    shift_items = input['data']['shift']
    if shift_items:
        extra = ("WHERE syncId IN (%s" + (",%s"*(len(shift_items)-1)) + ")",
                tuple(item['syncId'] for item in shift_items))
        existing += base.fetchall("shifts", ["syncId", "status", "edited"],
                                 extra)
    stock_items = input['data']['stock']
    if stock_items:
        extra = ("WHERE syncId IN (%s" + (",%s"*(len(stock_items)-1)) + ")",
                tuple(item['syncId'] for item in stock_items))
        existing += base.fetchall("stock", ["syncId", "status", "edited"],
                                 extra)
    existing = {x[0]: x for x in existing}
    synced = {
            "added": {"purchase": [], "shift": [], "stock": []},
            "edited": {"purchase": [], "shift": [], "stock": []},
            "deleted": {"purchase": [], "shift": [], "stock": []}
    }
    for _type, item_list in input['data'].iteritems():
        for item in item_list:
            status = item['status']
            sync_id = item['syncId']
            edited = util.stringdate(item['edited'])
            existing_status = None
            try:
                existing_status = existing[sync_id][1]  # ['status']
                existing_edited = existing[sync_id][2]  # ['edited']
            except KeyError:
                existing_status = None
            if status == 0:
                if existing_status is None:
                    insert_item(base, _type, item, sync_time)
                elif edited > existing_edited:
                    edit_item(base, _type, item, sync_time)
                synced['added'][_type].append(sync_id)
            elif status == 1:
                if existing_status == 0:
                    edit_item(base, _type, item, sync_time)
                elif (existing_status == 1
                     or existing_status == 2
                     or existing_status == 3):
                    if edited > existing_edited:
                        edit_item(base, _type, item, sync_time)
                elif existing_status is None:
                    insert_item(base, _type, item, sync_time)
                synced['edited'][_type].append(sync_id)
            elif status == 2:
                if existing_status == 0:
                    delete_item(base, _type, item, sync_time)
                elif existing_status == 1 or existing_status == 3:
                    if edited > existing_edited:
                        delete_item(base, _type, item, sync_time)
                elif existing_status == 2:
                    if edited > existing_edited:
                        edit_item(base, _type, item, sync_time)
                elif existing_status is None:
                    insert_item(base, _type, item, sync_time)
                synced['deleted'][_type].append(sync_id)
    base.db.commit()

    if dbdetails.server:
        # get data to return
        last_sync = util.stringdate(input['last_sync'])
        result = {"data": {}, "synced": synced}
        result['data']['purchase'] = base.get_purchases(
            newerthan=last_sync, datestring=True,
            simplecart=True, getDeleted=True, allLocations=True,
            notnow=sync_time)
        result['data']['shift'] = base.get_shifts(
            getDeleted=True, datestring=True,
            newerthan=last_sync, allLocations=True, notnow=sync_time)
        result['data']['stock'] = base.get_stock_items(
                datestring=True, newerthan=last_sync,
                allLocations=True, notnow=sync_time)
        return jsonify(result)
    else:
        for action, types in synced_up.iteritems():
            for _type, items in types.iteritems():
                for sync_id in items:
                    if _type == "purchase":
                        if action == "deleted":
                            base.delete_purchase(sync_id)
                        else:
                            base.mark_purchase_synced(sync_id)
                    elif _type == "shift":
                        if action == "deleted":
                            base.delete_shift(sync_id)
                        else:
                            base.mark_shift_synced(sync_id)
                    elif _type == "stock":
                        if action == "deleted":
                            pass # not possible to delete stock
                        else:
                            base.mark_stock_item_synced(sync_id)
        base.update_last_sync(sync_time)
        sync_summary = {"synced_up": synced_up, "synced_down": synced}
        sync_msg = handle_sync_result(sync_summary)
        util.log(str(sync_msg), json.dumps(sync_summary))

        redirect_target = request.args.get('redirect', False)
        if not redirect_target:
            return jsonify(sync_summary)
        else:
            return redirect(str(redirect_target) + "?msg=" + sync_msg)
Example #32
0
def get_location():
    response = jsonify({'locations': util.get_location()})
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response
Example #33
0
File: light.py Project: Tashus/beam
    def step(self, amt=1):
        for x, y in self.grid():
            c = beam_state.colors[beam_util.get_location(x, y) % len(beam_state.colors)]
            self.layout.set(x, y, c)

        self._step = 0
query_string = 'preschool,daycare in ' + CITY + ', ' + STATE
# Geocoding an address
daycare_result = gmaps.places(query=query_string)
i = 0

apartment_result = []
apartment = []
apartment_dict_result = []

while i <= 60:
    for item in daycare_result['results']:
        i = i + 1
        ut.print_gmap_address(i,item)
        j = 0
        time.sleep(0.1)
        org_loc = ut.get_location(item)
        apartment_result = gmaps.places_nearby(location=org_loc,keyword='apartment',radius=1000)
        for apartment in apartment_result['results']:
            dest_loc = ut.get_location(apartment)
            apartment_dict_result = gmap_dirt.directions(origin=org_loc,
                                                          destination=dest_loc,
                                                          mode='walking')
            for direction in apartment_dict_result[0]['legs']:
                if direction.get(u'duration').get('value') /60 <= 20:
                    j = j + 1

                    ut.print_gmap_dict_address(j,apartment,direction)

                    zr.print_zillow_price(apartment.get(u'vicinity'),'cary','NC')
    token = daycare_result.get(u'next_page_token',None)
    if token is None: