get the afp list and residue list for each block
190237
public static void blockInfo(AFPChain afpChain)
	{
		int     i, j, k, a, n;

		int blockNum = afpChain.getBlockNum();

		int[] blockSize =afpChain.getBlockSize();
		int[] afpChainList = afpChain.getAfpChainList();
		int[] block2Afp = afpChain.getBlock2Afp();
		int[][][]blockResList = afpChain.getBlockResList();

		List<AFP>afpSet = afpChain.getAfpSet();
		int[] blockResSize = afpChain.getBlockResSize();

		for(i = 0; i < blockNum; i ++)  {
			n = 0;
			for(j = 0; j < blockSize[i]; j ++)      {
				//the index in afpChainList, not in the whole afp set
				a = afpChainList[block2Afp[i] + j];
				for(k = 0; k < afpSet.get(a).getFragLen(); k ++)     {
					blockResList[i][0][n] = afpSet.get(a).getP1() + k;
					blockResList[i][1][n] = afpSet.get(a).getP2() + k;
					n ++;
				}
			}
			blockResSize[i] = n;
		}

		afpChain.setBlockResSize(blockResSize);
		afpChain.setBlockSize(blockSize);
		afpChain.setAfpChainList(afpChainList);
		afpChain.setBlock2Afp(block2Afp);
		afpChain.setBlockResList(blockResList);
	}
1220534
def collect_blocks(self):
        
        if self.mode == 'spark':
            return self.values.tordd().sortByKey().values().collect()

        if self.mode == 'local':
            return self.values.values.flatten().tolist()
896269
def _defrag_list(lst, defrag, missfrag):
    """"""
    p = lst[0]
    lastp = lst[-1]
    if p.frag > 0 or lastp.flags.MF:  # first or last fragment missing
        missfrag.append(lst)
        return
    p = p.copy()
    if conf.padding_layer in p:
        del(p[conf.padding_layer].underlayer.payload)
    ip = p[IP]
    if ip.len is None or ip.ihl is None:
        clen = len(ip.payload)
    else:
        clen = ip.len - (ip.ihl << 2)
    txt = conf.raw_layer()
    for q in lst[1:]:
        if clen != q.frag << 3:  # Wrong fragmentation offset
            if clen > q.frag << 3:
                warning("Fragment overlap (%i > %i) %r || %r ||  %r" % (clen, q.frag << 3, p, txt, q))  # noqa: E501
            missfrag.append(lst)
            break
        if q[IP].len is None or q[IP].ihl is None:
            clen += len(q[IP].payload)
        else:
            clen += q[IP].len - (q[IP].ihl << 2)
        if conf.padding_layer in q:
            del(q[conf.padding_layer].underlayer.payload)
        txt.add_payload(q[IP].payload.copy())
        if q.time > p.time:
            p.time = q.time
    else:
        ip.flags.MF = False
        del(ip.chksum)
        del(ip.len)
        p = p / txt
        p._defrag_pos = max(x._defrag_pos for x in lst)
        defrag.append(p)
378995
def generate_code_cover(self):
        

        lst = [ ]
        for irsb_addr in self.cfg.nodes():
            if irsb_addr not in self._block_size:
                continue
            irsb_size = self._block_size[irsb_addr]
            lst.append((irsb_addr, irsb_size))

        lst = sorted(lst, key=lambda x: x[0])

        return lst
1110300
def _extract_residues(self):
                
        
        r_list = self.handle.getElementsByTagName("response")
        
        r_data = {}
        
        for r in r_list:
            data = self._parse_residue(r)
            res_id = (data['model'], data['chain'], data['number']) # (A, 1, 1), (A, 1, 2), ...
            if not r_data.has_key(res_id):
                r_data[res_id] = data
            else: # Some atoms get repeated at the end with TER Hydrogens/oxygens
                r_data[res_id]['atoms'] += data['atoms'] # Append Atoms
        
        for key in sorted(r_data.keys()):
            yield r_data[key]
860658
def processing_blocks(self):
        """"""
        pb_list = ProcessingBlockList()
        # TODO(BMo) realtime, offline etc.
        return json.dumps(dict(active=pb_list.active,
                               completed=pb_list.completed,
                               aborted=pb_list.aborted))
267826
def blocks(self):
        

        for block_addr, block in self._local_blocks.items():
            try:
                yield self._get_block(block_addr, size=block.size,
                                      byte_string=block.bytestr if isinstance(block, BlockNode) else None)
            except (SimEngineError, SimMemoryError):
                pass
1301975
def listBlockChildren(self, block_name=""):
        
        if (not block_name) or re.search("['%','*']", block_name):
            dbsExceptionHandler("dbsException-invalid-input", "DBSBlock/listBlockChildren. Block_name must be provided." )
        conn = self.dbi.connection()
        try:
            results = self.blockchildlist.execute(conn, block_name)
            return results
        finally:
            if conn:
                conn.close()
438381
def get_table():
    """"""
    response = dict(blocks=[])
    block_ids = DB.get_sched_block_instance_ids()
    for index, block_id in enumerate(block_ids):
        block = DB.get_block_details([block_id]).__next__()
        info = [
            index,
            block['id'],
            block['sub_array_id'],
            len(block['processing_blocks'])
        ]
        response['blocks'].append(info)
    return response, HTTPStatus.OK
876837
def parameters(self):
        

        return self.block_tl, self.block_br, self.rows, self.cols, self.cells
659771
def list_blocks_of_type(self, blocktype, size):
        """"""

        blocktype = snap7.snap7types.block_types.get(blocktype)

        if not blocktype:
            raise Snap7Exception("The blocktype parameter was invalid")

        logger.debug("listing blocks of type: %s size: %s" %
                      (blocktype, size))

        if (size == 0):
            return 0
		
        data = (c_uint16 * size)()
        count = c_int(size)
        result = self.library.Cli_ListBlocksOfType(
            self.pointer, blocktype,
            byref(data),
            byref(count))

        logger.debug("number of items found: %s" % count)

        check_error(result, context="client")
        return data
1098558
public static final List<String> getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){
		List<String> lst = new ArrayList<String>();
		if ( aligPos > 1) {
			System.err.println("multiple alignments not supported yet!");
			return lst;
		}

		int blockNum = afpChain.getBlockNum();
		int[] optLen = afpChain.getOptLen();
		int[][][] optAln = afpChain.getOptAln();

		if ( optLen == null)
			return lst;

		for(int bk = 0; bk < blockNum; bk ++)       {

			for ( int i=0;i< optLen[bk];i++){

				int pos = optAln[bk][aligPos][i];
				if ( pos < ca.length) {
					String pdbInfo = JmolTools.getPdbInfo(ca[pos]);
					//lst.add(ca1[pos].getParent().getPDBCode());
					lst.add(pdbInfo);
				}
			}

		}
		return lst;
	}
1323942
def lcs_backtrace(c, x, y, i, j, &block)
      return [] if i == 0 || j == 0
      if (v = yield(x[i], y[j]))
        return lcs_backtrace(c, x, y, i - 1, j - 1, &block) << v
      end

      return lcs_backtrace(c, x, y, i, j - 1, &block) if c[i][j - 1] > c[i - 1][j]
      lcs_backtrace(c, x, y, i - 1, j, &block)
    end
1331152
def prune_structure_according_to_loops_file(self, loops_file_content, search_radius, expected_loop_length = None, generate_pymol_session = True):
        ''''''
        lf = LoopsFile(loops_file_content)
        assert(len(lf.data) == 1) # todo: remove

        # Extract the list of Residues defined in the loops file
        loop_residues = []
        for loop in lf.data:
            # Identify the Residues corresponding to the loops file definition
            start_id = str(loop['start'])
            end_id = str(loop['end'])
            start = []
            end = []
            for chain, chain_residues in self.residues.iteritems():
                for res, residue_object in chain_residues.iteritems():
                    if res.strip() == start_id:
                        start.append((chain, res, residue_object))
                    if res.strip() == end_id:
                        end.append((chain, res, residue_object))
            if len(start) != len(end) != 1:
                raise Exception('The PDB is ambiguous with respect to the loops file i.e. more than one PDB residue corresponds to the start or end residue defined in the loops file.')
            start, end = start[0], end[0]

            # We assume that the loops file identifies a range in document order
            loop_start = False
            for l in self.indexed_lines:
                if l[0] == 'ATOM' or l[0] == 'HETATM':
                    atom_residue = l[3].residue
                    if not loop_start:
                        if atom_residue == start[2]:
                            loop_start = True
                            if atom_residue not in loop_residues:
                                loop_residues.append(atom_residue)
                    else:
                        if atom_residue not in loop_residues:
                            loop_residues.append(atom_residue)
                        if atom_residue == end[2]:
                            break
        if expected_loop_length != None and expected_loop_length != len(loop_residues):
            raise Exception('Expected to identify {0} residues but {1} were identified.'.format(expected_loop_length, len(loop_residues)))

        # Determine the sidechain atoms to be removed
        sidechain_atom_serial_numbers = self.find_sidechain_atoms_within_radius_of_residue_objects(loop_residues, search_radius)

        # Determine the loop residue atoms to be removed
        loop_residues_ids = set()
        loop_atom_serial_numbers = set()
        for loop_residue in loop_residues:
            for aatom in loop_residue.get('ATOM'):
                loop_atom_serial_numbers.add(aatom.serial_number)
        assert(len(sidechain_atom_serial_numbers.intersection(loop_atom_serial_numbers)) == 0)

        return self.prune(loop_atom_serial_numbers, sidechain_atom_serial_numbers, generate_pymol_session = generate_pymol_session)
571473
def get_filelist(run_module_names):
    
    # Prep search patterns
    spatterns = [{},{},{},{},{},{},{}]
    epatterns = [{}, {}]
    ignored_patterns = []
    for key, sps in config.sp.items():
        mod_name = key.split('/', 1)[0]
        if mod_name.lower() not in [m.lower() for m in run_module_names]:
            ignored_patterns.append(key)
            continue
        files[key] = list()
        if not isinstance(sps, list):
            sps = [sps]

        # Warn if we have any unrecognised search pattern keys
        expected_sp_keys = [
            'fn',
            'fn_re',
            'contents',
            'contents_re',
            'num_lines',
            'shared',
            'max_filesize',
            'exclude_fn',
            'exclude_fn_re',
            'exclude_contents',
            'exclude_contents_re'
        ]
        unrecognised_keys = [y for x in sps for y in x.keys() if y not in expected_sp_keys]
        if len(unrecognised_keys) > 0:
            logger.warn("Unrecognised search pattern keys for '{}': {}".format(key, ', '.join(unrecognised_keys)))

        # Split search patterns according to speed of execution.
        if any([x for x in sps if 'contents_re' in x]):
            if any([x for x in sps if 'num_lines' in x]):
                spatterns[4][key] = sps
            elif any([x for x in sps if 'max_filesize' in x]):
                spatterns[5][key] = sps
            else:
                spatterns[6][key] = sps
        elif any([x for x in sps if 'contents' in x]):
            if any([x for x in sps if 'num_lines' in x]):
                spatterns[1][key] = sps
            elif any([x for x in sps if 'max_filesize' in x]):
                spatterns[2][key] = sps
            else:
                spatterns[3][key] = sps
        else:
            spatterns[0][key] = sps

    if len(ignored_patterns) > 0:
        logger.debug("Ignored {} search patterns as didn't match running modules.".format(len(ignored_patterns)))

    def add_file(fn, root):
        """
        Function applied to each file found when walking the analysis
        directories. Runs through all search patterns and returns True
        if a match is found.
        """
        f = {'fn': fn, 'root': root}

        # Check that this is a file and not a pipe or anything weird
        if not os.path.isfile(os.path.join(root, fn)):
            return None

        # Check that we don't want to ignore this file
        i_matches = [n for n in config.fn_ignore_files if fnmatch.fnmatch(fn, n)]
        if len(i_matches) > 0:
            logger.debug("Ignoring file as matched an ignore pattern: {}".format(fn))
            return None

        # Limit search to small files, to avoid 30GB FastQ files etc.
        try:
            f['filesize'] = os.path.getsize(os.path.join(root,fn))
        except (IOError, OSError, ValueError, UnicodeDecodeError):
            logger.debug("Couldn't read file when checking filesize: {}".format(fn))
        else:
            if f['filesize'] > config.log_filesize_limit:
                return False

        # Test file for each search pattern
        for patterns in spatterns:
            for key, sps in patterns.items():
                for sp in sps:
                    if search_file (sp, f):
                        # Check that we shouldn't exclude this file
                        if not exclude_file(sp, f):
                            # Looks good! Remember this file
                            files[key].append(f)
                        # Don't keep searching this file for other modules
                        if not sp.get('shared', False):
                            return
                        # Don't look at other patterns for this module
                        else:
                            break

    # Go through the analysis directories and get file list
    for path in config.analysis_dir:
        if os.path.islink(path) and config.ignore_symlinks:
            continue
        elif os.path.isfile(path):
            searchfiles.append([os.path.basename(path), os.path.dirname(path)])
        elif os.path.isdir(path):
            for root, dirnames, filenames in os.walk(path, followlinks=(not config.ignore_symlinks), topdown=True):
                bname = os.path.basename(root)

                # Skip any sub-directories matching ignore params
                orig_dirnames = dirnames[:]
                for n in config.fn_ignore_dirs:
                    dirnames[:] = [d for d in dirnames if not fnmatch.fnmatch(d, n.rstrip(os.sep))]
                    if len(orig_dirnames) != len(dirnames):
                        removed_dirs = [os.path.join(root, d) for d in set(orig_dirnames).symmetric_difference(set(dirnames))]
                        logger.debug("Ignoring directory as matched fn_ignore_dirs: {}".format(", ".join(removed_dirs)))
                        orig_dirnames = dirnames[:]
                for n in config.fn_ignore_paths:
                    dirnames[:] = [d for d in dirnames if not fnmatch.fnmatch(os.path.join(root, d), n.rstrip(os.sep))]
                    if len(orig_dirnames) != len(dirnames):
                        removed_dirs = [os.path.join(root, d) for d in set(orig_dirnames).symmetric_difference(set(dirnames))]
                        logger.debug("Ignoring directory as matched fn_ignore_paths: {}".format(", ".join(removed_dirs)))

                # Skip *this* directory if matches ignore params
                d_matches = [n for n in config.fn_ignore_dirs if fnmatch.fnmatch(bname, n.rstrip(os.sep))]
                if len(d_matches) > 0:
                    logger.debug("Ignoring directory as matched fn_ignore_dirs: {}".format(bname))
                    continue
                p_matches = [n for n in config.fn_ignore_paths if fnmatch.fnmatch(root, n.rstrip(os.sep))]
                if len(p_matches) > 0:
                    logger.debug("Ignoring directory as matched fn_ignore_paths: {}".format(root))
                    continue
                # Search filenames in this directory
                for fn in filenames:
                    searchfiles.append([fn, root])
    # Search through collected files
    with click.progressbar(searchfiles, label="Searching {} files..".format(len(searchfiles))) as sfiles:
        for sf in sfiles:
            add_file(sf[0], sf[1])
382918
def _selectedBlockNumbers(self):
        
        startBlock, endBlock = self._selectedBlocks()
        return startBlock.blockNumber(), endBlock.blockNumber()
605460
BlockInfo[] getTimedOutBlocks() {
    synchronized (timedOutItems) {
      if (timedOutItems.size() <= 0) {
        return null;
      }
      BlockInfo[] blockList = timedOutItems.toArray(
                              new BlockInfo[timedOutItems.size()]);
      timedOutItems.clear();
      return blockList;
    }
  }