Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds
480878
def find(query):
    
    assert type(query) == str or type(query) == str, 'query not a string object'
    searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % (urlquote(query), TOKEN)
    response = urlopen(searchurl)
    tree = ET.parse(response)
    elem = tree.getroot()
    csid_tags = elem.getiterator('{http://www.chemspider.com/}int')
    compoundlist = []
    for tag in csid_tags:
        compoundlist.append(Compound(tag.text))
    return compoundlist if compoundlist else None
325311
def search(self, search_phrase, limit=None):
        

        query_parts = [
            'SELECT identifier, type, name, similarity(name, :word) AS sml',
            'FROM identifier_index',
            'WHERE name % :word',
            'ORDER BY sml DESC, name']

        query_params = {
            'word': search_phrase}

        if limit:
            query_parts.append('LIMIT :limit')
            query_params['limit'] = limit

        query_parts.append(';')

        query = text('\n'.join(query_parts))

        self.backend.library.database.set_connection_search_path()

        results = self.execute(query, **query_params).fetchall()

        for result in results:
            vid, type, name, score = result
            yield IdentifierSearchResult(
                score=score, vid=vid,
                type=type, name=name)
251286
def searchlast(self,n=10):
        """"""            
        solutions = deque([], n)
        for solution in self:
            solutions.append(solution)
        return solutions
1288499
def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
	""""""
	s = Search()
	s.search(term=term, category=category, pages=pages, sort=sort, order=order)
	return s
1010037
def search(self, s, stype=1, offset=0, total='true', limit=60):
        """"""
        action = uri + '/search/get'
        data = {
            's': s,
            'type': stype,
            'offset': offset,
            'total': total,
            'limit': 60
        }
        resp = self.request('POST', action, data)
        if resp['code'] == 200:
            return resp['result']['songs']
        return []
690519
def search(query)
      regex = Regexp.new(query, 'i')
      _cookbooks.collect do |_, v|
        v[v.keys.first] if regex.match(v[v.keys.first].name)
      end.compact
    end
1005760
def find(self, start, end, chrom=None):
        """"""
        intervals = self.intervals[chrom]
        ilen = len(intervals)
        # NOTE: we only search for starts, since any feature that starts within max_len of
        # the query could overlap, we must subtract max_len from the start to get the needed
        # search space. everything else proceeds like a binary search.
        # (but add distance calc for candidates).
        if not chrom in self.max_len: return []
        ileft  = binsearch_left_start(intervals, start - self.max_len[chrom], 0, ilen)
        iright = binsearch_right_end(intervals, end, ileft, ilen)
        query = Feature(start, end)
        # we have to check the distance to make sure we didnt pick up anything 
        # that started within max_len, but wasnt as long as max_len
        return [f for f in intervals[ileft:iright] if distance(f, query) == 0]
517777
def search_ss_bonds(self, threshold=3.0):
        
        
        # Taken from http://docs.python.org/library/itertools.html
        # Python 2.4 does not include itertools.combinations

        def combinations(iterable, r):
            # combinations('ABCD', 2) --> AB AC AD BC BD CD
            # combinations(range(4), 3) --> 012 013 023 123
            pool = tuple(iterable)
            n = len(pool)
            if r > n:
                return
            indices = range(r)
            yield tuple(pool[i] for i in indices)
            while True:
                for i in reversed(range(r)):
                    if indices[i] != i + n - r:
                        break
                else:
                    return
                indices[i] += 1
                for j in range(i+1, r):
                    indices[j] = indices[j-1] + 1
                yield tuple(pool[i] for i in indices)

        
        
        model = self.child_list[0]
        cysteines = [r for r in model.get_residues() if r.get_resname() == 'CYS']

        pairs = combinations(cysteines, 2) # Iterator with pairs

        for cys_pair in pairs:
            if cys_pair[0]['SG'] - cys_pair[1]['SG'] < threshold:
                yield cys_pair
1073926
def findAll(haystack, needle) :
	""""""
	
	h = haystack
	res = []
	f = haystack.find(needle)
	offset = 0
	while (f >= 0) :
		#print h, needle, f, offset
		res.append(f+offset)
		offset += f+len(needle)
		h = h[f+len(needle):]
		f = h.find(needle)

	return res
1035424
def search(self, terms, prelim=True):
        """"""
        # TODO: There are now lots of additional data sources, make additional
        # searching optional (11/01/2017)
        if prelim:  # preliminary search
            res = self._resolve(terms, self.Id)
            self._write(res)
            return res
        else:  # search other DSs for alt names, search DS with these
            # quick fix: https://github.com/DomBennett/TaxonNamesResolver/issues/5
            # seems to be due to limit on number of ids in single request
            # switiching to a for loop for each data source
            # appending all results into single res
            res = []
            for ds_id in self.otherIds:
                tmp = self._resolve(terms, [ds_id])
                res.append(tmp[0])
            self._write(res)
            alt_terms = self._parseNames(res)
            if len(alt_terms) == 0:
                return False
            else:
                # search the main source again with alt_terms
                # replace names in json
                terms = [each[1] for each in alt_terms]  # unzip
                res = self._resolve(terms, self.Id)
                self._write(res)
                alt_res = self._replaceSupStrNames(res, alt_terms)
                return alt_res
1042441
def _index_by_name(self, name):
        """"""
        for i, t in enumerate(self._cache):
            if t[2] == name:
                return i
            # END found item
        # END for each item in cache
        return -1
43857
def _search(self, trie, strings, limit=None):
        
        results = [trie.has_keys_with_prefix(s) for s in strings]
        if not any(results):
            return []
        for result, s in zip(results, strings):
            if result is True:
                return trie.values(s)[:limit]
784194
def find_rings(self, mol, all_atoms):
        """"""
        data = namedtuple('aromatic_ring', 'atoms orig_atoms atoms_orig_idx normal obj center type')
        rings = []
        aromatic_amino = ['TYR', 'TRP', 'HIS', 'PHE']
        ring_candidates = mol.OBMol.GetSSSR()
        write_message("Number of aromatic ring candidates: %i\n" % len(ring_candidates), mtype="debug")
        # Check here first for ligand rings not being detected as aromatic by Babel and check for planarity
        for ring in ring_candidates:
            r_atoms = [a for a in all_atoms if ring.IsMember(a.OBAtom)]
            if 4 < len(r_atoms) <= 6:
                res = list(set([whichrestype(a) for a in r_atoms]))
                if ring.IsAromatic() or res[0] in aromatic_amino or ring_is_planar(ring, r_atoms):
                    # Causes segfault with OpenBabel 2.3.2, so deactivated
                    # typ = ring.GetType() if not ring.GetType() == '' else 'unknown'
                    # Alternative typing
                    typ = '%s-membered' % len(r_atoms)
                    ring_atms = [r_atoms[a].coords for a in [0, 2, 4]]  # Probe atoms for normals, assuming planarity
                    ringv1 = vector(ring_atms[0], ring_atms[1])
                    ringv2 = vector(ring_atms[2], ring_atms[0])
                    atoms_orig_idx = [self.Mapper.mapid(r_atom.idx, mtype=self.mtype,
                                                        bsid=self.bsid) for r_atom in r_atoms]
                    orig_atoms = [self.Mapper.id_to_atom(idx) for idx in atoms_orig_idx]
                    rings.append(data(atoms=r_atoms,
                                      orig_atoms=orig_atoms,
                                      atoms_orig_idx=atoms_orig_idx,
                                      normal=normalize_vector(np.cross(ringv1, ringv2)),
                                      obj=ring,
                                      center=centroid([ra.coords for ra in r_atoms]),
                                      type=typ))
        return rings
902196
def search(self, initial_ids, initial_cache):
    """"""
    state, state_shapes = self._create_initial_state(initial_ids, initial_cache)

    finished_state = tf.while_loop(
        self._continue_search, self._search_step, loop_vars=[state],
        shape_invariants=[state_shapes], parallel_iterations=1, back_prop=False)
    finished_state = finished_state[0]

    alive_seq = finished_state[_StateKeys.ALIVE_SEQ]
    alive_log_probs = finished_state[_StateKeys.ALIVE_LOG_PROBS]
    finished_seq = finished_state[_StateKeys.FINISHED_SEQ]
    finished_scores = finished_state[_StateKeys.FINISHED_SCORES]
    finished_flags = finished_state[_StateKeys.FINISHED_FLAGS]

    # Account for corner case where there are no finished sequences for a
    # particular batch item. In that case, return alive sequences for that batch
    # item.
    finished_seq = tf.where(
        tf.reduce_any(finished_flags, 1), finished_seq, alive_seq)
    finished_scores = tf.where(
        tf.reduce_any(finished_flags, 1), finished_scores, alive_log_probs)
    return finished_seq, finished_scores
127488
def film_search(self, title):
        """"""
        films = []
        #check for cache or update
        if not hasattr(self, 'film_list'):
            self.get_film_list()
        #iterate over films and check for fuzzy string match    
        for film in self.film_list:
            strength = WRatio(title, film['title'])
            if  strength > 80:
                film.update({u'strength':strength})
                films.append(film)
        #sort films by the strength of the fuzzy string match
        films_sorted = sorted(films, key=itemgetter('strength'), reverse = True)
        return films_sorted
273379
def getInstIdFromIndices(self, *indices):
        """"""
        try:
            return self._idxToIdCache[indices]
        except TypeError:
            cacheable = False
        except KeyError:
            cacheable = True
        idx = 0
        instId = ()
        parentIndices = []
        for impliedFlag, modName, symName in self._indexNames:
            if idx >= len(indices):
                break
            mibObj, = mibBuilder.importSymbols(modName, symName)
            syntax = mibObj.syntax.clone(indices[idx])
            instId += self.valueToOid(syntax, impliedFlag, parentIndices)
            parentIndices.append(syntax)
            idx += 1
        if cacheable:
            self._idxToIdCache[indices] = instId
        return instId
136540
def all(cls, start_position="", max_results=100, qb=None):
        
        return cls.where("", start_position=start_position, max_results=max_results, qb=qb)