コード例 #1
0
def main():
    filename, algorithm, cut_off_sec, random_seed = format_check(
    )  # check input format
    city, dim, edge_weight_type, coord = parse_input(
        filename)  # parse input information
    adj_mat = adjacency_mat(dim, edge_weight_type, coord)  # input matrix
    write_adj_mat_file(adj_mat, city, dim)  # save input matrix as csv

    if random_seed == None:
        random_seed = 0
    else:
        random_seed = int(random_seed)

    if algorithm == 'Approx':
        output = Output(filename, algorithm, cut_off_sec,
                        algorithm)  # init output object

        start_MST = time.time()
        c, tour = compute(dim, adj_mat, cut_off_sec=cut_off_sec)
        total_time = time.time() - start_MST

        output.solution([c] + tour)  # generate solution file
        output.sol_trace([('%.4f' % total_time, c)
                          ])  # generate solution trace file

    elif algorithm == 'BnB':
        output = Output(filename, algorithm, cut_off_sec,
                        algorithm)  # init output object

        bnb = BranchNBound(
            adj_mat, dim,
            cut_off_sec)  # param: dist_matrix, num_city, time_limit
        path, cost, trace_list = bnb.run_branch_and_bound()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file

    elif algorithm == 'LS1':  # Iterated LocalSearch
        output = Output(filename, algorithm, cut_off_sec, algorithm,
                        random_seed)  # init output object

        ils = ILS(adj_mat, dim, cut_off_sec, random_seed
                  )  # param: dist_matrix, num_city, time_limit, random_seed
        path, cost, trace_list = ils.iterated_local_search()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file

    elif algorithm == 'LS2':  # Simulated Annealing
        output = Output(filename, algorithm, cut_off_sec, algorithm,
                        random_seed)  # init output object

        sa = SA(adj_mat, dim, 1e30, 1, 0.999, random_seed, cut_off_sec)
        path, cost, trace_list = sa.run_simulated_annealing()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file
コード例 #2
0
class GetEnvVarAddrCommand(Command):
    command = "geva"
    usage = "[variable name]"
    output = Output()
    help = "\tGet address of an environment variable.\n\tex:\tgeva SHELL"

    def set_option(self, option, cmd):

        cm = ""
        for name, value in option.env.items():
            cm += 'export ' + name + '=' + '`python -c \'print "' + value + '"\'`;'

        if option.binType == BinType.THIRTY_TWO:
            getenv = "../utils/getenv32"
        else:
            getenv = "../utils/getenv64"

        try:
            addr = int(
                subprocess.check_output(cm + getenv + ' ' + cmd[1],
                                        shell=True), 16)
        except Exception:
            self.output.write_error_message("Env variable " + cmd[1] +
                                            " not Found")
            return

        addr += len(getenv) - len(option.binPath)

        self.output.write_message("Env variable " + cmd[1] + " Found at " +
                                  Color.blue + hex(addr) + Color.reset)
コード例 #3
0
    def __exec(self, command, switches, args):
        cwd = os.path.abspath(os.curdir)
        if (not os.path.exists(self.path)):
            if (not command == "branch"):
                raise ProjectPathError(
                    "Error executing bzr %s. The project path %s does not exist."
                    % (command, self.path))
        else:
            os.chdir(self.path)

        switchString = [it + "=" + switches[it] for it in switches]

        finalCommand = (" ").join([self.cmd, command] + switchString + args)

        p = subprocess.Popen(finalCommand,
                             shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=True)

        returnValue = Output(p.stdout, p.stderr)
        p.wait()
        os.chdir(cwd)
        if p.returncode != 0:
            raise BzrException(p.returncode, str(returnValue), finalCommand)
        return returnValue
コード例 #4
0
class MainLoop:
    option = Option()
    quit = False
    userInput = UserInput()
    commandHandler = CommandHandler()
    output = Output()
    execInstrution = ExecInstruction()

    def __init__(self, option):
        self.option = option
        self.start_loop()

    def start_loop(self):
        while not self.quit:
            self.output.load_prompt()
            try:
                cmd = self.userInput.read_input()

                if cmd:
                    self.option.payload = None
                    self.commandHandler.command_handler(cmd, self.option)

                    if self.option.payload:
                        self.execInstrution.run(self.option)

            except KeyboardInterrupt:
                self.output.write_message("use " + Color.pink + "\"quit\"" + Color.reset + " to exit")
コード例 #5
0
ファイル: Transaction.py プロジェクト: ketanch/IITKBucks
def transactionFromByteArray(trans_data):
    offset = 0
    in_arr = []
    out_arr = []
    no_of_input = int.from_bytes(trans_data[:4], 'big')
    offset += 4
    for i in range(no_of_input):
        trans_ID = trans_data[offset:offset + 32].hex()
        offset += 32
        index = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        sign_len = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        sign = trans_data[offset:offset + sign_len].hex()
        offset += sign_len
        inp_obj = Input(trans_ID, index, sign)
        in_arr.append(inp_obj)

    no_of_output = int.from_bytes(trans_data[offset:offset + 4], 'big')
    offset += 4
    for i in range(no_of_output):
        coins = int.from_bytes(trans_data[offset:offset + 8], 'big')
        offset += 8
        key_len = int.from_bytes(trans_data[offset:offset + 4], 'big')
        offset += 4
        key = trans_data[offset:offset + key_len].decode()
        offset += key_len
        out_obj = Output(coins, key)
        out_arr.append(out_obj)
    return [in_arr, out_arr]
コード例 #6
0
class ExecInstruction:
    output = Output()

    def __init__(self):
        pass

    def run(self, option):

        if option:
            cmd = ""

            for name, value in option.env.items():
                cmd += 'export ' + name + '=' + '`python -c \'print "' + value + '"\'`;'

            if option.execMode == Mode.PIPED:
                cmd += "(python -c 'print(" + option.payload + ")'; cat) | " + option.binPath

            elif option.execMode == Mode.ARG:
                cmd += option.binPath + " `python -c 'import sys; sys.stdout.write(" + option.payload + ")'`"

            if option.bruteforce:
                option.bruteforce = False
                try:
                    while True:
                        self.output.write_message(Color.yellow + "executing command: " + cmd + Color.reset)
                except KeyboardInterrupt:
                    pass

            self.output.write_message(Color.pink + "executing command: " + cmd + Color.reset)
            system(cmd)
コード例 #7
0
    def get_points(self):
        final_score = 0
        try:
            print("Raw input: " + str(self.raw_input))
            print("Raw output: " + str(self.raw_output))
            self.obj_in = Input(self.raw_input)
            self.obj_out = Output(self.raw_output)
            #self.obj_in.print()
            #self.obj_out.print()
            print("==================================================")
            for vehicle in self.obj_out.vehicles:
                print("----------------------------------------------")
                print("Calculating score for vehicle: {0}".format(vehicle.index))

                for ride_index in vehicle.rides_indexes:
                    ride = self.obj_in.rides[int(ride_index)]
                    print("Taking ride {0}".format(ride_index))
                    ride_score = self.calculate_points(vehicle, ride, int(self.obj_in.bonus))
                    print("Adding {0} to the total score of {1}".format(ride_score, final_score))
                    final_score += ride_score

                    print("Current step time {0}".format(vehicle.step_time))
                    print("------")

        except Exception as e:
            print("Something crashed: " + str(e))
            #raise e
            return 0

        return final_score
コード例 #8
0
    def extractTables(self, path, target):
        """
            Starts the table extraction. Using only this method, nothing will be returned,
            but the HTML output Files will be created in the specified output folder.
        """
        try:
            os.mkdir(target)
        except OSError:
            pass
        os.chdir(target)
        self.__dtdFile = open(target + "/pdf2xml.dtd", "w")
        self.buildDtd()
        self.__cmdLine = "pdftohtml -xml " + path
        print(self.__cmdLine)
        os.system(self.__cmdLine)
        xmlFile = os.path.basename(path).rstrip(".pdf") + ".xml"
        fileMover.moveXmlFile(path=path, target=target)

        #starting the extraction
        firstClassification = FirstClassification(target)
        self.__resultTuple = firstClassification.run(target + "/" + xmlFile)

        tableList = self.__resultTuple[0]
        fontsList = self.__resultTuple[1]
        path = self.__resultTuple[2]

        self.__outputObj = Output(tableList, fontsList, path)
        self.__outputObj.createOutput()
コード例 #9
0
ファイル: Email.py プロジェクト: aaronalt/summit-mail
 def send_external(self, csv_file, write_output=True):
     message = self.build()
     to_filter = ClientFilter(csv_file)
     to_contact = to_filter.filter_emails()
     output = Output(to_contact)
     print("\nClient list to be emailed:\n---------")
     for i in to_contact:
         print(i.name)
     print("-------")
     if write_output:
         output.write()
     proceed = input("Proceed  with emailing? y/n ... ")
     if proceed == 'y':
         with smtplib.SMTP_SSL("smtp.gmail.com", 465,
                               context=self.context) as server:
             server.login(self.sender_email, self.password)
             for each in to_contact:
                 try:
                     server.sendmail(self.sender_email, each.email,
                                     message.as_string())
                 except smtplib.SMTPRecipientsRefused as e:
                     print(e)
                     to_contact.pop(each)
                     pass
         print("\n")
     else:
         print("Aborting the mission...")
コード例 #10
0
ファイル: Transaction.py プロジェクト: ketanch/IITKBucks
 def from_json(self, data):
     data_inp = data['input']
     data_out = data['output']
     for i in data_inp:
         self.inp_arr.append(
             Input(i['transactionID'], i['index'], i['signature']))
     for i in data_out:
         self.out_arr.append(Output(i['amount'], i['recepient']))
コード例 #11
0
 def __init__(self):
     """
     creates a new program
     """
     self.input = Input()
     self.output = Output()
     self.inventory = Inventory()
     self.choice = None
コード例 #12
0
 def __init__(self):
     self.input = Input()
     pygame.init()
     pygame.display.set_mode(
         (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
     pygame.display.set_caption("color-based-multi-person-id-tracker")
     screen = pygame.display.get_surface()
     self.output = Output(screen, self.input)
コード例 #13
0
 def lint(self):
     statusoutput = self.status()
     lintoutput = ""
     for line in str(statusoutput).split("\n"):
         if line.startswith("?"):
             lintoutput += line + "\n"
     lintoutput += str(self.__exec("conflicts", {}, []))
     tmp = Output(StringIO.StringIO(lintoutput), StringIO.StringIO())
     return tmp
コード例 #14
0
ファイル: Pipeline.py プロジェクト: kushalmehta13/MIPS
 def __init__(self, instruction_path, register_path, config_path,
              memory_path):
     pp = pprint.PrettyPrinter(indent=4)
     self.configuration = self.getconfig(config_path)
     self.arch = self.getArch(memory_path, register_path,
                              self.configuration)
     self.instructions = self.getInstructions(instruction_path)
     print(self.instructions)
     self.labels = self.getLabels(instruction_path)
     self.instructionMapping = self.defineInstructions()
     self.OUT = Output()
コード例 #15
0
class CommandHandler:
    commands = []
    output = Output()

    def __init__(self):
        self.init_all_command()

    def init_all_command(self):
        self.commands.append(QuitCommand())
        self.commands.append(ChangeBinaryCommand())
        self.commands.append(ChangeModeCommand())
        self.commands.append(ChangeShellcodeCommand())
        self.commands.append(ListFilesCommand())
        self.commands.append(ListFunctionsCommand())
        self.commands.append(DisassFunctionsCommand())
        self.commands.append(CheckASLRCommand())
        self.commands.append(JumpToFunctionCommand())
        self.commands.append(ChangeBufferSizeCommand())
        self.commands.append(SetVariableValueCommand())
        self.commands.append(FindFunctionsCommand())
        self.commands.append(FindStringCommand())
        self.commands.append(ChangeBinTypeCommand())
        self.commands.append(JumpToShellcodeCommand())
        self.commands.append(RunPayloadCommand())
        self.commands.append(SetEnvCommand())
        self.commands.append(UnSetEnvCommand())
        self.commands.append(GetEnvVarAddrCommand())
        self.commands.append(GDBCommand())
        self.commands.append(GetBufferAddrCommand())
        self.commands.append(NopSpreadCommand())
        self.commands.append(FileCommand())

    def command_handler(self, cmd, option):

        if cmd[0] == "help":
            for command in self.commands:
                self.output.write_message(
                    Color.purple + command.get_command() + ":" + " " *
                    (10 - len(command.get_command())) + Color.reset,
                    end='')
                self.output.write_message(Color.pink + command.get_usage() +
                                          Color.reset)
                self.output.write_message(command.get_help(), end="\n\n")
            return

        for command in self.commands:
            if cmd[0] == command.get_command():
                try:
                    command.set_option(option, cmd)
                except Exception as ex:
                    print(ex)
                    self.output.write_error_message("usage: " + cmd[0] + ' ' +
                                                    command.get_usage())
コード例 #16
0
ファイル: ledger.py プロジェクト: cselman99/CSC323-lab4
def run_join(givers: list, receiver: User, send_amounts: list,
             total_send_amount: float, prior_blocks: list):
    remaining_amounts = [0] * len(givers)
    actual_total_amount = 0
    for giver in range(len(givers)):
        giver_total = 0
        for pBlock in range(len(prior_blocks[giver])):
            giver_total += prior_blocks[giver][pBlock].get_value(
                givers[giver].sk)
        actual_total_amount += giver_total
        remaining_amounts[giver] = giver_total - send_amounts[giver]
    return Output(remaining_amounts + [total_send_amount],
                  [giver.sk for giver in givers] + [receiver.sk])
コード例 #17
0
ファイル: IteratedLocalSearch.py プロジェクト: YunhanZou/TSP
def test_io():
    filename = "DATA/Cincinnati.tsp"
    city, dim, edge_weight_type, coord = parse_input(filename)
    adj_mat = adjacency_mat(dim, edge_weight_type, coord)
    algorithm = "TwoOpt"
    cut_off_sec = 10

    output = Output(filename, algorithm, cut_off_sec)
    to = TwoOpt(adj_mat, dim, cut_off_sec)
    path, cost, quality = to.two_opt()

    output.solution([cost] + path)
    output.sol_trace([(quality, cost)])
コード例 #18
0
ファイル: LogandTime.py プロジェクト: HerrNKD/FutaWatcher
    def get_log_time(self):
        """
        get log time
        """
        finish_string = datetime.now().strftime("%Y-%m-%d ")
        log_line = self.get_line()
        finish_line = finish_string + log_line
        try:
            finish = datetime.strptime(finish_line, "%Y-%m-%d %H:%M")
        except Exception as _e:
            Output(_e, 0, "Error in GetLogTime").call_result()

        return finish
コード例 #19
0
class CheckASLRCommand(Command):
    command = "cASLR"
    output = Output()
    help = "\tCheck if ASLR is On or Off."

    def set_option(self, option, cmd):
        f = open("/proc/sys/kernel/randomize_va_space", "r")
        nb = int(f.read())

        if nb == 2:
            self.output.write_message("ASLR is ON")
        else:
            self.output.write_message("ASLR is OFF")
コード例 #20
0
ファイル: ledger.py プロジェクト: cselman99/CSC323-lab4
def run_merge(giver: User, reciever: User, send_amount: float,
              prior_blocks: list):
    #print("in run merge __________")
    total_amount = 0
    try:
        for i in range(len(prior_blocks)):
            #print("merge key length: "+str(len(prior_blocks[i].keys)))
            total_amount += prior_blocks[i].get_value(giver.sk)
        giver_output_amount = total_amount - send_amount
        #print('leave run merge__________')
        return Output([giver_output_amount, send_amount],
                      [giver.sk, reciever.sk])
    except Exception as e:
        pass
コード例 #21
0
    def executeFunction(self,
                        output=True,
                        parsingCriteria=None,
                        default=False,
                        unpack=True,
                        **kargs):
        params = " ".join(list(map(lambda x: f"-{x[0]} {x[1]}",
                                   kargs.items())))
        if parsingCriteria is None:
            parsingCriteria = self.defaultParsingCriteria
        parsingOp = ParsingCriteria().generateCriteria(parsingCriteria)
        if parsingOp is None:
            parsingOp = ""
        code = f"""{self.funcDef}
 $result =  {self.funcName} {params} 
if($result -ne $null){{
    $result = $result {parsingOp} 
     return $result
}}
"""
        if output:
            powershell = sp.Popen(["powershell", code],
                                  stderr=sp.STDOUT,
                                  stdout=sp.PIPE)
            result = powershell.communicate()
            try:
                result = result[0].decode('utf-8')
            except:
                result = str(result[0])
                result = result[2:-1]

            result = Output(result)
            if default:
                if self.defaultParsing is None:
                    return result
                try:
                    parser = result.feed(self.defaultParsing)
                    parser.parsingArgs = self.parsingArgs
                    output = parser.parse()
                    if unpack:
                        return output.unpack()
                    else:
                        return output
                except:
                    return result
            else:
                return result
        else:
            sp.call(["powershell", code])
            return None
コード例 #22
0
 def runProgram(self):
     # try:
     self.output = Output(sleepChar=self.sleepChar,
                          sleepLine=self.sleepLine)
     self.write = self.output.write
     self.writeln = self.output.writeln
     self.canWrite = self.output.canWrite
     self.printHello()
     if not self.tryConnectToRemoteServer():
         print "Closing.. bye."
     self.dbManager = DbManager(self.output)
     self.tryConnectDB()
     self.mainBOT()
     self.newEntry()
コード例 #23
0
ファイル: LogandTime.py プロジェクト: HerrNKD/FutaWatcher
    def check_log(self):
        """
        check log
        """
        log_time = self.get_log_time()
        now_time = self.get_now_time()

        if log_time.hour == 00 and log_time.minute != 00:
            if not log_time.hour == now_time.hour:
                log_time = log_time + timedelta(days=1)

        time = log_time - now_time
        if time.total_seconds() > 0:
            Output("a", 0, "Thread has already been searched.").call_result()
コード例 #24
0
ファイル: IteratedLocalSearch.py プロジェクト: YunhanZou/TSP
def test_ils():
    # filename = "DATA/Cincinnati.tsp"
    filename = "DATA/UKansasState.tsp"

    city, dim, edge_weight_type, coord = parse_input(filename)
    adj_mat = adjacency_mat(dim, edge_weight_type, coord)
    algorithm = "IteratedLocalSearch"
    cut_off_sec = 600

    output = Output(filename, algorithm, cut_off_sec)
    ils = IteratedLocalSearch(adj_mat, dim, cut_off_sec, 20)
    path, cost, quality, _ = ils.iterated_local_search()

    output.solution([cost] + path)
    output.sol_trace([(quality, cost)])
コード例 #25
0
ファイル: Transaction.py プロジェクト: obaranni/pitcoin
 def create_outputs(self, outputs):
     try:
         outputs_dict = json.loads(outputs)['outputs']
         outputs_arr = [i for i in outputs_dict]
         for i in outputs_arr:
             self.validate_output(i)
             self.outputs.append(
                 Output(i['address'], i['value'], i['script_type']))
         self.numb_outputs = struct.pack("<B", len(self.outputs))
     except BadOutputData:
         print("Bad outputs data")
         raise BadOutputFormat
     except:
         print("Bad outputs json format")
         raise BadOutputFormat
コード例 #26
0
ファイル: Task.py プロジェクト: cm-hirano-shigetoshi/fzfyml
    def __init__(self, yml=None, variables=None, switch_expect=None):
        if yml is not None:
            self.__variables = variables

            self.__variables.set_vars(yml.get('vars', []))
            self.__opts = Opts(yml.get('opts', []), variables)
            self.__set_input(yml['input'])
            self.__transform = Transform(
                yml.get('transform', ''), variables,
                self.__opts.get('delimiter', None))
            self.__query = yml.get('query', '')
            self.__preview = yml.get('preview', '')
            self.__bind = Bind(yml.get('bind', {}), self.__variables, self.__transform)
            self.__output = Output(yml.get('output', {}), variables)

            self.__switch_expect = switch_expect
コード例 #27
0
    def missing(self, url, switches={}, revision=""):
        if self.pinnedPatchLevel != None:
            return Output(
                StringIO.StringIO("This branch is pinned to " + str(url) +
                                  " at revision " +
                                  str(self.pinnedPatchLevel)),
                StringIO.StringIO())

        try:
            retval = self.__exec("missing", {"--log-format": "short"}, [url])
        except BzrException, e:
            # If any patches are missing or you have any extra patches
            # Bazaar returns with errorcode 1. Output is on stdout.
            if not (e.errorcode == 1):
                raise BzrMissingException(e.errorcode, e.errormessage,
                                          e.command)
            return e.errormessage
コード例 #28
0
    def __init__(self, config, window):
        self._l = logging.getLogger("plugin.builder")
        self._l.debug("Entered")
        self._window = window
        self._config = config
        # Store last build/compile command run for each document
        # during this session
        self._prev_commands = {}

        # Map to record location of items found in the Output buffer
        # _item_locations[item number] ->
        #     if file loaded : a GtkTextBuffer mark
        #     else: a tuple of (path, line, col)
        self._item_locations = {}

        ui_builder = gtk.Builder()
        ui_builder.add_from_file(
            os.path.join(config.get_data_dir(), 'Builder.glade'))
        self._ui = ui_builder.get_object
        self._ui('dlg_unsaved_file').set_transient_for(window)
        self._ui('dlg_run_command').set_transient_for(window)

        # Add bottom panel console
        self._console = Output(config)
        self._console.set_item_selected_cb(self._goto)
        self._console.set_item_found_cb(self._record)
        bottom = self._window.get_bottom_panel()
        bottom.add_item(self._console.widget(), _('Build Output'),
                        gtk.STOCK_EXECUTE)

        # Insert menu item Tools->Compile
        manager = self._window.get_ui_manager()
        self._action_group = gtk.ActionGroup("plugin_builder")
        self._action_group.add_actions([
            ("plugin_builder_compile", None, _("_Compile"), "<control>F5",
             _("Compile the current document"), self._compile_doc),
            ("plugin_builder_build", None, _("_Build"), "<control>F6",
             _("Run the build command"), self._build)
        ])
        manager.insert_action_group(self._action_group, -1)
        self._ui_id = manager.add_ui_from_string(ui_str)
        self._l.info(manager.get_ui())
        self._save_action = manager.get_action(
            '/ui/MenuBar/FileMenu/FileSaveMenu')
        self._l.info(self._save_action)
コード例 #29
0
    def set_option(self, option, cmd):

        output = Output()

        if option.buffSize == 0:
            output.write_error_message(
                "Buffer size must be set to execute this command")
            return

        value = format_hex_value(cmd[1], option)

        if len(cmd) > 2 and cmd[2] == "after":
            option.payload = '"\\x90" * ' + str(
                option.buffSize
            ) + ' + "' + value + '" + "' + option.shellcode + '"'
        else:
            size = option.buffSize - (len(option.shellcode) / 4)
            option.payload = '"' + option.shellcode + '" + "\\x90" * ' + str(
                int(size)) + ' + "' + value + '"'
コード例 #30
0
ファイル: IteratedLocalSearch.py プロジェクト: YunhanZou/TSP
def run_all_data():
    dir = "DATA/"
    for f in os.listdir(dir):
        if f[-3:] == "tsp":
            print dir + f
            filename = dir + f

            city, dim, edge_weight_type, coord = parse_input(filename)
            adj_mat = adjacency_mat(dim, edge_weight_type, coord)
            algorithm = "IteratedLocalSearch"
            cut_off_sec = 600
            random_seed = 0

            output = Output(filename, algorithm, cut_off_sec)
            ils = IteratedLocalSearch(adj_mat, dim, cut_off_sec, random_seed)
            path, cost, trace_list = ils.iterated_local_search()
            print path, cost, trace_list

            output.solution([cost] + path)
            output.sol_trace(trace_list)