Python string.rfind() Examples

The following are 28 code examples for showing how to use string.rfind(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: ITWSV   Author: penetrate2hack   File: spider.py    License: MIT License 6 votes vote down vote up
def parseJavaScriptCalls():
	global database_js
	"""
		Parse the JavaScript and download the files
	"""
	for j in database_js:
		jsName = j[j.rfind('/')+1:]
		if not os.path.exists('local/js/' + jsName):
			# first download the file
			dl(j,'local/js/' + jsName)
			try:
				jsContent = open('local/js/' + jsName, 'r')
			except IOError:
				continue
			parseJavaScriptContent(jsContent)
			jsContent.close() 
Example 2
Project: code   Author: ActiveState   File: recipe-52278.py    License: MIT License 6 votes vote down vote up
def printexpr(expr_string):
    """ printexpr(expr) - 
        print the value of the expression, along with linenumber and filename.
    """

    stack = extract_stack ( )[-2:][0]
    actualCall = stack[3]
    left = string.find ( actualCall, '(' )
    right = string.rfind ( actualCall, ')' )
    caller_globals,caller_locals = _caller_symbols()
    expr = eval(expr_string,caller_globals,caller_locals)
    varType = type( expr )
    stderr.write("%s:%d>  %s == %s  (%s)\n" % (
        stack[0], stack[1],
        string.strip( actualCall[left+1:right] )[1:-1],
        repr(expr), str(varType)[7:-2])) 
Example 3
Project: python-for-android   Author: kuri65536   File: finger.py    License: Apache License 2.0 6 votes vote down vote up
def lineReceived(self, line):
        parts = string.split(line)
        if not parts:
            parts = ['']
        if len(parts) == 1:
            slash_w = 0
        else:
            slash_w = 1
        user = parts[-1]
        if '@' in user:
            host_place = string.rfind(user, '@')
            user = user[:host_place]
            host = user[host_place+1:]
            return self.forwardQuery(slash_w, user, host)
        if user:
            return self.getUser(slash_w, user)
        else:
            return self.getDomain(slash_w) 
Example 4
Project: medicare-demo   Author: ofermend   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def _fixupParents(self, alogger):
        """
        Ensure that there are either loggers or placeholders all the way
        from the specified logger to the root of the logger hierarchy.
        """
        name = alogger.name
        i = string.rfind(name, ".")
        rv = None
        while (i > 0) and not rv:
            substr = name[:i]
            if not self.loggerDict.has_key(substr):
                self.loggerDict[substr] = PlaceHolder(alogger)
            else:
                obj = self.loggerDict[substr]
                if isinstance(obj, Logger):
                    rv = obj
                else:
                    assert isinstance(obj, PlaceHolder)
                    obj.append(alogger)
            i = string.rfind(name, ".", 0, i - 1)
        if not rv:
            rv = self.root
        alogger.parent = rv 
Example 5
Project: BitTorrent   Author: kenorb-contrib   File: finger.py    License: GNU General Public License v3.0 6 votes vote down vote up
def lineReceived(self, line):
        parts = string.split(line)
        if not parts:
            parts = ['']
        if len(parts) == 1:
            slash_w = 0
        else:
            slash_w = 1
        user = parts[-1]
        if '@' in user:
            host_place = string.rfind(user, '@')
            user = user[:host_place]
            host = user[host_place+1:]
            return self.forwardQuery(slash_w, user, host)
        if user:
            return self.getUser(slash_w, user)
        else:
            return self.getDomain(slash_w) 
Example 6
Project: mirrord   Author: opencas   File: android.py    License: GNU General Public License v3.0 6 votes vote down vote up
def fetch(file):
   if base_url in file:
      dir = file[len(base_url) - 1:rfind(file, '/') + 1]
      file = file[rfind(file, '/') + 1:]
   elif 'http' in file:
      return
   else:
      dir = '/'
   process(dir + file)
   base_dir = path.dirname(dir + file)
   if base_dir != '/':
      base_dir += '/'
   tree = ElementTree.parse(out_dir + dir + file)
   for element in tree.getiterator():
      if element.tag.split('}')[1] == 'url':
         if element.text[-4:] != '.xml':
            if not 'http' in element.text:
               process(base_dir + element.text)
         else:
            fetch(element.text) 
Example 7
Project: ITWSV   Author: penetrate2hack   File: spider.py    License: MIT License 5 votes vote down vote up
def makeRoot(urlLocal):
	if allowedExtensions(urlLocal):
		return urlLocal[0:urlLocal.rfind('/')+1]
	return urlLocal 
Example 8
Project: ITWSV   Author: penetrate2hack   File: spider.py    License: MIT License 5 votes vote down vote up
def giveGoodURL(href, urlLocal):
	"""
		It should return a good url...
		href = argument retrieven from the href...
	"""
	if 'javascript' in href:
		return htmldecode(urlLocal)
	if 'http://' in href or 'https://' in href:
		if urlLocal in href:
			return htmldecode(href)
		else:
			return urlLocal
	if len(href) < 1:
		return htmldecode(urlLocal)
	if href[0] == '?' and '?' not in urlLocal and not allowedExtensions(urlLocal):
		for e in allowed:
			if '.'+e in urlLocal:
				return htmldecode(urlLocal + href)
		return htmldecode(urlLocal + '/' + href)
	else:
		# simple name
		if allowedExtensions(urlLocal) or '?' in urlLocal:
			return htmldecode(urlLocal[0:urlLocal.rfind('/')+1] + href)
		else:
			return htmldecode(urlLocal + '/' + href)
	return htmldecode(href) 
Example 9
Project: ITWSV   Author: penetrate2hack   File: spider.py    License: MIT License 5 votes vote down vote up
def rfindFirstJSChars(string):
	b = [string.rfind(k) for k in jsChars]
	return max(b) 
Example 10
Project: pivy   Author: coin3d   File: rpm.py    License: ISC License 5 votes vote down vote up
def collectintargz(target, source, env):
    """ Puts all source files into a tar.gz file. """
    # the rpm tool depends on a source package, until this is chagned
    # this hack needs to be here that tries to pack all sources in.
    sources = env.FindSourceFiles()

    # filter out the target we are building the source list for.
    #sources = [s for s in sources if not (s in target)]
    sources = filter(lambda s, t=target: not (s in t), sources)

    # find the .spec file for rpm and add it since it is not necessarily found
    # by the FindSourceFiles function.
    #sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
    spec_file = lambda s: string.rfind(str(s), '.spec') != -1
    sources.extend( filter(spec_file, source) )

    # as the source contains the url of the source package this rpm package
    # is built from, we extract the target name
    #tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
    tarball = string.replace(str(target[0])+".tar.gz", '.rpm', '')
    try:
        #tarball = env['SOURCE_URL'].split('/')[-1]
        tarball = string.split(env['SOURCE_URL'], '/')[-1]
    except KeyError as e:
        raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )

    tarball = src_targz.package(env, source=sources, target=tarball,
                                PACKAGEROOT=env['PACKAGEROOT'], )

    return (target, tarball) 
Example 11
Project: pivy   Author: coin3d   File: Util.py    License: ISC License 5 votes vote down vote up
def rightmost_separator(path, sep, _altsep=_altsep):
        rfind = string.rfind
        return max(rfind(path, sep), rfind(path, _altsep)) 
Example 12
Project: pivy   Author: coin3d   File: Util.py    License: ISC License 5 votes vote down vote up
def splitext(path):
    "Same as os.path.splitext() but faster."
    sep = rightmost_separator(path, os.sep)
    dot = string.rfind(path, '.')
    # An ext is only real if it has at least one non-digit char
    if dot > sep and not containsOnly(path[dot:], "0123456789."):
        return path[:dot],path[dot:]
    else:
        return path,"" 
Example 13
Project: pivy   Author: coin3d   File: Util.py    License: ISC License 5 votes vote down vote up
def RegGetValue(root, key):
        """This utility function returns a value in the registry
        without having to open the key first.  Only available on
        Windows platforms with a version of Python that can read the
        registry.  Returns the same thing as
        SCons.Util.RegQueryValueEx, except you just specify the entire
        path to the value, and don't have to bother opening the key
        first.  So:

        Instead of:
          k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\Microsoft\Windows\CurrentVersion')
          out = SCons.Util.RegQueryValueEx(k,
                'ProgramFilesDir')

        You can write:
          out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
        """
        # I would use os.path.split here, but it's not a filesystem
        # path...
        p = key.rfind('\\') + 1
        keyp = key[:p-1]          # -1 to omit trailing slash
        val = key[p:]
        k = RegOpenKeyEx(root, keyp)
        return RegQueryValueEx(k,val) 
Example 14
Project: pivy   Author: coin3d   File: sconsign.py    License: ISC License 5 votes vote down vote up
def my_import(mname):
    if '.' in mname:
        i = string.rfind(mname, '.')
        parent = my_import(mname[:i])
        fp, pathname, description = imp.find_module(mname[i+1:],
                                                    parent.__path__)
    else:
        fp, pathname, description = imp.find_module(mname)
    return imp.load_module(mname, fp, pathname, description) 
Example 15
Project: ibeis   Author: Erotemic   File: controller_inject.py    License: Apache License 2.0 5 votes vote down vote up
def authentication_hash_validate():
    """
    This function is called to check if a username /
    password combination is valid.
    """
    def last_occurence_delete(string, character):
        index = string.rfind(character)
        if index is None or index < 0:
            return string
        return string[:index] + string[index + 1:]

    hash_response = str(flask.request.headers.get('Authorization', ''))
    if len(hash_response) == 0:
        return False
    hash_challenge_list = []
    # Check normal url
    url = str(flask.request.url)
    hash_challenge = get_url_authorization(url)
    hash_challenge_list.append(hash_challenge)
    # If hash at the end of the url, try alternate hash as well
    url = last_occurence_delete(url, '/')
    hash_challenge = get_url_authorization(url)
    hash_challenge_list.append(hash_challenge)
    if '?' in url:
        url.replace('?', '/?')
        hash_challenge = get_url_authorization(url)
        hash_challenge_list.append(hash_challenge)
    return hash_response in hash_challenge_list 
Example 16
Project: script-languages   Author: exasol   File: datagen.py    License: MIT License 5 votes vote down vote up
def parse_primitive_type(col):
    idx = string.find(col, '(')
    ridx = string.rfind(col, ')')
    if idx < 0 and ridx < 0:
        return [col]
    elif idx > 0 and ridx > 0:
        type = col[: idx].strip()
        specs = col[idx + 1 : ridx]
        specs = specs.split(',')
        specs = map(str.strip, specs)
        return [type, specs]
    else:
        raise RuntimeError("Invalid primitive type: " + col) 
Example 17
Project: MARA_Framework   Author: xtiankisutsa   File: binwindow.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _search(self, data, text, start, previous=False):

        self._lastText = text
        if text == '':
            return -1

        if not previous:
            idx1 = string.find(data, text, start)
            text1 = '\0'.join(text)

            idx2 = string.find(data, text1, start)

            idx = idx1
            if idx1 == -1:
                idx = idx2
            else:
                if idx2 < idx1 and idx2 != -1:
                    idx = idx2

        else:
            idx1 = string.rfind(data, text, 0, start)
            text1 = '\0'.join(text)

            idx2 = string.rfind(data, text1, 0, start)

            idx = idx1

            if idx1 == -1:
                idx = idx2
            else:
                if idx2 > idx1 and idx2 != -1:
                    idx = idx2

        if idx > -1:
            self._lastIdx = idx

        if idx > -1:
            self._viewMode.selector.addSelection((idx, idx + len(text), QtGui.QBrush(QtGui.QColor(125, 0, 100)), 0.8) , type=TextSelection.SelectionType.NORMAL)
            self._viewMode.goTo(idx)

        return idx 
Example 18
Project: myelin-acorn-electron-hardware   Author: google   File: UEFtrans.py    License: Apache License 2.0 5 votes vote down vote up
def get_leafname(path):
	"""Get the leafname of the specified file."""

	pos = string.rfind(path, os.sep)
	if pos != -1:
		return path[pos+1:]
	else:
		return path 
Example 19
Project: spitfire   Author: youtube   File: yappsrt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format_error(input, err, scanner):
  """This is a really dumb long function to print error messages nicely."""
  error_message = StringIO.StringIO()
  p = err.pos
  print >> error_message, "error position", p
  # Figure out the line number
  line = count(input[:p], '\n')
  print >> error_message, err.msg, "on line", repr(line+1) + ":"
  # Now try printing part of the line
  text = input[max(p-80, 0):p+80]
  p = p - max(p-80, 0)

  # Strip to the left
  i = rfind(text[:p], '\n')
  j = rfind(text[:p], '\r')
  if i < 0 or (0 <= j < i): i = j
  if 0 <= i < p:
    p = p - i - 1
  text = text[i+1:]

  # Strip to the right
  i = find(text,'\n', p)
  j = find(text,'\r', p)
  if i < 0 or (0 <= j < i):
    i = j
  if i >= 0:
    text = text[:i]

  # Now shorten the text
  while len(text) > 70 and p > 60:
    # Cut off 10 chars
    text = "..." + text[10:]
    p = p - 7

  # Now print the string, along with an indicator
  print >> error_message, '> ', text.replace('\t', ' ').encode(sys.getdefaultencoding())
  print >> error_message, '> ', ' '*p + '^'
  print >> error_message, 'List of nearby tokens:', scanner
  return error_message.getvalue() 
Example 20
Project: BitTorrent   Author: kenorb-contrib   File: gtkcommon.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getCurrentWord(self, entry):
        i = entry.get_point()
        text = entry.get_chars(0,-1)
        word = re.split(r'\s', text)[-1]
        start = string.rfind(text, word)
        end = start+len(word)
        return (word, (start, end)) 
Example 21
Project: BitTorrent   Author: kenorb-contrib   File: pywidgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def isCursorOnLastLine(entry):
    if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'):
        return 1 
Example 22
Project: Dota2Server   Author: uin3566   File: video_spider.py    License: Apache License 2.0 5 votes vote down vote up
def __get_background_url(self, url):
        # background-image: url('http://img.178.com/dota2/201511/241827471049/241827723987.jpg');
        start_index = string.find(url, "'")
        end_index = string.rfind(url, "'")
        return url[start_index + 1:end_index] 
Example 23
Project: BioBlender   Author: MonZop   File: inputgen.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def printInputFiles(self):
        """
            Make the input file(s) associated with this object
        """
        
        # replaced find with rfind to located the rightmost '.'
        # ... in order to fix bug with dealing with.blender directory
        # ... mike pan
        period = string.rfind(self.pqrpath,".")

        if self.asyncflag == 1:
            outname = self.pqrpath[0:period] + "-para.in"

            # Temporarily disable async flag
            for elec in self.elecs:
                elec.asyncflag = 0
            file = open(outname, "w")
            file.write(str(self))
            file.close()

            # Now make the async files
            elec = self.elecs[0]
            
            nproc = elec.pdime[0] * elec.pdime[1] * elec.pdime[2]
            for i in range(int(nproc)):
                outname = self.pqrpath[0:period] + "-PE%i.in" % i
                for elec in self.elecs:
                    elec.asyncflag = 1
                    elec.async = i
                file = open(outname, "w")
                file.write(str(self))
                file.close()
        
        else:
            if period > 0:
                outname = self.pqrpath[0:period] + ".in"
            else:
                outname = self.pqrpath + ".in"
            file = open(outname, "w")
            file.write(str(self))
            file.close() 
Example 24
Project: BioBlender   Author: MonZop   File: inputgen.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dumpPickle(self):
        """
            Make a Python pickle associated with the APBS input parameters
        """
        period = string.rfind(self.pqrpath,".")
        # mike pan

        if period > 0:
            outname = self.pqrpath[0:period] + "-input.p"
        else:
            outname = self.pqrpath + "-input.p"
        pfile = open(outname, "w")
        pickle.dump(self, pfile)
        pfile.close() 
Example 25
Project: mirrord   Author: opencas   File: openwrt.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process(filename, size=-1):
   file = out_dir + filename
   if path.isfile(file) and stat(file).st_size == size:
      print 'Skipping: ' + filename
      return

   print 'Processing: ' + filename
   handle = urlopen(base_url + filename)
   headers = handle.info()
   content_length = int(headers.getheader('Content-Length'))
   last_modified = mktime(strptime(headers.getheader('Last-Modified'), '%a, %d %b %Y %H:%M:%S %Z'))

   if rfind(filename, '/') > 0:
      dir = out_dir + filename[:rfind(filename, '/')]
   else:
      dir = out_dir

   if not path.isdir(dir):
      print 'Creating ' + dir
      makedirs(dir)

   if not path.isfile(file):
      download(filename, last_modified)
   else:
      file_stat = stat(file)
      if file_stat.st_mtime != last_modified or file_stat.st_size != content_length:
         download(filename, last_modified)
      else:
         print 'Skipping: ' + filename 
Example 26
Project: mirrord   Author: opencas   File: android.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process(filename, size=-1):
   file = out_dir + filename
   if path.isfile(file) and stat(file).st_size == size:
      print 'Skipping: ' + filename
      return

   print 'Processing: ' + filename
   handle = urlopen(base_url + filename)
   headers = handle.info()
   content_length = int(headers.getheader('Content-Length'))
   last_modified = mktime(strptime(headers.getheader('Last-Modified'), '%a, %d %b %Y %H:%M:%S %Z'))

   if rfind(filename, '/') > 0:
      dir = out_dir + filename[:rfind(filename, '/')]
   else:
      dir = out_dir

   if not path.isdir(dir):
      print 'Creating ' + dir
      makedirs(dir)

   if not path.isfile(file):
      download(filename, last_modified)
   else:
      file_stat = stat(file)
      if file_stat.st_mtime != last_modified or file_stat.st_size != content_length:
         download(filename, last_modified)
      else:
         print 'Skipping: ' + filename 
Example 27
Project: pilot   Author: PanDAWMS   File: irods_replica.py    License: Apache License 2.0 4 votes vote down vote up
def upload (self, source, target, flags) :
        '''Uploads a file from the LOCAL, PHYSICAL filesystem to
           the replica management system.
           @param source: URL (should be file:// or local path) of local file
           @param target: Optional param containing ?resource=myresource query
                          This will upload the file to a specified iRODS
                          resource or group.
        '''

        #TODO: Make sure that the source URL is a local/file:// URL
        complete_path = saga.Url(source).get_path()

        # extract the path from the LogicalFile object, excluding
        # the filename
        destination_path=self._url.get_path()[0:string.rfind(
                         self._url.get_path(), "/")+1]

        try:
            #var to hold our command result, placed here to keep in scope
            returncode = out = 0
            
            # note we're uploading
            self._logger.debug("Beginning upload operation " +\
                           "will register file in logical dir: %s" %
                           destination_path)

            # the query holds our target resource
            query = saga.Url(target).get_query()

            # list of args we will generate
            arg_list = ""

            # parse flags + generate args
            if flags:
                if flags & saga.namespace.OVERWRITE:
                    arg_list += "-f "

            # was no resource selected?
            if query==None:
                self._logger.debug("Attempting to upload to default resource")
                returncode, out, _ = self.shell.run_sync("iput %s %s %s" %
                                         (arg_list, complete_path, destination_path))

            # resource was selected, have to parse it and supply to iput -R
            else:
                #TODO: Verify correctness
                resource = query.split("=")[1]
                self._logger.debug("Attempting to upload to query-specified resource %s" % resource)
                returncode, out, _ = self.shell.run_sync("iput -R %s %s %s %s" %
                                         (resource, arg_list, complete_path, destination_path))

            # check our result
            if returncode != 0:
                raise saga.NoSuccess ("Could not upload file %s, errorcode %s: %s"\
                                    % (complete_path, str(returncode),
                                       out))

        except Exception, ex:
            # couldn't upload for unspecificed reason
            raise saga.NoSuccess._log (self._logger, "Couldn't upload file: %s" % ex) 
Example 28
Project: BioBlender   Author: MonZop   File: inputgen.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def __init__(self, pqrpath, size, method, asyncflag, istrng=0, potdx=0):
        """
            Initialize the input file class.  Each input file contains
            a PQR name, a list of elec objects, and a list of strings
            containing print statements.  For starters assume two
            ELEC statements are needed, one for the inhomgenous and
            the other for the homogenous dielectric calculations.

            Users can edit the elec statements and the print statements.

            This assumes you have already run psize, either by
                 size.runPsize(/path/to/pqr) or

                 size.parseString(string)
                 size.setAll()

            Parameters
                pqrpath:   The path to the PQR file (string)
                size:      The Psize object (psize)
                method:    The method (para, auto, manual, async) to use
                asyncflag: 1 if async is desired, 0 otherwise
        """ 

        self.pqrpath = pqrpath
        self.asyncflag = asyncflag

        # Initialize variables to default elec values

        elec1 = Elec(pqrpath, size, method, asyncflag, istrng, potdx)
        if potdx == 0:
            elec2 = Elec(pqrpath, size, method, asyncflag, istrng, potdx)
            setattr(elec2, "sdie", 2.0)
            setattr(elec2, "write", [])
        else:
            elec2 = ""
        self.elecs = [elec1, elec2]
     
        i = string.rfind(pqrpath, "/") + 1
        self.pqrname = pqrpath[i:]

        if potdx == 0:
            self.prints = ["print elecEnergy 2 - 1 end"]     
        else:
            self.prints = []