Ejemplo n.º 1
0
def paste_image(piecespath):
    selectpaths = paste.random_select_pieces(piecespath, 4)
    codes = [os.path.basename(path)[0] for path in selectpaths]
    codes = ''.join(codes)
    image = paste.paste("L", selectpaths, (104, 30))
    image = process.add_spot(image, 20, 0)
    return image, codes
Ejemplo n.º 2
0
 def paste(self, entry = None, lexer = None):
     p = paste.paste()
     p.lexer = lexer
     p.host = cherrypy.request.remote.ip
     p.entry = entry
     p.save(self.db)
     raise cherrypy.HTTPRedirect('/view/')
Ejemplo n.º 3
0
def main():

    # Setup other variables
    already_visited = ["" for _ in range(int(CFG["already_visited_len"]))]
    x = 0  # iterator for the above

    # Initialization code
    refreshed = True
    current_page = paste.request_wrap(CFG)
    while current_page is None:
        current_page = paste.request_wrap(CFG)

    while True:
        if refreshed:
            refreshed = False
        else:
            # This is an edge-case if the last iteration, no good links were found and
            # the rightmost sidebar also did not get updated
            # This is basically re-initialization code to get updated latest pastes on the rightmost sidebar
            current_page = paste.request_wrap(CFG)
            while current_page is None:
                current_page = paste.request_wrap(CFG)
        # Seek out rightmost sidebar where the latest pastes are contained
        sidebar = current_page.find("div", {"id": "menu_2"})
        sidebar_elements = sidebar.findAll("li")
        # Seek out good links and work with them
        for s_e in sidebar_elements:
            href = s_e.find("a")["href"]
            description = s_e.find("span").text
            # Must be tagged as plain-text and must not have already been visited
            if "|" not in description and href not in already_visited:
                # Good link
                already_visited[x] = href
                x = (x + 1) % int(CFG["already_visited_len"])
                current_page = paste.request_wrap(CFG, href)
                if current_page != None:
                    try:
                        p = paste.paste(CFG, href, current_page,
                                        my.module_path)
                        result = p.scan()
                        if result.split(" ")[-1] == "MATCH":
                            PyBoiler.Log(f"{result} {'; '.join(p.keywords)}"
                                         ).to_larva()
                        #print(paste.scan())
                        refreshed = True
                    except:
                        PyBoiler.Log("Unknown parse error").to_larva()
Ejemplo n.º 4
0
    def _add_paste(self, update, context):
        try:
            if len(update.message.caption) > MAX_COMMENT_LENGTH:
                context.bot.send_message(chat_id=update.message.chat_id,
                                         text='Слишком длинный комментарий')
                return
        except TypeError:
            pass
        chat_id, current_tag, current_expire_date, current_paste_format,\
            current_private = \
            self.db_manager.get_user_info(update.message.chat_id)[0]
        downloaded_file_name = update.message.document.get_file().download()
        with open(downloaded_file_name) as file:

            try:
                link = paste(
                    code=file.read(),
                    token=self.pb_token,
                    name=update.message.document.file_name,
                    expire_date=current_expire_date,
                    paste_format=PASTE_FORMATS[downloaded_file_name.split('.')
                                               [-1]] if
                    (len(downloaded_file_name.split('.')) > 1
                     and downloaded_file_name.split('.')[-1]
                     in PASTE_FORMATS.keys()) else current_paste_format,
                    private=current_private)
            except UnicodeDecodeError as unicode_error:
                context.bot.send_message(chat_id=update.message.chat_id,
                                         text='Неподдерживаемый формат файла')
                os.unlink(downloaded_file_name)
                traceback.print_exc()
                raise unicode_error

            try:
                self.db_manager.insert_link(
                    update.message.chat_id, update.message.document.file_name,
                    current_tag, update.message.caption
                    if update.message.caption is not None else '',
                    str(update.message.date), link)
                context.bot.send_message(chat_id=update.message.chat_id,
                                         text=link)
            except sqlite3.Error:
                traceback.print_exc()
            os.unlink(downloaded_file_name)
Ejemplo n.º 5
0
Archivo: save.py Proyecto: bqv/sadaharu
def save(bot, ev):
    args = ev.params.split()
    try:
        if args[0].strip().isdigit():
            lines = '\n'.join(reversed(list(bot.chans[ev.dest].getlog())[0:int(ev.params.strip())]))
        else:
            if len(args) > 2 or len(args) < 2 or int(args[1]) > 16 or int(args[1]) < 1:
                bot.reply(ev.dest, "Too many arguments! Use: "+ev.cmd+" [nick] <num>")
                return ev
            victim = args[0].lower()
            lines = '\n'.join(reversed(["<" + victim + "> " + x for x in bot.chans[ev.dest].getlog(victim)][0:int(args[1])]))
        link = paste(lines)
        print(link)
        if link:
            bot.reply(ev.dest, ev.user.nick+": "+link+".txt")
        else:
            bot.reply(ev.dest, "\x02[;_;]\x02 Failed to paste!")
    except Exception as e:
        bot.privmsg(ev.dest, "Use: "+ev.cmd+" [nick] <num>")
        print(e)
    return ev
Ejemplo n.º 6
0
 def dump_greeting_image(self, name, greeting_image_path):
     paste.paste(name, greeting_image_path)
Ejemplo n.º 7
0
def main():
    best_score = 0

    # Load all stations from the csv file
    skip = False
    stations_data = load_data("data/StationsNationaal.csv", skip)

    # Prompt user for necessary input
    user_choices = user_interface(stations_data)

    # Load the connections data from the csv file (Heel Nederland or Noord- en
    # Zuid Holland), skipping a station if necessary
    data_list = load_data(user_choices["data"], user_choices["skip"])

    for _ in range(user_choices["attempts"]):
        # Load all stations as objects into a dictionary
        stations_objects = load_stations(data_list, stations_data)

        # Load all connections into a dictionary
        connection_objects = load_connections(
            data_list, stations_objects, user_choices["change_connections"])

        # Generate a random solution with chosen heuristics
        solution = random_solution(stations_objects, connection_objects,
                                   user_choices)

        # Run the heuristic of "cutting" trains, if the user chose this option
        if user_choices["cut_connections"]:
            solution = cut(solution)

        # Run the heuristic of "pasting" trains, if the user chose this option
        if user_choices["paste_connections"]:
            solution = paste(solution, user_choices["max_minutes"])

        # Delete empty trains from solution
        solution = delete_trains(solution)

        # Calculate the K of a solution with the given function
        score = calculate(solution)

        # Set score to new values
        if score > best_score:
            best_solution = solution
            best_score = score

    # Open outputfile
    f = open("output.csv", "w")
    f.write("random:\ntrein, lijnvoering\n")

    counter = 0

    # Write random solution to outputfile
    for train in best_solution["trains"]:
        counter += 1
        f.write(f'trein_{counter}, "{train}"\n')
    f.write(f"SCORE:{best_score}\n\n")
    f.close()

    # If simulated annealing is chosen
    if user_choices["sim_annealing"] == True:
        best_solution = simulated_annealing(solution, stations_objects,
                                            user_choices)

        # If heuristic cut is chosen
        if user_choices["SA_cut_connections"]:
            best_solution = cut(best_solution)

        best_solution = delete_trains(best_solution)
        better_score = calculate(best_solution)

        # Open outputfile
        f = open("output.csv", "a+")
        f.write("simulated annealing:\ntrein, lijnvoering\n")
        counter = 0

        # Write simulated annealing solution to outputfile
        for train in best_solution["trains"]:
            counter += 1
            f.write(f'trein_{counter}, "{train}"\n')
        f.write(f"SCORE:{better_score}\n\n")
        f.close()

    # Draw the map
    if user_choices["data"] == "data/ConnectiesHolland.csv":
        draw_train_holland(best_solution, stations_objects)
    else:
        draw_train(best_solution, stations_objects)
Ejemplo n.º 8
0
    sftp_dst = remote.sftpclient(args.destination) if origin_dst == 'remote' else None

    root_src = remote.info(args.source).root if origin_src == 'remote' else os.path.abspath(args.source)
    root_dst = remote.info(args.destination).root if origin_dst == 'remote' else os.path.abspath(args.destination)

    ignore = ignore(root_src + os.sep + 'config.json', sftp_src)

    if args.backup:
        print 'backuping folder ' + root_dst
        zip(root_dst, paths(root_dst, ignore, sftp_dst), args.backup, sftp_dst)

    for file_src in paths(root_src, ignore, sftp_src):
        file_dst = file_src.replace(root_src, root_dst)
        if utils.isdir(file_src, sftp_src):
            print 'creating folder ' + file_dst
            utils.mkdir(file_dst, sftp_dst)
        else:
            data_src = copy(file_src, sftp_src)
            if exists(file_dst):
                data_dst = copy(file_dst, sftp_dst)
                md5_data_src = md5(data_src).digest()
                md5_data_dst = md5(data_dst).digest()
                if md5_data_src == md5_data_dst:
                    print 'unchanged ' + file_dst
                else:
                    print 'modificing ' + file_dst
                    paste(file_dst, data_src, sftp_dst)
            else:
                print 'creating ' + file_dst
                paste(file_dst, data_src, sftp_dst)
    print 'golem finish'
Ejemplo n.º 9
0
	def __getitem__(self,index):
		row = self.cur.fetchone()
		if row is None:
			raise IndexError
		else:
			return paste.paste(row[0],row[3],row[1],row[4],row[2])
Ejemplo n.º 10
0
	def next(self):
		row = self.cur.fetchone() 
		if row is None:
			return None
		else:
			return paste.paste(row[0],row[3],row[1],row[4],row[2])