Ejemplo n.º 1
1
def start_match(team1, team2):
    """Start a match between team1 and team2. Return which team won (1 or 2) or
    0 if there was a draw.
    """
    global rnames
    print
    print rnames[team1], "vs", rnames[team2]
    print
    args = CMD_STUB.split()
    args.extend([team1, team2])
    print "Starting", " ".join(args)
    stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE).communicate()
    tmp = reversed(stdout.splitlines())
    lastline = None
    # get the real names of the teams.
    # pelitagame will output two lines of the following form:
    # Using factory 'RandomPlayer' -> 'The RandomPlayers'
    for line in stdout.splitlines():
        if line.startswith("Using factory '"):
            split = line.split("'")
            tname, rname = split[1], split[3]
            rnames[tname] = rname
    for line in tmp:
        if line.startswith("Finished."):
            lastline = line
            break
    if not lastline:
        print "*** ERROR: Apparently the game crashed. At least I could not find the outcome of the game."
        print "*** Maybe stderr helps you to debug the problem"
        print stderr
        print "***"
        return 0
    print "***", lastline
    if lastline.find("had a draw.") >= 0:
        print "Draw!"
        return 0
    else:
        tmp = lastline.split("'")
        winner = tmp[1]
        loser = tmp[3]
        if winner == rnames[team1]:
            print team1, "wins."
            return 1
        elif winner == rnames[team2]:
            print team2, "wins."
            return 2
        else:
            print "Unable to parse winning result :("
            return 0
Ejemplo n.º 2
0
def test_rename_combo():    
    comm = "vk rename --prefix PREFIX_ --suffix _SUFFIX --subst N2:TEST --subst WN2001,TEST2 --subst AB1=TEST3 test_data/test.vcf.gz | bcftools query --list-samples"
    rename.main(["rename","--prefix","PREFIX_","--suffix","_SUFFIX","--subst","N2:TEST","--subst","WN2001,TEST2","--subst","AB1=TEST3","test_data/test.vcf.gz"])
    out, err = Popen(comm, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    assert all([x.startswith("PREFIX_") for x in out.splitlines()])
    assert sum(["TEST" in x for x in out.splitlines()]) == 3
    assert all([x.endswith("_SUFFIX") for x in out.splitlines()])
Ejemplo n.º 3
0
def main():
    branch = is_repo()

    res, err = Popen(['git','diff','--name-status'], stdout=PIPE, stderr=PIPE).communicate()
    err_string = err.decode('utf-8')
    if 'fatal' in err_string:
        sys.exit(0)
    changed_files = [namestat[0] for namestat in res.splitlines()]
    staged_files = [namestat[0] for namestat in Popen(['git','diff', '--staged','--name-status'], stdout=PIPE).communicate()[0].splitlines()]
    nb_changed = len(changed_files) - changed_files.count('U')
    nb_U = staged_files.count('U')
    nb_staged = len(staged_files) - nb_U
    staged = str(nb_staged)
    conflicts = str(nb_U)
    changed = str(nb_changed)
    nb_untracked = len(Popen(['git','ls-files','--others','--exclude-standard'],stdout=PIPE).communicate()[0].splitlines())
    untracked = str(nb_untracked)
    if not nb_changed and not nb_staged and not nb_U and not nb_untracked:
        clean = '1'
    else:
        clean = '0'

    remote = ''

    if not branch: # not on any branch
        branch = symbols['prehash']+ Popen(['git','rev-parse','--short','HEAD'], stdout=PIPE).communicate()[0][:-1]
    else:
        remote_name = Popen(['git','config','branch.%s.remote' % branch], stdout=PIPE).communicate()[0].strip()
        if remote_name:
            merge_name = Popen(['git','config','branch.%s.merge' % branch], stdout=PIPE).communicate()[0].strip()
            if remote_name == '.': # local
                remote_ref = merge_name
            else:
                remote_ref = 'refs/remotes/%s/%s' % (remote_name, merge_name[11:])
            revgit = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % remote_ref],stdout=PIPE, stderr=PIPE)
            revlist = revgit.communicate()[0]
            if revgit.poll(): # fallback to local
                revlist = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % merge_name],stdout=PIPE, stderr=PIPE).communicate()[0]
            behead = revlist.splitlines()
            ahead = len([x for x in behead if x[0]=='>'])
            behind = len(behead) - ahead
            if behind:
                remote += '%s%s' % (symbols['behind'], behind)
            if ahead:
                remote += '%s%s' % (symbols['ahead of'], ahead)

    out = '\n'.join([
        branch,
        remote,
        staged,
        conflicts,
        changed,
        untracked,
        clean])
    print(out)
Ejemplo n.º 4
0
def disk_usage(path):
    """Return disk usage statistics about the given path."""    	
    output = Popen(['df', '-k', path], stdout=PIPE).communicate()[0]
    try:
        df = output.splitlines()[2].split()
        device = output.splitlines()[1]
        (size, used, free, percent, mountpoint) = df
    except IndexError:
        df = output.splitlines()[1].split()
        (device, size, used, free, percent, mountpoint) = df
    return (device, int(size), int(used), int(free), percent, mountpoint)
Ejemplo n.º 5
0
def monitor(p):
    def cputimestring2secs(str):
        m = cputime_RE.match(str)

        secs = 60 * int(m.group(2)) + float(m.group(3))
        if m.group(1) is not None:
            secs += 3600 * int(m.group(1))

        return secs

    rsz = vsz = cpu = -1
    while p.poll() is None:
        try:
            r = Popen(("ps", "-p", str(p.pid), "-o" "rsz,vsz,cputime"),
                      stdout=PIPE,
                      env=os.environ).communicate()[0]

            ps = r.splitlines()[1].split()
            rsz = max(rsz, int(ps[0]) * 1024)
            vsz = max(vsz, int(ps[1]) * 1024)
            cpu = max(cpu, cputimestring2secs(ps[2]))
        except:
            break

    return rsz, vsz, cpu
Ejemplo n.º 6
0
def execute(*command):
	out, err = Popen(stdout=PIPE, stderr=PIPE, *command).communicate()
	if not err:
		nb = len(out.splitlines())
	else:
		nb = '?'
	return nb
def diff(old,new):
    """
        Do a diff of two src trees, parse out file names, returns a dict
        with lists
        { new: [...], differ: [...], removed: [...] }
    """
        #do a diff of old and new
    cmd = 'LC_ALL=C diff -rq %s %s | grep -v .svn' % (old,new)    
    res = Popen(cmd,shell=True,stdout=PIPE).communicate()[0]

    differ  = []
    new     = []
    removed = []
    for l in res.splitlines():
        if l.endswith('differ'):
            differ.append(l.split()[3])
        elif l.startswith('Only'):
            s = l.split()
            fpth = path.join(s[2][:-1],s[3])

            if 'alfresco-enterprise-3.4.4' in l:
                new.append(fpth)
            else:
                removed.append(fpth)
                
    return { 'differ': differ, 'removed':removed, 'new':new }
Ejemplo n.º 8
0
	def _generate_mountpoint_topology(cls):
		"""
		Gets the information about disks, partitions and mountpoints. Stores information about used filesystem and
		creates a list of all underlying devices (in case of LVM) for each mountpoint.
		"""
		mountpoint_topology = {}
		current_disk = None

		stdout, stderr = Popen(["/usr/bin/lsblk", "-rno", "TYPE,RM,KNAME,FSTYPE,MOUNTPOINT"], stdout=PIPE, stderr=PIPE, close_fds=True).communicate()
		for columns in map(lambda line: line.split(), stdout.splitlines()):
			if len(columns) < 3:
				continue
			device_type, device_removable, device_name = columns[:3]
			filesystem = columns[3] if len(columns) > 3 else None
			mountpoint = columns[4] if len(columns) > 4 else None

			if device_type == "disk":
				current_disk = device_name
				continue

			# skip removable, skip nonpartitions
			if device_removable == "1" or device_type not in ["part", "lvm"]:
				continue

			if mountpoint is None or mountpoint == "[SWAP]":
				continue

			mountpoint_topology.setdefault(mountpoint, {"disks": set(), "device_name": device_name, "filesystem": filesystem})
			mountpoint_topology[mountpoint]["disks"].add(current_disk)

		cls._mountpoint_topology = mountpoint_topology
Ejemplo n.º 9
0
    def __queueCheck (self):
        """This method runs over each hop in a route and checks the latency 
        of all hops"""
        
        print "Going for a quick run using one packetsize, to check the queue delay"
        
        roundTimeStamp = time.time()

        for packetCount in range (self.maxHopReps):
            sleep (0.5)
            for hop in range (1,self.hopsRequired+1):
                output = Popen (["traceroute", "-n", "-q", "1", "-T", "-f", str (hop), "-m", str (hop), self.targetHost, "1042"], stdout=PIPE).communicate()[0]
                print output

                for line in output.splitlines()[1:]:
                    
                    traceroute = line.split()
                    self.packetsSent += 1
                    # If the packet timed out
                    if len (traceroute) < 3:
                        self.packetsLost += 1
                        continue

                    # interperating the stuff we got back from traceroute
                    tracerouteHop = traceroute[0].strip() 
                    tracerouteIP  = traceroute[1].strip().lstrip("(").rstrip(")")
                    tracerouteRTT = traceroute[2].strip() # this is still a string, not a float
                    
                    tracerouteRTT = float (tracerouteRTT) / 1000.0        
                    self.resultset.add (tracerouteHop, 1098, tracerouteRTT, roundTimeStamp)
        
        print "Queuecheck done"
        print "Send {0} packets, lost {1}".format(self.packetsSent,self.packetsLost)
Ejemplo n.º 10
0
 def __init__(self):
     self.logger = logging.getLogger(__name__)
     self.logger.debug('Initializing notify object')
     if sys.platform == 'linux2':
         self.user = ''
         who = Popen(['/usr/bin/who'], stdout=PIPE).stdout.read()
         for line in who.splitlines():
             if 'tty7' in line:
                 self.user = line.split()[0]  
                 if '(' in line.split()[-1]:
                     self.display = line.split()[-1].replace('(','').replace(')','')
                 else:
                     self.display = ':0'
                 break
         if not self.user:
             self.logger.error('User not found in tty7. Probably no one logged in or in other terminal') 
             raise Exception('No user found.')              
         self.logger.debug('Set user : {0}'.format(self.user))
         self.logger.debug('Set display : {0}'.format(self.display))
         self.logger.debug('Initializing pynotify')
         pynotify.init('Summary')
         self.__notifier = pynotify.Notification
         self.message = self.__message
                    
     if sys.platform == 'win32':
         self.logger.debug('Initializing WindowsBalloonTip')
         self.__notifier = WindowsBalloonTip()
         self.message = self.__message
Ejemplo n.º 11
0
def add_new_apps(apps):
    """ Add new applications to apps' dict
    """
    curr_apps = Popen(DMENU_PATH, stdout=PIPE).communicate()[0]
    for app in curr_apps.splitlines():
        apps.setdefault(app, 0)
    return apps
Ejemplo n.º 12
0
def git_status():
    """
    Get git status.
    """
    git_cmd = ['git', 'status', '-b', '--porcelain']
    result, __ = Popen(git_cmd, stdout=PIPE).communicate()

    branch = remote_branch = ''
    staged = changed = untracked = unmerged = ahead = behind = 0
    commit = ''
    for line in result.splitlines():
        line = line.decode('utf-8')
        prefix = line[0:2]
        line = line[3:]

        if prefix == '##':  # branch name + ahead & behind info
            branch, remote_branch, ahead, behind, commit = parse_git_branch(line)
        elif prefix == '??':  # untracked file
            untracked += 1
        elif prefix in ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'):  # unmerged
            unmerged += 1
        else:
            if prefix[0] in ('M', 'A', 'D', 'R', 'C'):  # changes in index
                staged += 1
            if prefix[1] in ('M', 'D'):  # changes in work tree
                changed += 1

    return (branch, remote_branch, staged, changed, untracked, unmerged,
            ahead, behind, commit)
Ejemplo n.º 13
0
def nslookup(addr):
    result = Popen(['nslookup', addr], stdout=PIPE, stderr=PIPE)\
            .communicate()[0].decode('utf8')
    for line in result.splitlines():
        if 'name = ' in line:
            return line.rsplit('name = ')[-1]
    return None
Ejemplo n.º 14
0
def runcmd(cmd, *args):
    "helper function to grab output of a shell command."
    if args:
        cmd = cmd + ' ' + ' '.join(args)

    output = Popen(shlex.split(cmd), stdout=PIPE).communicate()[0]
    return output.splitlines()
Ejemplo n.º 15
0
    def test_flake8(self):
        """Test if the code is Flake8 compliant."""
        if os.environ.get('ON_TRAVIS', False):
            root = '../'
            command = ['flake8']
            output = Popen(command, stdout=PIPE, cwd=root).communicate()[0]
            default_number_lines = 0
        elif sys.platform.startswith('win'):
            # ET I don't know on windows.
            pass

        else:
            # OSX and linux just delegate to make
            root = '../../'
            command = ['make', 'flake8']
            output = Popen(command, stdout=PIPE, cwd=root).communicate()[0]
            default_number_lines = 0

        # make pep8 produces some extra lines by default.
        lines = len(output.splitlines()) - default_number_lines
        print output
        message = (
            'Hey mate, go back to your keyboard :) (expected %s, got %s '
            'lines from PEP8.)' % (default_number_lines, lines))
        self.assertEquals(lines, 0, message)
Ejemplo n.º 16
0
	def updatevalues(self):
		variable = Popen("sensors -A", stdout=PIPE, shell=True).stdout.read()
		splitvar = variable.splitlines()
		if variable == "":
			print("no sensors")
			return False
		self.titlelist = []
		self.fanarray = {}
		self.temperaturearray = {}
		for x in range(0, len(splitvar)):
			if not(splitvar[x] == ""):
				#sensors output means only titles lack a colon
				if (splitvar[x].find(':') == -1): 
					self.titlelist.append(splitvar[x])
					currentsection = splitvar[x]
				#find all the fan lines
				elif not(splitvar[x].find('fan') == -1):
					splitline = splitvar[x].split()
					data = [(currentsection, splitline[0], splitline[1])]
					for busdevice, sensor, value in data:
						self.fanarray.setdefault(busdevice, {})[sensor] = value
				#find all the lines with a degree sign in
				elif not(splitvar[x].find('\xc2') == -1):
					splitline = splitvar[x].split(':')
					data = [(currentsection,splitline[0],splitline[1].split()[0])]
					for busdevice, sensor, value in data:
						self.temperaturearray.setdefault(busdevice, {})[sensor] = value
Ejemplo n.º 17
0
def main():
    args = parse_args()
    redis_info = Popen(('redis-cli', '-a', redis_pwd(), 'info'),
                       stdout=PIPE).stdout.read()
    redis_info = redis_info.splitlines()

    redis_stats = {}
    for x in redis_info:
        if x.find(':') != -1:
            key, value = x.split(':')
            redis_stats[key] = value

    template = args.prefix + '.{} {} ' + str(int(time()))
    headers = (
        'total_connections_received',
        'total_commands_processed',
        'keyspace_hits',
        'keyspace_misses',
        'used_memory',
        'used_cpu_sys',
        'used_cpu_user',
        'used_cpu_sys_children',
        'used_cpu_user_children',
    )
    for metric in headers:
        print(template.format(metric, redis_stats[metric]))
Ejemplo n.º 18
0
def dosetup(**kwargs):
    if 'enabled' not in kwargs:
	kwargs['enabled'] = False

    kwargs['server']=kwargs['server'][:-1] # take out extra /
    for set in ['hash_id', 'server', 'password', 'enabled',
		'cron_minute', 'cron_hour', 'cron_dom', 'cron_month', 'cron_dow']:
	setSetting(set, kwargs[set])

    old_crontab=Popen(['crontab', '-l'], stdout=PIPE).communicate()[0]
    print old_crontab

    filename = tempfile.mkstemp('crontab')[1]
    new_crontab=file(filename, 'w')
    for line in old_crontab.splitlines():
	if line.find('pushrecords')==-1:
	    new_crontab.write('%s\n' % line)

    if kwargs['enabled']:
	line = '%(cron_minute)s %(cron_hour)s %(cron_dom)s %(cron_month)s %(cron_dow)s' % kwargs
	line = '%s cd /opt/openproximity2; /bin/bash manager.sh egg_command pushrecords >> /tmp/pushrecords.log' % line
	new_crontab.write('%s\n' % line)
    new_crontab.close()

    call(['crontab', filename])
    print Popen(['crontab', '-l'], stdout=PIPE).communicate()[0]
    os.unlink(filename)
Ejemplo n.º 19
0
  def getContentInformation(self):
    """Returns the information about the PDF document with pdfinfo.
    """
    if not self.hasData():
      return dict()
    try:
      return self._content_information.copy()
    except AttributeError:
      pass
    tmp = tempfile.NamedTemporaryFile()
    tmp.write(self.getData())
    tmp.seek(0)
    command_result = None
    try:

      # First, we use pdfinfo to get standard metadata
      command = ['pdfinfo', '-meta', '-box', tmp.name]
      try:
        command_result = Popen(command, stdout=PIPE).communicate()[0]
      except OSError, e:
        if e.errno == errno.ENOENT:
          raise ConversionError('pdfinfo was not found')
        raise

      result = {}
      for line in command_result.splitlines():
        item_list = line.split(':')
        key = item_list[0].strip()
        value = ':'.join(item_list[1:]).strip()
        result[key] = value

      # Then we use PyPDF2 to get extra metadata
      try:
        from PyPDF2 import PdfFileReader
        from PyPDF2.utils import PdfReadError
      except ImportError:
        # if PyPDF2 not found, pass
        pass
      else:
        try:
          pdf_file = PdfFileReader(tmp)
          for info_key, info_value in (pdf_file.getDocumentInfo() or {}).iteritems():
            info_key = info_key.lstrip("/")
            if isinstance(info_value, unicode):
              info_value = info_value.encode("utf-8")

            # Ignore values that cannot be pickled ( such as AAPL:Keywords )
            try:
              pickle.dumps(info_value)
            except pickle.PicklingError:
              LOG("PDFDocument.getContentInformation", INFO,
                "Ignoring non picklable document info on %s: %s (%r)" % (
                self.getRelativeUrl(), info_key, info_value))
            else:
              result.setdefault(info_key, info_value)
        except PdfReadError:
          LOG("PDFDocument.getContentInformation", PROBLEM,
            "PyPDF2 is Unable to read PDF, probably corrupted PDF here : %s" % \
            (self.getRelativeUrl(),))
Ejemplo n.º 20
0
def run_command(command):
	version = sys.version.split()[0].split(".")

	if map(int, version) >= [2, 4]:
		from subprocess import Popen, PIPE
		if type(command) == type(""):
			stdout = Popen([command], stdout=PIPE).communicate()[0]
			return [l.strip() for l in stdout.splitlines()]
		else:
			stdout = Popen(command, stdout=PIPE).communicate()[0]
			return [l.strip() for l in stdout.splitlines()]

	else:
		if type(command) == type(""):
			return [l.strip() for l in os.popen2(command)[1].readlines()]
		else:
			return [l.strip() for l in os.popen2(" ".join(command))[1].readlines()]
Ejemplo n.º 21
0
Archivo: symmap.py Proyecto: ztane/zsos
def read_content():
    output = Popen(["nm", "--demangle", get_kernel_bin_path()], stdout=PIPE).communicate()[0]
    lines = output.splitlines()

    global _split_records
    _split_records = [ i.split(' ', 3) for i in lines ]
    _split_records = [ (int(i[0], 16), i[1], i[2]) for i in _split_records ]

    _split_records.sort(lambda x, y: cmp(y[0], x[0]))
Ejemplo n.º 22
0
 def run(self):
     command = sh_split(' '.join(self.arguments[0:]))
     stdout = Popen(command, stdout=PIPE, stdin=open(os.devnull)
                    ).communicate()[0]
     node = nodes.section()
     node.document = self.state.document
     nested_parse_with_titles(self.state, ViewList(stdout.splitlines()),
                              node)
     return node.children
Ejemplo n.º 23
0
def execute(*command):
	out, err = Popen(*command, stdout=PIPE, stderr=PIPE).communicate()
	out = out.decode("utf-8")
	err = err.decode("utf-8")

	if not err:
		nb = len(out.splitlines())
	else:
		nb = '?'
	return nb
Ejemplo n.º 24
0
 def current_branch(self):
     '''
     Return the name of the current branch
     '''
     out, _ = Popen(self.git_cmd + ['branch'],
                    stdout=PIPE, stderr=PIPE).communicate()
     for line in out.splitlines():
         if line.startswith('*'):
             return line[1:].strip()
     return None
Ejemplo n.º 25
0
def get_prog_version(prog):
    if prog == "libdiscid":
        version = discid.LIBDISCID_VERSION_STRING
    elif prog == "cdrdao":
        outdata = Popen([prog], stderr=PIPE).communicate()[1]
        version = b" ".join(outdata.splitlines()[0].split()[::2][0:2])
    else:
        version = prog

    return decode(version)
Ejemplo n.º 26
0
def get_version():
    """Get the last git tag and call that our version"""
    # Probably not such a great idea
    cmd = "git tag -l | tail -n 1"
    try:
        v = Popen(cmd, stdout=PIPE, shell=True).communicate()[0]
        v = v.splitlines()[0]
    except:
        v = 'unknown'
    return v
Ejemplo n.º 27
0
    def get_data(self):
        d1 = {}
        r1 = re.compile("(.*?)\s=>\s(.*)")

        output = Popen(["facter"], stdout=PIPE, shell=True).communicate()[0]
        for line in output.splitlines():
            match = r1.match(line)
            if match:
                d1[match.group(1)] = match.group(2)

        return d1
Ejemplo n.º 28
0
def get_sockinfo(pid):
    sockinfo = []
    nulldev = open(os.devnull, "w")
    # netstat -plan 2>/dev/null | awk '/[tcp|udp].*pid\/node/{print $4}'
    netstat_process = Popen(['netstat', '-plan'], stdout=PIPE, stderr=nulldev.fileno())
    awk_process_output = Popen([r"awk", "/^[tcp|udp].*\s*" + pid + "\s*\/node/{print $4}"], stdin=netstat_process.stdout, stdout=PIPE, stderr=PIPE).communicate()[0]
    netstat_process.stdout.close()
    if awk_process_output:
        for line in awk_process_output.splitlines():
            sockinfo.append(line)
    return sockinfo
Ejemplo n.º 29
0
def disk_usage(path):
    """Return disk usage statistics about the given path.
	Found at: http://stackoverflow.com/a/7285509/940204
    Returned valus is a named tuple with attributes 'total', 'used' and
    'free', which are the amount of total, used and free space, in bytes.
    """    
	
    output = Popen(['df', '-k', path], stdout=PIPE).communicate()[0]
    df = output.splitlines()[1].split()
    (device, size, used, free, percent, mountpoint) = df
    return (device, int(size), int(used), int(free), percent, mountpoint)
Ejemplo n.º 30
0
def fetch_ntp_state():
    offset = 0
    try:
        raw_data = Popen(['ntpq', '-pn'], stdout=PIPE, stderr=PIPE).communicate()[0]
        for line in raw_data.splitlines():
            if line.startswith('*'):
                offset = line.split()[8]
    except OSError:
        pass

    create_record(offset)
Ejemplo n.º 31
0
    def getContentInformation(self):
        """Returns the information about the PDF document with pdfinfo.
    """
        if not self.hasData():
            return {}
        try:
            return self._content_information.copy()  # pylint: disable=access-member-before-definition
        except AttributeError:
            pass
        tmp = tempfile.NamedTemporaryFile()
        tmp.write(self.getData())
        tmp.seek(0)
        command_result = None
        try:

            # First, we use pdfinfo to get standard metadata
            command = ['pdfinfo', '-meta', '-box', tmp.name]
            try:
                command_result = Popen(command, stdout=PIPE).communicate()[0]
            except OSError, e:
                if e.errno == errno.ENOENT:
                    raise ConversionError('pdfinfo was not found')
                raise

            result = {}
            for line in command_result.splitlines():
                item_list = line.split(':')
                key = item_list[0].strip()
                value = ':'.join(item_list[1:]).strip()
                result[key] = value

            # Then we use PyPDF2 to get extra metadata
            try:
                from PyPDF2 import PdfFileReader
                from PyPDF2.utils import PdfReadError
            except ImportError:
                # if PyPDF2 not found, pass
                pass
            else:
                try:
                    pdf_file = PdfFileReader(tmp)
                    for info_key, info_value in (pdf_file.getDocumentInfo()
                                                 or {}).iteritems():
                        info_key = info_key.lstrip("/")
                        if isinstance(info_value, unicode):
                            info_value = info_value.encode("utf-8")

                        # Ignore values that cannot be pickled ( such as AAPL:Keywords )
                        try:
                            pickle.dumps(info_value)
                        except pickle.PicklingError:
                            LOG(
                                "PDFDocument.getContentInformation", INFO,
                                "Ignoring non picklable document info on %s: %s (%r)"
                                %
                                (self.getRelativeUrl(), info_key, info_value))
                        else:
                            result.setdefault(info_key, info_value)
                except (PdfReadError, AssertionError):
                    LOG("PDFDocument.getContentInformation", PROBLEM,
                      "PyPDF2 is Unable to read PDF, probably corrupted PDF here : %s" % \
                      (self.getRelativeUrl(),))
                except Exception:
                    # an exception of Exception class will be raised when the
                    # document is encrypted.
                    pass
Ejemplo n.º 32
0
]

# search for dependencies only
extra_include_dirs = [
    '%s/include/python%s' %
    (SAGE_LOCAL, platform.python_version().rsplit('.', 1)[0]),
    # finally, standard C/C++ include dirs
    '/usr/local/include/',
    '/usr/include'
]

try:
    from subprocess import Popen, PIPE
    gccinclude = Popen(['gcc', '--print-file-name=include'],
                       stdout=PIPE).communicate()[0]
    extra_include_dirs.extend(gccinclude.splitlines())
except OSError:
    pass

extra_compile_args = []
extra_link_args = []

# comment these four lines out to turn on warnings from gcc
import distutils.sysconfig
NO_WARN = True
if NO_WARN and distutils.sysconfig.get_config_var('CC').startswith("gcc"):
    extra_compile_args.append('-w')

DEVEL = False
if DEVEL:
    extra_compile_args.append('-ggdb')
Ejemplo n.º 33
0
    def evaluate(self,
                 score_functions,
                 on_dev=True,
                 output=None,
                 remove_unk=False,
                 max_dev_size=None,
                 raw_output=False,
                 fix_edits=True,
                 max_test_size=None,
                 post_process_script=None,
                 unk_replace=False,
                 **kwargs):
        """
        Decode a dev or test set, and perform evaluation with respect to gold standard, using the provided
        scoring function. If `output` is defined, also save the decoding output to this file.
        When evaluating development data (`on_dev` to True), several dev sets can be specified (`dev_prefix` parameter
        in configuration files), and a score is computed for each of them.

        :param score_function: name of the scoring function used to score and rank models (typically 'bleu_score')
        :param on_dev: if True, evaluate the dev corpus, otherwise evaluate the test corpus
        :param output: save the hypotheses to this file
        :param remove_unk: remove the UNK symbols from the output
        :param max_dev_size: maximum number of lines to read from dev files
        :param max_test_size: maximum number of lines to read from test files
        :param raw_output: save raw decoder output (don't do post-processing like UNK deletion or subword
            concatenation). The evaluation is still done with the post-processed output.
        :param fix_edits: when predicting edit operations, pad shorter hypotheses with KEEP symbols.
        :return: scores of each corpus to evaluate
        """
        utils.log('starting evaluation')

        if on_dev:
            filenames = self.filenames.dev
        else:
            filenames = [self.filenames.test]

        # convert `output` into a list, for zip
        if isinstance(output, str):
            output = [output]
        elif output is None:
            output = [None] * len(filenames)

        scores = []

        # evaluation on multiple corpora
        for dev_id, (filenames_, output_, prefix) in enumerate(
                zip(filenames, output, self.dev_prefix)):
            if self.ref_ext is not None:
                filenames_ = filenames_[:len(self.src_ext)] + filenames_[-1:]

            if self.dev_batches:
                dev_batches = self.dev_batches[dev_id]
                dev_loss = sum(
                    self.seq2seq_model.step(batch, update_model=False).loss *
                    len(batch) for batch in dev_batches)
                dev_loss /= sum(map(len, dev_batches))
            else:  # TODO
                dev_loss = 0

            src_lines = list(
                utils.read_lines(filenames_[:len(self.src_ext)],
                                 binary=self.binary[:len(self.src_ext)]))
            trg_lines = list(utils.read_lines([filenames_[len(self.src_ext)]]))

            assert len(trg_lines) % len(src_lines) == 0

            references = []
            ref_count = len(trg_lines) // len(src_lines)
            for i in range(len(src_lines)):
                ref = trg_lines[i * ref_count:(i + 1) * ref_count]
                ref = [
                    ref_[0].strip().replace('@@ ', '').replace('@@', '')
                    for ref_ in ref
                ]
                references.append(ref)

            if on_dev and max_dev_size:
                max_size = max_dev_size
            elif not on_dev and max_test_size:
                max_size = max_test_size
            else:
                max_size = len(src_lines)

            src_lines = src_lines[:max_size]
            references = references[:max_size]

            hypotheses = []
            output_file = None
            try:
                if output_ is not None:
                    output_file = open(output_, 'w', encoding='utf8')

                hypothesis_iter = self.decode_batch(src_lines,
                                                    self.batch_size,
                                                    remove_unk=remove_unk,
                                                    fix_edits=fix_edits,
                                                    unk_replace=unk_replace)
                if post_process_script is not None:
                    hypotheses, raw = zip(*hypothesis_iter)
                    data = '\n'.join(hypotheses).encode()
                    data = Popen(
                        [post_process_script], stdout=PIPE,
                        stdin=PIPE).communicate(input=data)[0].decode()
                    hypotheses = data.splitlines()
                    hypothesis_iter = zip(hypotheses, raw)

                for i, hypothesis in enumerate(hypothesis_iter):
                    hypothesis, raw = hypothesis
                    hypotheses.append(hypothesis)
                    if output_file is not None:
                        if raw_output:
                            hypothesis = raw
                        output_file.write(hypothesis + '\n')
                        output_file.flush()
            finally:
                if output_file is not None:
                    output_file.close()

            scores_ = []
            summary = None

            for score_function in score_functions:
                try:
                    if score_function != 'bleu':
                        references_ = [ref[0] for ref in references]
                    else:
                        references_ = references

                    if score_function == 'loss':
                        score = dev_loss
                        reversed_ = True
                    else:
                        fun = getattr(evaluation, 'corpus_' + score_function)
                        try:
                            reversed_ = fun.reversed
                        except AttributeError:
                            reversed_ = False
                        score, score_summary = fun(hypotheses, references_)
                        summary = summary or score_summary

                    scores_.append((score_function, score, reversed_))
                except:
                    pass

            score_info = [
                '{}={:.2f}'.format(key, value) for key, value, _ in scores_
            ]
            score_info.insert(0, prefix)
            if summary:
                score_info.append(summary)

            if self.name is not None:
                score_info.insert(0, self.name)

            utils.log(' '.join(map(str, score_info)))

            # main score
            _, score, reversed_ = scores_[0]
            scores.append(-score if reversed_ else score)

        return scores
Ejemplo n.º 34
0
import sys
gitsym = Popen(['git', 'symbolic-ref', 'HEAD'], stdout=PIPE, stderr=PIPE)
branch, error = gitsym.communicate()

error_string = error.decode('utf-8')

if 'fatal: not a git repository (or any of the parent directories): .git' in error_string:
	sys.exit(0)

branch = branch.strip()[11:]

res, err = Popen(['git','diff','--name-status'], stdout=PIPE, stderr=PIPE).communicate()
err_string = err.decode('utf-8')
if 'fatal' in err_string:
	sys.exit(0)
changed_files = [namestat[0] for namestat in res.splitlines()]
staged_files = [namestat[0] for namestat in Popen(['git','diff', '--staged','--name-status'], stdout=PIPE).communicate()[0].splitlines()]
nb_changed = len(changed_files) - changed_files.count('U')
nb_U = staged_files.count('U')
nb_staged = len(staged_files) - nb_U
staged = str(nb_staged)
conflicts = str(nb_U)
changed = str(nb_changed)
nb_untracked = len(Popen(['git','ls-files','--others','--exclude-standard'],stdout=PIPE).communicate()[0].splitlines())
untracked = str(nb_untracked)
if not nb_changed and not nb_staged and not nb_U and not nb_untracked:
	clean = '1'
else:
	clean = '0'

remote = ''
Ejemplo n.º 35
0
def sensores_ipmi(tela_leds):
    #executa o pyimpi criado na versão py

    tela_leds.ui.progressBar.setValue(0)
    tela_leds.repaint()
    QApplication.processEvents()

    local = "cd IPMI_PY27/criado_pyinstaller_py27/dist/ipmi_py27\n"
    comando = "./ipmi_py27"
    command_stdout = Popen(local + comando,
                           shell=True,
                           stdin=PIPE,
                           stdout=PIPE,
                           stderr=PIPE).communicate()[0]
    command_stdout = command_stdout.splitlines()

    print(command_stdout)

    tela_leds.ui.progressBar.setValue(90)
    tela_leds.repaint()
    QApplication.processEvents()

    if (len(command_stdout) < 1):
        sensores_ipmi_aprovacao = "FAIL"
        sensores_ipmi_result = "SENSORES IPMI - RESULTADO DO TESTE: FAIL"
    else:
        sensores_ipmi_aprovacao = "OK"
        sensores_ipmi_result = "SENSORES IPMI - RESULTADO DO TESTE: OK"
    i = 0
    cont = 0
    outputs = []

    while (i < len(command_stdout)):
        if (str(command_stdout[i].decode("utf-8")) != ""):
            outputs.append(command_stdout[i].decode("utf-8"))
            cont = cont + 1
        i = i + 1

    sensores_ipmi_data_type = []
    sensores_ipmi_data_value = []
    sensores_ipmi_data_units = []
    sensores_ipmi_medicao = []
    text_reading_type_aux = "Reading Type: "
    text_reading_value_aux = "Reading Value: "
    text_reading_units_aux = "Reading Units: "

    i = 0
    for i in range(0, len(outputs) - 2, 3):
        sensores_ipmi_data_type.append(outputs[i].replace(
            text_reading_type_aux, ""))
        sensores_ipmi_data_value.append(outputs[i + 1].replace(
            text_reading_value_aux, ""))
        sensores_ipmi_data_units.append(outputs[i + 2].replace(
            text_reading_units_aux, ""))

    i = 0
    for i in range(0, len(sensores_ipmi_data_type)):
        sensores_ipmi_medicao.append(i + 1)

    tela_leds.ui.progressBar.setValue(100)

    if (sensores_ipmi_aprovacao == "OK"):
        tela_leds.ui.kled_SENSORES_IPMI.setState(1)
        tela_leds.ui.kled_SENSORES_IPMI.setColor(QtGui.QColor(0, 255, 0))
        tela_leds.repaint()
        QApplication.processEvents()
        print("Led SENSORES_IPMI", tela_leds.repaint())
        print("Led SENSORES_IPMI", QApplication.processEvents())
    else:
        tela_leds.ui.kled_SENSORES_IPMI.setState(1)
        tela_leds.ui.kled_SENSORES_IPMI.setColor(QtGui.QColor(255, 0, 0))
        tela_leds.repaint()
        QApplication.processEvents()
        print("Led SENSORES_IPMI", tela_leds.repaint())
        print("Led SENSORES_IPMI", QApplication.processEvents())

    return (sensores_ipmi_data_type, sensores_ipmi_data_value,
            sensores_ipmi_data_units, sensores_ipmi_medicao,
            sensores_ipmi_aprovacao, sensores_ipmi_result)
Ejemplo n.º 36
0
    def evaluate(self,
                 score_function,
                 on_dev=True,
                 output=None,
                 remove_unk=False,
                 max_dev_size=None,
                 raw_output=False,
                 fix_edits=True,
                 max_test_size=None,
                 post_process_script=None,
                 **kwargs):
        """
        Decode a dev or test set, and perform evaluation with respect to gold standard, using the provided
        scoring function. If `output` is defined, also save the decoding output to this file.
        When evaluating development data (`on_dev` to True), several dev sets can be specified (`dev_prefix` parameter
        in configuration files), and a score is computed for each of them.

        :param score_function: name of the scoring function used to score and rank models (typically 'bleu_score')
        :param on_dev: if True, evaluate the dev corpus, otherwise evaluate the test corpus
        :param output: save the hypotheses to this file
        :param remove_unk: remove the UNK symbols from the output
        :param max_dev_size: maximum number of lines to read from dev files
        :param max_test_size: maximum number of lines to read from test files
        :param raw_output: save raw decoder output (don't do post-processing like UNK deletion or subword
            concatenation). The evaluation is still done with the post-processed output.
        :param fix_edits: when predicting edit operations, pad shorter hypotheses with KEEP symbols.
        :return: scores of each corpus to evaluate
        """
        utils.log('starting decoding')

        if on_dev:
            filenames = self.filenames.dev
        else:
            filenames = [self.filenames.test]
        print(filenames)

        # convert `output` into a list, for zip
        if isinstance(output, str):
            output = [output]
        elif output is None:
            output = [None] * len(filenames)

        scores = []
        new_lines = []
        for filenames_, output_, prefix in zip(
                filenames, output,
                self.dev_prefix):  # evaluation on multiple corpora
            extensions = list(self.extensions)
            if self.ref_ext is not None:
                extensions.append(self.ref_ext)

            lines = list(utils.read_lines(filenames_, binary=self.binary))
            if on_dev and max_dev_size:
                lines = lines[:max_dev_size]
            elif not on_dev and max_test_size:
                lines = lines[:max_test_size]

            hypotheses = []
            references = []

            output_file = None

            try:
                if output_ is not None:
                    output_file = open(output_, 'w')

                lines_ = list(zip(*lines))

                src_sentences = list(zip(*lines_[:len(self.src_ext)]))
                trg_sentences = list(zip(*lines_[len(self.src_ext):]))

                hypothesis_iter = self.decode_batch(lines,
                                                    self.batch_size,
                                                    remove_unk=remove_unk,
                                                    fix_edits=fix_edits)
                #ref_file_path = '../data/valid/ref.out'
                #ref_file = open(ref_file_path, 'w')

                for i, (sources, hypothesis, reference) in enumerate(
                        zip(src_sentences, hypothesis_iter, trg_sentences)):
                    if self.ref_ext is not None and on_dev:
                        reference = reference[-1]
                    else:
                        reference = reference[0]  # single output for now

                    hypothesis, raw = hypothesis

                    hypotheses.append(hypothesis)

                    # FIXME: c.f. utils.py:174 for reasons
                    # reference = reference.strip().split('\t')[1]
                    reference = reference.strip()

                    references.append(reference)
                    if output_file is not None:
                        if raw_output:
                            hypothesis = raw

                        output_file.write(hypothesis + '\n')
                        output_file.flush()
                    #ref_file.write(reference + '\n')

            finally:
                if output_file is not None:
                    output_file.close()
                    #ref_file.close()

            if post_process_script is not None:
                data = '\n'.join(hypotheses).encode()
                data = Popen([post_process_script], stdout=PIPE,
                             stdin=PIPE).communicate(input=data)[0].decode()
                hypotheses = data.splitlines()
            print("hypotheses:%d, references: %d" %
                  (len(hypotheses), len(references)))
            print(hypotheses[:2])
            print(references[:2])
            # default scoring function is utils.bleu_score
            # score, avg_score = getattr(evaluation, score_function)(hypotheses, references)
            score = getattr(evaluation, score_function)(hypotheses, references)

            # print scoring information
            # score_info = [prefix, 'score={:.4f} avg_score={:.4f}'.format(score, avg_score)]
            score_info = [prefix, 'score={:.4f}'.format(score)]

            # if score_summary:
            #    score_info.append(score_summary)

            if self.name is not None:
                score_info.insert(0, self.name)

            utils.log(' '.join(map(str, score_info)))
            scores.append(score)

        return scores
Ejemplo n.º 37
0
#!/usr/bin/python

import sys
from subprocess import call, Popen, PIPE

call(["adb", "devices"])

adbStdout, err = Popen(["adb", "devices"], stdout=PIPE).communicate()

print(adbStdout)

adbStdoutList = adbStdout.splitlines()
print(adbStdoutList)
adbDevices = []
for item in adbStdoutList:
    temp = item.split('\t')
    if len(temp) == 2 and temp[1] == "device":
        print(temp[0])
        adbDevices.append(temp[0])

if len(adbDevices) > 1:
    while (1):
        for device in adbDevices:
            print(adbDevices.index(device), ")", device)
        deviceInput = sys.stdin.readline()
        if int(deviceInput) < len(adbDevices) and int(deviceInput) >= 0:
            break
    serial = adbDevices[int(deviceInput)]
elif len(adbDevices) == 1:
    serial = adbDevices[0]
else:
Ejemplo n.º 38
0
def fpga(gravar_fpga_check, IP_CRATE, USERNAME, PASSWORD, POSITION_CRATE,
         tela_leds):
    if (gravar_fpga_check == True):
        print("Iniciou a Gravação da FPGA")
        local = "cd Fpga/impact_fpga\n"
        comando1 = "impact -batch gravar_arquivo_svf_script"
        comando2 = "impact -batch gravar_arquivo_bit_script"

        tela_leds.ui.progressBar.setValue(0)
        tela_leds.repaint()
        QApplication.processEvents()

        command_stdout = Popen(local + comando1,
                               shell=True,
                               stdin=PIPE,
                               stdout=PIPE,
                               stderr=PIPE).communicate()[0]
        command_stdout = command_stdout.splitlines()
        fpga_str = 'Cable connection established'
        check_fpga = fpga_str in str(command_stdout)
        if (check_fpga == True):
            print("Fase 1 de 2 da Gravação da FPGA: Completa")
            tela_leds.ui.progressBar.setValue(10)
            tela_leds.repaint()
            QApplication.processEvents()
        else:
            print("Fase 1 de 2 da Gravação da FPGA: FAIL")
            print(command_stdout)
            print("Encerrando o Programa...")
            tela_leds.ui.kled_fpga.setState(1)
            tela_leds.ui.kled_fpga.setColor(QtGui.QColor(255, 0, 0))
            tela_leds.repaint()
            QApplication.processEvents()
            print(tela_leds.repaint())
            print(QApplication.processEvents())
            time.sleep(SLEEP_TIME)
            sys.exit()
            sys.exit()

        command_stdout = Popen(local + comando2,
                               shell=True,
                               stdin=PIPE,
                               stdout=PIPE,
                               stderr=PIPE).communicate()[0]
        command_stdout = command_stdout.splitlines()

        fpga_str = 'Programmed successfully'

        check_fpga = fpga_str in str(command_stdout)
        if (check_fpga == True):
            print("Fase 2 de 2 da Gravação da FPGA: Completa")
            print("FPGA Gravada com Sucesso!")

            tela_leds.ui.progressBar.setValue(70)
            tela_leds.repaint()
            QApplication.processEvents()
            #FIXME: Isto ocorre pois algumas vezes ao gravarmos a FPGA o CRATE não reconhece a fpga...
            print("Verificando se a FPGA foi reconhecida no CRATE...")
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(IP_CRATE,
                        username=str(USERNAME),
                        password=str(PASSWORD))
            stdin, stdout, stderr = ssh.exec_command('cd /dev/;ls')
            stdin.flush()
            fpga_line = stdout.readlines()
            fgpa_str = 'fpga\n'
            fpga_check = fgpa_str in fpga_line
            if (fpga_check == True):
                print("FPGA reconhecida!")
                tela_leds.ui.progressBar.setValue(100)
                tela_leds.repaint()
                QApplication.processEvents()
            else:
                print("FPGA nao reconhecida!")
                print("Encerrando o programa...")
                tela_leds.ui.kled_fpga.setState(1)
                tela_leds.ui.kled_fpga.setColor(QtGui.QColor(255, 0, 0))
                tela_leds.repaint()
                QApplication.processEvents()
                print(tela_leds.repaint())
                print(QApplication.processEvents())
                time.sleep(SLEEP_TIME)
                sys.exit()
        else:
            print("Fase 2 de 2 da Gravação da FPGA: FAIL")
            print(command_stdout)
            print("Encerrando o Programa...")
            tela_leds.ui.kled_fpga.setState(1)
            tela_leds.ui.kled_fpga.setColor(QtGui.QColor(255, 0, 0))
            tela_leds.repaint()
            QApplication.processEvents()
            print(tela_leds.repaint())
            print(QApplication.processEvents())
            time.sleep(SLEEP_TIME)
            sys.exit()

    fpga_str_result = "FPGA: Gravacao realizada com sucesso"

    return (fpga_str_result)
Ejemplo n.º 39
0
def cis_configuration(
        ad9510_pll_function_config, ad9510_pll_clock_sel_config,
        ad9510_pll_clock_sel_ref_config, ad9510_a_divider_config,
        ad9510_b_divider_config, ad9510_r_divider_config,
        ad9510_prescaler_config, ad9510_pll_powerdown_config,
        ad9510_current_config, ad9510_outputs_config, si571_freq_config,
        si571_output_config, ad9510_a_divider_config_check,
        ad9510_b_divider_config_check, ad9510_current_config_check,
        ad9510_outputs_config_check, ad9510_pll_clock_sel_config_check,
        ad9510_pll_clock_sel_ref_config_check, ad9510_prescaler_config_check,
        ad9510_pll_function_config_check, ad9510_pll_powerdown_config_check,
        ad9510_r_divider_config_check, si571_freq_config_check,
        si571_output_config_check, all_config_check, IP_CRATE, POSITION_ADC,
        POSITION_CRATE, tela_principal):

    ping_crate = Popen(['ping', str(IP_CRATE), '-c', '1', "-W", "2"])
    ping_crate.wait()
    ping_result = ping_crate.poll()
    if (ping_result == 0):
        crate_str_result_msg = "CRATE - COMUNICAÇÃO: OK"
        crate_str_IP = "CRATE - IP: " + str(IP_CRATE)
        print(crate_str_result_msg)
        tela_principal.ui.communication_config.setText("OK")
        tela_principal.repaint()
        QApplication.processEvents()
        communication_config_str = "OK"

    else:
        crate_str_result_msg = "CRATE - COMUNICAÇÃO: FAIL"
        crate_str_IP = "CRATE IP - " + str(IP_CRATE)
        print(crate_str_result_msg)
        print("Encerrando conexão")
        tela_principal.ui.communication_config.setText("FAIL")
        tela_principal.repaint()
        QApplication.processEvents()
        communication_config_str = "FAIL"
        time.sleep(SLEEP_TIME)
        sys.exit()

    if (communication_config_str == "OK"):
        fail_general = 0
        local = "cd CRATE_ACESSO/bpm-app/.halcs-libs/examples\n"

        tela_principal.ui.progressBar_config.setValue(0)
        tela_principal.repaint()
        QApplication.processEvents()

        print("Iniciou a Configuração dos CIs - AD9510 & Si571")
        start_time = datetime.datetime.now()
        start_time_str = start_time.strftime("%Y-%m-%d %H:%M:%S")
        print("Start_write_time:", start_time_str)

        cis_configuration_log = []

        write_text = "WRITTEN VALUE: "
        read_text = "READ VALUE: "
        write_verification_text = "WRITE CHECK: "
        read_verification_text = "READ CHECK: "

        if (all_config_check == True):
            ad9510_pll_function_config_check = True
            ad9510_pll_clock_sel_config_check = True
            ad9510_pll_clock_sel_ref_config_check = True
            ad9510_a_divider_config_check = True
            ad9510_b_divider_config_check = True
            ad9510_r_divider_config_check = True
            ad9510_prescaler_config_check = True
            ad9510_pll_powerdown_config_check = True
            ad9510_current_config_check = True
            ad9510_outputs_config_check = True
            si571_freq_config_check = True
            si571_output_config_check = True

        if (ad9510_pll_function_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -fmc_pll_function " + str(
                            ad9510_pll_function_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")

            cis_configuration_log.append("PLL_FUNCTION CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("PLL_FUNCTION TEST: OK")
                cis_configuration_log.append("PLL_FUNCTION TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("PLL_FUNCTION TEST: FAIL")
                cis_configuration_log.append("PLL_FUNCTION TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("PLL_FUNCTION CONFIG: Não Realizado")

        if (ad9510_pll_clock_sel_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -pll_clk_sel " + str(
                            ad9510_pll_clock_sel_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("PLL_CLOCK_SEL CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("PLL_CLOCK_SEL: OK")
                cis_configuration_log.append("PLL_CLOCK_SEL TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("PLL_CLOCK_SEL TEST: FAIL")
                cis_configuration_log.append("PLL_CLOCK_SEL TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("PLL_CLOCK_SEL CONFIG: Não Realizado")

        if (ad9510_pll_clock_sel_ref_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -pll_clk_sel_ref " + str(
                            ad9510_pll_clock_sel_ref_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("PLL_CLOCK_SEL_REF CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("PLL_CLOCK_SEL_REF: OK")
                cis_configuration_log.append("PLL_CLOCK_SEL_REF TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("PLL_CLOCK_SEL_REF TEST: FAIL")
                cis_configuration_log.append("PLL_CLOCK_SEL_REF TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append(
                "PLL_CLOCK_SEL_REF CONFIG: Não Realizado")

        if (ad9510_a_divider_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE
            ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
                POSITION_ADC) + " -a_div " + str(ad9510_a_divider_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("A_DIVIDER CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("A_DIVIDER: OK")
                cis_configuration_log.append("A_DIVIDER TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("A_DIVIDER TEST: FAIL")
                cis_configuration_log.append("A_DIVIDER TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("A_DIVIDER CONFIG: Não Realizado")

        if (ad9510_b_divider_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE
            ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
                POSITION_ADC) + " -b_div " + str(ad9510_b_divider_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("B_DIVIDER CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("B_DIVIDER: OK")
                cis_configuration_log.append("B_DIVIDER TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("B_DIVIDER: FAIL")
                cis_configuration_log.append("B_DIVIDER TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("B_DIVIDER CONFIG: Não Realizado")

        tela_principal.ui.progressBar_config.setValue(50)
        tela_principal.repaint()
        QApplication.processEvents()

        if (ad9510_r_divider_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE
            ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
                POSITION_ADC) + " -r_div " + str(ad9510_r_divider_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("R_DIVIDER CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("R_DIVIDER TEST: OK")
                cis_configuration_log.append("R_DIVIDER TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("R_DIVIDER TEST: FAIL")
                cis_configuration_log.append("R_DIVIDER TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("R_DIVIDER CONFIG: Não Realizado")

        if (ad9510_prescaler_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -prescaler_div " + str(
                            ad9510_prescaler_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("PRESCALER CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("PRESCALER: OK")
                cis_configuration_log.append("PRESCALER TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("PRESCALER TEST: FAIL")
                cis_configuration_log.append("PRESCALER TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("PRESCALER CONFIG: Não Realizado")

        if (ad9510_pll_powerdown_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -pll_pdown " + str(
                            ad9510_pll_powerdown_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("PLL_PDOWN CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("PLL_PDOWN: OK")
                cis_configuration_log.append("PLL_PDOWN TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("PLL_PDOWN TEST: FAIL")
                cis_configuration_log.append("PLL_PDOWN TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("PLL_PDOWN CONFIG: Não Realizado")

        if (ad9510_current_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE
            ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
                POSITION_ADC) + " -cp_current " + str(ad9510_current_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("CURRENT CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("CURRENT: OK")
                cis_configuration_log.append("CURRENT TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("CURRENT TEST: FAIL")
                cis_configuration_log.append("CURRENT TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("CURRENT CONFIG: Não Realizado")

        if (ad9510_outputs_config_check == True):

            command = "./THALES_ad9510_ctl_CONFIG -b tcp://" + str(
                IP_CRATE
            ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
                POSITION_ADC) + " -outputs " + str(ad9510_outputs_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            cis_configuration_log.append("OUTPUTS CONFIG")
            ad9510_write_check = 0
            ad9510_read_check = 0
            check_function = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            if (write_aux != read_aux):
                cis_configuration_log.append(
                    "Fail Detected - Valor Escrito: " + str(write_aux) +
                    " Valor lido: " + str(read_aux))
                print("Fail Detected - Valor Escrito: ", write_aux,
                      " Valor lido: ", read_aux)
                check_function = check_function + 1

            if (check_function == 0):
                print("OUTPUTS: OK")
                cis_configuration_log.append("OUTPUTS TEST: OK")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
            else:
                print("OUTPUTS TEST: FAIL")
                cis_configuration_log.append("OUTPUTS TEST: FAIL")
                cis_configuration_log.append("Valor Escrito: ", write_aux,
                                             " Valor lido: ", read_aux)
                fail_general = fail_general + 1

        else:
            cis_configuration_log.append("OUTPUTS CONFIG: Não Realizado")
        '''################################################################'''
        if (si571_freq_config_check == True):

            command = "./THALES_si571_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -freq " + str(si571_freq_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            si571_freq_write_check = 0
            si571_freq_read_check = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                si571_freq_write_check = si571_freq_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                si571_freq_read_check = si571_freq_read_check + 1

            print("Verificação...")

            si571_freq_check = 0

            if (read_value != write_value
                    or read_value != str(format(si571_freq_config, '.6f'))):
                print("Valor Enviado pelo Comando: ", si571_freq_config)
                print("Valor Escrito :", write_value)
                print("Valor Lido: ", read_value)
                si571_freq_check = si571_freq_check + 1

            if (si571_freq_check == 0):
                print("Si571 Test: OK")
                si571_freq_result = "OK"
            else:
                print("Si571 Test: FAIL")
                si571_freq_result = "FAIL"
                fail_general = fail_general + 1

            if (si571_freq_write_check != 0):
                si571_freq_write_check_result = "FAIL"
                print("Utilizacao do método de Escrita: ",
                      si571_freq_write_check_result)
                fail_general = fail_general + 1
            else:
                si571_freq_write_check_result = "OK"
                print("Utilizacao do método de Escrita: ",
                      si571_freq_write_check_result)

            if (si571_freq_read_check != 0):
                si571_freq_read_check_result = "FAIL"
                fail_general = fail_general + 1
                print("Utilizacao do método de Leitura: ",
                      si571_freq_read_check_result)
            else:
                si571_freq_read_check_result = "OK"
                print("Utilizacao do método de Leitura: ",
                      si571_freq_read_check_result)

            cis_configuration_log.append(
                "Configuração para o Parâmetro: Si571 - Frequência")
            cis_configuration_log.append("Valor Enviado pelo Comando [Hz]: " +
                                         str(si571_freq_config))
            cis_configuration_log.append("Valor Escrito [Hz]: " +
                                         str(write_value))
            cis_configuration_log.append("Valor Lido [Hz]: " + str(read_value))

            cis_configuration_log.append("Utilizacao do método de Escrita: " +
                                         str(si571_freq_write_check_result))
            cis_configuration_log.append("Utilizacao do método de Leitura: " +
                                         str(si571_freq_read_check_result))
            cis_configuration_log.append("FINAL RESULT: " +
                                         str(si571_freq_result))

        else:
            cis_configuration_log.append("Si571 Freq CONFIG: Não Realizado")
        '''################################################################'''
        if (si571_output_config_check == True):

            command = "./THALES_si571_output_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -output " + str(si571_output_config)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
            write_value = write_aux.replace(write_text, "")
            read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
            read_value = read_aux.replace(read_text, "")

            si571_output_write_check = 0
            si571_output_read_check = 0

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                si571_output_write_check = si571_output_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                si571_output_read_check = si571_output_read_check + 1

            print("Verificação...")

            si571_output_check = 0

            if (read_value != write_value
                    or read_value != str(format(si571_output_config))):
                print("Valor Enviado pelo Comando: ", si571_output_config)
                print("Valor Escrito :", write_value)
                print("Valor Lido: ", read_value)
                si571_output_check = si571_output_check + 1

            if (si571_output_check == 0):
                print("Si571 Test: OK")
                si571_output_result = "OK"
            else:
                print("Si571 Test: FAIL")
                si571_output_result = "FAIL"
                fail_general = fail_general + 1

            if (si571_output_write_check != 0):
                si571_output_write_check_result = "FAIL"
                fail_general = fail_general + 1
                print("Utilizacao do método de Escrita: ",
                      si571_output_write_check_result)
            else:
                si571_output_write_check_result = "OK"
                print("Utilizacao do método de Escrita: ",
                      si571_output_write_check_result)

            if (si571_output_read_check != 0):
                si571_output_read_check_result = "FAIL"
                fail_general = fail_general + 1
                print("Utilizacao do método de Leitura: ",
                      si571_output_read_check_result)
            else:
                si571_output_read_check_result = "OK"
                print("Utilizacao do método de Leitura: ",
                      si571_output_read_check_result)

            cis_configuration_log.append(
                "Configuração para o Parâmetro: Si571 - Ouput")
            cis_configuration_log.append("Valor Enviado pelo Comando: " +
                                         str(si571_output_config))
            cis_configuration_log.append("Valor Escrito: " + str(write_value))
            cis_configuration_log.append("Valor Lido: " + str(read_value))

            cis_configuration_log.append("Utilizacao do método de Escrita: " +
                                         str(si571_output_write_check_result))
            cis_configuration_log.append("Utilizacao do método de Leitura: " +
                                         str(si571_output_read_check_result))
            cis_configuration_log.append("FINAL RESULT: " +
                                         str(si571_output_result))

        else:
            cis_configuration_log.append("Si571 Output CONFIG: Não Realizado")

        tela_principal.ui.progressBar_config.setValue(100)
        tela_principal.repaint()
        QApplication.processEvents()

        if (fail_general == 0):
            tela_principal.ui.result_config.setText("OK")
            tela_principal.repaint()
            QApplication.processEvents()
        else:
            tela_principal.ui.result_config.setText("FAIL")
            tela_principal.repaint()
            QApplication.processEvents()

        #ad9510_pll_status_config = "Teste2"

    return (cis_configuration_log)
Ejemplo n.º 40
0
    'changed': '‣',
    'untracked': '…',
    'clean': '⚡',
    'unmerged': '≠',
    'sha1': ':'
}

output, error = Popen(['git', 'status'],
                      stdout=PIPE,
                      stderr=PIPE,
                      universal_newlines=True).communicate()

if error:
    import sys
    sys.exit(0)
lines = output.splitlines()

behead_re = re.compile(
    r"^# Your branch is (ahead of|behind) '(.*)' by (\d+) commit")
diverge_re = re.compile(r"^# and have (\d+) and (\d+) different")

status = ''
staged = re.compile(r'^# Changes to be committed:$', re.MULTILINE)
changed = re.compile(r'^# Changed but not updated:$', re.MULTILINE)
untracked = re.compile(r'^# Untracked files:$', re.MULTILINE)
unmerged = re.compile(r'^# Unmerged paths:$', re.MULTILINE)


def execute(*command):
    out, err = Popen(stdout=PIPE, stderr=PIPE, *command).communicate()
    if not err:
Ejemplo n.º 41
0
def eeprom(IP_CRATE, POSITION_CRATE, POSITION_ADC, tela_leds):

    local = "cd CRATE_ACESSO/bpm-app/.halcs-libs/examples\n"

    #Para escrever todos os valores possíveis em 2 Bytes [00 - FF]
    j = 0
    eeprom_all_values_hex = []
    eeprom_all_values_dec = []
    #Máximo de posições na memória que devo escrever/ler na eeprom é a posição 8191
    #Os valors all_values_hex são os valores que serão mostrados como escritos pelo crate
    #pois o código do LNLS mostra o valor que foi escrito em hexadecimal
    #convertendo o valor de decimal (entrada do usuário) para um valor em hexadecimal (saída no terminal)

    while (j < 8192):
        i = 0
        while (i < 256):
            eeprom_all_values_hex.append(format(i, '02x').upper())
            eeprom_all_values_dec.append(i)
            i = i + 1
        j = j + i

    #Posições na memória em hexadecimal
    eeprom_memory_position_standard_hex = []
    i = 0

    while (i < 8192):
        eeprom_memory_position_standard_hex.append(format(i, '02x').upper())
        i = i + 1

    print("Iniciou a ESCRITA na EEPROM do ADC")
    start_write_time = datetime.datetime.now()
    start_write_time_str = start_write_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Start_write_time:", start_write_time_str)

    memory_text = "MEMORY ADDRESS: 0x"
    write_text = "WRITTEN VALUE: 0x"
    write_verification_text = "WRITE CHECK: "
    read_verification_text = "READ CHECK: "

    memory_position_write = []
    eeprom_value_write = []
    write_verification = []
    address = 0
    eeprom_memory_position_standard_dec = []

    while (address < len(eeprom_all_values_dec)):
        command_write = "./THALES_fmc130m_eeprom_ctl -b tcp://" + str(
            IP_CRATE
        ) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
            POSITION_ADC) + " -rw 1 -addr " + str(address) + " -data " + str(
                eeprom_all_values_dec[address])
        command_stdout_write = Popen(local + command_write,
                                     shell=True,
                                     stdin=PIPE,
                                     stdout=PIPE,
                                     stderr=PIPE).communicate()[0]
        command_stdout_write = command_stdout_write.splitlines()
        memory_position_aux = command_stdout_write[len(command_stdout_write) -
                                                   2].decode("utf-8")
        memory_position_aux = memory_position_aux.replace(memory_text, "")
        value_aux = command_stdout_write[len(command_stdout_write) -
                                         1].decode("utf-8")
        value_aux = value_aux.replace(write_text, "")
        memory_position_write.append(memory_position_aux)
        eeprom_value_write.append(value_aux)
        eeprom_memory_position_standard_dec.append(address)

        #Verifica se foi capaz de enviar comandos através do método de escrita
        write_verification_aux = command_stdout_write[len(command_stdout_write)
                                                      - 3].decode("utf-8")
        write_verification_aux = write_verification_aux.replace(
            write_verification_text, "")
        write_verification.append(write_verification_aux)

        tela_leds.ui.progressBar.setValue(
            (address * 50) / len(eeprom_all_values_dec))
        tela_leds.repaint()
        QApplication.processEvents()
        address = address + 1

    end_write_time = datetime.datetime.now()
    end_write_time_str = end_write_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Fim da ESCRITA na EEPROM do ADC")
    print("End_write_time:", end_write_time_str)

    print("Iniciou a LEITURA na EEPROM do ADC")
    start_read_time = datetime.datetime.now()
    start_read_time_str = start_read_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Start_read_time:", start_read_time_str)
    read_text = "VALUE READ: 0x"
    memory_position_read = []
    eeprom_value_read = []
    read_verification = []
    address = 0

    while (address < len(eeprom_all_values_dec)):
        command_read = "./THALES_fmc130m_eeprom_ctl -b tcp://" + str(
            IP_CRATE) + ":8978 -board " + str(
                POSITION_CRATE) + " -halcs " + str(
                    POSITION_ADC) + " -rw 0 -addr " + str(address)
        command_stdout_read = Popen(local + command_read,
                                    shell=True,
                                    stdin=PIPE,
                                    stdout=PIPE,
                                    stderr=PIPE).communicate()[0]
        command_stdout_read = command_stdout_read.splitlines()
        memory_position_aux = command_stdout_read[len(command_stdout_read) -
                                                  2].decode("utf-8")
        memory_position_aux = memory_position_aux.replace(memory_text, "")
        value_aux = command_stdout_read[len(command_stdout_read) -
                                        1].decode("utf-8")
        value_aux = value_aux.replace(read_text, "")
        memory_position_read.append(memory_position_aux)
        eeprom_value_read.append(value_aux)

        #Verifica se foi capaz de enviar comandos através do método de escrita
        read_verification_aux = command_stdout_read[len(command_stdout_read) -
                                                    3].decode("utf-8")
        read_verification_aux = read_verification_aux.replace(
            read_verification_text, "")
        read_verification.append(read_verification_aux)

        tela_leds.ui.progressBar.setValue((address * 50) /
                                          len(eeprom_all_values_dec) + 50)
        tela_leds.repaint()
        QApplication.processEvents()

        address = address + 1

    end_read_time = datetime.datetime.now()
    end_read_time_str = end_read_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Fim da LEITURA na EEPROM do ADC")
    print("End_read_time:", end_read_time_str)

    print("Verificação das memórias da eeprom...")
    start_check_time = datetime.datetime.now()
    start_check_time_str = start_check_time.strftime("%Y-%m-%d %H:%M:%S")
    memory_test_check = 0
    for i in range(0, len(eeprom_all_values_dec)):
        if (memory_position_read[i] != memory_position_write[i]
                or memory_position_read[i] !=
                eeprom_memory_position_standard_hex[i]):
            #if (memory_position_read[i]!=memory_position_standard_hex[i]):
            print("Memória Acessada Escrita/Leitura Diferem - Posição: ", i)
            print(memory_position_read[i], memory_position_write[i],
                  eeprom_memory_position_standard_hex[i])
            memory_test_check = memory_test_check + 1

    value_test_check = 0
    for i in range(0, len(eeprom_all_values_dec)):
        if (eeprom_value_read[i] != eeprom_value_write[i]
                or eeprom_value_read[i] != eeprom_all_values_hex[i]):
            #if (value_read[i]!=all_values_hex[i]):
            print("Valor Escrito/Lido com Diferem - Posição: ", i)
            print(eeprom_value_read[i], eeprom_value_write[i],
                  eeprom_all_values_hex[i])
            value_test_check = value_test_check + 1

    end_check_time = datetime.datetime.now()
    end_check_time_str = end_check_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Fim da Teste da EEPROM do ADC")
    print("Start_check_time:", start_check_time_str)
    print("End_check_time:", end_check_time_str)

    duration_write = ((end_write_time - start_write_time).total_seconds()) / 60
    duration_read = ((end_read_time - start_read_time).total_seconds()) / 60
    duration_check = ((end_check_time - start_check_time).total_seconds()) / 60
    duration_global = (
        (end_check_time - start_write_time).total_seconds()) / 60

    print("Duracao do Teste de ESCRITA:", round(duration_write, 4))
    print("Duracao do Teste de LEITURA:", round(duration_read, 4))
    print("Duracao do Teste de CHECK:", round(duration_check, 4))
    print("Duracao do Teste TOTAL:", round(duration_global, 4))

    if (memory_test_check == 0):
        print("Memórias Acessadas: OK")
    else:
        print("Memórias Acessadas: FAIL")

    if (value_test_check == 0):
        print("Valores Escritos/Lidos: OK")
    else:
        print("Valores Escritos/Lidos: FAIL")

    eeprom_write_check = 0
    eeprom_read_check = 0
    i = 0
    for i in range(0, len(eeprom_value_write)):
        if (write_verification[i] != str(0)):
            eeprom_write_check = eeprom_write_check + 1

        if (read_verification[i] != str(0)):
            eeprom_read_check = eeprom_read_check + 1

    if (eeprom_write_check == 0):
        print("Utilizacao do método de Escrita: OK")
        eeprom_write_check_result = "OK"
    else:
        print("Utilizacao do método de Escrita: FAIL")
        print(eeprom_write_check)
        eeprom_write_check_result = "FAIL"

    if (eeprom_read_check == 0):
        print("Utilizacao do método de Leitura: OK")
        eeprom_read_check_result = "OK"
    else:
        print("Utilizacao do método de Leitura: FAIL")
        print(eeprom_read_check)
        eeprom_read_check_result = "FAIL"

    if (value_test_check == 0 and memory_test_check == 0):
        eeprom_result = "OK"
        print("EEPROM: OK")
    else:
        eeprom_result = "FAIL"
        print("EEPROM: FAIL")

    tela_leds.ui.progressBar.setValue(100)
    tela_leds.repaint()
    QApplication.processEvents()

    return (eeprom_result, eeprom_write_check_result, eeprom_read_check_result,
            eeprom_all_values_dec, eeprom_all_values_hex,
            eeprom_memory_position_standard_dec,
            eeprom_memory_position_standard_hex, eeprom_value_write,
            eeprom_value_read)
Ejemplo n.º 42
0
def getsystemdlog(name=None):
    if name is None:
        return ''
    out = Popen(JOURNALCTL + name, shell=True, stdout=PIPE).stdout.read()
    lines = out.splitlines()
    return lines
Ejemplo n.º 43
0
def ad9510(IP_CRATE, POSITION_CRATE, POSITION_ADC, tela_leds):

    local = "cd CRATE_ACESSO/bpm-app/.halcs-libs/examples\n"

    tela_leds.ui.progressBar.setValue(0)
    tela_leds.repaint()
    QApplication.processEvents()

    print("Iniciou o Teste do AD9510")
    start_time = datetime.datetime.now()
    start_time_str = start_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Start_write_time:", start_time_str)
    ad9510_log = []

    write_text = "WRITTEN VALUE: "
    read_text = "READ VALUE: "
    write_verification_text = "WRITE CHECK: "
    read_verification_text = "READ CHECK: "
    ad9510_write_check = 0
    ad9510_read_check = 0

    #Teste do PLL_CLK_SEL
    if (PLL_CLK_SEL_RUN == "yes"):
        print("Iniciou o Teste do PLL_CLK_SEL")
        ad9510_log.append("Iniciou o Teste do PLL_CLK_SEL")
        start_pll_clk_sel_time = datetime.datetime.now()
        start_pll_clk_sel_time_str = start_pll_clk_sel_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        print("start_pll_clk_sel: ", start_pll_clk_sel_time_str)
        i = PLL_CLK_SEL_MIN
        read_text = "READ VALUE OF PLL_CLK_SEL: "
        write_text = "WRITTEN VALUE OF PLL_CLK_SEL: "
        pll_clk_sel_write = []
        pll_clk_sel_read = []
        #Realiza a escrita e leitura no mesmo loop, pois a funcao ./THALES_ad9510_ctl realiza ambos os processos automaticamente
        while (i < PLL_CLK_SEL_MAX + 1):
            command = "./THALES_ad9510_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -pll_clk_sel " + str(i)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")
            pll_clk_sel_write.append(write_aux)
            pll_clk_sel_read.append(read_aux)

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            i = i + 1

        #Teste de verificação
        print("Verificando resultado...")
        i = 0
        check_pll_clk_sel = 0
        while (i < PLL_CLK_SEL_MAX - PLL_CLK_SEL_MIN + 1):
            ad9510_log.append("Valor Escrito: " + str(pll_clk_sel_write[i]) +
                              " - Valor lido: " + str(pll_clk_sel_read[i]))
            if (pll_clk_sel_write[i] != pll_clk_sel_read[i]):
                ad9510_log.append("Fail Detected - Valor Escrito: " +
                                  str(pll_clk_sel_write[i]) + " Valor lido: " +
                                  str(pll_clk_sel_read[i]))
                print("Fail Detected - Valor Escrito: ", pll_clk_sel_write[i],
                      " Valor lido: ", pll_clk_sel_read[i])
                check_pll_clk_sel = check_pll_clk_sel + 1
            i = i + 1

        if (check_pll_clk_sel == 0):
            print("PLL_CLK_SEL TEST: OK")
            ad9510_log.append("PLL_CLK_SEL TEST: OK")
        else:
            print("PLL_CLK_SEL TEST: FAIL")
            ad9510_log.append("PLL_CLK_SEL TEST: FAIL")

        print("Fim do Teste do PLL_CLK_SEL")
        ad9510_log.append("Fim do Teste do PLL_CLK_SEL\n")
        end_pll_clk_sel_time = datetime.datetime.now()
        end_pll_clk_sel_time_str = end_pll_clk_sel_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        print("end_pll_clk_sel_time: ", end_pll_clk_sel_time_str)
        duration_pll_clk_sel = (
            (end_pll_clk_sel_time -
             start_pll_clk_sel_time).total_seconds()) / 60  #desprezível
        print("Duração do Teste PLL_CLK_SEL [min]: ",
              round(duration_pll_clk_sel, 4))
    else:
        print("PLL_CLK_SEL WILL NOT BE PERFORMED")
        ad9510_log.append("PLL_CLK_SEL WILL NOT BE PERFORMED\n")
        #FIXME: ESTA PARTE SÓ SERVE PARA DEBUG
        check_pll_clk_sel = 0
        ad9510_write_check = 0
        ad9510_read_check = 0

    #Teste do A_DIV
    if (A_DIV_RUN == "yes"):
        print("Iniciou o Teste do A_DIV")
        ad9510_log.append("Iniciou o Teste do A_DIV")
        start_a_div_time = datetime.datetime.now()
        start_a_div_time_str = start_a_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("start_a_div_time: ", start_a_div_time_str)
        i = A_DIV_MIN
        read_text = "READ VALUE OF A_DIV: "
        write_text = "WRITTEN VALUE OF A_DIV: "
        a_div_write = []
        a_div_read = []
        #Realiza a escrita e leitura no mesmo loop, pois a funcao ./THALES_ad9510_ctl realiza ambos os processos automaticamente
        while (i < A_DIV_MAX + 1):
            command = "./THALES_ad9510_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -a_div " + str(i)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")
            a_div_write.append(write_aux)
            a_div_read.append(read_aux)
            #print(write_aux)

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            i = i + 1

        #Teste de verificação
        print("Verificando resultado...")
        i = 0
        check_a_div = 0
        while (i < A_DIV_MAX - A_DIV_MIN + 1):
            ad9510_log.append("Valor Escrito: " + str(a_div_write[i]) +
                              " - Valor lido: " + str(a_div_read[i]))
            if (a_div_write[i] != a_div_read[i]):
                ad9510_log.append("Fail Detected - Valor Escrito: " +
                                  str(a_div_write[i]) + " - Valor lido: " +
                                  str(a_div_read[i]))

                print("Fail Detected - Valor Escrito: ", a_div_write[i],
                      " Valor lido: ", a_div_read[i])
                check_a_div = check_a_div + 1
            i = i + 1

        if (check_a_div == 0):
            print("A_DIV TEST: OK")
            ad9510_log.append("A_DIV TEST: OK")
        else:
            print("A_DIV TEST: FAIL")
            ad9510_log.append("A_DIV TEST: FAIL")

        print("Fim do Teste do A_DIV")
        ad9510_log.append("Fim do Teste do A_DIV\n")

        end_a_div_time = datetime.datetime.now()
        end_a_div_time_str = end_a_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("end_a_div_time: ", end_a_div_time_str)
        duration_a_div = (
            (end_a_div_time -
             start_a_div_time).total_seconds()) / 60  #desprezível
        print("Duração do Teste A_DIV [min]: ", round(duration_a_div, 4))

    else:
        print("A_DIV WILL NOT BE PERFORMED")
        ad9510_log.append("A_DIV WILL NOT BE PERFORMED\n")
        #FIXME: ESTA PARTE SÓ SERVE PARA DEBUG
        check_a_div = 0
        ad9510_write_check = 0
        ad9510_read_check = 0

    #Teste do B_DIV
    if (B_DIV_RUN == "yes"):
        print("Iniciou o Teste do B_DIV")
        ad9510_log.append("Iniciou o Teste do B_DIV")
        start_b_div_time = datetime.datetime.now()
        start_b_div_time_str = start_b_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("start_b_div_time: ", start_b_div_time_str)
        i = B_DIV_MIN
        read_text = "READ VALUE OF B_DIV: "
        write_text = "WRITTEN VALUE OF B_DIV: "
        b_div_write = []
        b_div_read = []
        #Realiza a escrita e leitura no mesmo loop, pois a funcao ./THALES_ad9510_ctl realiza ambos os processos automaticamente
        while (i < B_DIV_MAX + 1):
            command = "./THALES_ad9510_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -b_div " + str(i)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")
            b_div_write.append(write_aux)
            b_div_read.append(read_aux)
            #print(write_aux)
            #print(read_aux)

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            tela_leds.ui.progressBar.setValue((i + B_DIV_MIN) * 40 / B_DIV_MAX)
            tela_leds.repaint()
            QApplication.processEvents()

            i = i + 1

        #Teste de verificação
        print("Verificando resultado...")
        i = 0
        check_b_div = 0
        while (i < B_DIV_MAX - B_DIV_MIN + 1):
            ad9510_log.append("Valor Escrito: " + str(b_div_write[i]) +
                              " - Valor lido: " + str(b_div_read[i]))
            if (b_div_write[i] != b_div_read[i]):
                print("Fail Detected - Valor Escrito: ", b_div_write[i],
                      " Valor lido: ", b_div_read[i])
                ad9510_log.append("Fail Detected - Valor Escrito: " +
                                  str(b_div_write[i]) + " - Valor lido: " +
                                  str(b_div_read[i]))
                check_b_div = check_b_div + 1
            i = i + 1

        if (check_b_div == 0):
            print("B_DIV TEST: OK")
            ad9510_log.append("B_DIV TEST: OK")
        else:
            print("B_DIV TEST: FAIL")
            ad9510_log.append("B_DIV TEST: FAIL")

        print("Fim do Teste do B_DIV")
        ad9510_log.append("Fim do Teste do B_DIV\n")
        end_b_div_time = datetime.datetime.now()
        end_b_div_time_str = end_b_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("end_b_div_time: ", end_b_div_time_str)
        duration_b_div = (
            (end_b_div_time -
             start_b_div_time).total_seconds()) / 60  #demora 4.5 minutos
        print("Duração do Teste B_DIV [min]: ", round(duration_b_div, 4))

    else:
        print("B_DIV WILL NOT BE PERFORMED")
        ad9510_log.append("B_DIV WILL NOT BE PERFORMED\n")
        #FIXME: ESTA PARTE SÓ SERVE PARA DEBUG
        check_b_div = 0
        ad9510_write_check = 0
        ad9510_read_check = 0

    tela_leds.ui.progressBar.setValue(40)
    tela_leds.repaint()
    QApplication.processEvents()

    #Teste do R_DIV
    if (R_DIV_RUN == "yes"):
        print("Iniciou o Teste do R_DIV")
        ad9510_log.append("Iniciou o Teste do R_DIV")
        start_r_div_time = datetime.datetime.now()
        start_r_div_time_str = start_r_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("start_r_div_time: ", start_r_div_time_str)
        i = R_DIV_MIN
        read_text = "READ VALUE OF R_DIV: "
        write_text = "WRITTEN VALUE OF R_DIV: "
        r_div_write = []
        r_div_read = []
        #Realiza a escrita e leitura no mesmo loop, pois a funcao ./THALES_ad9510_ctl realiza ambos os processos automaticamente
        while (i < R_DIV_MAX + 1):
            command = "./THALES_ad9510_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -r_div " + str(i)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")
            r_div_write.append(write_aux)
            r_div_read.append(read_aux)
            #print(write_aux)
            #print(read_aux)
            #print(i+1," de ", R_DIV_MAX," ",read_aux)

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            tela_leds.ui.progressBar.setValue((i + R_DIV_MIN) * 60 /
                                              R_DIV_MAX + 40)
            tela_leds.repaint()
            QApplication.processEvents()

            i = i + 1

        #Teste de verificação
        print("Verificando resultado...")
        i = 0
        check_r_div = 0
        while (i < R_DIV_MAX - R_DIV_MIN + 1):
            ad9510_log.append("Valor Escrito: " + str(r_div_write[i]) +
                              " - Valor lido: " + str(r_div_read[i]))
            if (r_div_write[i] != r_div_read[i]):
                ad9510_log.append("Fail Detected - Valor Escrito: " +
                                  str(r_div_write[i]) + " - Valor lido: " +
                                  str(r_div_read[i]))
                print("Fail Detected - Valor Escrito: " + str(r_div_write[i]) +
                      " - Valor lido: " + str(r_div_read[i]))
                check_r_div = check_r_div + 1
            i = i + 1

        if (check_r_div == 0):
            print("R_DIV TEST: OK")
            ad9510_log.append("R_DIV TEST: OK")
        else:
            print("R_DIV TEST: FAIL")
            ad9510_log.append("R_DIV TEST: FAIL")

        print("Fim do Teste do R_DIV")
        ad9510_log.append("Fim do Teste do R_DIV\n")
        end_r_div_time = datetime.datetime.now()
        end_r_div_time_str = end_r_div_time.strftime("%Y-%m-%d %H:%M:%S")
        print("end_r_div_time: ", end_r_div_time_str)
        duration_r_div = (
            (end_r_div_time - start_r_div_time).total_seconds()) / 60
        print("Duração do Teste R_DIV [min]: ", round(duration_r_div,
                                                      4))  #8.7 minutos

    else:
        print("R_DIV WILL NOT BE PERFORMED")
        ad9510_log.append("R_DIV WILL NOT BE PERFORMED\n")
        #FIXME: ESTA PARTE SÓ SERVE PARA DEBUG
        check_r_div = 0
        ad9510_write_check = 0
        ad9510_read_check = 0

    #Teste do PRESCALER_DIV
    if (PRESCALER_DIV_RUN == "yes"):
        print("Iniciou o Teste do PRESCALER_DIV")
        ad9510_log.append("Iniciou o Teste do PRESCALER_DIV")
        start_prescaler_div_time = datetime.datetime.now()
        start_prescaler_div_time_str = start_prescaler_div_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        print("start_prescaler_div_time: ", start_prescaler_div_time_str)
        i = PRESCALER_DIV_MIN
        read_text = "READ VALUE OF PRESCALER_DIV: "
        write_text = "WRITTEN VALUE OF PRESCALER_DIV: "
        prescaler_div_write = []
        prescaler_div_read = []
        #Realiza a escrita e leitura no mesmo loop, pois a funcao ./THALES_ad9510_ctl realiza ambos os processos automaticamente
        while (i < PRESCALER_DIV_MAX + 1):
            command = "./THALES_ad9510_ctl -b tcp://" + str(
                IP_CRATE) + ":8978 -board " + str(
                    POSITION_CRATE) + " -halcs " + str(
                        POSITION_ADC) + " -prescaler_div " + str(i)
            command_stdout = Popen(local + command,
                                   shell=True,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   stderr=PIPE).communicate()[0]
            command_stdout = command_stdout.splitlines()
            write_value = command_stdout[len(command_stdout) -
                                         2].decode("utf-8")
            read_value = command_stdout[len(command_stdout) -
                                        1].decode("utf-8")
            write_aux = str(write_value).replace(write_text, "")
            read_aux = str(read_value).replace(read_text, "")
            prescaler_div_write.append(write_aux)
            prescaler_div_read.append(read_aux)
            #print(write_aux)
            #print(read_aux)
            #print(i+1," de ", R_DIV_MAX," ",read_aux)

            #Verifica se foi capaz de enviar comandos através do método de escrita
            write_verification_aux = command_stdout[len(command_stdout) -
                                                    4].decode("utf-8")
            write_verification_aux = write_verification_aux.replace(
                write_verification_text, "")
            if (write_verification_aux != str(0)):
                ad9510_write_check = ad9510_write_check + 1

            #Verifica se foi capaz de enviar comandos através do método de leitura
            read_verification_aux = command_stdout[len(command_stdout) -
                                                   3].decode("utf-8")
            read_verification_aux = read_verification_aux.replace(
                read_verification_text, "")
            if (read_verification_aux != str(0)):
                ad9510_read_check = ad9510_read_check + 1

            i = i + 1

        #Teste de verificação
        print("Verificando resultado...")
        i = 0
        check_prescaler_div = 0
        while (i < PRESCALER_DIV_MAX - PRESCALER_DIV_MIN + 1):
            ad9510_log.append("Valor Escrito: " + str(prescaler_div_write[i]) +
                              " - Valor lido: " + str(prescaler_div_read[i]))
            if (prescaler_div_write[i] != prescaler_div_read[i]):
                ad9510_log.append("Fail Detected -Valor Escrito: " +
                                  str(prescaler_div_write[i]) +
                                  " - Valor lido: " +
                                  str(prescaler_div_read[i]))
                print("Fail Detected - Valor Escrito: ",
                      prescaler_div_write[i], " Valor lido: ",
                      prescaler_div_read[i])
                check_prescaler_div = check_prescaler_div + 1
            i = i + 1

        if (check_prescaler_div == 0):
            print("PRESCALER_DIV TEST: OK")
            ad9510_log.append("PRESCALER_DIV TEST: OK")
        else:
            print("PRESCALER_DIV TEST: FAIL")
            ad9510_log.append("PRESCALER_DIV TEST: FAIL")

        print("Fim do Teste do PRESCALER_DIV")
        ad9510_log.append("Fim do Teste do PRESCALER_DIV\n")
        end_prescaler_div_time = datetime.datetime.now()
        end_prescaler_div_time_str = end_prescaler_div_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        print("end_prescaler_div_time: ", end_prescaler_div_time_str)
        duration_prescaler_div = (
            (end_prescaler_div_time -
             start_prescaler_div_time).total_seconds()) / 60
        print("Duração do Teste PRESCALER_DIV [min]: ",
              round(duration_prescaler_div, 4))  #desprezível

    else:
        print("PRESCALER_DIV WILL NOT BE PERFORMED")
        ad9510_log.append("PRESCALER_DIV WILL NOT BE PERFORMED\n")
        #FIXME: ESTA PARTE SÓ SERVE PARA DEBUG
        check_prescaler_div = 0
        ad9510_write_check = 0
        ad9510_read_check = 0

    if (check_pll_clk_sel == 0 and check_a_div == 0 and check_b_div == 0
            and check_prescaler_div == 0 and check_r_div == 0):
        ad9510_result = "OK"
        print("AD9510 OK")
    else:
        ad9510_result = "FAIL"
        print("AD9510 FAIL")

    if (ad9510_write_check != 0):
        ad9510_write_check_result = "FAIL"
        print("Utilizacao do método de Escrita: ", ad9510_write_check_result)
    else:
        ad9510_write_check_result = "OK"
        print("Utilizacao do método de Escrita: ", ad9510_write_check_result)

    if (ad9510_read_check != 0):
        ad9510_read_check_result = "FAIL"
        print("Utilizacao do método de Leitura: ", ad9510_read_check_result)
    else:
        ad9510_read_check_result = "OK"
        print("Utilizacao do método de Leitura: ", ad9510_read_check_result)

    ad9510_log.append("Utilizacao do método de Escrita: " +
                      str(ad9510_write_check_result))
    ad9510_log.append("Utilizacao do método de Leitura: " +
                      str(ad9510_read_check_result))
    ad9510_log.append("FINAL RESULT: " + str(ad9510_result))
    end_time = datetime.datetime.now()
    duracao = ((end_time - start_time).total_seconds()) / 60
    print("Duração do Teste: ", round(duracao, 4))

    tela_leds.ui.progressBar.setValue(100)
    tela_leds.repaint()
    QApplication.processEvents()

    return (ad9510_result, ad9510_write_check_result, ad9510_read_check_result,
            ad9510_log)
Ejemplo n.º 44
0
def test_rename_prefix():
    comm = "vk rename --prefix prefix_ data/test.vcf.gz | bcftools query --list-samples"
    # Run 2x for testing
    rename.main(["rename","--prefix","prefix_","test_data/test.vcf.gz"])
    out, err = Popen(comm, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    assert all([x.startswith("prefix") for x in out.splitlines()])
Ejemplo n.º 45
0
    def evaluate(self, score_functions, on_dev=True, output=None, remove_unk=False, max_dev_size=None,
                 raw_output=False, fix_edits=True, max_test_size=None, post_process_script=None,
                 unk_replace=False, **kwargs):
        """
        Decode a dev or test set, and perform evaluation with respect to gold standard, using the provided
        scoring function. If `output` is defined, also save the decoding output to this file.
        When evaluating development data (`on_dev` to True), several dev sets can be specified (`dev_prefix` parameter
        in configuration files), and a score is computed for each of them.

        :param score_function: name of the scoring function used to score and rank models (typically 'bleu_score')
        :param on_dev: if True, evaluate the dev corpus, otherwise evaluate the test corpus
        :param output: save the hypotheses to this file
        :param remove_unk: remove the UNK symbols from the output
        :param max_dev_size: maximum number of lines to read from dev files
        :param max_test_size: maximum number of lines to read from test files
        :param raw_output: save raw decoder output (don't do post-processing like UNK deletion or subword
            concatenation). The evaluation is still done with the post-processed output.
        :param fix_edits: when predicting edit operations, pad shorter hypotheses with KEEP symbols.
        :return: scores of each corpus to evaluate
        """
        utils.log('starting evaluation')

        if on_dev:
            filenames = self.filenames.dev
        else:
            filenames = [self.filenames.test]

        # convert `output` into a list, for zip
        if isinstance(output, str):
            output = [output]
        elif output is None:
            output = [None] * len(filenames)

        scores = []
        utils.log('show output')
        utils.log(output)

        # evaluation on multiple corpora
        for dev_id, (filenames_, output_, prefix) in enumerate(zip(filenames, output, self.dev_prefix)):
            utils.log('filenames, output, self.dev_prefix')
            utils.log(filenames)
            utils.log(output)

            if self.dev_batches:
                dev_batches = self.dev_batches[dev_id]
                dev_loss = sum(self.seq2seq_model.step(batch, update_model=False).loss * len(batch)
                               for batch in dev_batches)
                dev_loss /= sum(map(len, dev_batches))
            else:  # TODO
                dev_loss = 0

            extensions = list(self.extensions)
            if self.ref_ext is not None:
                extensions.append(self.ref_ext)

            lines = list(utils.read_lines(filenames_, binary=self.binary))

            if on_dev and max_dev_size:
                lines = lines[:max_dev_size]
            elif not on_dev and max_test_size:
                lines = lines[:max_test_size]

            hypotheses = []
            references = []
            utils.log("making hypotheses")
            output_file = None
            try:
                if output_ is not None:
                    output_file = open(output_, 'w', encoding='utf-8')

                lines_ = list(zip(*lines))

                src_sentences = list(zip(*lines_[:len(self.src_ext)]))
                trg_sentences = list(zip(*lines_[len(self.src_ext):]))

                utils.log("making decode_batch")
                hypothesis_iter = self.decode_batch(lines, self.batch_size, remove_unk=remove_unk,
                                                    fix_edits=fix_edits, unk_replace=unk_replace)

                for i, (sources, hypothesis, reference) in enumerate(zip(src_sentences, hypothesis_iter,
                                                                         trg_sentences)):
                    if self.ref_ext is not None and on_dev:
                        reference = reference[-1]
                    else:
                        reference = reference[0]  # single output for now

                    hypothesis, raw = hypothesis
                    # hypothesis: [10items],each item is a "token sequence"
                    hypotheses.append(hypothesis)
                    references.append(reference.strip().replace('@@ ', ''))

                    if output_file is not None:
                        if raw_output:
                            hypothesis = raw
                        line = "source:\t" + str(sources) + "\nref:\t" + str(reference) + "\n"
                        for item in hypothesis:
                            line += str(item) + '\n'
                        line += "\n"
                        # line = hypothesis + '\n'
                        output_file.write(line)
                        output_file.flush()

            finally:
                if output_file is not None:
                    output_file.close()

            if post_process_script is not None:
                data = '\n'.join(hypotheses).encode()
                data = Popen([post_process_script], stdout=PIPE, stdin=PIPE).communicate(input=data)[0].decode()
                hypotheses = data.splitlines()

            scores_ = []
            summary = None

            for score_function in score_functions:
                try:
                    if score_function == 'loss':
                        score = dev_loss
                        reversed_ = True
                    else:
                        fun = getattr(evaluation, 'corpus_' + score_function)
                        try:
                            reversed_ = fun.reversed
                        except AttributeError:
                            reversed_ = False

                        func_arg = []
                        for item in hypotheses:
                            func_arg.append(item[0])
                        score, score_summary = fun(func_arg, references)
                        summary = summary or score_summary

                    scores_.append((score_function, score, reversed_))
                except:
                    pass

            score_info = ['{}={:.2f}'.format(key, value) for key, value, _ in scores_]
            score_info.insert(0, prefix)
            if summary:
                score_info.append(summary)

            if self.name is not None:
                score_info.insert(0, self.name)

            utils.log(' '.join(map(str, score_info)))

            # main score
            _, score, reversed_ = scores_[0]
            scores.append(-score if reversed_ else score)

        return scores
Ejemplo n.º 46
0
'''
Create and format a dependency graph for the project.
'''
from subprocess import Popen, PIPE

# create the graph file
result_1 = Popen(['sfood', 'quicknxs'], stdout=PIPE).communicate()[0]
dot = Popen(['sfood-graph'], stdout=PIPE, stdin=PIPE).communicate(result_1)[0]

# process result dot file data

out_dot = []
ext_packages = []
first_add = True

for line in dot.splitlines():
    if line.startswith('"quicknxs"') or 'version' in line or '"logging"' in line or \
          'sip' in line or 'figureoptions' in line or 'types' in line or 'nxutils.so' in line or\
          'output_templates' in line or 'os' in line or 'sys' in line:
        continue
    elif line.startswith('"quicknxs/'):
        line = line.replace(
            'style=filled',
            'style=filled, color="#00aa00" shape=box, fontsize=24').replace(
                'quicknxs/', '')
    if 'PyQt4' in line or 'email' in line or 'scipy' in line or 'matplotlib/' in line or \
        'IPython' in line:
        line = line.split('/')[0] + '";'
        if first_add:
            first_add = False
            out_dot.append(
Ejemplo n.º 47
0
    if remote_name:
        merge_name = Popen(
            ['git', 'config', 'branch.%s.merge' % branch],
            stdout=PIPE).communicate()[0].strip()
        if remote_name == '.':  # local
            remote_ref = merge_name
        else:
            remote_ref = 'refs/remotes/%s/%s' % (remote_name, merge_name[11:])
        revgit = Popen(
            ['git', 'rev-list', '--left-right',
             '%s...HEAD' % remote_ref],
            stdout=PIPE,
            stderr=PIPE)
        revlist = revgit.communicate()[0]
        if revgit.poll():  # fallback to local
            revlist = Popen(
                ['git', 'rev-list', '--left-right',
                 '%s...HEAD' % merge_name],
                stdout=PIPE,
                stderr=PIPE).communicate()[0]
        behead = revlist.splitlines()
        ahead = len([x for x in behead if x[0] == '>'])
        behind = len(behead) - ahead
        if behind:
            remote += '%s%s' % (symbols['behind'], behind)
        if ahead:
            remote += '%s%s' % (symbols['ahead of'], ahead)

out = '\n'.join([branch, remote, staged, conflicts, changed, untracked, clean])
print out
Ejemplo n.º 48
0
def getPIDsOfProcess(processName):
    # print >> stderr, "=> APPEL a la fonction getPIDsOfProcess !"
    selfPID = str(os.getpid())
    myProcessNamePattern = re.compile(processName, re.I)

    PIDs = []
    if os.name == "posix":
        if platform.system() == "Linux":
            proc = Popen('pgrep ' + " ".join(args.patternList), stdout=PIPE)
            for line in proc.stdout:
                print "line = " + line
        else:
            interpreter = "ksh"
            if checkPythonVersion(2.7):
                from subprocess import check_output
                outPut = check_output("ps -elf | grep " + processName,
                                      shell=True)
                for line in outPut:
                    print "line = " + line
            else:
                proc1 = Popen('ps -elf', stdout=PIPE)
                proc = Popen('grep ' + processName,
                             stdin=proc1.stdout,
                             stdout=PIPE)
                for line in proc.stdout:
                    print "line = " + line
            print >> stderr, "TO BE DONE !"
    elif platform.system() == "Windows":
        interpreter = "cmd"
        regExp2 = "Prompt \- "
        tasklistPrompt = re.compile(regExp2)
        separator = ","

        if isAdmin():
            wmicProcessProcStdout, wmicProcessProcStderr = Popen(
                "wmic process where \"name = '" + processName +
                "'\" get caption,commandline,processid -format:csv",
                stdout=PIPE,
                stderr=PIPE).communicate()
            if not wmicProcessProcStderr:
                for line in wmicProcessProcStdout.splitlines():
                    line = line.strip()
                    wmicLineColumns = line.split(separator)
                    if not line or wmicLineColumns[0] == "Node": continue
                    if myProcessNamePattern.search(line):
                        pid = wmicLineColumns[-1]
                        if pid != selfPID:
                            PIDs.append(pid)
        else:
            tasklistProc = Popen('tasklist -fo:csv', stdout=PIPE)
            for line in tasklistProc.stdout:
                line = line.strip()
                tlistLineColumns = line.split(separator)
                if not line or tlistLineColumns[0] == '"Image Name"': continue
                if myProcessNamePattern.search(
                        line) and not tasklistPrompt.search(line):
                    pid = tlistLineColumns[1].split('"')[1]
                    if pid != selfPID:
                        PIDs.append(pid)

    return PIDs
Ejemplo n.º 49
0
def test_rename_subst():
    comm = "vk rename --subst N2:TEST --subst WN2001,TEST2 --subst AB1=TEST3 test_data/test.vcf.gz | bcftools query --list-samples"
    rename.main(["rename","--subst","N2:TEST","--subst","WN2001,TEST2","--subst","AB1=TEST3", "test_data/test.vcf.gz"])
    out, err = Popen(comm, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    assert sum([x.startswith("TEST") for x in out.splitlines()]) == 3
Ejemplo n.º 50
0
def test_rename_suffix():
    comm = "vk rename --suffix _suffix data/test.vcf.gz | bcftools query --list-samples"
    rename.main(["rename","--suffix","_suffix","test_data/test.vcf.gz"])
    out, err = Popen(comm, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    assert all([x.endswith("_suffix") for x in out.splitlines()])
Ejemplo n.º 51
0
def is_present(name):
    """Checks if the given locale is currently installed."""
    output = Popen(["locale", "-a"], stdout=PIPE).communicate()[0]
    return any(
        fix_case(name) == fix_case(line) for line in output.splitlines())
Ejemplo n.º 52
0
import smtplib

# Settings to send emails with SMTP with gmail.
server = "smtp.gmail.com"
port = 587
user = '******'
pw = 'ENTER_PW'  # Please use an application-specific password for security!
email_to = 'ENTER_TO_EMAIL'
email_from = 'ENTER_FROM_EMAIL'
root_url = 'ENTER_URL'

cmd = ["linkchecker", "--no-warnings", "--no-status", "--external", root_url]
output = Popen(cmd, stdout=PIPE).communicate()[0].decode("UTF-8")

bad_urls = []
for line in output.splitlines():
    if line.startswith("URL"):
        current_url = line
    if line.startswith("Parent URL"):
        parent_url = line
    elif line.startswith("Result"):
        current_result = line
        toks = line.split()
        if toks[1] != "Valid:":
            bad_urls.append((current_url, parent_url, current_result))

if bad_urls:
    message_contents = "Error checking links for " + root_url + "\n\n"
    for url in bad_urls:
        message_contents += "\n".join(url) + "\n\n"
Ejemplo n.º 53
0
                    nargs='?',
                    type=str,
                    default='2',
                    help='Specify the outgoing subnet')
parser.add_argument(
    '--st',
    '--secondary-table',
    dest='stable',
    action='store_const',
    const=True,
    default=False,
    help='Configure a secondary routing table for multihomed enclaves')
args = parser.parse_args()

output, _ = Popen(["ip", "route"], stdout=PIPE, stderr=PIPE).communicate()
out = output.splitlines()

lines_to_remove = []
ifaces = {}

subnet = args.subnet

# pylint: disable=too-many-boolean-expressions
for line in out:
    tokens = line.strip("\n").split()
    if (len(tokens) >= 5 and tokens[1] == "via" and tokens[0] != 'default' and
        (tokens[0] != '192.168.0.0/22' and tokens[0] != '172.16.0.0/12'
         and tokens[0] != '192.168.0.0/16' and tokens[0] != '224.0.0.0/4'
         and tokens[0] != '172.17.0.0/16')):
        lines_to_remove.append(line)
    else:
Ejemplo n.º 54
0
def si571(IP_CRATE,POSITION_CRATE,POSITION_ADC,tela_leds):
    
    local = "cd CRATE_ACESSO/bpm-app/.halcs-libs/examples\n"
    
    tela_leds.ui.progressBar.setValue(0)  
    tela_leds.repaint()
    QApplication.processEvents() 
       
    print("Iniciou o Teste do Si571")
    start_time=datetime.datetime.now()
    start_time_str=start_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Start_write_time:",start_time_str)
    
    si571_log=[]
   
    write_text="WRITTEN VALUE: "
    read_text="READ VALUE: "
    write_verification_text="WRITE CHECK: "
    read_verification_text="READ CHECK: "
    si571_write_check=0
    si571_read_check=0
    
    #Este valor ainda precisa ser melhor definido - 130000000 Hz
    freq_value=120000000
    
    command= "./THALES_si571_ctl -b tcp://"+str(IP_CRATE)+":8978 -board "+str(POSITION_CRATE)+" -halcs "+str(POSITION_ADC)+" -freq "+str(freq_value) 
    command_stdout = Popen(local+command,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE).communicate()[0]
    command_stdout=command_stdout.splitlines()
    write_aux=command_stdout[len(command_stdout)-2].decode("utf-8")
    write_value=write_aux.replace(write_text,"")
    read_aux=command_stdout[len(command_stdout)-1].decode("utf-8")
    read_value=read_aux.replace(read_text,"")
    
    tela_leds.ui.progressBar.setValue(50)  
    tela_leds.repaint()
    QApplication.processEvents() 
    
    #Verifica se foi capaz de enviar comandos através do método de escrita
    write_verification_aux=command_stdout[len(command_stdout)-4].decode("utf-8")
    write_verification_aux=write_verification_aux.replace(write_verification_text,"")
    if (write_verification_aux!=str(0)):
        si571_write_check=si571_write_check+1
    
    #Verifica se foi capaz de enviar comandos através do método de leitura
    read_verification_aux=command_stdout[len(command_stdout)-3].decode("utf-8")
    read_verification_aux=read_verification_aux.replace(read_verification_text,"")
    if (read_verification_aux!=str(0)):
        si571_read_check=si571_read_check+1    
    
    print("Verificação...")
    
    si571_check=0
    
    if(read_value!=write_value or read_value!=str(format(freq_value, '.6f'))):
        print("Valor Enviado pelo Comando: ",freq_value)
        print("Valor Escrito :",write_value)
        print("Valor Lido: ",read_value)
        si571_check=si571_check+1
        
    
    if(si571_check==0):
        print("Si571 Test: OK")
        si571_result="OK"
    else:
        print("Si571 Test: FAIL")
        si571_result="FAIL"    
    
    if(si571_write_check!=0):
        si571_write_check_result = "FAIL"
        print("Utilizacao do método de Escrita: ",si571_write_check_result)
    else:
        si571_write_check_result = "OK"  
        print("Utilizacao do método de Escrita: ",si571_write_check_result)
 
    if(si571_read_check!=0):
        si571_read_check_result = "FAIL"
        print("Utilizacao do método de Leitura: ",si571_read_check_result)
    else:
        si571_read_check_result = "OK"  
        print("Utilizacao do método de Leitura: ",si571_read_check_result)   
    
    tela_leds.ui.progressBar.setValue(100)  
    tela_leds.repaint()
    QApplication.processEvents() 
    
    end_time=datetime.datetime.now()
    end_time_str=end_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Fim da ESCRITA na EEPROM do ADC")
    print("End_write_time:",end_time_str)
    duracao=((end_time - start_time).total_seconds())/60
    print("Duração do Teste: ",round(duracao,4))
    
    si571_log.append("Valor Enviado pelo Comando: "+str(freq_value))
    si571_log.append("Valor Escrito: "+str(write_value))
    si571_log.append("Valor Lido: "+str(read_value))

    si571_log.append("Utilizacao do método de Escrita: "+str(si571_write_check_result))
    si571_log.append("Utilizacao do método de Leitura: "+str(si571_read_check_result))
    si571_log.append("FINAL RESULT: "+str(si571_result))

    return (si571_result,si571_write_check_result,si571_read_check_result,si571_log)
Ejemplo n.º 55
0
def ics854s01i(IP_CRATE, POSITION_CRATE, POSITION_ADC, tela_leds):

    local = "cd CRATE_ACESSO/bpm-app/.halcs-libs/examples\n"

    tela_leds.ui.progressBar.setValue(0)
    tela_leds.repaint()
    QApplication.processEvents()

    print("Iniciou o teste do ICS854S01I")
    start_time = datetime.datetime.now()
    start_time_str = start_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Start_write_time:", start_time_str)

    write_text = "WRITTEN VALUE: "
    read_text = "READ VALUE: "
    write_verification_text = "WRITE CHECK: "
    read_verification_text = "READ CHECK: "
    ics854s01i_write_check = 0
    ics854s01i_read_check = 0
    ics854s01i_log = []

    #pll_clk_sel = 0 Clock from external source (MMCX J4) function mode
    ics854s01i_log.append(
        "Teste do PLL_CLK_SEL FROM EXTERNAL SOURCE - MMCX J4: 0")
    print("Teste do PLL_CLK_SEL FROM EXTERNAL SOURCE - MMCX J4: 0")
    pll_clk_sel = 0
    command = "./THALES_ics854s01i_ctl -b tcp://" + str(
        IP_CRATE) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
            POSITION_ADC) + " -fmc_pll_function " + str(pll_clk_sel)
    command_stdout = Popen(local + command,
                           shell=True,
                           stdin=PIPE,
                           stdout=PIPE,
                           stderr=PIPE).communicate()[0]
    command_stdout = command_stdout.splitlines()
    write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
    write_value = write_aux.replace(write_text, "")

    read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
    read_value = read_aux.replace(read_text, "")

    #Verifica se foi capaz de enviar comandos através do método de escrita
    write_verification_aux = command_stdout[len(command_stdout) -
                                            4].decode("utf-8")
    write_verification_aux = write_verification_aux.replace(
        write_verification_text, "")
    if (write_verification_aux != str(0)):
        ics854s01i_write_check = ics854s01i_write_check + 1

    #Verifica se foi capaz de enviar comandos através do método de leitura
    read_verification_aux = command_stdout[len(command_stdout) -
                                           3].decode("utf-8")
    read_verification_aux = read_verification_aux.replace(
        read_verification_text, "")
    if (read_verification_aux != str(0)):
        ics854s01i_read_check = ics854s01i_read_check + 1

    print("Verificação...")

    tela_leds.ui.progressBar.setValue(50)
    tela_leds.repaint()
    QApplication.processEvents()

    pll_clk_sel_check_mmcx = 0
    if (read_value != write_value or read_value != str(pll_clk_sel)):
        print("PLL_CLK_SEL: FAIL")
        print("Valor Enviado pelo Comando: ", pll_clk_sel)
        print("Valor Escrito : ", write_value)
        print("Valor Lido: ", read_value)
        pll_clk_sel_check_mmcx = pll_clk_sel_check_mmcx + 1

    if (pll_clk_sel_check_mmcx == 0):
        print("PLL_CLK_SEL FROM EXTERNAL SOURCE - MMCX J4: OK")
        pll_clk_sel_mmcx_result = "OK"
    else:
        print("PLL_CLK_SEL FROM EXTERNAL SOURCE - MMCX J4: FAIL")
        pll_clk_sel_mmcx_result = "FAIL"

    ics854s01i_log.append("Valor Enviado pelo Comando: " + str(pll_clk_sel))
    ics854s01i_log.append("Valor Escrito : " + str(write_value))
    ics854s01i_log.append("Valor Lido : " + str(read_value))

    #pll_clk_sel = 1 Clock from FMC PIN (FMC_CLK line) function mode
    ics854s01i_log.append(
        "Teste do PLL_CLK_SEL FROM FMC PIN (FMC_CLK LINE): 1")
    print("Teste do PLL_CLK_SEL FROM FMC PIN (FMC_CLK LINE): 1")
    pll_clk_sel = 1
    command = "./THALES_ics854s01i_ctl -b tcp://" + str(
        IP_CRATE) + ":8978 -board " + str(POSITION_CRATE) + " -halcs " + str(
            POSITION_ADC) + " -fmc_pll_function " + str(pll_clk_sel)
    command_stdout = Popen(local + command,
                           shell=True,
                           stdin=PIPE,
                           stdout=PIPE,
                           stderr=PIPE).communicate()[0]
    command_stdout = command_stdout.splitlines()
    write_aux = command_stdout[len(command_stdout) - 2].decode("utf-8")
    write_value = write_aux.replace(write_text, "")

    read_aux = command_stdout[len(command_stdout) - 1].decode("utf-8")
    read_value = read_aux.replace(read_text, "")

    #Verifica se foi capaz de enviar comandos através do método de escrita
    write_verification_aux = command_stdout[len(command_stdout) -
                                            4].decode("utf-8")
    write_verification_aux = write_verification_aux.replace(
        write_verification_text, "")
    if (write_verification_aux != str(0)):
        ics854s01i_write_check = ics854s01i_write_check + 1

    #Verifica se foi capaz de enviar comandos através do método de leitura
    read_verification_aux = command_stdout[len(command_stdout) -
                                           3].decode("utf-8")
    read_verification_aux = read_verification_aux.replace(
        read_verification_text, "")
    if (read_verification_aux != str(0)):
        ics854s01i_read_check = ics854s01i_read_check + 1

    tela_leds.ui.progressBar.setValue(100)
    tela_leds.repaint()
    QApplication.processEvents()

    print("Verificação...")

    pll_clk_sel_check_fmc_pin = 0
    if (read_value != write_value or read_value != str(pll_clk_sel)):
        print("PLL_CLK_SEL : FAIL")
        print("Valor Enviado pelo Comando: ", pll_clk_sel)
        print("Valor Escrito :", write_value)
        print("Valor Lido: ", read_value)
        pll_clk_sel_check_fmc_pin = pll_clk_sel_check_fmc_pin + 1

    if (pll_clk_sel_check_fmc_pin == 0):
        print("PLL_CLK_SEL FROM FMC PIN (FMC_CLK LINE): OK")
        pll_clk_sel_fmc_pin_result = "OK"
    else:
        print("PLL_CLK_SEL FROM FMC PIN (FMC_CLK LINE): FAIL")
        pll_clk_sel_fmc_pin_result = "FAIL"

    if (pll_clk_sel_mmcx_result != "OK" or pll_clk_sel_fmc_pin_result != "OK"):
        ics854s01i_result = "FAIL"
        print("Teste do ICS854S01I: FAIL")
    else:
        ics854s01i_result = "OK"
        print("Teste do ICS854S01I: OK")

    if (ics854s01i_write_check != 0):
        ics854s01i_write_check_result = "FAIL"
        print("Utilizacao do método de Escrita: ",
              ics854s01i_write_check_result)
    else:
        ics854s01i_write_check_result = "OK"
        print("Utilizacao do método de Escrita: ",
              ics854s01i_write_check_result)

    if (ics854s01i_read_check != 0):
        ics854s01i_read_check_result = "FAIL"
        print("Utilizacao do método de Leitura: ",
              ics854s01i_read_check_result)
    else:
        ics854s01i_read_check_result = "OK"
        print("Utilizacao do método de Leitura: ",
              ics854s01i_read_check_result)

    ics854s01i_log.append("Valor Enviado pelo Comando: " + str(pll_clk_sel))
    ics854s01i_log.append("Valor Escrito : " + str(write_value))
    ics854s01i_log.append("Valor Lido : " + str(read_value))
    ics854s01i_log.append("Utilizacao do metodo de Escrita: " +
                          str(ics854s01i_write_check_result))
    ics854s01i_log.append("Utilizacao do metodo de Leitura: " +
                          str(ics854s01i_read_check_result))
    ics854s01i_log.append("FINAL RESULT: " + str(ics854s01i_result))

    end_time = datetime.datetime.now()
    end_time_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
    print("Fim do Teste do ICS854S01I")
    print("End_write_time:", end_time_str)
    duracao = ((end_time - start_time).total_seconds()) / 60
    print("Duração do Teste: ", round(duracao, 4))

    return (ics854s01i_result, ics854s01i_write_check_result,
            ics854s01i_read_check_result, ics854s01i_log)
Ejemplo n.º 56
0
def main():
    branch = str(get_branch().decode('utf-8'))
    name_status = get_name_status()

    changed, nb_conflicts, nb_staged, nb_untracked = get_numbers(name_status)
    if changed or nb_staged or nb_conflicts or nb_untracked:
        clean = '0'
    else:
        clean = '1'

    remote = ''
    branch = branch.strip()[11:]
    if not branch:
        branch = str(
            Popen(['git', 'rev-parse', '--short', 'HEAD'],
                  stdout=PIPE).communicate()[0][:-1].decode('utf-8'))
    else:
        remote_name = str(
            Popen(['git', 'config', 'branch.{}.remote'.format(branch)],
                  stdout=PIPE).communicate()[0].decode('utf-8').strip())

        if remote_name:
            merge_name = str(
                Popen(['git', 'config', 'branch.{}.merge'.format(branch)],
                      stdout=PIPE).communicate()[0].strip().decode('utf-8'))

            if remote_name == '.':  # local
                remote_ref = merge_name
            else:
                remote_ref = 'refs/remotes/{}/{}'.format(
                    remote_name, merge_name[11:])

            revgit = Popen([
                'git', 'rev-list', '--left-right',
                '{}...HEAD'.format(remote_ref)
            ],
                           stdout=PIPE,
                           stderr=PIPE)
            revlist = revgit.communicate()[0]
            if revgit.poll():  # fallback to local
                revlist = Popen([
                    'git', 'rev-list', '--left-right',
                    '%s...HEAD' % merge_name
                ],
                                stdout=PIPE,
                                stderr=PIPE).communicate()[0]

            behead = revlist.splitlines()
            ahead = len([x for x in behead if x[0] == '>'])
            behind = len(behead) - ahead
            if behind:
                remote += '{}{}'.format(SYMBOLS['behind'], behind)
            if ahead:
                remote += '{}{}'.format(SYMBOLS['ahead'], ahead)

    out = ', '.join([
        str(branch), remote,
        str(nb_staged),
        str(nb_conflicts),
        str(changed),
        str(nb_untracked), clean
    ])

    print(out)
Ejemplo n.º 57
0
def create_release(plugin_name=None):
    """Verify the plugin name and create the current release."""
    # Was no plugin name provided?
    if plugin_name not in plugin_list:
        print(
            'Invalid plugin name "{plugin_name}"'.format(
                plugin_name=plugin_name,
            )
        )
        return

    # Get the plugin's base path
    plugin_path = START_DIR / plugin_name

    plugin_path.chdir()
    output = Popen(
        'git ls-tree --full-tree -r HEAD'.split(),
        stdout=PIPE,
    ).communicate()[0]
    START_DIR.chdir()
    repo_files = [
        '{sep}{path}'.format(
            sep=sep,
            path=str(x).split('\\t')[1].replace('/', sep)[:~0],
        ) for x in output.splitlines()
    ]

    # Does the plugin not exist?
    if not plugin_path.isdir():
        print(
            'Plugin "{plugin_name}" not found.'.format(plugin_name=plugin_name)
        )
        return

    # Get the plugin's current version
    info_file = plugin_path.joinpath(
        'addons', 'source-python', 'plugins', plugin_name, 'info.ini'
    )
    config_obj = ConfigObj(info_file)
    version = config_obj['version']

    # Was no version information found?
    if version is None:
        print('No version found.')
        return

    # Get the directory to save the release in
    save_path = RELEASE_DIR / plugin_name

    # Create the directory if it doesn't exist
    if not save_path.isdir():
        save_path.makedirs()

    # Get the zip file location
    zip_path = save_path / '{plugin_name} - v{version}.zip'.format(
        plugin_name=plugin_name,
        version=version,
    )

    # Does the release already exist?
    if zip_path.isfile():
        print('Release already exists for current version.')
        return

    # Create the zip file
    with ZipFile(zip_path, 'w', ZIP_DEFLATED) as zip_file:

        # Loop through all allowed directories
        for allowed_path in allowed_filetypes:

            # Get the full path to the directory
            check_path = plugin_path.joinpath(*allowed_path.split('/'))

            # Does the directory exist?
            if not check_path.isdir():
                continue

            # Loop through all files with the plugin's name
            for full_file_path in _find_files(
                check_path.files(
                    '{plugin_name}.*'.format(
                        plugin_name=plugin_name,
                    )
                ),
                allowed_path,
                allowed_filetypes,
            ):

                relative_file_path = full_file_path.replace(plugin_path, '')
                if relative_file_path in repo_files:

                    # Add the file to the zip
                    _add_file(
                        zip_file, full_file_path, relative_file_path,
                        plugin_path,
                    )

            # Loop through all files within the plugin's directory
            for full_file_path in _find_files(
                check_path.joinpath(
                    plugin_name,
                ).walkfiles(),
                allowed_path,
                allowed_filetypes,
            ):

                relative_file_path = full_file_path.replace(plugin_path, '')
                if relative_file_path in repo_files:

                    # Add the file to the zip
                    _add_file(
                        zip_file, full_file_path, relative_file_path,
                        plugin_path,
                    )

        # Loop through all other allowed directories
        for allowed_path in other_filetypes:

            # Get the full path to the directory
            check_path = plugin_path.joinpath(*allowed_path.split('/'))

            # Does the directory exist?
            if not check_path.isdir():
                continue

            # Loop through all files in the directory
            for full_file_path in _find_files(
                check_path.walkfiles(), allowed_path, other_filetypes
            ):

                relative_file_path = full_file_path.replace(plugin_path, '')
                if relative_file_path in repo_files:

                    # Add the file to the zip
                    _add_file(
                        zip_file, full_file_path, relative_file_path,
                        plugin_path,
                    )

    # Print a message that everything was successful
    print(
        'Successfully created {plugin_name} version {version} release:'.format(
            plugin_name=plugin_name,
            version=version,
        )
    )
    print('\t"{zip_path}"\n\n'.format(zip_path=zip_path))
Ejemplo n.º 58
0
def get_size(path):
    out = Popen([SIZE, path], stdout=PIPE).communicate()[0]
    return map(int, out.splitlines()[1].split()[:4])
Ejemplo n.º 59
0
t = 0
for x in IPandMAC:
    if routerIP in x[1]:
        routerMAC = x[0]
        t = 1
        break
if t == 0:
    sys.exit('Router MAC not found')

#Do nbtscan for windows netbios names
print '[+] Running nbtscan'
try:
    nbt = Popen(['nbtscan', IPprefix + '0/24'], stdout=PIPE, stderr=DN)
    nbt = nbt.communicate()[0]
    nbt = nbt.splitlines()
except:
    print '[-] nbtscan error, are you sure it is installed?'
if len(nbt) < 5:
    print '[-] nbtscan failed'
for l in nbt:
    if l.startswith(IPprefix):
        ip_name = re.search('(\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\w+)', l)
        try:
            nbtip = ip_name.group(1)
        except:
            continue
        try:
            netbios = ip_name.group(2)
        except:
            continue
Ejemplo n.º 60
0
from subprocess import Popen,PIPE

a = False
#b = True
#print("Escolha o teste de loopback a ser feito:\n")
#print("1- Pinos de alta velocidade\n")
#print("2- Pinos RTM\n")
if (a==True):
    comando2 = "sudo /opt/Xilinx/Vivado/2016.2/bin/vivado -source /home/engenharia/Project_Test/GTP.tcl\n"
    command_stdout = Popen(comando2,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE).communicate()[0]
    command_stdout=command_stdout.splitlines()

if (a==False):
    comando2 = "sudo /opt/Xilinx/Vivado/2016.2/bin/vivado -source /home/engenharia/Project_Test/RTM_IO.tcl\n"
    command_stdout = Popen(comando2,shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE).communicate()[0]
    command_stdout=command_stdout.splitlines()