Example #1
0
def main():
    if len(sys.argv) < 2:
        print("Usage: init_fortune.py <fortune_filename> [table name]")
        sys.exit(1)

    fortune_file = sys.argv[1]

    # If [table name] specified, use it. Otherwise get table name from fortune filename.
    if len(sys.argv) >= 3:
        tbl = sys.argv[2]
    else:
        (sdir, filename) = os.path.split(fortune_file)
        tbl = os.path.splitext(filename)[0]

    con = db.connect_db()

    db.purge_table(con, tbl)
    db.init_table(con, tbl)

    cur = con.cursor()
    sql = f"INSERT INTO {tbl} (_id, _body) VALUES (?, ?)"

    body_lines = []

    with open(fortune_file, "r") as f:
        # Skip over lines until the first "%" line
        #for line in f:
        #    line = line.rstrip()
        #    print(line)
        #    if re.search(r'^%\s*$', line):
        #        break

        for line in f:
            line = line.rstrip()

            # "%" separator line
            if re.search(r'^%\s*$', line):
                body = "\n".join(body_lines).strip()
                if body != "":
                    print(body)
                    print("---")
                    cur.execute(sql, [util.gen_id(), body])

                body_lines = []
                continue

            body_lines.append(line)

        body = "\n".join(body_lines).strip()
        if body != "":
            print(body)
            print("---")
            cur.execute(sql, [util.gen_id(), body])

    con.commit()
Example #2
0
def create_post(username, message, likes=0, post_tags="", photo_path=None, video_path=None):
    """
    Create a post
    :param photo_path:
    :param video_path:
    :param username:
    :param message:
    :param post_tags:
    :param likes:
    :return:
    """

    cursor = db.cursor()

    post_id = util.gen_id()
    date = datetime.datetime.now()

    post_sql = "INSERT INTO post (post_id, message, post_tags, likes, username_id, photo_path, video_path, post_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
    values = (post_id, message, post_tags, likes, username, photo_path, video_path, date)

    # Check tags are valid
    post_tags = post_tags[1:] if post_tags.startswith(",") else post_tags
    post_tags = post_tags[:-1] if post_tags.endswith(",") else post_tags

    try:
        cursor.execute(post_sql, values)
        db.commit()
    except:
        print("Unable to create post")
        raise Exception

    return post_id
Example #3
0
def add_comment(
        post_id,
        message,
        username):
    """
    Add a comment to a post
    :param post_id:
    :param message:
    :return:
    """

    try:
        cursor = db.cursor()

        comment_id = util.gen_id()

        comment_sql = "INSERT INTO comment (comment_id, message, post_id, username) VALUES (%s, %s, %s, %s)"
        values = (comment_id, message, post_id, username)

        cursor.execute(comment_sql, values)
    except:
        print("Unable to add comment")
        raise Exception
    finally:
        db.commit()

    return comment_id
Example #4
0
def create_advert(
    name,
    message,
    link,
    frequency,
    photo_path=None,
    video_path=None,
):
    """
    Create an advert
    :param name:
    :param message:
    :param photo_path:
    :param video_path:
    :param link:
    :return:
    """

    try:
        cursor = db.cursor()
        advert_id = util.gen_id()

        advert_sql = "INSERT INTO advert (advert_id, name, message, photo_path, link, frequency, video_path) VALUE (%s,%s,%s,%s,%s,%s,%s)"
        values = (advert_id, name, message, photo_path, link, frequency,
                  video_path)
        cursor.execute(advert_sql, values)
    except:
        print("Unable to create advert")
        raise Exception

    finally:
        db.commit()
Example #5
0
    def setup(self, con, tbl, recid, on_edit_save=None, on_edit_close=None):
        self.connect("destroy", self.on_destroy)

        self.con = con
        self.tbl = tbl
        self.on_edit_save = on_edit_save
        self.on_edit_close = on_edit_close
        self.tbl_cols = db.table_cols(con, tbl)

        self.rec = None
        self.winid = ""
        self.is_new_rec = False

        # This is an 'Edit Rec' window if an existing recid was passed.
        # In this case, the recid will be used as the windows id.
        if recid:
            self.set_title("Edit Record")
            self.rec = db.read_rec(con, tbl, recid)
            self.winid = recid

        # This is a 'New Rec' window if no recid passed or if nonexisting recid.
        # A window id will be programmatically generated.
        if self.rec == None:
            self.set_title("New Record")
            self.rec = db.rec_new()
            self.winid = util.gen_id()
            self.is_new_rec = True

        self.setup_widgets()
Example #6
0
def main():
    try:
        global conf, uid, key, ip, port, sock, status_file
        conf = read_json(os.path.join(os.path.dirname(__file__), config_path))
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socket.setdefaulttimeout(3)
        sock.settimeout(3)
        status_file = open(status_path, "w")
        #sock.setblocking(False)
        ip = conf['remote']
        port = conf['remote_port']

        if isfile(key_path):
            key = read_text(key_path)
        else:
            prompt_for_key()

        if isfile(uid_path):
            uid = read_text(uid_path)
        else:
            uid = gen_id()
            write_text(uid_path, uid)

        check_alive()
        #schedule.every(conf['interval']).seconds.do(check_alive)
        schedule.every(5).seconds.do(check_alive)
        print("client is running")
        while True:
            schedule.run_pending()
    except KeyboardInterrupt:
        print('manual exit')
        post_request("GBYE")
        sock.close()
Example #7
0
def main():
    con = db.connect_db()
    tbl = "art_of_worldly_wisdom"

    db.purge_table(con, tbl)
    db.init_table(con, tbl)

    cur = con.cursor()
    sql = f"INSERT INTO {tbl} (_id, _body) VALUES (?, ?)"

    body_lines = []

    is_last_line_page_break = False

    with open("aww.txt", "r") as aww:
        for line in aww:
            line = line.rstrip()

            # Skip over "[p. nnn]" lines
            if re.search(r'^\[p\..*]', line):
                is_last_line_page_break = True
                continue

            # Skip the line after the "[p. nnn]" line
            if is_last_line_page_break and line.strip() == "":
                is_last_line_page_break = False
                continue

            # Title: "iii Keep Matters for a Time in Suspense."
            if re.search(r'^[ivxlcdm]+\s+\w+', line):
                body = "\n".join(body_lines).strip()
                print(body)
                print("---")
                cur.execute(sql, [util.gen_id(), body])

                body_lines = []

            line = line.replace("[paragraph continues] ", "")
            body_lines.append(line)

        if len(body_lines) > 0:
            body = "\n".join(body_lines).strip()
            print(body)
            print("\n---\n")
            cur.execute(sql, [util.gen_id(), body])

    con.commit()
Example #8
0
def index():
	
	if not 'uuid' in session:
		session['uuid'] = util.gen_id()
	else:
		print('we have session uuid: %s' % session['uuid'])

	return render_template('index.html')
Example #9
0
File: tree.py Project: fmgc/mdp
    def __init__(self):
        self.__node_id = gen_id()

        self.__root_id = None

        self.__childs = dict()
        self.__parent = dict()
        self.__depth = dict()
Example #10
0
def gen_uid():
    try:
        db = get_db()
        cur = db.cursor()
        uid = util.gen_id()
        res = cur.execute(
            "INSERT INTO usr(uid, time)VALUES(?,?)", [uid, time.strftime("%Y-%m-%d %A %X", time.localtime())]
        )
        db.commit()
    except sqlite3.IntegrityError, e:
        return gen_uid()
Example #11
0
    def test_duplicate_id(self):
        id_list = []
        for system in self.systems:
            for contact in system['contacts']:
                if 'id' in system['contacts'][contact]:
                    id = system['contacts'][contact]['id']
                else:
                    id = gen_id(contact, system['contacts'][contact])['id']
                if id:
                    id_list.append(id)

        self.assertEqual(len(id_list), len(set(id_list)), "System does not have unique IDs!")
Example #12
0
def build_handshake(torrent):

    # pstrlen
    buffer = (19).to_bytes(1, 'big')
    # pstr
    buffer += 'BitTorrent protocol'.encode()
    # reserved
    buffer += (0).to_bytes(8, 'big')
    # info hash
    buffer += get_info_hash(torrent)
    # peer id
    buffer += gen_id()

    return buffer
Example #13
0
  def spawn(self, entity_type, x=None, y=None):
    height, width = self.window.size

    entity_id = util.gen_id()
    pos_x = x or random.randrange(round(height * 0.1), round(height * 0.9))
    pos_y = y or random.randrange(round(width * 0.1), round(width * 0.9))

    if entity_type == "automata":
      entity = Automata(entity_id, pos_x, pos_y, global_vars=self.global_vars)
    
    elif entity_type == "algae":
      entity = Algae(entity_id, pos_x, pos_y, global_vars=self.global_vars)

    self.entities.append(entity)
Example #14
0
def create_reward_profile():
    """
    Create a blank reward profile
    :return:
    """
    cursor = db.cursor()

    id = util.gen_id()
    reward_sql = "INSERT INTO reward_profile (reward_id,points) VALUES (%s,%s)"
    values = (id, 0)
    cursor.execute(reward_sql, values)
    db.commit()

    return id
Example #15
0
def insert_db(uid, shown, hidden, nickname, option):
    try:
        db = get_db()
        cur = db.cursor()
        newid = util.gen_id()
        cur.execute(
            "INSERT INTO belong(id,uid,time)VALUES(?,?,?)",
            [newid, uid, time.strftime("%Y-%m-%d %A %X", time.localtime())],
        )
        cur.execute(
            "INSERT INTO msg(id,shown,hidden,cnt,nickname,option)VALUES(?,?,?,?,?,?)",
            [newid, shown, hidden, 0, nickname, option],
        )
        db.commit()
    except sqlite3.IntegrityError, e:
        return insert_db(uid, shown, hidden, nickname, option)
Example #16
0
def main():
    if os.path.exists("video.db"):
        os.remove("video.db")

    parser = ConfigParser()
    parser.read('config.ini')

    nsqd_addr = parser.get("nsqd", "address")
    nsq_port = int(parser.get("nsqd", "port"))
    topic = parser.get("nsqd", "topic")
    offset = parser.get("task", "offset")
    size = parser.get("task", "size")
    flow = parser.get("task", "flow")
    task_name = parser.get("task", "task_name")

    writer = pub.Publisher(nsqd_addr=nsqd_addr, port=nsq_port, topic=topic)

    conn = sqlite3.connect('video.db')
    cursor = conn.cursor()
    index = 0
    for label, sum in Gen().gen():
        msgs = []

        cmd = "select * from video_info where label={} order by idx".format(
            label)
        for row in cursor.execute(cmd):
            index += 1
            msg = {
                "id": util.gen_id(),
                "label": label,
                "idx": row[2],
                "cmd": "",
                "video_name": row[6],
                "offset": offset,
                "frames": 10,
                "task_topic": task_name
            }
            print(msg)
            msgs.append(str(msg))
        print(msgs)
        writer.put_msgs(msgs)

    print("total input:", index)
Example #17
0
def update_rec(con, tbl, rec):
    """ Add a new rec to table.
    con: sqlite connection
    tbl: table name
    rec: dict containing rec fields
    """

    # Create table if it doesn't exist.
    if not tbl in all_tables(con):
        init_table(con, tbl)

    # If existing rec, delete rec first before insert.
    id = rec.get('_id')
    if id != None:
        sql = """DELETE FROM %s WHERE _id = ?""" % (tbl)
        con.cursor().execute(sql, [id])

    # Make sure table schema has all rec columns needed.
    # Create new columns if necessary.
    add_table_cols(con, tbl, set(rec.keys()))

    # Generate new id if not specified
    if id == None or id == "":
        rec['_id'] = util.gen_id()

    rec_cols = list(rec.keys())  # ['_id', '_body', 'field1', 'field2']
    qs = ['?'] * len(rec_cols)  # ['?', '?', '?', '?']

    sql_cols = ", ".join(rec_cols)  # Ex. "_id, _body, field1, field2"
    q_cols = ", ".join(qs)  # Ex. "?, ?, ?, ?"
    sql = """INSERT INTO %s (%s) VALUES (%s)""" % (tbl, sql_cols, q_cols)

    vals = []
    for k in rec_cols:
        vals.append(rec[k])

    con.cursor().execute(sql, vals)
    con.commit()

    return rec['_id']
Example #18
0
    def _do_update_rec():
        # If existing rec, delete rec first before insert.
        id = rec.get('_id')
        if id != None:
            sql = f"DELETE FROM [{tbl}] WHERE _id = ?"
            con.cursor().execute(sql, [id])

        # Generate new id if not specified
        if id == None or id == "":
            rec['_id'] = util.gen_id()

        rec_cols = list(rec.keys())      # ['_id', '_body', 'field1', 'field2']
        qs = ['?'] * len(rec_cols)       # ['?', '?', '?', '?']

        sql_cols = ", ".join(rec_cols)   # Ex. "_id, _body, field1, field2"
        q_cols   = ", ".join(qs)         # Ex. "?, ?, ?, ?"
        sql = f"INSERT INTO [{tbl}] ({sql_cols}) VALUES ({q_cols})"

        vals = []
        for k in rec_cols:
            vals.append(rec[k])
        con.cursor().execute(sql, vals)
        return rec['_id']
Example #19
0
File: start.py Project: zcdy/NoXss
     elif url:
         scope_url = url
     domain = get_domain_from_url(scope_url)
     if is_ip(scope_url):
         save_cookie_ip(args.cookie, domain)
     else:
         from cookie import save_cookie
         save_cookie(args.cookie, domain)
 if url or file or burp or args.id or args.filter:
     if args.id:
         id = args.id
         if not Engine.is_scanned(id):
             print 'Task %s not found,exit.'
             exit(0)
     else:
         id = gen_id()
     engine = Engine(id=id,
                     url=url,
                     file=file,
                     burp=burp,
                     process=num,
                     browser=browser,
                     coroutine=coroutine,
                     filter=filter)
     result = engine.start()
     if result:
         save(result, id)
     else:
         print_info('No xss found!')
     if args.clear:
         from util import clear
Example #20
0
 async def new_group(cls):
     group_ident = gen_id()
     group = Group(group_ident)
     await group.redis.set(group.key(cls.CREATED_DATE_KEY), now_tsi())
     return group
Example #21
0
    f for f in os.listdir(SYSTEM_DIR)
    if os.path.isfile(os.path.join(SYSTEM_DIR, f))
]

for system in systems:
    with open(os.path.join(SYSTEM_DIR, system)) as json_file:
        data = json.load(json_file)

        if 'code' not in data:
            data['code'] = cp_hash(data['name'], CODE_OCTETS)

        for contact in data['contacts']:
            c = data['contacts'][contact]

            if 'id' not in c:
                gen_id(contact, c)

        print(f"# {data['name']}")
        print()
        print(f"System type: {data['type']}")
        print(f"System code: {data['code']}")
        print()

        print("## Contacts")
        print()
        print("Name             | Type         | ID")
        print("---------------- | ------------ | -----")
        rows = []
        ic = 0
        for name in data['contacts']:
            contact = data['contacts'][name]
Example #22
0
    def __init__(self, con, tbl, recid, parentw=None):
        super().__init__(border_width=10, title="Add Rec")
        self.set_default_size(EDITREC_WIDTH, EDITREC_HEIGHT)
        self.connect("destroy", self.on_destroy)

        self.con = con
        self.tbl = tbl
        self.parentw = parentw
        self.tbl_cols = db.table_cols(con, tbl)

        self.rec = None
        self.winid = ""

        # This is an 'Edit Rec' window if an existing recid was passed.
        # In this case, the recid will be used as the windows id.
        if recid:
            self.set_title("Edit Rec")
            self.rec = db.read_rec(con, tbl, recid)
            self.winid = recid

        # This is a 'New Rec' window if no recid passed or if nonexisting recid.
        # A window id will be programmatically generated.
        if self.rec == None:
            self.set_title("New Rec")
            self.rec = db.rec_new()
            self.winid = util.gen_id()

        # Grid
        self.grid = Gtk.Grid()
        self.add(self.grid)
        self.grid.set_row_spacing(5)
        self.grid.set_column_spacing(5)

        # Current Table display
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        lbl = Gtk.Label("Table: ")
        lbl_tbl = Gtk.Label()
        lbl_tbl.set_markup(
            f"<span weight='bold' font-family='monospace'>{self.tbl}</span>")
        hbox.pack_start(lbl, False, False, 0)
        hbox.pack_start(lbl_tbl, False, False, 0)
        self.grid.attach(hbox, 0, 0, 10, 1)

        # Horizontal box containing textview and fields
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        self.grid.attach(hbox, 0, 1, 8, 4)

        # Textview in scrolledwindow
        self.mktext_sw = Gtk.ScrolledWindow()
        hbox.pack_start(self.mktext_sw, True, True, 0)
        self.mktext_sw.set_size_request(300, 0)

        self.mktext_sw.set_hexpand(True)
        self.mktext_sw.set_vexpand(True)
        self.mktext_sw.set_policy(Gtk.PolicyType.AUTOMATIC,
                                  Gtk.PolicyType.AUTOMATIC)

        self.mktext_tv = Gtk.TextView()
        self.mktext_sw.add(self.mktext_tv)
        self.mktext_tv.set_wrap_mode(Gtk.WrapMode.WORD)

        # Set textview width
        sw_width = int(EDITREC_WIDTH * 1 / 2)
        self.mktext_sw.set_size_request(sw_width, 0)

        # Fields listbox
        # show_fields() to show fields, hide_fields() to hide.
        # fields listbox is initially hidden until dotfields are entered or parsed.
        self.fields_sw = Gtk.ScrolledWindow()
        hbox.pack_start(self.fields_sw, True, True, 0)
        self.fields_sw.set_hexpand(True)
        self.fields_sw.set_vexpand(False)
        self.fields_sw.set_policy(Gtk.PolicyType.AUTOMATIC,
                                  Gtk.PolicyType.AUTOMATIC)

        self.fields_lb = Gtk.ListBox()
        self.fields_sw.add(self.fields_lb)
        self.fields_lb.set_selection_mode(Gtk.SelectionMode.NONE)

        self.hide_fields()

        # Save, Cancel buttons
        self.save = Gtk.Button(label="Save")
        self.cancel = Gtk.Button(label="Cancel")

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        hbox.pack_start(self.save, False, False, 0)
        hbox.pack_start(self.cancel, False, False, 0)
        self.grid.attach(hbox, 0, 6, 4, 1)

        # Events
        self.mktext_tv.connect("key-release-event", self.mktext_key_release)
        self.save.connect("clicked", self.on_save)
        self.cancel.connect("clicked", self.on_cancel)

        self.show_all()
        self.refresh_ui()
        tv_move_cursor_start(self.mktext_tv)
Example #23
0
 def gen_key(self, max=10):
     key = gen_id()
     self.db[key] = {'uid': {}, 'max': max}
     return key
Example #24
0
File: pomcp.py Project: fmgc/mdp
import random