Пример #1
0
 def on_close(self, event):
  """Try and stop the reactor."""
  functions.output('Goodbye', process = False)
  try:
   application.log_object.flush()
   config.save()
   reactor.stop()
  except Exception as e:
   logger.exception(e)
  event.Skip()
Пример #2
0
 def write(self, line):
  line = line.decode(sys.getdefaultencoding(), 'ignore')
  self.history.append(line)
  try:
   functions.output(line)
  except (wx.PyDeadObjectError, AttributeError):
   pass # The frame hasn't been created yet or has already been closed.
  except Exception as e:
   self.logger.exception(e)
  if len(self.history) >= self.log_interval:
   self.flush()
Пример #3
0
def play(path, **kwargs):
    """Plays a sound from the sound directory."""
    try:
        return functions.sound(
            os.path.join(application.config.get("sound", "path"), path + application.config.get("sound", "ext")),
            **kwargs
        )
        return True  # Sound played successfully.
    except BassError:
        functions.output(
            "Sound %s failed to play. Ensure your sound path is set properly in settings." % path, process=False
        )
Пример #4
0
 def __init__(self):
  application.frame = self
  self.last_review = [0.0, None, None]
  super(MainFrame, self).__init__(None, title = application.name)
  self._review = 0 # The current position of the review cursor.
  self.commands = [] # Command history.
  self._command_pos = 0 # The current position in the command history.
  p = wx.Panel(self)
  self.CreateStatusBar()
  self.SetStatusText('Not connected.')
  s = wx.BoxSizer(wx.VERTICAL)
  self.output = MyTextCtrl(p, style = wx.TE_READONLY | wx.TE_MULTILINE)
  s.Add(self.output, 1, wx.GROW)
  s1 = wx.BoxSizer(wx.HORIZONTAL)
  self.prompt = wx.StaticText(p, label = '&Entry')
  s1.Add(self.prompt, 0, wx.GROW)
  self.entry = wx.TextCtrl(p, style = wx.TE_RICH2)
  self.entry.SetFocus()
  s1.Add(self.entry, 1, wx.GROW)
  s.Add(s1, 0, wx.GROW)
  p.SetSizerAndFit(s)
  keys.add_accelerator(self.entry, 'RETURN', self.do_send)
  keys.add_accelerator(self.entry, 'ESCAPE', lambda event: self.do_clear(save = True))
  keys.add_accelerator(self.entry, 'UP', lambda event: self.do_command_history(self._command_pos - 1)) # Commands are entered using append.
  keys.add_accelerator(self.entry, 'DOWN', lambda event: self.do_command_history(self._command_pos + 1))
  keys.add_accelerator(self.entry, 'CTRL+HOME', lambda event: self.do_command_history(-1))
  keys.add_accelerator(self.entry, 'CTRL+END', lambda event: self.do_command_history(0))
  keys.add_accelerator(self.entry, 'SHIFT+RETURN', lambda event: self.do_send(event, clear = False))
  keys.add_accelerator(self.entry, 'CTRL+RETURN', lambda event: functions.send(self.commands[0]) if self.commands else functions.bell())
  for x in xrange(10):
   keys.add_accelerator(self, 'ALT+%s' % x, lambda event, i = x: self.do_review(-10 if not i else (i * -1), move = False))
   keys.add_accelerator(self, 'ALT+%s' % x, lambda event, i = x: self.output.SpeakLineText(10 if not i else i))
  keys.add_accelerator(self, 'CTRL+SHIFT+Y', lambda event: self.do_review(0))
  keys.add_accelerator(self, 'CTRL+SHIFT+P', lambda event: self.do_review(-1))
  keys.add_accelerator(self, 'CTRL+SHIFT+U', lambda event: self.do_review(max(self._review - 1, 0)))
  keys.add_accelerator(self, 'CTRL+SHIFT+I', lambda event: self.do_review(self._review))
  keys.add_accelerator(self, 'CTRL+SHIFT+O', lambda event: self.do_review(self._review + 1))
  functions.output('Welcome to %s (V%s).\nType %scommands() for help with builtin functions.' % (application.name, application.version, application.config.get('application', 'command_char')))
  mb = wx.MenuBar()
  self.file_menu = wx.Menu()
  self.Bind(wx.EVT_MENU, self.do_load, self.file_menu.Append(wx.ID_ANY, '&Load Script...', 'Load a script.'))
  self.Bind(wx.EVT_MENU, lambda event: application.config.get_gui().Show(True), self.file_menu.Append(wx.ID_PREFERENCES, '&Preferences...', 'Change program configuration.'))
  self.Bind(wx.EVT_MENU, lambda event: functions.quit(), self.file_menu.Append(wx.ID_EXIT, '&Quit', 'Quit the program.'))
  mb.Append(self.file_menu, '&File')
  self.connect_menu = wx.Menu()
  self.Bind(wx.EVT_MENU, lambda event: do_connect(), self.connect_menu.Append(wx.ID_ANY, '&Connect...', 'Create a new connection.'))
  self.Bind(wx.EVT_MENU, lambda event: functions.disconnect(), self.connect_menu.Append(wx.ID_ANY, '&Disconnect', 'Disconnect from the MUD.'))
  mb.Append(self.connect_menu, '&Connect')
  self.SetMenuBar(mb)
  self.Bind(wx.EVT_CLOSE, self.on_close)
Пример #5
0
def run():
    args = parse_arguments()
    # repo = repository.Repository(args.path, args.rev, args.rev_from, args.rev_to)
    repo = repository.Repository(args.path, args.rev)
    repo.connect()

    files.output(repo, './data/files')
    commits.output(repo, './data/commits')
    functions.output(repo, './data/functions')
    features.output(repo, './data/features')

    archive = model.Archive(None, None, None, None)
    archive.project = model.Project(repo.origin, repo.commit, repo.owner, repo.name)
    archive.commits = commits.retrieve(repo)
    archive.files = files.retrieve(repo)
    archive.functions = features.retrieve(repo)
    with open('./data/'+repo.name+'@'+repo.owner+'#'+repo.commit+'.json', 'wb+') as out_json:
        json.dump(archive, out_json, default=model.default, indent=2)

    sys.exit("SOVA: Software warehouse successfully generated")
Пример #6
0
def main(args):

    # Load in data from file
    df = functions.data_load()

    MODEL = 0
    # Check if user wanted
    if args.model is not None:
        MODEL = int(args.model[0])

    # If you want to generate a new model
    if MODEL:
        start = time.time()
        # Process data from data_frame
        tagged_recipes = functions.data_process(df)
        end = time.time()

        print("Data process execution: " + str(round((end - start), 2)) +
              " seconds")
        print("Model training and generation started for 20 epochs")

        start = time.time()
        # Build the model for predictions of recipes
        model = functions.build_model(tagged_recipes)
        end = time.time()

        print("Model build execution: " + str(round((end - start), 2)) +
              " seconds")
        print("")

    # Convert list of list to flat list
    ingredients_list = [
        ingredient for sublist in args.ingredient for ingredient in sublist
    ]

    # Generate predictions
    predictions = functions.build_predictions('Models/NLP.model',
                                              ingredients_list)

    # Build output
    functions.output(predictions, df)
Пример #7
0
def handle_outgoing(line, process = True):
 """Handles a line from the user."""
 sep = application.config.get("application", "command_sep")
 for line in line.split(sep) if sep else [line]:
  if application.config.get("application", "print_commands"):
   functions.output(line, process = False, speak = False)
  line_stripped = line.strip() # Check it irrispective of indent.
  if process:
   to_search = list(triggers.enabled_aliases)
   initial = triggers.literal_aliases.get(line)
   if initial:
    to_search.insert(0, initial)
   for a in to_search:
    logger.debug('Checking alias: %s.', a)
    m = a.pattern.match(line)
    if m:
     try:
      if callable(a.func):
       a.func(a, line, *m.groups(), **m.groupdict())
      else:
       handle_outgoing(a.func.format(a, line, *m.groups(), **m.groupdict()))
     except Exception as e:
      logger.exception(e)
     if a.stop:
      return # Execution should stop.
  if line_stripped.startswith(application.config.get('application', 'command_char')):
   try:
    exec(line_stripped[len(application.config.get('application', 'command_char')):], functions.functions)
   except Exception as e:
    logger.exception(e)
  elif functions.connected():
   if application.factory:
    try:
     application.factory.transport.write(line.encode(application.config.get('application', 'encoding')) + '\r\n'.encode(application.config.get('application', 'encoding')))
    except Exception as e:
     logger.exception(e)
   else:
    logger.warning('Unable to send commands because connection not fully established.')
  else:
   logger.warning('Not connected. Please type %sconnect {host} {port} to begin.', application.config.get('application', 'command_char'))
Пример #8
0
def stedtxt(text: str,
            spaces=False,
            capitals=False,
            mistakes=False,
            statistics=False,
            out=None) -> str:
    """Main sted function

    Args:
        text(str): either path to text file or actual text
        spaces(bool): removes excessive spaces
        capitals(bool): replaces lowercase letter to uppercase where needed
        mistakes(bool): checks for mistakes in text
        statistics(bool): gives statistics of formatted text
        out(str OR None): path to output file
    Returns:
        formatted_text(str), statistic(str): if [out] is None, print formatted text to
            console/terminal, statistic is optional, either a string or None
        statistic(str), output(str): if [out] is not None, returns the result of writing text to file
            attempt, statistic is optional, either a string or None
    """

    # Extract text from file/string and assing it to new [list] variable
    original_text = functions.opener(text)  # list
    formatted_text = original_text[:]  # list

    # Execute function [spaces] if its flag is True
    if spaces:
        formatted_text = functions.spaces(formatted_text)

    # Execute function [capitals] if its flag is True
    if capitals:
        formatted_text = functions.capitals(formatted_text)

    # Execute function [statistics] if its flag is True, else assing None to variable
    statistic = functions.statisctics(formatted_text) if statistics else None

    #! Assemble text back to string before return/writing to file
    formatted_text = functions.assembler(formatted_text)

    # Execute function [mistakes] if its flag is True, else assing None to variable
    mistake = functions.mistakes(formatted_text) if mistakes else None

    # Writing to file if filepath in [out] is specified
    if out is not None:
        return statistic, mistake, functions.output(out, formatted_text)

    # Return text to console/terminal otherwise
    terminal_out = f"\n{30*'='}Output{30*'='}\n" + \
        formatted_text + f"\n{66*'='}\n"
    return terminal_out, statistic, mistake
Пример #9
0
def handle_incoming(line):
 """Handles lines coming from the MUD."""
 for c in re.findall(colour_re, line):
  if application.config.get('application', 'print_colours'):
   res = ''
   for bit in c.split(';'):
    if res:
     res += ' + '
    res += colour_codes.get(bit, 'unknown')
   res = '<%s>' % res
  else:
   res = ''
  line = line.replace('\x1b[%sm' % c, res)
 to_search = list(triggers.enabled_triggers)
 initial = triggers.literal_triggers.get(line)
 if initial:
  to_search.insert(0, initial)
 for t in to_search:
  logger.debug('Checking trigger: %s.', t)
  m = t.pattern.match(line)
  if m:
   try:
    if callable(t.func):
     t.func(t, line, *m.groups(), **m.groupdict())
    else:
     handle_outgoing(t.func.format(t, line, *m.groups(), **m.groupdict()))
   except Exception as e:
    logger.exception(e)
   if t.stop:
    break # Processing should be halted.
 if line in gags:
  return
 elif application.substitute != None:
  line = application.substitute
  application.substitute = None
  if line == False:
   return
 functions.output(line) 
Пример #10
0
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi("app.ui", self)

        components = [self.comp_1, self.comp_2]
        combo = [self.singleComp_1, self.singleComp_2]
        images = [self.image_1, self.image_2]
        openImages = [self.actionImage_1, self.actionImage_2]
        sliders = [self.slider_1, self.slider_2]
        sliderLabels = [self.sliderValue_1, self.sliderValue_2]
        imageComp = [self.mixerImage_1, self.mixerImage_2]
        mixers = [self.mixerComp_1, self.mixerComp_2]
        self.outputs = {"Output 1": self.output_1, "Output 2": self.output_2}
        self.actionExit.triggered.connect(self.close)
        for i in range(2):
            tools.openConnect(self, images[i], openImages[i], i)
            tools.comboConnect(self, combo[i], components[i], i)
            tools.sliderConnect(self, sliders[i], sliderLabels[i])
            tools.outComboConnect(self, mixers[i])
            tools.imageCompConnect(self, imageComp[i])
        self.setOutput.activated[str].connect(lambda: tools.output(self))
Пример #11
0
 def __init__(self):
     super(Ui, self).__init__()
     uic.loadUi("app.ui", self)
     components = [self.comp_1, self.comp_2]
     comboBoxes = [self.singleComp_1, self.singleComp_2]
     images = [self.image_1, self.image_2]
     openImages = [self.actionImage_1, self.actionImage_2]
     sliders = [self.slider_1, self.slider_2]
     sliderLabels = [self.sliderValue_1, self.sliderValue_2]
     imageCompnts = [self.mixerImage_1, self.mixerImage_2]
     mixers = [self.mixerComp_1, self.mixerComp_2]
     self.outputs = {"Output 1": self.output_1, "Output 2": self.output_2}
     for i in range(2):
         comboBoxes[i].setCurrentIndex(-1)
         tools.openConnect(self, images[i], openImages[i], i)
         tools.fftCompConnect(self, comboBoxes[i], components[i], i)
         tools.sliderConnect(self, sliders[i], sliderLabels[i])
         tools.outComboConnect(self, mixers[i])
         tools.mixerImagesConnect(self, imageCompnts[i])
     self.setOutput.setCurrentIndex(-1)
     self.setOutput.activated[str].connect(lambda: tools.output(self))
     self.actionReset.triggered.connect(lambda: tools.reset(
         self, images, components, comboBoxes, self.outputs))
Пример #12
0
d = d.replace(",", "", 1)
d = d.replace('"', "", 10000000)
d = d.replace("])", "]", 10000000)

b = data1("https://www.defensenews.com/home/",
          'generic-results-list-main-wrapper')
b = str(b)
b = ' = ', b
b = str(b)
b = b.replace('(', '', 10000000)
b = b.replace("'", "", 2)
b = b.replace(",", "", 1)
b = b.replace('"', "", 10000000)
b = b.replace("])", "]", 10000000)

c = output()
c = str(c)
c = ' = ', c
c = str(c)
c = c.replace('(', '', 10000000)
c = c.replace("'", "", 2)
c = c.replace(",", "", 1)
c = c.replace('"', "", 10000000)
c = c.replace("])", "]", 10000000)

img = []
for k in range(
        len(
            data1("https://www.defensenews.com/home/",
                  'generic-results-list-main-wrapper')[0])):
    if 'https' not in data1("https://www.defensenews.com/home/",
Пример #13
0
#prepare data for prediction
dataframe = pandas.DataFrame(seq_mat)
dataset = dataframe.values

x = dataset[:,0:1364].astype(float)

X = np.zeros(shape=(len(x),4,341,1))

for i in range(len(x)):
	tp = np.asarray(x[i])
	tp = np.resize(tp,(4,341,1))
	X[i] = tp

#prediction
print("Loading Model and predicting ...")
sp = int(args.species)

out = prediction(X, sp)

#get piRNA sequences
piRNA = output(out, seq_id, seq_dic)#piRNA is a dict to store the piRNA sequences from the prediction result

#get the output file
out = open(args.output_file,'w+')
print("piRNA are saving in %s ..." % args.output_file)
for k,v in piRNA.items():
	out.write(k)
	out.write("\n")
	out.write(v)
	out.write("\n")
Пример #14
0
    def Check_Options(self):

        functions.globstring = "./GenCoF-master/Sickle/sickle-master/sickle"
        errors = ''

        if (self.var_se_pe.get() == "Paired-end"):
            functions.args_se_pe(self.var_se_pe.get())
            if (self.var_g.get()):
                functions.args_se_and_pe_non_man("-g", "")

            if (self.var_reverse_file == ''):

                if ((".fastq" not in self.var_filename
                     and ".fq" not in self.var_filename)
                        or self.var_filename == ''):
                    errors += "Enter file with .fastq or .fq appended to the end\n"
                else:
                    functions.file_input_inter(self.var_filename)

                if (self.var_qual.get() != "Pick Quality Type"):
                    functions.quality_vals(self.var_qual.get())
                else:
                    errors += "Enter quality type\n"

                if (self.var_m.get()):
                    if (self.var_g.get()):
                        if (self.var_out_file.get() == '' or
                                self.var_out_file.get() == 'Output Filename'):
                            functions.inter_big_m('TRIMMED_OUTPUT.fastq.gz')
                        elif (".fastq" not in self.var_out_file.get()
                              and ".fq" not in self.var_out_file.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.inter_big_m(self.var_out_file.get() +
                                                  '.gz')
                    else:
                        if (self.var_out_file.get() == '' or
                                self.var_out_file.get() == 'Output Filename'):
                            functions.inter_big_m('TRIMMED_OUTPUT.fastq')
                        elif (".fastq" not in self.var_out_file.get()
                              and ".fq" not in self.var_out_file.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.inter_big_m(self.var_out_file.get())

                else:
                    if (self.var_g.get()):
                        if (self.var_out_file.get() == '' or
                                self.var_out_file.get() == 'Output Filename'):
                            functions.inter_m('TRIMMED_OUTPUT.fastq.gz')
                        elif (".fastq" not in self.var_out_file.get()
                              and ".fq" not in self.var_out_file.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.inter_m(self.var_out_file.get() + '.gz')

                        if (self.var_singles.get() == ''
                                or self.var_singles.get()
                                == 'Trimmed Singles Filename'):
                            functions.trimmed('TRIMMED_SINGLES.fastq.gz')
                        elif (".fastq" not in self.var_singles.get()
                              and ".fq" not in self.var_singles.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.trimmed(self.var_singles.get() + '.gz')
                    else:
                        if (self.var_out_file.get() == '' or
                                self.var_out_file.get() == 'Output Filename'):
                            functions.inter_m('TRIMMED_OUTPUT.fastq')
                        elif (".fastq" not in self.var_out_file.get()
                              and ".fq" not in self.var_out_file.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.inter_m(self.var_out_file.get())

                        if (self.var_singles.get() == ''
                                or self.var_singles.get()
                                == 'Trimmed Singles Filename'):
                            functions.trimmed('TRIMMED_SINGLES.fastq')
                        elif (".fastq" not in self.var_singles.get()
                              and ".fq" not in self.var_singles.get()):
                            errors += "Enter file with .fastq or .fq appended to the end\n"
                        else:
                            functions.trimmed(self.var_singles.get())

            else:
                if ((".fastq" not in self.var_filename
                     and ".fq" not in self.var_filename)
                        or (self.var_filename == '')):
                    errors += "Enter file with .fastq or .fq appended to the end\n"
                else:
                    functions.file_input(self.var_filename)

                if (".fastq" not in self.var_reverse_file
                        and ".fq" not in self.var_reverse_file):
                    errors += "Enter file with .fastq or .fq appended to the end or clear contents of reverse entry\n"
                else:
                    functions.file_rev_input(self.var_reverse_file)

                if (self.var_qual.get() != "Pick Quality Type"):
                    functions.quality_vals(self.var_qual.get())
                else:
                    errors += "Enter quality value\n"

                if (self.var_g.get()):
                    if (self.var_out_file.get() == ''
                            or self.var_out_file.get() == 'Output Filename'):
                        functions.output('TRIMMED_OUTPUT.fastq.gz')
                    elif ('.fastq' not in self.var_out_file.get()
                          and ".fq" not in self.var_out_file.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.output(self.var_out_file.get() + '.gz')
                else:
                    if (self.var_out_file.get() == ''
                            or self.var_out_file.get() == 'Output Filename'):
                        functions.output('TRIMMED_OUTPUT.fastq')
                    elif ('.fastq' not in self.var_out_file.get()
                          and ".fq" not in self.var_out_file.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.output(self.var_out_file.get())

                if (self.var_g.get()):
                    if (self.var_reverse_output.get() == ''
                            or self.var_reverse_output.get()
                            == 'Trimmed PE Reverse Output Filename'):
                        functions.output_rev('TRIMMED_OUTPUT_REV.fastq.gz')
                    elif (".fastq" not in self.var_reverse_output.get()
                          and ".fq" not in self.var_reverse_output.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.output_rev(self.var_reverse_output.get() +
                                             '.gz')
                else:
                    if (self.var_reverse_output.get() == ''
                            or self.var_reverse_output.get()
                            == 'Trimmed PE Reverse Output Filename'):
                        functions.output_rev('TRIMMED_OUTPUT_REV.fastq')
                    elif (".fastq" not in self.var_reverse_output.get()
                          and ".fq" not in self.var_reverse_output.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.output_rev(self.var_reverse_output.get())

                if (self.var_g.get()):
                    if (self.var_singles.get() == '' or self.var_singles.get()
                            == 'Trimmed Singles Filename'):
                        functions.trimmed('TRIMMED_SINGLES.fastq.gz')
                    elif (".fastq" not in self.var_singles.get()
                          and ".fq" not in self.var_singles.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.trimmed(self.var_singles.get() + '.gz')
                else:
                    if (self.var_singles.get() == '' or self.var_singles.get()
                            == 'Trimmed Singles Filename'):
                        functions.trimmed('TRIMMED_SINGLES.fastq')
                    elif (".fastq" not in self.var_singles.get()
                          and ".fq" not in self.var_singles.get()):
                        errors += "Enter file with .fastq or .fq appended to the end\n"
                    else:
                        functions.trimmed(self.var_singles.get())

        elif (self.var_se_pe.get() == "Single-end            "):
            functions.args_se_pe(self.var_se_pe.get())

            if ((".fastq" not in self.var_filename
                 and ".fq" not in self.var_filename)
                    or (self.var_filename == '')):
                errors += "Pick file with .fastq or .fq appended to the end\n"
            else:
                functions.file_input(self.var_filename)

            if (self.var_qual.get() != "Pick Quality Type"):
                functions.quality_vals(self.var_qual.get())
            else:
                errors += "Enter quality value\n"

            if (self.var_g.get()):
                if (self.var_out_file.get() == ''
                        or self.var_out_file.get() == 'Output Filename'):
                    functions.output('TRIMMED_OUTPUT.fastq.gz')
                elif (".fastq" not in self.var_out_file.get()
                      or ".fq" not in self.var_out_file.get()):
                    errors += "Enter file with .fastq or .fq appended to the end\n"
                else:
                    functions.output(self.var_out_file.get() + '.gz')

            else:
                if (self.var_out_file.get() == ''
                        or self.var_out_file.get() == 'Output Filename'):
                    functions.output('TRIMMED_OUTPUT.fastq')
                elif (".fastq" not in self.var_out_file.get()
                      or ".fq" not in self.var_out_file.get()):
                    errors += "Enter file with .fastq or .fq appended to the end\n"
                else:
                    functions.output(self.var_out_file.get())

        else:
            errors += "Enter SE or PE\n"

        if (functions.is_int(self.var_q_num.get())):
            functions.args_se_and_pe_non_man("-q", int(self.var_q_num.get()))

        if (functions.is_int(self.var_L_num.get())):
            functions.args_se_and_pe_non_man("-l", int(self.var_L_num.get()))

        if (self.var_x.get()):
            functions.args_se_and_pe_non_man("-x", "")

        if (self.var_n.get()):
            functions.args_se_and_pe_non_man("-n", "")

        self.err_message.config(text="Running....", font="Times 18")
        self.update()
        if (errors == ''):
            cmd_line = shlex.split(functions.globstring)
            if ('sickle'
                    in os.listdir('./GenCoF-master/Sickle/sickle-master/')):
                subprocess.call([
                    'chmod', '+x',
                    './GenCoF-master/Sickle/sickle-master/sickle'
                ])
                p = subprocess.Popen(cmd_line,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                result, error = p.communicate()
                if (error.decode('utf-8') == ''):
                    self.err_message.config(text="OUTPUT: \n" +
                                            result.decode('utf-8'),
                                            font="Times 18")
                else:
                    self.err_message.config(text='\nERRORS: \n' +
                                            error.decode('utf-8'),
                                            font="Times 18")
            elif ('sickle'
                  not in os.listdir('./GenCoF-master/Sickle/sickle-master/')
                  and 'Makefile'
                  in os.listdir('./GenCoF-master/Sickle/sickle-master/')):
                subprocess.call(
                    ["make", "-C", "./GenCoF-master/Sickle/sickle-master/"])
                p = subprocess.Popen(cmd_line,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                result, error = p.communicate()
                if (error.decode('utf-8') == ''):
                    self.err_message.config(text="\n" + result.decode('utf-8'),
                                            font="Times 18")
                else:
                    self.err_message.config(text='\n' + error.decode('utf-8'),
                                            font="Times 18")
            else:
                self.err_message.config(
                    text="ERRORS: \n makefile not in correct directory",
                    fg='dark red',
                    font="Times 18")
        else:
            self.err_message.config(text=('ERRORS: \n' + errors),
                                    fg='dark red',
                                    font="Times 18")

        return
Пример #15
0
def main():
    """Define argument parses, process arguments and call functions."""
    # Define argument parsers and subparsers
    parser = argparse.ArgumentParser(description='A program for testing '
                                     'implementations of the sieve of '
                                     'Eratosthenes. '
                                     '(https://github.com/flozo/Eratosthenes)')
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version='%(prog)s ' + version_str)
    parser.add_argument('-v',
                        '--verbose',
                        action='count',
                        default=0,
                        help='verbosity level (-v, -vv, -vvv): '
                        'default = single-line output, v = multi-line, '
                        'vv = detailed')
    parser.add_argument('-q',
                        '--quiet',
                        action='store_true',
                        help=('disable terminal output (terminates all '
                              'verbosity)'))
    parser.add_argument('-p',
                        '--progress',
                        action='store_true',
                        help=('show progress bar'))
    parser.add_argument('-s',
                        '--sievemethod',
                        dest='sievemethod',
                        choices=('all', 'odd', '3k', '4k', '6k', 'list',
                                 'list-np', 'divisors'),
                        default='6k',
                        help='sieve method (default: 6k)')
    parser.add_argument('-d',
                        '--divisormethod',
                        choices=('all', 'sqrt', 'odd', 'sqrt-odd'),
                        default='sqrt-odd',
                        help='divisor method (default: sqrt-odd)')
    parser.add_argument('-a',
                        '--auto-name',
                        dest='autoname',
                        action='store_true',
                        help='generate name for output file automatically as '
                        '\'Eratosthenes_<limit>_<sievemethod>_<divisormethod>'
                        '_<mode>.dat\' with path from [outfile]')
    parser.add_argument('-m',
                        '--mode',
                        choices=('memory', 'storage'),
                        default='memory',
                        help='on-the-fly writing mode '
                        '(memory=keep result in array before writing to file, '
                        'storage=write to storage on the fly)')
    parser.add_argument('-k',
                        '--keep',
                        choices=('always', 'never', 'interrupt'),
                        default='interrupt',
                        help='keep mode for temporary '
                        'file (storage mode only)')
    parser.add_argument('limit',
                        type=int,
                        default=100,
                        help='upper limit of test range (a non-negative '
                        'integer)')
    parser.add_argument('outfile', nargs='?', help='write to file \'outfile\'')

    args = parser.parse_args()

    # Translate verbosity level
    verbosity = fn.verbosity_level(args)

    # Print argument list if -v, -vv, or -vvv
    if verbosity >= 1:
        print(args)

    # Define file extension for temporary file
    temp_ext = '.temp'
    # Translate progress option
    # hide_progress = not(args.progress)

    # Create divisor-method object
    divisor_method = classes.DivisorMethod(args.divisormethod)
    # Create sieve-method object
    sieve_method = classes.SieveMethod(args.sievemethod)
    # divisorfunc = fn.select_divisormethod(args)
    # Generate automatic filename
    path, outfile = fn.auto_filename(args, verbosity)
    # Make limit integer
    limit_specified = int(args.limit)
    # Define settings object
    settings = classes.Settings(divisor_method.name, sieve_method.name,
                                version_str, limit_specified,
                                sieve_method.get_iterations(limit_specified),
                                args.progress, args.mode, args.keep,
                                args.autoname, path, outfile, temp_ext)
    if verbosity >= 1:
        settings.show_description()
    # algorithm = classes.Algorithm(args.divisormethod, args.sievemethod)
    # Set interrupt switch to default
    interrupt = False

    # if verbosity >= 1:
    #     print()
    # Start timer
    start = time.process_time()
    # Check writing mode
    if settings.mode == 'storage':
        # Write to temporary file
        interrupt, last_iter, limit_actual = fn.select_algorithm_storage_mode(
            divisor_method, sieve_method, settings, verbosity)
    else:
        # Determine prime numbers
        primes, interrupt, last_iter, limit_actual = fn.select_algorithm_memory_mode(
            divisor_method, sieve_method, settings, verbosity)
    # Stop timer
    elapsed_time = (time.process_time() - start)
    if settings.mode == 'storage':
        # Read temporary file
        with open(settings.tempfile, 'r') as f:
            primes = f.read().splitlines()
    # Calculate percentage of completed iterations
    percentage_completed = last_iter / settings.iterations * 100
    # Define Result object
    result = classes.Result(last_iter, percentage_completed, limit_actual,
                            elapsed_time, interrupt, primes)
    # Print result if -vv
    if verbosity >= 2:
        print(primes)

    # Generate output
    fn.output(divisor_method, sieve_method, settings, result, verbosity)
Пример #16
0
#!/usr/bin/python3
"""
A fantasy rpg, using classes to define and track characters, monsters, etc.
"""
#Import all other files and modules
import maps
import character_classes as CC
import creatures as C
import functions as func
import messages

#Welcome screen
func.output(messages.welcome)
func.clear()

#Title
func.output("Chracter Classes")

#Show character menu
print("#", "Job    ", "Ability       ", "Health", "Attack", "Defense", "Speed")
print("1", CC.Cleric.job, "", CC.Cleric.ability, " " * 9, CC.Cleric.health,
      " " * 2, CC.Cleric.attack, " " * 3, CC.Cleric.defense, " " * 4,
      CC.Cleric.speed)
print("2", CC.Brute.job, " ", CC.Brute.ability, " " * 8, CC.Brute.health,
      " " * 2, CC.Brute.attack, " " * 3, CC.Brute.defense, " " * 4,
      CC.Brute.speed)
print("3", CC.Mage.job, " " * 2, CC.Mage.ability, " " * 8, CC.Mage.health,
      " " * 2, CC.Mage.attack, " " * 3, CC.Mage.defense, " " * 4,
      CC.Mage.speed)
print("4", CC.Knight.job, "", CC.Knight.ability, " " * 7, CC.Knight.health,
      " " * 2, CC.Knight.attack, " " * 3, CC.Knight.defense, " " * 4,