Example #1
0
 def _fetchNewMarketData(self):
   C = {}
   A = self._getConsolData()
   for x in A['return']:
     startname = string.lower(A['return'][x]["primaryname"])
     endname = string.lower(A['return'][x]["secondaryname"])
     combname = startname + "-" + endname
     C[combname]={
       "name": A['return'][x]["label"],
       "start": startname,
       "end": endname,
       "marketid": A['return'][x]["marketid"],
       "useable": True
     }
     try:
       C[combname]["bestsell"] = {
           "price": A['return'][x]["sellorders"][0]["price"],
           "quantity": A['return'][x]["sellorders"][0]["quantity"]
         }
     except TypeError:
       C[combname]["bestsell"] = {
           "price": None,
           "quantity": None
         }
     try:
       C[combname]["bestbuy"] = {
           "price": A['return'][x]["buyorders"][0]["price"],
           "quantity": A['return'][x]["buyorders"][0]["quantity"]
         }
     except TypeError:
       C[combname]["bestbuy"] = {
           "price": None,
           "quantity": None
         }
   return C
Example #2
0
def findparam(name, plist):
    name = string.lower(name) + '='
    n = len(name)
    for p in plist:
        if string.lower(p[:n]) == name:
            return p[n:]
    return ''
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
	subtitles_list = []
	msg = ""
	searchstring_notclean = ""
	searchstring = ""
	global israr
	israr = os.path.abspath(file_original_path)
	israr = os.path.split(israr)
	israr = israr[0].split(os.sep)
	israr = string.split(israr[-1], '.')
	israr = string.lower(israr[-1])
	
	if len(tvshow) == 0:
		if 'rar' in israr and searchstring is not None:
			if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
				dirsearch = os.path.abspath(file_original_path)
				dirsearch = os.path.split(dirsearch)
				dirsearch = dirsearch[0].split(os.sep)
				if len(dirsearch) > 1:
					searchstring_notclean = dirsearch[-3]
					searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
					searchstring = searchstring[0]
				else:
					searchstring = title
			else:
				searchstring = title
		elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
			dirsearch = os.path.abspath(file_original_path)
			dirsearch = os.path.split(dirsearch)
			dirsearch = dirsearch[0].split(os.sep)
			if len(dirsearch) > 1:
				searchstring_notclean = dirsearch[-2]
				searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
				searchstring = searchstring[0]
			else:
				#We are at the root of the drive!!! so there's no dir to lookup only file#
				title = os.path.split(file_original_path)
				searchstring = title[-1]
		else:
			if title == "":
				title = os.path.split(file_original_path)
				searchstring = title[-1]
			else:
				searchstring = title
			
	if len(tvshow) > 0:
		searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
	log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))

	portuguese = 0
	if string.lower(lang1) == "portuguese": portuguese = 1
	elif string.lower(lang2) == "portuguese": portuguese = 2
	elif string.lower(lang3) == "portuguese": portuguese = 3

	getallsubs(searchstring, "pt", "Portuguese", file_original_path, subtitles_list, searchstring_notclean)

	if portuguese == 0:
		msg = "Won't work, LegendasDivx is only for Portuguese subtitles!"
	
	return subtitles_list, "", msg #standard output
Example #4
0
def coards2year(time_in, timestringIn):
    """ coards2year(time_in, timestringIn)  assume a numpy array for time_in,
    and a string of the sort 'hours since 1950-01-01 00:00:00.0' or the like for timestringIn"""
    import string
    import re
    ntim = time_in.shape[0]
    time_out = np.zeros([ntim])
    stringwords = string.split(timestringIn)
    units = stringwords[0]
    datestartstring = stringwords[2]
    timestartstring = stringwords[3]
    ### strip off any fractions of a second
    timestartstring_split = re.split('\.', timestartstring)
    datetimestartstring = datestartstring + ' ' + timestartstring_split[0]
    datetimestart = string2datetime(datetimestartstring)
    if string.lower(units) == 'hours':
        for i in range(0,ntim):
            thedays = int(time_in[i])/24
            thehours = int(time_in[i])%24
            offsettime = datetime.timedelta(hours=thehours, days=thedays)
            newtime = datetimestart + offsettime
            time_out[i] = date2decimalyear(newtime)
    elif string.lower(units) == 'days':
        for i in range(0,ntim):
            offsettime = datetime.timedelta(days=time_in[i])
            newtime = datetimestart + offsettime
            time_out[i] = date2decimalyear(newtime)
        
    return time_out
 def handle_starttag(self, tag, attrs):
     if tag == "meta":
         # look for encoding directives
         http_equiv = content = None
         for k, v in attrs:
             if k == "http-equiv":
                 http_equiv = string.lower(v)
             elif k == "content":
                 content = v
         if http_equiv == "content-type" and content:
             # use mimetools to parse the http header
             header = mimetools.Message(
                 io.StringIO("%s: %s\n\n" % (http_equiv, content))
             )
             encoding = header.getparam("charset")
             if encoding:
                 self.encoding = encoding
     if tag in AUTOCLOSE:
         if self.__stack and self.__stack[-1] == tag:
             self.handle_endtag(tag)
     self.__stack.append(tag)
     attrib = {}
     if attrs:
         for k, v in attrs:
             attrib[string.lower(k)] = v
     self.__builder.start(tag, attrib)
     if tag in IGNOREEND:
         self.__stack.pop()
         self.__builder.end(tag)
Example #6
0
 def WhereIs(file, path=None, pathext=None, reject=[]):
     if path is None:
         try:
             path = os.environ['PATH']
         except KeyError:
             return None
     if is_String(path):
         path = string.split(path, os.pathsep)
     if pathext is None:
         pathext = ['.exe', '.cmd']
     for ext in pathext:
         if string.lower(ext) == string.lower(file[-len(ext):]):
             pathext = ['']
             break
     if not is_List(reject) and not is_Tuple(reject):
         reject = [reject]
     for dir in path:
         f = os.path.join(dir, file)
         for ext in pathext:
             fext = f + ext
             if os.path.isfile(fext):
                 try:
                     reject.index(fext)
                 except ValueError:
                     return os.path.normpath(fext)
                 continue
     return None
Example #7
0
 def findT1File(self, ext='.pfb'):
     possible_exts = (string.lower(ext), string.upper(ext))
     if hasattr(self,'pfbFileName'):
         r_basename = os.path.splitext(self.pfbFileName)[0]
         for e in possible_exts:
             if os.path.isfile(r_basename + e):
                 return r_basename + e
     try:
         r = _fontdata.findT1File(self.name)
     except:
         afm = bruteForceSearchForAFM(self.name)
         if afm:
             if string.lower(ext) == '.pfb':
                 for e in possible_exts:
                     pfb = os.path.splitext(afm)[0] + e
                     if os.path.isfile(pfb):
                         r = pfb
                     else:
                         r = None
             elif string.lower(ext) == '.afm':
                 r = afm
         else:
             r = None
     if r is None:
         warnOnce("Can't find %s for face '%s'" % (ext, self.name))
     return r
Example #8
0
    def search(self, event):
        self.apps = codecs.open(Variables.playonlinux_rep+"/configurations/listes/search",'r',"utf-8")
        self.apps = self.apps.readlines()
        self.j = 0;
        while(self.j < len(self.apps)):
            self.apps[self.j] = self.apps[self.j].replace("\n","")
            self.j += 1

        self.j = 0;
        self.k = 0;
        self.user_search =self.searchbox.GetValue()
        self.search_result = []

        while(self.j < len(self.apps)):
            if(string.lower(self.user_search) in string.lower(self.apps[self.j])):
                self.search_result.append(self.apps[self.j])
                self.k = self.k + 1;
            self.j = self.j + 1;

        if(self.user_search == "about:creator"):
            self.search_result.append("about:creator")

        if(len(self.user_search) < 2 or "~" in self.user_search):
            self.search_result = []
        self.user_search_cut = string.split(self.user_search,":")
        if(len(self.user_search_cut) > 1):
            if(self.user_search_cut[0] == "get" and self.user_search_cut[1].isdigit()):
                self.search_result.append(self.user_search)

        if(self.user_search != ""):
            self.WriteApps(self.search_result)
        else:
            self.DelApps()
Example #9
0
 def Read(self,filename):
     """Read units from file with specified name.
     
     The units file is an ascii file where each line contains a couple of
     words separated by a colon and a blank. The first word is the type of
     quantity, the second is the unit to be used for this quantity.
     Lines starting with '#' are ignored.
     A 'problem: system' line sets all units to the corresponding value of
     the specified units system.
     """
     fil = file(filename,'r')
     self.units = {}
     for line in fil:
         if line[0] == '#':
             continue
         s = string.split(line)
         if len(s) == 2:
             key,val = s
             key = string.lower(string.rstrip(key,':'))
             self.units[key] = val
             if key == 'problem':
                 self.Add(self.Predefined(string.lower(val)))
         else:
             print "Ignoring line : %s\n",line     
     fil.close()
Example #10
0
 def search(self, pattern='', context=''):
     pattern = string.replace(string.lower(pattern),'*','%')
     pattern = string.replace(string.lower(pattern),'?','_')
     if pattern:
         return self.select("context LIKE '%s'" % pattern, orderBy="context")
     else:
         return self.select(orderBy="context")
def search_subtitles(file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack): #standard input
    subtitles_list = []
    msg = ""

    if not (string.lower(lang1) or string.lower(lang2) or string.lower(lang3)) == "greek":
        msg = "Won't work, subtitles.gr is only for Greek subtitles."
        return subtitles_list, "", msg #standard output

    try:
        log( __name__ ,"%s Clean title = %s" % (debug_pretext, title))
        premiered = year
        title, year = xbmc.getCleanMovieTitle( title )
    except:
        pass

    if len(tvshow) == 0: # Movie
        searchstring = "%s (%s)" % (title, premiered)
    elif len(tvshow) > 0 and title == tvshow: # Movie not in Library
        searchstring = "%s (%#02d%#02d)" % (tvshow, int(season), int(episode))
    elif len(tvshow) > 0: # TVShow
        searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
    else:
        searchstring = title

    log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))
    get_subtitles_list(searchstring, "el", "Greek", subtitles_list)
    return subtitles_list, "", msg #standard output
Example #12
0
def SuspiciousChk2(list_str):
     pattern = "C:\\Windows\\System32\\"
     pattern = string.lower(pattern)
     list_str = string.lower(list_str)
     if list_str.find(pattern) >= 0:
       return True
     return False           
Example #13
0
def SvchostChk(list_str):
     pattern = "C:\\WINDOWS\\system32\\svchost.exe"
     pattern = string.lower(pattern)
     list_str = string.lower(list_str)
     if list_str.find(pattern) >= 0:
       return True
     return False        
Example #14
0
def SuspiciousChk(list_str):
     pattern = "C:\\Documents and Settings\\"
     pattern = string.lower(pattern)
     list_str = string.lower(list_str)
     if list_str.find(pattern) >= 0:
       return True
     return False
Example #15
0
def SuspiciousChk1(list_str):
     pattern = "C:\\DOCUME~1\\"
     pattern = string.lower(pattern)
     list_str = string.lower(list_str)
     if list_str.find(pattern) >= 0:
       return True
     return False                
def find_tv_show_season(content, tvshow, season):
    url_found = None
    possible_matches = []
    all_tvshows = []

    h = HTMLParser.HTMLParser()
    for matches in re.finditer(movie_season_pattern, content, re.IGNORECASE | re.DOTALL):
        found_title = matches.group('title')
        found_title = h.unescape(found_title)

        log(__name__, "Found tv show season on search page: %s" % found_title)
        s = difflib.SequenceMatcher(None, string.lower(found_title + ' ' + matches.group('year')), string.lower(tvshow))
        all_tvshows.append(matches.groups() + (s.ratio() * int(matches.group('numsubtitles')),))
        if string.find(string.lower(found_title), string.lower(tvshow) + " ") > -1:
            if string.find(string.lower(found_title), string.lower(season)) > -1:
                log(__name__, "Matching tv show season found on search page: %s" % found_title)
                possible_matches.append(matches.groups())

    if len(possible_matches) > 0:
        possible_matches = sorted(possible_matches, key=lambda x: -int(x[3]))
        url_found = possible_matches[0][0]
        log(__name__, "Selecting matching tv show with most subtitles: %s (%s)" % (
            possible_matches[0][1], possible_matches[0][3]))
    else:
        if len(all_tvshows) > 0:
            all_tvshows = sorted(all_tvshows, key=lambda x: -int(x[4]))
            url_found = all_tvshows[0][0]
            log(__name__, "Selecting tv show with highest fuzzy string score: %s (score: %s subtitles: %s)" % (
                all_tvshows[0][1], all_tvshows[0][4], all_tvshows[0][3]))

    return url_found
Example #17
0
def get_encodings(headers):
    content_encoding = transfer_encoding = None
    if headers.has_key("content-encoding"):
        content_encoding = string.lower(headers["content-encoding"])
    if headers.has_key("content-transfer-encoding"):
        transfer_encoding = string.lower(headers["content-transfer-encoding"])
    return content_encoding, transfer_encoding
Example #18
0
	def search(self, prog):
		import regex, string
		if type(prog) == type(''):
			prog = regex.compile(string.lower(prog))
		if self.selection:
			iold = self.selection[0][0]
		else:
			iold = -1
		hit = None
		for i in range(len(self.paralist)):
			if i == iold or i < iold and hit:
				continue
			p = self.paralist[i]
			text = string.lower(p.extract())
			if prog.search(text) >= 0:
				a, b = prog.regs[0]
				long1 = i, a
				long2 = i, b
				hit = long1, long2
				if i > iold:
					break
		if hit:
			self.setselection(hit)
			i = hit[0][0]
			p = self.paralist[i]
			self.window.show((p.left, p.top), (p.right, p.bottom))
			return 1
		else:
			return 0
Example #19
0
def getsourcefile(object):
    """Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    """
    filename = getfile(object)
    
    if filename == "<stdin>":
        return filename
    
    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None

    if filename not in pathExistsOnDiskCache_:
        pathExistsOnDiskCache_[filename] = os.path.exists(filename)

    if pathExistsOnDiskCache_[filename]:
        return filename

    # only return a non-existent filename if the module has a PEP 302 loader
    if hasattr(getmodule(object, filename), '__loader__'):
        return filename
    # or it is in the linecache
    if filename in linecache.cache:
        return filename
Example #20
0
def splitArgs(s, casetype=LOWER_ALL):
    res = []
    i = 0
    n = len(s)
    if casetype==LOWER_ALL:
	s = string.lower(s)

    while i < n:
	while i < n and s[i] in string.whitespace: i = i+1
	if i == n: break
	if s[i] == '"' or s[i] == "'":
	    quote = s[i]
	    i = i+1
	    j = i
	    while j < n and s[j] != quote: j = j+1
	    res.append(s[i:j])
	    i = j+1
	else:
	    j = i
	    while j < n and s[j] not in string.whitespace: j = j+1
	    if casetype == LOWER_NON_QUOTED:
		res.append(string.lower(s[i:j]))
	    else:
		res.append(s[i:j])
	    i = j
    return res
Example #21
0
 def authorize (self, channel, username, password):
     if string.lower(username) in ['anonymous', 'ftp']:
         import pwd
         try:
             # ok, here we run into lots of confusion.
             # on some os', anon runs under user 'nobody',
             # on others as 'ftp'.  ownership is also critical.
             # need to investigate.
             # linux: new linuxen seem to have nobody's UID=-1,
             #    which is an illegal value.  Use ftp.
             ftp_user_info = pwd.getpwnam ('ftp')
             if string.lower(os.uname()[0]) == 'linux':
                 nobody_user_info = pwd.getpwnam ('ftp')
             else:
                 nobody_user_info = pwd.getpwnam ('nobody')
             channel.read_only = 1
             if self.root is None:
                 self.root = ftp_user_info[5]
             fs = filesys.unix_filesystem (self.root, '/')
             return 1, 'Anonymous Login Successful', fs
         except KeyError:
             return 0, 'Anonymous account not set up', None
     elif self.real_users:
         return unix_authorizer.authorize (
                 self,
                 channel,
                 username,
                 password
                 )
     else:
         return 0, 'User logins not allowed', None
Example #22
0
	def do_examine( self, s ):
		cur_room = self.map.getRooms()[self.player.getPos()]
		for item in cur_room.getItems() + cur_room.getDroppedItems():
			if string.lower(item.getName()) == string.lower(s):
				print self.parser.parseDescription(item.getExamineText())
				return
		print "You don't see anything that looks like a " + yellow(s) + '.'
Example #23
0
def vertDimParse(entry):
    description = 'None'
    units = 'None'
    verticality = slats.SingleLevel
    positive = slats.UpDirection
    grib_id = 0
    grib_p1 = 0
    grib_p2 = 0
    grib_p3 = 0
    nentry = len(entry)
    if nentry>1: description = string.strip(entry[1])
    if nentry>2: units = string.strip(entry[2])
    if nentry>3:
	if string.lower(string.strip(entry[3]))=='single':
	    verticality = slats.SingleLevel
	else:
	    verticality = slats.MultiLevel
    if nentry>4:
	if string.lower(string.strip(entry[4]))=='up':
	    positive = slats.UpDirection
	else:
	    positive = slats.DownDirection
    if nentry>5: grib_id = string.atoi(entry[5])
    if nentry>6: grib_p1 = string.atoi(entry[6])
    if nentry>7: grib_p2 = string.atoi(entry[7])
    if nentry>8: grib_p3 = string.atoi(entry[8])
    return [description, units, verticality, positive, grib_id, grib_p1, grib_p2, grib_p3]
Example #24
0
def ExtractSource( file ):
	from xml.dom.minidom import parse
	dom = parse( file )
	files = dom.getElementsByTagName( 'File' )
	l = []
	for i in files:
		s = i.getAttribute( 'RelativePath' )
		s = s.encode('ascii', 'ignore')
		s = re.sub( '\\\\', '/', s )
		s = re.sub( '^\./', '', s )

		# this is a bit of a hack, and should probably be thought about more.
		# if the file is excluded from the Release|win32 config it will be excluded in linux.
		# Not necessarily correct, but thats how it will be for now. Could add a linux config
		# if we get files that only want to exclude in one and not the other.
		exclude = 0
		configs = i.getElementsByTagName( 'FileConfiguration')
		for thisConfig in configs:
			if (string.lower(thisConfig.getAttribute('ExcludedFromBuild')) == 'true' and 
				string.lower(thisConfig.getAttribute('Name')) == 'release|win32'):
				exclude = 1

		if (exclude == 0) and (( string.lower( s[-4:] ) == '.cpp' or string.lower( s[-2:] ) == '.c' )):
			l.append( s )

	return l
Example #25
0
def makeChoice(choice, pad, alpha):
    if choice == "1":
        message = lower(raw_input("Enter a message you wish to encrypt, with no spaces\n"))
        try:
            encryptedMessage = convertMessage(message, pad, alpha)
            print "Encrypted message is as follows\n", encryptedMessage
        except IndexError:
            print "Error: Pad is smaller than message"

    elif choice == "2":
        message = lower(raw_input("Enter a message you wish to decrypt, with no spaces\n"))
        try:
            decryptedMessage = deconvertMessage(message, pad, alpha)
            print "Decrypted message is as follows\n", decryptedMessage
        except IndexError:
            print "Error: Pad is smaller than message"

    elif choice == "3":
    	padFile = raw_input("Enter a filename to write to\nWARNING, DO NOT ENTER AN EXISTING TXT FILE: ")
    	writeOutPad(padFile, pad)

    else:
        print "Error: selection was not 1, 2 or 3\n\n"

    return choice
Example #26
0
def query(prompt):
	answer = raw_input(prompt + "[Y or N]: ")	
	answer = string.lower(answer)
	while answer[0] != 'y' and answer[0]!= 'n':
		answer = raw_input("Invalid response. Please type Y or N: ")
		answer = string.lower(answer)
	return answer[0] == 'y'
Example #27
0
def index_sort(s1, s2):
    if not s1:
        return -1

    if not s2:
        return 1

    l1 = len(s1)
    l2 = len(s2)
    m1 = string.lower(s1)
    m2 = string.lower(s2)

    for i in range(l1):
        if i >= l2 or m1[i] > m2[i]:
            return 1

        if m1[i] < m2[i]:
            return -1

        if s1[i] < s2[i]:
            return -1

        if s1[i] > s2[i]:
            return 1

    if l2 > l1:
        return -1

    return 0
def download(id, url, filename, search_string=""):
    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]

    ## Cleanup temp dir, we recomend you download/unzip your subs
    ## in temp folder and pass that to XBMC to copy and activate
    if xbmcvfs.exists(__temp__):
        shutil.rmtree(__temp__)
    xbmcvfs.mkdirs(__temp__)

    filename = os.path.join(__temp__, filename + ".zip")
    req = urllib2.Request(url, headers={"User-Agent": "Kodi-Addon"})
    sub = urllib2.urlopen(req).read()
    with open(filename, "wb") as subFile:
        subFile.write(sub)
    subFile.close()

    xbmc.sleep(500)
    xbmc.executebuiltin(
        (
            'XBMC.Extract("%s","%s")' % (filename, __temp__,)
        ).encode('utf-8'), True)

    for file in xbmcvfs.listdir(__temp__)[1]:
        file = os.path.join(__temp__, file)
        if os.path.splitext(file)[1] in exts:
            if search_string and string.find(
                string.lower(file),
                string.lower(search_string)
            ) == -1:
                continue
            log(__name__, "=== returning subtitle file %s" % file)
            subtitle_list.append(file)

    return subtitle_list
Example #29
0
   def remove_alias( self, dim_name ):
      try:
         selected_alias = self.alias_list.getcurselection()[0]
         d_name = string.lower( dim_name )
      except:
         return
      d_name = string.lower( dim_name )

      if d_name == 'longitude':
         cdms.axis.longitude_aliases.remove( selected_alias )
      elif d_name == 'latitude':
         cdms.axis.latitude_aliases.remove( selected_alias )
      elif d_name == 'time':
         cdms.axis.time_aliases.remove( selected_alias )
      elif d_name == 'level':
         cdms.axis.level_aliases.remove( selected_alias )
      elif d_name == 'directory':
         gui_control.favorite_directories.remove( selected_alias )
      elif d_name == 'mybinfiles':
         gui_control.favorite_files.remove( selected_alias )

      # Update the alias list widget
      ret_alias_list = return_alias_list( dim_name )
      self.alias_list.setlist( ret_alias_list )

      # Update VCDAT's alias list
      if d_name not in [ 'directory','mybinfiles']:
         update_vcdat_alias_list()
      else:
         record_bookmarks( d_name )
 def OnLOSNotify(self,ID,noHitFlag,sceneobject,hitPoint,distance):
     PtDebugPrint("tldnVaporScope:LOSNotify:  ID=%d  noHitFlag=%d at a distance of %g" % (ID,noHitFlag,distance),level=kDebugDumpLevel)
     PtShootBulletFromScreen(self.key,0.5,0.5,1.0,10000)
     if sceneobject:
         PtDebugPrint("tldnVaporScope:LOSNotify: ===>hit object %s at point(%g,%g,%g)" % (sceneobject.getName(),hitPoint.getX(),hitPoint.getY(),hitPoint.getZ()),level=kDebugDumpLevel)
         # first look for a python file guy (before responders)
         pmlist = sceneobject.getPythonMods()
         if len(pmlist) > 0:
             PtDebugPrint("tldnVaporScope:LOSNotify:  ...python mod list:",level=kDebugDumpLevel)
             for pm in pmlist:
                 PtDebugPrint("       %s" % (pm.getName()),level=kDebugDumpLevel)
                 if string.lower(pm.getName()).startswith("vaporminerhitme"):
                     PtDebugPrint("tldnVaporScope:LOS: VaporMiner HIT!",level=kDebugDumpLevel)
                     notify = ptNotify(self.key)
                     notify.clearReceivers()
                     notify.addReceiver(pm)
                     notify.setActivate(1.0)
                     notify.send()
         else:
             PtDebugPrint("tldnVaporScope:LOSNotify: ...no python mods found",level=kDebugDumpLevel)
         # next look for responders attached
         resplist = sceneobject.getResponders()
         if len(resplist) > 0:
             PtDebugPrint("tldnVaporScope:LOSNotify:  ...responder list:",level=kDebugDumpLevel)
             for resp in resplist:
                 PtDebugPrint("       %s" % (resp.getName()),level=kDebugDumpLevel)
                 if string.lower(resp.getName()).startswith("vaporminerhitme"):
                     PtDebugPrint("tldnVaporScope:LOS: VaporMiner HIT!",level=kDebugDumpLevel)
                     atResp = ptAttribResponder(42)
                     atResp.__setvalue__(resp)
                     atResp.run(self.key)
         else:
             PtDebugPrint("tldnVaporScope:LOSNotify: ...no responders found",level=kDebugDumpLevel)
     else:
         PtDebugPrint("tldnVaporScope:LOSNotify: No sceneobject found...",level=kDebugDumpLevel)
Example #31
0
    def rdfParse(self, files):

        #make sure a list was passed
        if type(files) != list:
            files = [files]

        #Loop over all RDF files

        for file in files:

            #open the file
            try:
                fin = open(file, "r")
            except:
                raise Exception("Cannot open file: %s" % file)

            #get a line and parse it
            while 1:

                #read the line
                line = fin.readline()
                if not line: break

                # strip comments

                line = self.stripComments(line)

                #while continuation line, read next line and append
                m = re.match("(.*)" + self.rdfCont, line)  #regexp match
                if m: line = m.group(1)
                while (m != None):
                    nextLine = self.stripComments(fin.readline())
                    m = re.match("(.*)" + self.rdfCont, nextLine)
                    if m: line = line + m.group(1)
                    else: line = line + nextLine

                #extract keyword and value
                m = re.match("([^=]+)" + self.rdfSep + "(.*)", line)
                if m:  #an RDF line

                    k = m.group(1)
                    v = m.group(2)
                    v = string.strip(v)

                    #units key separation
                    m = re.match("(.*)\((.*)\).*", k)
                    if m:
                        u = string.strip(m.group(2))
                        if u == "": u = "-"

                        k = string.lower(string.strip(m.group(1)))
                        self.units[k].append(u)
                    else:
                        k = string.lower(string.strip(k))
                        self.units[k].append("-")

                    self.value[k].append(v)
                    if k not in self.key_list: self.key_list.append(k)

                    # if the keyword eof is set, the end of the header of
                    #  an RDF/binary file has been reached. Exit parsing loop

                    if re.match(self.eof, k): break

            #close RDF file
            fin.close()
        return self
Example #32
0
def _normalize(codeset):
    codeset = string.lower(codeset)
    codeset = string.translate(codeset, _trans)
    return codeset
Example #33
0
def xmlToDict(fPath, stopPath=None, splitTxt=False, get_pubmed=False):
    '''
    Converts study data from (ref man generated) XML to a dictionary matching study IDs (keys) to 
    title/abstract tuples (values). For example: dict[n] might map to a tuple [t_n, a_n] where t_n is the
    title of the nth paper and a_n is the abstract
    '''

    refIDToAbs = {}
    numNoPubmeds = 0
    numNoAbs = 0  # Keep track of how many studies have no abstracts.
    tree = ElementTree(file=fPath)

    for record in tree.findall('.//record'):
        pubmed_id = None
        refmanid = eval(record.findall('.//rec-number')[0].text)

        try:
            pubmed = record.findall('.//notes/style')[0].text
            pubmed = pubmed.split("-")
            for i in range(len(pubmed)):
                if "UI" in pubmed[i]:
                    pubmed_str = pubmed[i + 1].strip()
                    pubmed_id = eval("".join(
                        [x for x in pubmed_str if x in string.digits]))
                    #pubmed_id = eval(pubmed[i+1].replace("PT", "").replace("IN", ""))
                    #print pubmed
                    break
        except Exception, ex:
            print ex

        if pubmed_id is None:
            #if not "Cochrane" in pubmed[2]:
            #	pdb.set_trace()
            numNoPubmeds += 1
            print "%s has no pubmed id" % refmanid

        abstract = record.findall('.//abstract/style')
        abText = ""
        try:
            if abstract and splitTxt:
                abText = (abstract[0].text).split(" ")
                abText = [string.lower(s) for s in abText]
                abText = cleanUpTxt(abText, stopListPath=stopPath)
            elif abstract:
                abText = abstract[0].text
            else:
                numNoAbs += 1
        except:
            pdb.set_trace()

        title = ""
        if splitTxt:
            title = cleanUpTxt(string.lower(
                record.findall('.//titles/title/style')[0].text).split(" "),
                               stopListPath=stopPath)
        else:
            try:
                title = record.findall('.//titles/title/style')[0].text
            except:
                pdb.set_trace()

# Also grab keywords
        keywords = [
            string.lower(keyword.text.strip())
            for keyword in record.findall(".//keywords/keyword/style")
        ]
        if pubmed_id is not None or True:
            refIDToAbs[refmanid] = [title, abText, keywords, pubmed_id]
Example #34
0
            canv.setFont('Times-BoldItalic', 12)
            canv.drawRightString(515, 744, 'Labels in ' + caption)

            #for dingbats, we need to use another font for the numbers.
            #do two parallel text objects.
            for byt in range(32, 256):
                col, row = divmod(byt - 32, 32)
                x = 72 + (66 * col)
                y = 720 - (18 * row)
                canv.setFont('Helvetica', 14)
                canv.drawString(x, y, label_formatter % byt)
                canv.setFont(fontName, 14)
                canv.drawString(
                    x + 44, y,
                    chr(byt).decode(encLabel, 'ignore').encode('utf8'))
            canv.showPage()
        canv.save()


if __name__ == '__main__':
    if len(sys.argv) == 2:
        mode = string.lower(sys.argv[1])
        if mode not in ['dec', 'oct', 'hex']:
            print __doc__

    elif len(sys.argv) == 1:
        mode = 'dec'
        run(mode)
    else:
        print __doc__
Example #35
0
    def set_top_params(self):
        """
        Set topology optimisation problem parameters (you must already have
        instantiated a Topology object).

        EXAMPLES:
            >>> import topy
            >>> t = topy.Topology()
            >>> # load a ToPy problem definition file:
            >>> t.load_tpd_file('filename.tpd')
            >>> # now set the problem parameters:
            >>> t.set_top_params()

        You can now access all the class methods or instance variables. To see
        the dictionary of parameters, just type

            >>> t.topydict

        You can also reset some parameters without reloading the file, but use
        with caution. For example, you can change the filer radius (FILT_RAD)
        as follows:

            >>> t.topydict['FILT_RAD'] = 1.5

        Remember to reset the problem parameters again, whereafter you can
        solve the problem.

            >>> t.set_top_params()

        See also: load_tpd_file

        """
        print '-' * 79
        # Set all the mandatory minimum amount of parameters that constitutes
        # a completely defined topology optimisation problem:
        if not self.topydict:
            raise ToPyError('You must first load a TPD file!')
        self.probtype = self.topydict['PROB_TYPE'] #  Problem type
        self.probname = self.topydict['PROB_NAME'] #  Problem name
        self.volfrac = self.topydict['VOL_FRAC'] #  Volume fraction
        self.filtrad = self.topydict['FILT_RAD'] #  Filter radius
        self.p = self.topydict['P_FAC'] #  'Standard' penalisation factor
        self.dofpn = self.topydict['DOF_PN'] #  DOF per node
        self.e2sdofmapi = self.topydict['E2SDOFMAPI'] #  Elem to structdof map
        self.nelx = self.topydict['NUM_ELEM_X'] #  Number of elements in X
        self.nely = self.topydict['NUM_ELEM_Y'] #  Number of elements in Y
        self.nelz = self.topydict['NUM_ELEM_Z'] #  Number of elements in Z
        self.fixdof = self.topydict['FIX_DOF'] #  Fixed dof vector
        self.loaddof = self.topydict['LOAD_DOF'] #  Loaded dof vector
        self.loadval = self.topydict['LOAD_VAL'] #  Loaded dof values
        self.Ke = self.topydict['ELEM_K'] #  Element stiffness matrix
        self.K = self.topydict['K'] #  Global stiffness matrix
        if self.nelz:
            print 'Domain discretisation (NUM_ELEM_X x NUM_ELEM_Y x \
NUM_ELEM_Z) = %d x %d x %d' % (self.nelx, self.nely, self.nelz)
        else:
            print 'Domain discretisation (NUM_ELEM_X x NUM_ELEM_Y) = %d x %d'\
            % (self.nelx, self.nely)

        print 'Element type (ELEM_K) =', self.topydict['ELEM_TYPE']
        print 'Filter radius (FILT_RAD) =', self.filtrad

        # Check for either one of the following two, will take NUM_ITER if both
        # are specified.
        try:
            self.numiter = self.topydict['NUM_ITER'] #  Number of iterations
            print 'Number of iterations (NUM_ITER) = %d' % (self.numiter)
        except KeyError:
            self.chgstop = self.topydict['CHG_STOP'] #  Change stop criteria
            print 'Change stop value (CHG_STOP) = %.3e (%.2f%%)' \
            % (self.chgstop, self.chgstop * 100)
            self.numiter = MAX_ITERS

        # All DOF vector and design variables arrays:
        # This needs to be recoded at some point, perhaps. I originally
        # (incorrectly) thought I could do everything just by looking at DOF
        # per node, not so, Cartesian dimension also plays a role.
        # Thus, the 'if'* below is a hack for this to work, and it does...
        if self.dofpn == 1:
            if self.nelz == 0: #  *had to this
                self.e2sdofmapi = self.e2sdofmapi[0:4]
                self.alldof = arange(self.dofpn * (self.nelx + 1) * \
                (self.nely + 1))
                self.desvars = zeros((self.nely, self.nelx)) + self.volfrac
            else:
                self.alldof = arange(self.dofpn * (self.nelx + 1) * \
                (self.nely + 1) * (self.nelz + 1))
                self.desvars = zeros((self.nelz, self.nely, self.nelx)) + \
                self.volfrac
        elif self.dofpn == 2:
            self.alldof = arange(self.dofpn * (self.nelx + 1) * (self.nely +
            1))
            self.desvars = zeros((self.nely, self.nelx)) + self.volfrac
        else:
            self.alldof = arange(self.dofpn * (self.nelx + 1) *\
            (self.nely + 1) * (self.nelz + 1))
            self.desvars = zeros((self.nelz, self.nely, self.nelx)) + \
            self.volfrac
        self.df = zeros_like(self.desvars) #  Derivatives of obj. func. (array)
        self.freedof = setdiff1d(self.alldof, self.fixdof) #  Free DOF vector
        self.r = zeros_like(self.alldof).astype(float) #  Load vector
        self.r[self.loaddof] = self.loadval #  Assign load values at loaded dof
        self.rfree = self.r[self.freedof] #  Modified load vector (free dof)
        self.d = zeros_like(self.r) #  Displacement vector
        self.dfree = zeros_like(self.rfree) #  Modified load vector (free dof)
        # Determine which rows and columns must be deleted from global K:
        self._rcfixed = where(in1d(self.alldof, self.fixdof), 0, 1)

        # Print this to screen, just so that the user knows what type of
        # problem is being solved:
        print 'Problem type (PROB_TYPE) = ' + self.probtype
        print 'Problem name (PROB_NAME) = ' + self.probname

        # Set extra parameters if specified:
        # (1) Continuation parameters for 'p':
        try:
            self._pmax = self.topydict['P_MAX']
            self._phold = self.topydict['P_HOLD']
            self._pincr = self.topydict['P_INCR']
            self._pcon = self.topydict['P_CON']
        except KeyError: #  If they're None
            print 'Continuation of penalisation factor (P_FAC) not specified'
            self._pmax = 1
            self._pcon = self.numiter #  'p' stays constant for all iterations
            self._phold = self.numiter
        # (2) Extra penalisation factor (q) and continuation parameters:
        try:
            self.q = self.topydict['Q_FAC']
            print 'GSF active'
        except KeyError:
            print 'GSF not active'
            self.q = 1
        try:
            self._qmax = self.topydict['Q_MAX']
            self._qhold = self.topydict['Q_HOLD']
            self._qincr = self.topydict['Q_INCR']
            self._qcon = self.topydict['Q_CON']
        except KeyError:  #  If they're None
            self._qmax = self.q
            self._qcon = self.numiter #  'q' stays constant for all iterations
            self._qhold = self.numiter
        # (3) Exponential approximation of eta:
        try:
            self.eta = float(self.topydict['ETA']) * ones(self.desvars.shape)
            print 'Damping factor (ETA) = %3.2f' % (self.eta.mean())
        except ValueError:
            if self.topydict['ETA'] == 'exp':
                #  Initial value of exponent for comp and heat problems:
                self.a = - ones(self.desvars.shape)
                if self.probtype == 'mech':
                    #  Initial value of exponent for mech problems:
                    self.a = self.a * 7 / 3
                self.eta = 1 / (1 - self.a)
                print 'Damping factor (ETA) = exp'
        # (4) Diagonal quadratic approximation:
        try:
            self.approx = lower(self.topydict['APPROX'])
        except KeyError:
            self.approx = None
        if self.approx == 'dquad':
            print 'Using diagonal quadratic approximation (APPROX = dquad)'
        # (5) Set passive elements:
        self.pasv = self.topydict['PASV_ELEM']
        if self.pasv.any():
            print 'Passive elements (PASV_ELEM) specified'
        else:
            print 'No passive elements (PASV_ELEM) specified'
        # (6) Set active elements:
        self.actv = self.topydict['ACTV_ELEM']
        if self.actv.any():
            print 'Active elements (ACTV_ELEM) specified'
        else:
            print 'No active elements (ACTV_ELEM) specified'

        # Set parameters for compliant mechanism synthesis, if they exist:
        if self.probtype == 'mech':
            if self.topydict['LOAD_DOF_OUT'].any() and \
            self.topydict['LOAD_VAL_OUT'].any():
                self.loaddofout = self.topydict['LOAD_DOF_OUT']
                self.loadvalout = self.topydict['LOAD_VAL_OUT']
            else:
                raise ToPyError('Not enough input data for mechanism \
synthesis!')

            self.rout = zeros_like(self.alldof).astype(float)
            self.rout[self.loaddofout] = self.loadvalout
            self.rfreeout = self.rout[self.freedof]
            self.dout = zeros_like(self.rout)
            self.dfreeout = zeros_like(self.rfreeout)
            ksin = ones(self.loaddof.shape, dtype='int') * KDATUM
            ksout = ones(self.loaddofout.shape, dtype='int') * KDATUM
            maskin = ones(self.loaddof.shape, dtype='int')
            maskout = ones(self.loaddofout.shape, dtype='int')
            if len(ksin) > 1:
                self.K.update_add_mask_sym([ksin, ksin], self.loaddof, maskin)
                self.K.update_add_mask_sym([ksout, ksout], self.loaddofout, \
                maskout)
            else:
                self.K.update_add_mask_sym([ksin], self.loaddof, maskin)
                self.K.update_add_mask_sym([ksout], self.loaddofout, maskout)
        print '=' * 79
# This script generates a Python interface for an Apple Macintosh Manager.
# It uses the "bgen" package to generate C code.
# The function specifications are generated by scanning the mamager's header file,
# using the "scantools" package (customized for this particular manager).

#error missing SetActionFilter

import string

# Declarations that change for each manager
MODNAME = '_CF'                         # The name of the module

# The following is *usually* unchanged but may still require tuning
MODPREFIX = 'CF'                        # The prefix for module-wide routines
INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner
OUTPUTFILE = MODNAME + "module.c"       # The file generated by this program

from macsupport import *

# Special case generator for the functions that have an AllocatorRef first argument,
# which we skip anyway, and the object as the second arg.
class MethodSkipArg1(MethodGenerator):
    """Similar to MethodGenerator, but has self as last argument"""

    def parseArgumentList(self, args):
        if len(args) < 2:
            raise ValueError, "MethodSkipArg1 expects at least 2 args"
        a0, a1, args = args[0], args[1], args[2:]
        t0, n0, m0 = a0
        if t0 != "CFAllocatorRef" and m0 != InMode:
            raise ValueError, "MethodSkipArg1 should have dummy AllocatorRef first arg"
Example #37
0
 def __delitem__(self, key):
     key = string.lower(key)
     del self.value[key]
     del self.units[key]
     self.key_list.remove(key)
Example #38
0
def nameFixup(name, classe, type, file):
    listname = classe + "List"
    ll = len(listname)
    l = len(classe)
    if name[0:l] == listname:
        func = name[l:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:12] == "xmlParserGet" and file == "python_accessor":
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:12] == "xmlParserSet" and file == "python_accessor":
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:10] == "xmlNodeGet" and file == "python_accessor":
        func = name[10:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:9] == "xmlURIGet" and file == "python_accessor":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:9] == "xmlURISet" and file == "python_accessor":
        func = name[6:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:11] == "xmlErrorGet" and file == "python_accessor":
        func = name[11:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:17] == "xmlXPathParserGet" and file == "python_accessor":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:11] == "xmlXPathGet" and file == "python_accessor":
        func = name[11:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:11] == "xmlXPathSet" and file == "python_accessor":
        func = name[8:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:15] == "xmlOutputBuffer" and file != "python":
        func = name[15:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:20] == "xmlParserInputBuffer" and file != "python":
        func = name[20:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:9] == "xmlRegexp" and file == "xmlregexp":
        func = "regexp" + name[9:]
    elif name[0:6] == "xmlReg" and file == "xmlregexp":
        func = "regexp" + name[6:]
    elif name[0:20] == "xmlTextReaderLocator" and file == "xmlreader":
        func = name[20:]
    elif name[0:18] == "xmlTextReaderConst" and file == "xmlreader":
        func = name[18:]
    elif name[0:13] == "xmlTextReader" and file == "xmlreader":
        func = name[13:]
    elif name[0:12] == "xmlReaderNew" and file == "xmlreader":
        func = name[9:]
    elif name[0:11] == "xmlACatalog":
        func = name[11:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:l] == classe:
        func = name[l:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:7] == "libxml_":
        func = name[7:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:6] == "xmlGet":
        func = name[6:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:3] == "xml":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    else:
        func = name
    if func[0:5] == "xPath":
        func = "xpath" + func[5:]
    elif func[0:4] == "xPtr":
        func = "xpointer" + func[4:]
    elif func[0:8] == "xInclude":
        func = "xinclude" + func[8:]
    elif func[0:2] == "iD":
        func = "ID" + func[2:]
    elif func[0:3] == "uRI":
        func = "URI" + func[3:]
    elif func[0:4] == "uTF8":
        func = "UTF8" + func[4:]
    elif func[0:3] == 'sAX':
        func = "SAX" + func[3:]
    return func
Example #39
0
def get_guessWord():
    print ""
    guess = string.lower(raw_input("Input puzzle solution: ", ))
    print ""

    return guess
Example #40
0
def askquestion(title,message):
    import string
    val = message_box(title,message,["Yes","No"])
    return string.lower(val)
def normalize_line(l):
    (label, header, content) = split_line(l)
    return label + ' ' + delete_non_letters(
        string.lower(header)) + ': ' + delete_non_letters(
            string.lower(content))
Example #42
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from string import letters, lower
import xmlrpc.client
"""
13 call him
"""
# site = "http://www.pythonchallenge.com/pc/return/"
# opt = "disproportional.html"
"""
solve possible with interactive python:
>>> import xmlrpc.client
>>> conn.system.listMethods()
['phone', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall', 'system.getCapabilities']
>>> conn.system.methodHelp("phone")
'Returns the phone of a person'
conn.phone("Bert")
'555-ITALY'

"""
conn = xmlrpc.client.ServerProxy(
    "http://www.pythonchallenge.com/pc/phonebook.php")
answer_to_find = conn.phone("Bert")

# answer_to_find = "in progress"
print("answer to find is: ", answer_to_find)
opt = "".join(x for x in lower(answer_to_find) if x in letters)
print(" new site: http://www.pythonchallenge.com/pc/return/" + opt + ".html")
##webbrowser.open(site + answer_to_find)
Example #43
0
def nommer_lien_wiki_fre(langue, string):
    return 'http://{langue}.wikipedia.org/wiki/{string}'.format(
        langue=langue, string=string.lower())
Example #44
0
            run_id = v
            try:
                all_digits = int(run_id)
            except ValueError:
                print "#* ERROR: invalid run ID '%s' - has to be an integer value" % run_id
                sys.exit(1)                
            continue

        if o == "--dbhost":
            db_info['host'] = v
            continue
        if o == "--dbport":
            db_info['port'] = v
            continue
        if o == "--dbname":
            db_info['name'] = lower(v)
            continue
        if o == "--dbuser":
            db_info['user'] = v
            continue
        if o == "--dbpasswd":
            db_info['password'] = v
            continue

    if not exp_name:
        print "#* ERROR: Experiment name needs to be specified explicitely."
        print "          Option --help shows syntax. Exiting."
        sys.exit(1)
    if not run_id:
        print "#* ERROR: ID of run needs to be specified."
        print "          Option --help shows syntax. Exiting."
Example #45
0
 def IsTable(self, tableName):
     for aD in self.GetTables():
         if string.lower(aD[0]) == string.lower(tableName):
             return True
     return False
Example #46
0
def typeOfStr(tname):
    if not tname: return None
    return _typeOfStr[string.lower(tname)]
def detect_anagrams(test_word, candidates):
    return [word for word in candidates if is_anagram(lower(test_word), lower(word))]
Example #48
0
    def _make_spec_file(self):
        """Generate the text of an RPM spec file and return it as a
        list of strings (one per line).
        """
        # definitions and headers
        spec_file = [
            '%define name ' + self.distribution.get_name(),
            '%define version ' +
            self.distribution.get_version().replace('-', '_'),
            '%define release ' + self.release.replace('-', '_'),
            '',
            'Summary: ' + self.distribution.get_description(),
        ]

        # put locale summaries into spec file
        # XXX not supported for now (hard to put a dictionary
        # in a config file -- arg!)
        #for locale in self.summaries.keys():
        #    spec_file.append('Summary(%s): %s' % (locale,
        #                                          self.summaries[locale]))

        spec_file.extend([
            'Name: %{name}',
            'Version: %{version}',
            'Release: %{release}',
        ])

        # XXX yuck! this filename is available from the "sdist" command,
        # but only after it has run: and we create the spec file before
        # running "sdist", in case of --spec-only.
        if self.use_bzip2:
            spec_file.append('Source0: %{name}-%{version}.tar.bz2')
        else:
            spec_file.append('Source0: %{name}-%{version}.tar.gz')

        spec_file.extend([
            'License: ' + self.distribution.get_license(),
            'Group: ' + self.group,
            'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
            'Prefix: %{_prefix}',
        ])

        if not self.force_arch:
            # noarch if no extension modules
            if not self.distribution.has_ext_modules():
                spec_file.append('BuildArch: noarch')
        else:
            spec_file.append('BuildArch: %s' % self.force_arch)

        for field in (
                'Vendor',
                'Packager',
                'Provides',
                'Requires',
                'Conflicts',
                'Obsoletes',
        ):
            val = getattr(self, string.lower(field))
            if type(val) is ListType:
                spec_file.append('%s: %s' % (field, string.join(val)))
            elif val is not None:
                spec_file.append('%s: %s' % (field, val))

        if self.distribution.get_url() != 'UNKNOWN':
            spec_file.append('Url: ' + self.distribution.get_url())

        if self.distribution_name:
            spec_file.append('Distribution: ' + self.distribution_name)

        if self.build_requires:
            spec_file.append('BuildRequires: ' +
                             string.join(self.build_requires))

        if self.icon:
            spec_file.append('Icon: ' + os.path.basename(self.icon))

        if self.no_autoreq:
            spec_file.append('AutoReq: 0')

        spec_file.extend(
            ['', '%description',
             self.distribution.get_long_description()])

        # put locale descriptions into spec file
        # XXX again, suppressed because config file syntax doesn't
        # easily support this ;-(
        #for locale in self.descriptions.keys():
        #    spec_file.extend([
        #        '',
        #        '%description -l ' + locale,
        #        self.descriptions[locale],
        #        ])

        # rpm scripts
        # figure out default build script
        def_build = "%s setup.py build" % self.python
        if self.use_rpm_opt_flags:
            def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build

        # insert contents of files

        # XXX this is kind of misleading: user-supplied options are files
        # that we open and interpolate into the spec file, but the defaults
        # are just text that we drop in as-is.  Hmmm.

        script_options = [
            ('prep', 'prep_script', "%setup"),
            ('build', 'build_script', def_build),
            ('install', 'install_script',
             ("%s setup.py install "
              "--root=$RPM_BUILD_ROOT "
              "--record=INSTALLED_FILES") % self.python),
            ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"),
            ('verifyscript', 'verify_script', None),
            ('pre', 'pre_install', None),
            ('post', 'post_install', None),
            ('preun', 'pre_uninstall', None),
            ('postun', 'post_uninstall', None),
        ]

        for (rpm_opt, attr, default) in script_options:
            # Insert contents of file referred to, if no file is referred to
            # use 'default' as contents of script
            val = getattr(self, attr)
            if val or default:
                spec_file.extend([
                    '',
                    '%' + rpm_opt,
                ])
                if val:
                    spec_file.extend(string.split(open(val, 'r').read(), '\n'))
                else:
                    spec_file.append(default)

        # files section
        spec_file.extend([
            '',
            '%files -f INSTALLED_FILES',
            '%defattr(-,root,root)',
        ])

        if self.doc_files:
            spec_file.append('%doc ' + string.join(self.doc_files))

        if self.changelog:
            spec_file.extend([
                '',
                '%changelog',
            ])
            spec_file.extend(self.changelog)

        return spec_file
def lowstr(string):
    res = string.lower()
    return res
Example #50
0
    def __setattr__(self, name, value):
        """`object.<name> = value` sets the XML content of the element with an
        `id` of `name`, or if no such element exists, sets the value of the
        `name` attribute on the outermost element.  If the attribute is not
        already there, a new attribute is created.

        >>> p = Meld('<p style="one">Hello <b id="who">World</b></p>')
        >>> p.who = "Richie"
        >>> p.style = "two"
        >>> p.align = "center"
        >>> p.who.id = "newwho"
        >>> print p
        <p align="center" style="two">Hello <b id="newwho">Richie</b></p>
        """

        if name[0] == '_' and name != '_content':
            self.__dict__[name] = value
            return
        if self._readonly:
            raise ReadOnlyError, READ_ONLY_MESSAGE
        if self._dashes:
            name = string.replace(name, '_', '-')
        self._updatePositions()
        if not isinstance(value, StringType) or isinstance(value, UnicodeType):
            value = str(value)
        if name == '_content':
            self._markup.s = self._markup.s[:self._openEnd] + \
                             value + \
                             self._markup.s[self._closeStart:]
            return
        start = self._findElementFromID(name)
        if start is not None:
            child = self._makeChild(name, start)
            if self._markup.s[child._openStart:child._closeEnd] == value:
                return   # `x.y = x.y`, as happens via `x.y += z`
            self._markup.s = self._markup.s[:child._openEnd] + \
                             value + \
                             self._markup.s[child._closeStart:]
        else:
            # Set the attribute value.
            openTag = self._markup.s[self._openStart:self._openEnd]
            attributeMatch = re.search(attributeRE % name, openTag)
            escapedValue = self._quoteAttribute(value)
            if attributeMatch:
                # This is a change to an existing attribute.
                attributeStart, attributeEnd = attributeMatch.span()
                quote = attributeMatch.group('quote')
                newOpenTag = openTag[:attributeStart] + \
                             '%s%s=%s%s%s' % (attributeMatch.group('space'),
                                               attributeMatch.group('name'),
                                               quote, escapedValue, quote) + \
                             openTag[attributeEnd:]
                self._markup.s = self._markup.s[:self._openStart] + \
                                 newOpenTag + \
                                 self._markup.s[self._openEnd:]
            else:
                # This is introducing a new attribute.
                newAttributePos = self._openStart + 1 + len(self._tagName)
                newAttribute = ' %s="%s"' % (name, escapedValue)
                self._markup.s = self._markup.s[:newAttributePos] + \
                                 newAttribute + \
                                 self._markup.s[newAttributePos:]
        if string.lower(name) == 'id':
            self._name = value
def sanitize(string):
    string = string.lower()
    return ''.join([char for char in string if char.isalnum()])
Example #52
0
def calculate_tf_idf_and_print(hash_freqs, num_distinct_words, num_words,
                               named_entities_tweeters_map, outfile):
    global g_hash_tf_idf
    global g_dashboard_fp
    freq_list_for_sorting = []

    for (k, v) in hash_freqs.items():
        tf = float(v[0]) / num_words
        tf_idf = tf * g_hash_idf[k][2]
        freq_list_for_sorting.append((tf_idf, k))
        g_hash_tf_idf[k] = (
            v[0], tf_idf
        )  # store in hash - tf_idf can be read directly from list too
    freq_list_for_sorting.sort()
    freq_list_for_sorting.reverse()

    #trends_fp = open(outfile, 'w')
    #trends_json_fp = open(outfile + '.json', 'w')

    #trends_json_fp.write('{ "trends": {')
    g_dashboard_fp.write('<table border=1 valign="top">\n')
    g_dashboard_fp.write('<tr>')
    g_dashboard_fp.write('<td align="left">trends n = %.0f </td>' %
                         num_distinct_words)
    g_dashboard_fp.write(
        '<td align="center">t</td><td align="center">trended by</td>')
    g_dashboard_fp.write(
        '<td align="center">f</td> <td align="center">F</td> <td align="center">m</td> <td align="center">M</td><td align="center"> idf = log(N/M)</td> <td align="center"> f/&#931;n * idf (&#931;n = %d)</td>\n'
        % num_words)
    g_dashboard_fp.write('</tr>')
    for i in range(len(freq_list_for_sorting)):

        # trends
        #trends_fp.write('%f | %d | %s\n' % (freqs[i][0], freqs[i][1], freqs[i][2]))

        # trends json
        #trends_json_fp.write(', "trend%d": {"%s":%.4f}' % (i, final_result_bag[i][1], final_result_bag[i][0]))

        # dashboard
        g_dashboard_fp.write('<tr>\n')
        word = freq_list_for_sorting[i][1]
        g_dashboard_fp.write(
            '<td><a href="http://inagist.com/trends/%s">%s</a></td>' %
            (lower(word.replace(' ', '_')), word))
        g_dashboard_fp.write(
            '<td>&nbsp;<a href="http://search.twitter.com/search?q=%s">t</a>&nbsp;</td>\n'
            % (lower(word.replace(' ', '+'))))
        g_dashboard_fp.write('<td>')
        if (named_entities_tweeters_map.has_key(word)):
            for (k, v) in named_entities_tweeters_map[word].items():
                g_dashboard_fp.write(
                    '<a href="http://twitter.com/%s">%s</a> ' % (k, k))
                if (v > 1):
                    g_dashboard_fp.write('(%d) ' % (v))
        g_dashboard_fp.write('</td>')
        numbers = g_hash_idf[word]
        g_dashboard_fp.write(
            '<td align="right"> %d </td> <td align="right"> %d </td> <td align="right"> %d </td> <td align="right"> %d </td> <td align="right"> %.4f </td> <td align="right"> %.4f </td>\n'
            % (g_hash_tf_idf[word][0], numbers[0], hash_freqs[word][1],
               numbers[1], numbers[2], g_hash_tf_idf[word][1]))
        g_dashboard_fp.write('</tr>\n')

    g_dashboard_fp.write('</table>\n')
Example #53
0
for f in input_files.split("\n")[:5]:
    try:
        n = parsefile(f)
        if n:
            print "%s - %s" % (len(n), f)
            rr.extend(n)
        else:
            print "!! - %s" % (f, )
    except Exception, e:
        raise
        print "!!! - %s - %s" % (f, e)

import simplejson, string

rr_germany = filter(
    lambda a: string.lower("%(category)s %(share)s %(fund)s" % defaultdict(
        lambda: "", a)).find("germany") > -1, rr)
simplejson.dump(rr,
                open(os.path.join(output_dir, "resultate-%s.json" % _me), "w"))
simplejson.dump(
    rr_germany,
    open(os.path.join(output_dir, "resultate-%s-germany.json" % _me), "w"))

from unicodecsv import UnicodeWriter

uw = UnicodeWriter(open(os.path.join(output_dir, "resultate-%s.csv" % _me),
                        "w"),
                   delimiter=";")
uw.writerows(
    map(
        lambda a: [
            a["date"], a["category"],
Example #54
0
def mainLoop():
    global slide_num, last_slide, last_text1, last_text2, last_logo, line1_num, line2_num, logo_num
    global line1, line2, stock, weather
    now = time.time()

    DISPLAYSURF.fill(WHITE)
    #bg = pygame.image.load('/var/media/bg.jpg').convert()
    #DISPLAYSURF.blit(bg, (0,870))

    borderColor = (255, 255, 255)
    lineColor = (64, 64, 64)

    s1w = 1440
    s1h = 900
    so = 5
    #pygame.draw.rect(DISPLAYSURF, borderColor, (so,so,s1w,s1h), 1)
    #pygame.draw.rect(DISPLAYSURF, borderColor, (2*so+s1w,so,364,131), 1)
    pygame.draw.rect(
        DISPLAYSURF, BLUE,
        (2 * so + s1w, 5, 1920 - s1w - 3 * so, 1920 - s1w - 3 * so), 0)
    pygame.draw.rect(DISPLAYSURF, BLUE,
                     (2 * so + s1w, 480, 1920 - s1w - 3 * so, 425), 0)
    #pygame.draw.rect(DISPLAYSURF, borderColor, (2*so+s1w,510,364,364), 1)
    pygame.draw.rect(DISPLAYSURF, WHITE, (0, 0, 1920 - 1, 1080 - 1), 1)
    pygame.draw.rect(DISPLAYSURF, BLUE,
                     (5, s1h + 2 * so, 1920 - 2 * so, 1080 - s1h - 3 * so), 0)

    # Display Slides
    slides = [f for f in listdir(SLIDES_DIR) if isfile(join(SLIDES_DIR, f))]

    if slide_num >= len(slides):
        slide_num = 0

    slide = pygame.image.load(SLIDES_DIR + slides[slide_num]).convert()
    slide2 = pygame.transform.scale(slide, (s1w - 2, s1h - 2))
    DISPLAYSURF.blit(slide2, (6, 6))
    if now - last_slide > update_slide:
        last_slide = now
        slide_num = slide_num + 1

    # Draw Text Ticker
    if line1_num >= len(line1):
        line1_num = 0

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 100)
    text_surface = font.render(line1[line1_num], True, (255, 255, 200))
    DISPLAYSURF.blit(text_surface, (10, 880))
    if now - last_text1 > update_text1:
        last_text1 = now
        line1_num = line1_num + 1

    if line2_num >= len(line2):
        line2_num = 0

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 70)
    text_surface = font.render(line2[line2_num], True, (255, 255, 200))
    DISPLAYSURF.blit(text_surface, (10, 980))
    if now - last_text2 > update_text2:
        last_text2 = now
        line2_num = line2_num + 1

    # Display Logo
    logos = [f for f in listdir(LOGOS_DIR) if isfile(join(LOGOS_DIR, f))]

    if logo_num >= len(logos):
        logo_num = 0

    logo = pygame.image.load(LOGOS_DIR + logos[logo_num]).convert()
    logo2 = pygame.transform.scale(logo, (500, 500))
    DISPLAYSURF.blit(logo2, (2 * so + s1w, 5))
    if now - last_logo > update_logo:
        last_logo = now
        logo_num = logo_num + 1

    # Display Stock Info
    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50)
    # text_surface = font.render(stock['name'], True, (255, 255, 255), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,515))

    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30)
    # text_surface = font.render(stock['share'], True, (200, 255, 200), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,565))

    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50)
    # text_surface = font.render("" + stock['change'], True, (255, 100, 100), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,615))

    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50)
    # text_surface = font.render("Price: " + stock['price'], True, (200, 200, 200), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,665))

    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 20)
    # text_surface = font.render("Todays High: " + stock['high'], True, (255, 200, 200), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,735))

    # font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 20)
    # text_surface = font.render("Todays Low: " + stock['low'], True, (255, 200, 200), None)  # White text
    # DISPLAYSURF.blit(text_surface, (2*so+s1w+5,765))
    move_y_axis = 50
    # Display Weather
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50)
    text_surface = font.render(weather['location'], True, (255, 255, 255),
                               None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 480 + move_y_axis))

    #    pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5,195,350,150), 0)
    if os.path.isfile(WEATHER_IMG + weather['current_conditions']['icon'] +
                      ".gif"):
        icon = pygame.image.load(WEATHER_IMG +
                                 weather['current_conditions']['icon'] +
                                 ".gif").convert()
        DISPLAYSURF.blit(icon, (2 * so + s1w + 5, 530 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 50)
    text_surface = font.render(weather['current_conditions']['temperature'] +
                               "F", True, BLACK)  # Black text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 100, 530 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30)
    text_surface = font.render(weather['current_conditions']['text'], True,
                               GRAY)
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 585 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 30)
    text_surface = font.render(
        "Wind: " +
        string.lower(weather['current_conditions']['wind']['speed']) +
        weather['current_conditions']['wind']['text'], True, (100, 100, 100))
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 635 + move_y_axis))

    #    pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5,350,55,55), 0)
    #    pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5+110,350,55,55), 0)
    #    pygame.draw.rect(DISPLAYSURF, (255,255,255), (2*so+s1w+5+220,350,55,55), 0)
    if os.path.isfile(WEATHER_IMG + weather['current_conditions']['icon'] +
                      ".gif"):
        icon = pygame.image.load(WEATHER_IMG +
                                 weather['current_conditions']['icon'] +
                                 ".gif").convert()
        DISPLAYSURF.blit(icon, (2 * so + s1w + 5, 690 + move_y_axis))
    if os.path.isfile(WEATHER_IMG + weather['forecasts'][1]['day']['icon'] +
                      ".gif"):
        icon = pygame.image.load(WEATHER_IMG +
                                 weather['forecasts'][1]['day']['icon'] +
                                 ".gif").convert()
        DISPLAYSURF.blit(icon, (2 * so + s1w + 5 + 110, 690 + move_y_axis))
    if os.path.isfile(WEATHER_IMG + weather['forecasts'][2]['day']['icon'] +
                      ".gif"):
        icon = pygame.image.load(WEATHER_IMG +
                                 weather['forecasts'][2]['day']['icon'] +
                                 ".gif").convert()
        DISPLAYSURF.blit(icon, (2 * so + s1w + 5 + 220, 690 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render(weather['forecasts'][0]['day_of_week'], True,
                               (255, 255, 255), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 740 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("High: " + weather['forecasts'][0]['high'],
                               True, (255, 100, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 770 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("Low: " + weather['forecasts'][0]['low'], True,
                               (100, 255, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5, 800 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render(weather['forecasts'][1]['day_of_week'], True,
                               (220, 220, 220), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 110, 740 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("High: " + weather['forecasts'][1]['high'],
                               True, (255, 100, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 110, 770 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("Low: " + weather['forecasts'][1]['low'], True,
                               (100, 255, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 110, 800 + move_y_axis))

    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render(weather['forecasts'][2]['day_of_week'], True,
                               (200, 200, 200), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 220, 740 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("High: " + weather['forecasts'][2]['high'],
                               True, (255, 100, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 220, 770 + move_y_axis))
    font = pygame.font.Font("../fonts/TitilliumTitle12.otf", 15)
    text_surface = font.render("Low: " + weather['forecasts'][2]['low'], True,
                               (100, 255, 100), None)  # White text
    DISPLAYSURF.blit(text_surface, (2 * so + s1w + 5 + 220, 800 + move_y_axis))

    print "."
Example #55
0
def protocol_access(url, mode, params, data=None):
    scheme, resturl = splittype(url)
    if not scheme:
        raise IOError, ("protocol error", "no scheme identifier in URL", url)
    scheme = string.lower(scheme)
    sanitized = regsub.gsub("[^a-zA-Z0-9]", "_", scheme)
    #
    # Check first to see if proxies are enabled
    manual_proxy_enabled = grailutil.pref_or_getenv('manual_proxy_enabled',
                                                    type_name='int')

    app = grailutil.get_grailapp()
    if manual_proxy_enabled:
        proxy_name = sanitized + "_proxy"
        if manual_proxy_enabled == -1:
            #
            # We should only get here when there are no user preferences
            # for proxies, which should only happen once... so check the
            # environment for the rest of the known scheme proxy env vars
            # and load them into prefs if they exist.
            app.prefs.Set('proxies', 'manual_proxy_enabled', 0)
            proxy = None
            for next_proxy_name in VALID_PROXIES:
                next_proxy = grailutil.pref_or_getenv(next_proxy_name,
                                                      check_ok=VALID_PROXIES)
                if next_proxy:
                    app.prefs.Set('proxies', 'manual_proxy_enabled', 1)

                if next_proxy_name == proxy_name:
                    proxy = next_proxy

            no_proxy_enabled = grailutil.pref_or_getenv('no_proxy_enabled',
                                                        type_name='int')
            if no_proxy_enabled == -1:
                no_proxy = grailutil.pref_or_getenv('no_proxy')
            if no_proxy:
                app.prefs.Set('proxies', 'no_proxy_enabled', 1)
            else:
                app.prefs.Set('proxies', 'no_proxy_enabled', 0)
        else:
            proxy = grailutil.pref_or_getenv(proxy_name,
                                             check_ok=VALID_PROXIES)
    else:
        proxy = None

    if proxy:
        if not valid_proxy(proxy):
            error = 'Invalid proxy: ' + proxy
            raise IOError, error
        no_proxy_enabled = grailutil.pref_or_getenv('no_proxy_enabled',
                                                    type_name='int')
        if no_proxy_enabled:
            no_proxy = grailutil.pref_or_getenv('no_proxy')
        else:
            no_proxy = None

        do_proxy = 1
        if no_proxy:
            list = map(string.strip, string.split(no_proxy, ","))
            url_host, url_remains = splithost(resturl)
            url_host = string.lower(url_host or '')
            if proxy_exception(url_host, list):
                do_proxy = 0
            else:
                url_host, url_port = splitport(url_host)
                if proxy_exception(url_host, list):
                    do_proxy = 0
        if do_proxy:
            proxy_scheme, proxy_resturl = splittype(proxy)
            proxy_host, proxy_remains = splithost(proxy_resturl)
            resturl = (proxy_host, url)
            scheme = string.lower(proxy_scheme)
            sanitized = regsub.gsub("[^a-zA-Z0-9]", "_", scheme)


##          print "Sending", url
##          print "     to", scheme, "proxy", proxy_host
    modname = sanitized + "API"
    app = grailutil.get_grailapp()
    access = app.find_extension('protocols', sanitized).access
    if not access:
        raise IOError, ("protocol error", "no class for %s" % scheme)
    try:
        if data:
            return access(resturl, mode, params, data)
        else:
            return access(resturl, mode, params)
    except socket.error, msg:
        raise IOError, ("socket error", msg)
Example #56
0
    def __parseCfg(self, cfgFile, data, lItem):
        tmpList = CList()

        data = data.replace('\r\n', '\n').split('\n')

        items = []
        tmp = None
        hasOwnCfg = False

        for m in data:
            if m and m[0] != '#':
                index = m.find('=')
                if index != -1:
                    key = lower(m[:index]).strip()
                    value = m[index + 1:]

                    index = value.find('|')
                    if value[:index] == 'sports.devil.locale':
                        value = common.translate(int(value[index + 1:]))
                    elif value[:index] == 'sports.devil.image':
                        value = os.path.join(common.Paths.imgDir,
                                             value[index + 1:])

                    if key == 'start':
                        tmpList.start = value
                    elif key == 'section':
                        tmpList.section = value
                    elif key == 'sort':
                        tmpList.sort = value
                    elif key == 'skill':
                        tmpList.skill = value
                    elif key == 'catcher':
                        tmpList.catcher = value

                    elif key == 'item_infos':
                        rule_tmp = CRuleItem()
                        hasOwnCfg = False
                        rule_tmp.infos = value
                    elif key == 'item_order':
                        rule_tmp.order = value
                    elif key == 'item_skill':
                        rule_tmp.skill = value
                    elif key == 'item_curr':
                        rule_tmp.curr = value
                    elif key == 'item_precheck':
                        rule_tmp.precheck = value

                    elif key.startswith('item_info'):
                        tmpkey = key[len('item_info'):]
                        if tmpkey == '_name':
                            info_tmp = CItemInfo()
                            info_tmp.name = value
                            if value == 'cfg':
                                hasOwnCfg = True
                        elif tmpkey == '_from':
                            info_tmp.src = value
                        elif tmpkey == '':
                            info_tmp.rule = value
                        elif tmpkey == '_default':
                            info_tmp.default = value
                        elif tmpkey == '_convert':
                            info_tmp.convert.append(value)
                        elif tmpkey == '_build':
                            info_tmp.build = value
                            rule_tmp.info_list.append(info_tmp)

                    elif key == 'item_url_build':
                        rule_tmp.url_build = value

                        if tmpList.catcher != '':

                            refInf = CItemInfo()
                            refInf.name = 'referer'
                            refInf.build = value

                            rule_tmp.info_list.append(refInf)

                            if not hasOwnCfg:
                                refInf = CItemInfo()
                                refInf.name = 'catcher'
                                refInf.build = tmpList.catcher

                                rule_tmp.info_list.append(refInf)

                        tmpList.rules.append(rule_tmp)

                    # static menu items (without regex)
                    elif key == 'title':
                        tmp = CListItem()
                        tmp['title'] = value
                        if tmpList.skill.find('videoTitle') > -1:
                            tmp['videoTitle'] = value
                    elif key == 'url':
                        tmp['url'] = value
                        if lItem:
                            tmp.merge(lItem)

                        if tmpList.catcher != '':
                            tmp['referer'] = value
                            if not hasOwnCfg:
                                tmp['catcher'] = tmpList.catcher

                        tmp['definedIn'] = cfgFile
                        items.append(tmp)
                        tmp = None
                    elif tmp != None:
                        if key == 'cfg':
                            hasOwnCfg = True
                        tmp[key] = value

        tmpList.items = items
        tmpList.cfg = cfgFile
        return tmpList
Example #57
0
#! /usr/bin/env python
Example #58
0
def main():
    places_file = PLACES
    if os.environ.has_key('HOME'):
        places_file = os.path.join(os.environ['HOME'], places_file)
    #
    wantbyaddr = wantbytitle = 0
    #
    opts, args = getopt.getopt(sys.argv[1:], 'atp:')
    for o, a in opts:
        if o == '-p':
            places_file = a
        if o == '-a':
            wantbyaddr = 1
        if o == '-t':
            wantbytitle = 1
    #
    if not wantbyaddr and not wantbytitle:
        wantbytitle = 1
    #
    types = []
    progs = []
    for arg in args:
        if not arg: continue
        if arg[0] == '!':
            type = '!'
            arg = arg[1:]
        else:
            type = ''
        progs.append(type, regex.compile(string.lower(arg)))
        if type not in types: types.append(type)
    #
    f = open(places_file, 'r')
    places = marshal.load(f)
    f.close()
    #
    bytitle = []
    byaddr = []
    #
    for addr in places.keys():
        title, exits = places[addr]
        title = string.strip(title)
        if progs:
            lctitle = string.lower(title)
            lcaddr = string.lower(addr)
            good = 0
            bad = 0
            for type, prog in progs:
                if prog.search(lctitle) >= 0 or \
                   prog.search(lcaddr) >= 0:
                    if type == '!':
                        bad = 1
                    else:
                        good = 1
                    break
            if bad:
                continue
            if not good:
                if '' in types:
                    continue
        if not title: title = '(untitled)'
        bytitle.append(title, addr)
        byaddr.append(addr, title)
    #
    bytitle.sort()
    byaddr.sort()
    #
    print '<TITLE>Places you have visited</TITLE>'
    if args:
        print 'Search keywords:'
        for arg in args:
            print arg
        print '<P>'
    if wantbytitle:
        print '<H1>Places you have visited, by title</H1>'
        for title, addr in bytitle:
            print '<A HREF=' + addr + '>'+ title + '</A>', \
                  addr, '<P>'
    if wantbyaddr:
        print '<H1>Places you have visited, by address</H1>'
        for addr, title in byaddr:
            print '<A HREF=' + addr + '>' + addr + '</A>', \
                  title, '<P>'
Example #59
0
    def next(self):
        dict = {}

        # read entry till next blank line
        text = []
        field = ''
        while 1:
            line = self.file.readline()
            if line == '': break
            line = string.rstrip(line)

            # starting with a blank ?
            if line == '' or line[0] == ' ':
                # ...then we continue the current text
                text.append(string.lstrip(line))
                continue

            # new entry ?
            if separator_re.match(line): break

            # else, this is a new field
            if field:
                # save the previous one if needed
                dict[field] = '\n'.join(text)
                text = []

            # store the name of this new field
            field = string.lower(line)

        # don't waste the last field content
        if field:
            dict[field] = '\n'.join(text)

        # did we parse a field ?
        if len(dict) == 0: return None

        # create the entry content
        entry = Base.Entry(type=self.deftype)

        for key in dict.keys():
            if not self.mapping.has_key(key):
                #print "warning: unused key `%s'" % key
                continue

            (name, type) = self.mapping[key]
            text_type = Types.get_field(name).type

            # parse a simple text field
            if type == SimpleField:
                entry[name] = text_type(string.strip(dict[key]))

            elif type == KeywordField:
                text = string.strip(dict[key])
                if entry.has_key(name):
                    text = str(entry[name]) + '\n  ' + text

                entry[name] = text_type(text)

            # parse an author field
            elif type == AuthorField:
                entry[name] = self.parse_author(dict[key])
                continue

            # parse a source field
            elif type == SourceField:
                dict_key = ' '.join(dict[key].split('\n'))
                m = self.source_re.match(dict_key.strip())
                if m:
                    year, month, day = None, None, None
                    j, v, s, n, p, o, y, d = m.group('journal', 'volume',
                                                     'inseries', 'number',
                                                     'pages', 'other', 'year',
                                                     'month')

                    if s:  ### article in a monograph series
                        entry['booktitle'] = Fields.Text(j)
                        if d:
                            entry['beigabevermerk'] = Fields.LongText(d)
                        entry.type = Types.get_entry('incollection')

                    elif j:
                        entry['journal'] = Fields.Text(j)
                        if d and not d.isspace():
                            dates = d.split()
                            try:
                                month = long_month[dates[0]]
                            except KeyError:
                                pass
##                                 import warnings
##                                 warnings.filterwarnings ('once',
##                                                          message='date',
##                                                          module='OvidLike')
##                                 warnings.warn (
##                                     'OVID: %s is not representable in date '
##                                     'field %s' %(dates[0], d), stacklevel=2)
                            if len(dates) > 1:
                                day = int(dates[1])

                    if v:
                        entry['volume'] = Fields.Text(v)

                    if n:
                        entry['number'] = Fields.Text(n)

                    if p:
                        entry['pages'] = Fields.Text(p)

                    if o:
                        entry['other-note'] = Fields.Text(o)

                    if y:
                        year = int(y)

                    entry['date'] = Fields.Date((year, month, day))
                else:
                    print '>>> Error: Source field  does not parse correctly:'
                    print dict_key
                    print entry
                continue

        return entry
Example #60
0
def get_platform():
    """Return a string that identifies the current platform.  This is used
    mainly to distinguish platform-specific build directories and
    platform-specific built distributions.  Typically includes the OS name
    and version and the architecture (as supplied by 'os.uname()'),
    although the exact information included depends on the OS; eg. for IRIX
    the architecture isn't particularly important (IRIX only runs on SGI
    hardware), but for Linux the kernel version isn't particularly
    important.

    Examples of returned values:
       linux-i586
       linux-alpha (?)
       solaris-2.6-sun4u
       irix-5.3
       irix64-6.2

    For non-POSIX platforms, currently just returns 'sys.platform'.
    """
    if os.name != "posix" or not hasattr(os, 'uname'):
        # XXX what about the architecture? NT is Intel or Alpha,
        # Mac OS is M68k or PPC, etc.
        return sys.platform

    # Try to distinguish various flavours of Unix

    (osname, host, release, version, machine) = os.uname()

    # Convert the OS name to lowercase, remove '/' characters
    # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
    osname = string.lower(osname)
    osname = string.replace(osname, '/', '')
    machine = string.replace(machine, ' ', '_')
    machine = string.replace(machine, '/', '-')

    if osname[:5] == "linux":
        # At least on Linux/Intel, 'machine' is the processor --
        # i386, etc.
        # XXX what about Alpha, SPARC, etc?
        return "%s-%s" % (osname, machine)
    elif osname[:5] == "sunos":
        if release[0] >= "5":  # SunOS 5 == Solaris 2
            osname = "solaris"
            release = "%d.%s" % (int(release[0]) - 3, release[2:])
        # fall through to standard osname-release-machine representation
    elif osname[:4] == "irix":  # could be "irix64"!
        return "%s-%s" % (osname, release)
    elif osname[:3] == "aix":
        return "%s-%s.%s" % (osname, version, release)
    elif osname[:6] == "cygwin":
        osname = "cygwin"
        rel_re = re.compile(r'[\d.]+')
        m = rel_re.match(release)
        if m:
            release = m.group()
    elif osname[:6] == "darwin":
        #
        # For our purposes, we'll assume that the system version from
        # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
        # to. This makes the compatibility story a bit more sane because the
        # machine is going to compile and link as if it were
        # MACOSX_DEPLOYMENT_TARGET.
        from distutils.sysconfig import get_config_vars
        cfgvars = get_config_vars()

        macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
        if not macver:
            macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')

        if not macver:
            # Get the system version. Reading this plist is a documented
            # way to get the system version (see the documentation for
            # the Gestalt Manager)
            try:
                f = open('/System/Library/CoreServices/SystemVersion.plist')
            except IOError:
                # We're on a plain darwin box, fall back to the default
                # behaviour.
                pass
            else:
                m = re.search(
                    r'<key>ProductUserVisibleVersion</key>\s*' +
                    r'<string>(.*?)</string>', f.read())
                f.close()
                if m is not None:
                    macver = '.'.join(m.group(1).split('.')[:2])
                # else: fall back to the default behaviour

        if macver:
            from distutils.sysconfig import get_config_vars
            release = macver
            osname = 'macosx'
            platver = os.uname()[2]
            osmajor = int(platver.split('.')[0])

            if osmajor >= 8 and \
                    get_config_vars().get('UNIVERSALSDK', '').strip():
                # The universal build will build fat binaries, but not on
                # systems before 10.4
                machine = 'fat'

            elif machine in ('PowerPC', 'Power_Macintosh'):
                # Pick a sane name for the PPC architecture
                machine = 'ppc'

    return "%s-%s-%s" % (osname, release, machine)