rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
fileDialog = QgsEncodingFileDialog( parent, "Save output shapefile", dirName, filtering, encode )
|
title = QCoreApplication.translate( "MergeShapesDialog", "Save output shapefile" ) fileDialog = QgsEncodingFileDialog( parent, title, dirName, filtering, encode )
|
def saveDialog( parent ): settings = QSettings() dirName = settings.value( "/UI/lastShapefileDir" ).toString() filtering = QString( "Shapefiles (*.shp)" ) encode = settings.value( "/UI/encoding" ).toString() fileDialog = QgsEncodingFileDialog( parent, "Save output shapefile", dirName, filtering, encode ) fileDialog.setDefaultSuffix( QString( "shp" ) ) fileDialog.setFileMode( QFileDialog.AnyFile ) fileDialog.setAcceptMode( QFileDialog.AcceptSave ) fileDialog.setConfirmOverwrite( True ) if not fileDialog.exec_() == QDialog.Accepted: return None, None files = fileDialog.selectedFiles() settings.setValue("/UI/lastShapefileDir", QVariant( QFileInfo( unicode( files.first() ) ).absolutePath() ) ) return ( unicode( files.first() ), unicode( fileDialog.encoding() ) )
|
fileDialog = QgsEncodingFileDialog( parent, "Open input shapefile(s)", dirName, QString(filtering), encode )
|
title = QCoreApplication.translate( "MergeShapesDialog", "Open input shapefile(s)" ) fileDialog = QgsEncodingFileDialog( parent, title, dirName, QString(filtering), encode )
|
def openDialog( parent ): settings = QSettings() dirName = settings.value( "/UI/lastShapefileDir" ).toString() filtering = QString( "Shapefiles (*.shp)" ) encode = settings.value( "/UI/encoding" ).toString() fileDialog = QgsEncodingFileDialog( parent, "Open input shapefile(s)", dirName, QString(filtering), encode ) fileDialog.setFileMode( QFileDialog.ExistingFiles ) fileDialog.setAcceptMode( QFileDialog.AcceptOpen ) if not fileDialog.exec_() == QDialog.Accepted: return None, None files = fileDialog.selectedFiles() settings.setValue("/UI/lastShapefileDir", QVariant( QFileInfo( unicode( files.first() ) ).absolutePath() ) ) # save file names as unicode openedFiles = QStringList() for f in files: openedFiles << unicode( f ) return ( ( openedFiles ), unicode( fileDialog.encoding() ) )
|
output = str(process.stdout.read(10000))
|
output = str(process.stdout.read())
|
def file_getinfo(self): #################### # Description # =========== """ This function finds the information about the current selected file. Displays number of frames, audio codec and video codec.""" # Arguments # ========= # # Further Details # =============== # #################### self.audio_codec = ['N/A','N/A','N/A','N/A','N/A'] self.video_codec = ['N/A','N/A','N/A','N/A','N/A'] self.file_frames = 0 InputFileName=self.input[-1] command = ["ffmpeg","-i",InputFileName]
|
if i>=2 and output_split[i]=='tb(r)\n':
|
if i>=2 and (output_split[i]=='tb(r)\n' or output_split[i]=='tb(r)\nMust'):
|
def file_getinfo(self): #################### # Description # =========== """ This function finds the information about the current selected file. Displays number of frames, audio codec and video codec.""" # Arguments # ========= # # Further Details # =============== # #################### self.audio_codec = ['N/A','N/A','N/A','N/A','N/A'] self.video_codec = ['N/A','N/A','N/A','N/A','N/A'] self.file_frames = 0 InputFileName=self.input[-1] command = ["ffmpeg","-i",InputFileName]
|
flag = 0 if counter >= 1000:
|
if counter >= 1000 or output_spilt[i]=='file\n':
|
def file_getinfo(self): #################### # Description # =========== """ This function finds the information about the current selected file. Displays number of frames, audio codec and video codec.""" # Arguments # ========= # # Further Details # =============== # #################### self.audio_codec = ['N/A','N/A','N/A','N/A','N/A'] self.video_codec = ['N/A','N/A','N/A','N/A','N/A'] self.file_frames = 0 InputFileName=self.input[-1] command = ["ffmpeg","-i",InputFileName]
|
if i>=2 and (output_split[i]=='tb(r)\n' or output_split[i]=='tb(r)\nMust'):
|
if i>=2 and (output_split[i]=='tb(r)\n' or output_split[i]=='tb(r)\nMust' or output_split[i]=='tbr,'):
|
def file_getinfo(self): #################### # Description # =========== """ This function finds the information about the current selected file. Displays number of frames, audio codec and video codec.""" # Arguments # ========= # # Further Details # =============== # #################### self.audio_codec = ['N/A','N/A','N/A','N/A','N/A'] self.video_codec = ['N/A','N/A','N/A','N/A','N/A'] self.file_frames = 0 InputFileName=self.input[-1] command = ["ffmpeg","-i",InputFileName]
|
dialog.destroy() dialog.destroy() if Response == gtk.RESPONSE_OK:
|
if Response == gtk.RESPONSE_OK:
|
def RemoveInputFile(self,widget): #################### # Description # =========== """ Dialog that allows the user to remove a file from the list of input tiles. Once the user presses the 'ok' button, the file is removed from the list.""" # Arguments # ========= # # Further Details # =============== # #################### #base this on a message dialog dialog = gtk.MessageDialog(None,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_QUESTION,gtk.BUTTONS_OK_CANCEL,None) dialog.set_markup('Enter the number of the input file you wish to remove') #create the text input field entry = gtk.Entry() #allow the user to press enter to do ok #entry.connect("activate", dialog.response(response), dialog, gtk.RESPONSE_OK) #create a horizontal box to pack the entry and a label hbox = gtk.HBox() hbox.pack_start(gtk.Label("#"), False, 5, 5) hbox.pack_end(entry) #some secondary text dialog.format_secondary_markup(self.ListOfInputFiles) #add it and show it dialog.vbox.pack_end(hbox, True, True, 0) dialog.show_all() #go go go Response=dialog.run() dialog.destroy() dialog.destroy() if Response == gtk.RESPONSE_OK: try: InputFileToRemove = int(entry.get_text())-1 # Clear everything if we are removing the last tile if len(self.input) >= 2: del self.input[InputFileToRemove] self.setinput(widget) self.NextInputFileToConvert = 0 else: self.ResetSinthgunt(widget) self.ResetSinthgunt(widget) except: pass
|
dialog.destroy()
|
def RemoveInputFile(self,widget): #################### # Description # =========== """ Dialog that allows the user to remove a file from the list of input tiles. Once the user presses the 'ok' button, the file is removed from the list.""" # Arguments # ========= # # Further Details # =============== # #################### #base this on a message dialog dialog = gtk.MessageDialog(None,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_QUESTION,gtk.BUTTONS_OK_CANCEL,None) dialog.set_markup('Enter the number of the input file you wish to remove') #create the text input field entry = gtk.Entry() #allow the user to press enter to do ok #entry.connect("activate", dialog.response(response), dialog, gtk.RESPONSE_OK) #create a horizontal box to pack the entry and a label hbox = gtk.HBox() hbox.pack_start(gtk.Label("#"), False, 5, 5) hbox.pack_end(entry) #some secondary text dialog.format_secondary_markup(self.ListOfInputFiles) #add it and show it dialog.vbox.pack_end(hbox, True, True, 0) dialog.show_all() #go go go Response=dialog.run() dialog.destroy() dialog.destroy() if Response == gtk.RESPONSE_OK: try: InputFileToRemove = int(entry.get_text())-1 # Clear everything if we are removing the last tile if len(self.input) >= 2: del self.input[InputFileToRemove] self.setinput(widget) self.NextInputFileToConvert = 0 else: self.ResetSinthgunt(widget) self.ResetSinthgunt(widget) except: pass
|
|
output = str(process.stdout.read(500))
|
output = str(process.stdout.read())
|
def download_youtube_dl(self,widget,url): #################### # Description # =========== """Downloads video files from sites like youtube.com, metacafe.com and video.google.com.""" # Arguments # ========= # url http url of the remote file to download eg. http://www.example.org/movie.mpg # # Further Details # =============== # This function uses youtube-dl to get the url of the video and the title. #################### # Get video url from youtube-dl command = ["youtube-dl","-g","-b",url] output = '' try: process = subprocess.Popen(args=command,stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT) output = str(process.stdout.read(500)) except: None video_url = output # Get video title from youtube-dl command = ["youtube-dl","-e",url] output = '' try: process = subprocess.Popen(args=command,stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT) output = str(process.stdout.read(500)) except: None
|
video_url = output
|
video_url = output.strip()
|
def download_youtube_dl(self,widget,url): #################### # Description # =========== """Downloads video files from sites like youtube.com, metacafe.com and video.google.com.""" # Arguments # ========= # url http url of the remote file to download eg. http://www.example.org/movie.mpg # # Further Details # =============== # This function uses youtube-dl to get the url of the video and the title. #################### # Get video url from youtube-dl command = ["youtube-dl","-g","-b",url] output = '' try: process = subprocess.Popen(args=command,stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT) output = str(process.stdout.read(500)) except: None video_url = output # Get video title from youtube-dl command = ["youtube-dl","-e",url] output = '' try: process = subprocess.Popen(args=command,stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT) output = str(process.stdout.read(500)) except: None
|
command = ["youtube-dl","-g","-b",url]
|
command = ["youtube-dl","-g",url]
|
def download_youtube_dl(self,widget,url): #################### # Description # =========== """Downloads video files from sites like youtube.com, metacafe.com and video.google.com.""" # Arguments # ========= # url http url of the remote file to download eg. http://www.example.org/movie.mpg # # Further Details # =============== # This function uses youtube-dl to get the url of the video and the title. #################### # Get video url from youtube-dl command = ["youtube-dl","-g","-b",url] output = '' try: process = subprocess.Popen(args=command,stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT) output = str(process.stdout.read()) except: None
|
""" This function determines which codecs the user has installed by looking at the output from "ffmpeg -formats"
|
""" This function determines which codecs the user has installed by looking at the output from both "ffmpeg -formats" and "ffmpeg -codecs"
|
def ffmpeg_getcodecs(self): #################### # Description # =========== """ This function determines which codecs the user has installed by looking at the output from "ffmpeg -formats" """ # Arguments # ========= # # Further Details # =============== # #################### command = ["ffmpeg","-formats"] output = ''
|
jour.values[i] = creche.capacite
|
line.values[i] = creche.capacite
|
def UpdateContents(self): if "Week-end" in creche.feries: self.count = 5 else: self.count = 7 first_monday = getFirstMonday() lines = [] for week_day in range(self.count): date = first_monday + datetime.timedelta(self.semaine * 7 + week_day) if date in creche.jours_fermeture: continue day_lines = {} if len(creche.sites) > 1: lines.append(days[week_day]) for site in creche.sites: line = Day() for i in range(int(creche.ouverture*60/BASE_GRANULARITY), int(creche.fermeture*60/BASE_GRANULARITY)): jour.values[i] = creche.capacite line.label = site.nom day_lines[site] = line lines.append(line) else: site_line = Day() for i in range(int(creche.ouverture*60/BASE_GRANULARITY), int(creche.fermeture*60/BASE_GRANULARITY)): site_line.values[i] = creche.capacite site_line.reference = None site_line.label = days[week_day] lines.append(site_line) for inscrit in creche.inscrits: inscription = inscrit.getInscription(date) if inscription is not None: # print inscrit.prenom, if date in inscrit.journees: line = inscrit.journees[date] else: line = inscrit.getReferenceDay(date) if len(creche.sites) > 1: if inscription.site and inscription.site.nom in day_lines: site_line = day_lines[inscription.site.nom] else: continue for i, value in enumerate(line.values): if value > 0 and value & PRESENT: site_line.values[i] -= 1
|
if inscription.site and inscription.site.nom in day_lines: site_line = day_lines[inscription.site.nom]
|
if inscription.site and inscription.site in day_lines: site_line = day_lines[inscription.site]
|
def UpdateContents(self): if "Week-end" in creche.feries: self.count = 5 else: self.count = 7 first_monday = getFirstMonday() lines = [] for week_day in range(self.count): date = first_monday + datetime.timedelta(self.semaine * 7 + week_day) if date in creche.jours_fermeture: continue day_lines = {} if len(creche.sites) > 1: lines.append(days[week_day]) for site in creche.sites: line = Day() for i in range(int(creche.ouverture*60/BASE_GRANULARITY), int(creche.fermeture*60/BASE_GRANULARITY)): jour.values[i] = creche.capacite line.label = site.nom day_lines[site] = line lines.append(line) else: site_line = Day() for i in range(int(creche.ouverture*60/BASE_GRANULARITY), int(creche.fermeture*60/BASE_GRANULARITY)): site_line.values[i] = creche.capacite site_line.reference = None site_line.label = days[week_day] lines.append(site_line) for inscrit in creche.inscrits: inscription = inscrit.getInscription(date) if inscription is not None: # print inscrit.prenom, if date in inscrit.journees: line = inscrit.journees[date] else: line = inscrit.getReferenceDay(date) if len(creche.sites) > 1: if inscription.site and inscription.site.nom in day_lines: site_line = day_lines[inscription.site.nom] else: continue for i, value in enumerate(line.values): if value > 0 and value & PRESENT: site_line.values[i] -= 1
|
for mois in periode: debut = datetime.date(annee, mois+1, 1) fin = getMonthEnd(debut) for inscrit in creche.inscrits: if inscrit.getInscriptions(debut, fin): facture = FactureFinMois(inscrit, annee, mois+1) heures_contractualisees += facture.heures_contractualisees heures_realisees += facture.heures_realisees heures_facturees += sum(facture.heures_facturees) self.presences_contrat_heures.SetValue("%.2f heures" % heures_contractualisees) self.presences_realisees_heures.SetValue("%.2f heures" % heures_realisees) self.presences_facturees_heures.SetValue("%.2f heures" % heures_facturees)
|
try: for mois in periode: debut = datetime.date(annee, mois+1, 1) fin = getMonthEnd(debut) for inscrit in creche.inscrits: if inscrit.getInscriptions(debut, fin): facture = FactureFinMois(inscrit, annee, mois+1) heures_contractualisees += facture.heures_contractualisees heures_realisees += facture.heures_realisees heures_facturees += sum(facture.heures_facturees) self.presences_contrat_heures.SetValue("%.2f heures" % heures_contractualisees) self.presences_realisees_heures.SetValue("%.2f heures" % heures_realisees) self.presences_facturees_heures.SetValue("%.2f heures" % heures_facturees) except: self.presences_contrat_heures.SetValue("<erreur>") self.presences_realisees_heures.SetValue("<erreur>") self.presences_facturees_heures.SetValue("<erreur>")
|
def EvtPeriodeChoice(self, evt): annee = self.anneechoice.GetClientData(self.anneechoice.GetSelection()) periode = self.periodechoice.GetClientData(self.periodechoice.GetSelection()) heures_contractualisees = 0.0 heures_realisees = 0.0 heures_facturees = 0.0 for mois in periode: debut = datetime.date(annee, mois+1, 1) fin = getMonthEnd(debut) for inscrit in creche.inscrits: if inscrit.getInscriptions(debut, fin): facture = FactureFinMois(inscrit, annee, mois+1) heures_contractualisees += facture.heures_contractualisees heures_realisees += facture.heures_realisees # print inscrit.prenom, facture.heures_contrat, facture.heures_realisees heures_facturees += sum(facture.heures_facturees) self.presences_contrat_heures.SetValue("%.2f heures" % heures_contractualisees) self.presences_realisees_heures.SetValue("%.2f heures" % heures_realisees) self.presences_facturees_heures.SetValue("%.2f heures" % heures_facturees)
|
wx.lib.masked.TimeCtrl.SetValue(self, value) def onText(self, event): value = self.GetValue() try: self.AutoChange(float(value[:2]) + float(value[3:5]) / 60) except: pass event.Skip()
|
wx.lib.masked.TimeCtrl.SetValue(self, value)
|
def SetValue(self, value): if isinstance(value, float): wx.lib.masked.TimeCtrl.SetValue(self, "%02d:%02d" % (int(value), round((value - int(value)) * 60))) else: wx.lib.masked.TimeCtrl.SetValue(self, value)
|
print " " + str(buildingType.name) + " cost per turn:" + str(buildingType.buildCost) + " minimum build time:" + str(buildingType.buildTime)
|
print " " + str(buildingType.name) + " total cost to produce:" + str(buildingType.productionCost) + " minimum time to produce:" + str(buildingType.productionTime)
|
def generateProductionOrders(): "generate production orders" print "Production:" empire = fo.getEmpire() totalPP = empire.productionPoints print "total Production Points: " + str(totalPP) print "possible building types to build:" possibleBuildingTypes = empire.availableBuildingTypes for buildingTypeID in possibleBuildingTypes: buildingType = fo.getBuildingType(buildingTypeID) print " " + str(buildingType.name) + " cost per turn:" + str(buildingType.buildCost) + " minimum build time:" + str(buildingType.buildTime) print "possible ship designs to build:" possibleShipDesigns = empire.availableShipDesigns for shipDesignID in possibleShipDesigns: shipDesign = fo.getShipDesign(shipDesignID) print " " + str(shipDesign.name(True)) + " cost per turn:" + str(shipDesign.cost) + " minimum build time:" + str(shipDesign.buildTime) print "projects already in building queue:" productionQueue = empire.productionQueue for element in productionQueue: print " " + element.name + " turns left:" + str(element.turnsLeft) + " allocated PP:" + str(element.allocation) if productionQueue.empty: for shipDesignID in possibleShipDesigns: locationIDs = getAvailableBuildLocations(shipDesignID) shipDesign = fo.getShipDesign(shipDesignID) if len(locationIDs) > 0 and shipDesign.cost <= (totalPP * 2): if shipDesign.attack > 0: # attack ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) elif shipDesign.canColonize: # colony ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) print ""
|
print " " + str(shipDesign.name(True)) + " cost per turn:" + str(shipDesign.cost) + " minimum build time:" + str(shipDesign.buildTime)
|
print " " + str(shipDesign.name(True)) + " total cost to produce:" + str(shipDesign.productionCost) + " minimum time to produce:" + str(shipDesign.productionTime)
|
def generateProductionOrders(): "generate production orders" print "Production:" empire = fo.getEmpire() totalPP = empire.productionPoints print "total Production Points: " + str(totalPP) print "possible building types to build:" possibleBuildingTypes = empire.availableBuildingTypes for buildingTypeID in possibleBuildingTypes: buildingType = fo.getBuildingType(buildingTypeID) print " " + str(buildingType.name) + " cost per turn:" + str(buildingType.buildCost) + " minimum build time:" + str(buildingType.buildTime) print "possible ship designs to build:" possibleShipDesigns = empire.availableShipDesigns for shipDesignID in possibleShipDesigns: shipDesign = fo.getShipDesign(shipDesignID) print " " + str(shipDesign.name(True)) + " cost per turn:" + str(shipDesign.cost) + " minimum build time:" + str(shipDesign.buildTime) print "projects already in building queue:" productionQueue = empire.productionQueue for element in productionQueue: print " " + element.name + " turns left:" + str(element.turnsLeft) + " allocated PP:" + str(element.allocation) if productionQueue.empty: for shipDesignID in possibleShipDesigns: locationIDs = getAvailableBuildLocations(shipDesignID) shipDesign = fo.getShipDesign(shipDesignID) if len(locationIDs) > 0 and shipDesign.cost <= (totalPP * 2): if shipDesign.attack > 0: # attack ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) elif shipDesign.canColonize: # colony ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) print ""
|
if len(locationIDs) > 0 and shipDesign.cost <= (totalPP * 2):
|
if len(locationIDs) > 0 and shipDesign.productionCost <= (totalPP * 2):
|
def generateProductionOrders(): "generate production orders" print "Production:" empire = fo.getEmpire() totalPP = empire.productionPoints print "total Production Points: " + str(totalPP) print "possible building types to build:" possibleBuildingTypes = empire.availableBuildingTypes for buildingTypeID in possibleBuildingTypes: buildingType = fo.getBuildingType(buildingTypeID) print " " + str(buildingType.name) + " cost per turn:" + str(buildingType.buildCost) + " minimum build time:" + str(buildingType.buildTime) print "possible ship designs to build:" possibleShipDesigns = empire.availableShipDesigns for shipDesignID in possibleShipDesigns: shipDesign = fo.getShipDesign(shipDesignID) print " " + str(shipDesign.name(True)) + " cost per turn:" + str(shipDesign.cost) + " minimum build time:" + str(shipDesign.buildTime) print "projects already in building queue:" productionQueue = empire.productionQueue for element in productionQueue: print " " + element.name + " turns left:" + str(element.turnsLeft) + " allocated PP:" + str(element.allocation) if productionQueue.empty: for shipDesignID in possibleShipDesigns: locationIDs = getAvailableBuildLocations(shipDesignID) shipDesign = fo.getShipDesign(shipDesignID) if len(locationIDs) > 0 and shipDesign.cost <= (totalPP * 2): if shipDesign.attack > 0: # attack ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) elif shipDesign.canColonize: # colony ship print "adding new ship to production queue: " + shipDesign.name(True) fo.issueEnqueueShipProductionOrder(shipDesignID, locationIDs[0]) print ""
|
if planet.type == fo.planetType.terran: return 2 if planet.type == fo.planetType.ocean: return 1 if planet.type == fo.planetType.desert: return 1 if planet.type == fo.planetType.tundra: return 0.5 if planet.type == fo.planetType.swamp: return 0.5
|
if planetEnvironment == fo.planetEnvironment.good: return 2 if planetEnvironment == fo.planetEnvironment.adequate: return 1 if planetEnvironment == fo.planetEnvironment.poor: return 1 if planetEnvironment == fo.planetEnvironment.hostile: return 0.5 if planetEnvironment == fo.planetEnvironment.uninhabitable: return 0.5
|
def getPlanetHospitality(planetID): "returns a value depending on the planet type" universe = fo.getUniverse() planet = universe.getPlanet(planetID) if planet == None: return 0 # should be reworked with races if planet.type == fo.planetType.terran: return 2 if planet.type == fo.planetType.ocean: return 1 if planet.type == fo.planetType.desert: return 1 if planet.type == fo.planetType.tundra: return 0.5 if planet.type == fo.planetType.swamp: return 0.5 return 0
|
self.__active_workers_lock = RLock() self.__active_workers = 0
|
self.__worker_count_lock = RLock() self.__worker_count = 0 self.__active_worker_count = 0
|
def __init__(self, max_workers = 5, kill_workers_after = 3): if (not isinstance(max_workers, int)): raise TypeError("max_workers is not an int") if (max_workers < 1): raise ValueError('max_workers must be >= 1') if (not isinstance(kill_workers_after, int)): raise TypeError("kill_workers_after is not an int") self.__max_workers = max_workers self.__kill_workers_after = kill_workers_after # This Queue is assumed Thread Safe self.__jobs = Queue() self.__active_workers_lock = RLock() self.__active_workers = 0 self.__shutting_down = False logger = logging.getLogger('threadpool') logger.info('started')
|
with self.__active_workers_lock:
|
with self.__worker_count_lock:
|
def shutdown(self, wait_for_workers_period = 1, clean_shutdown_reties = 5): if (not isinstance(clean_shutdown_reties, int)): raise TypeError("clean_shutdown_reties is not an int") if (not clean_shutdown_reties >= 0): raise ValueError('clean_shutdown_reties must be >= 0') if (not isinstance(wait_for_workers_period, int)): raise TypeError("wait_for_workers_period is not an int") if (not wait_for_workers_period >= 0): raise ValueError('wait_for_workers_period must be >= 0') logger = logging.getLogger("threadpool") logger.info("shutting down") with self.__active_workers_lock: self.__shutting_down = True self.__max_workers = 0 self.__kill_workers_after = 0 retries_left = clean_shutdown_reties while (retries_left > 0): with self.__active_workers_lock: logger.info("waiting for workers to shut down (%i), %i workers left"%(retries_left, self.__active_workers)) if (self.__active_workers > 0): retries_left -= 1 else: retries_left = 0 sleep(wait_for_workers_period) with self.__active_workers_lock: if (self.__active_workers > 0): logger.warning("shutdown stopped waiting. Still %i active workers"%self.__active_workers) clean_shutdown = False else: clean_shutdown = True logger.info("shutdown complete") return clean_shutdown
|
with self.__active_workers_lock: logger.info("waiting for workers to shut down (%i), %i workers left"%(retries_left, self.__active_workers)) if (self.__active_workers > 0):
|
with self.__worker_count_lock: logger.info("waiting for workers to shut down (%i), %i workers left"%(retries_left, self.__worker_count)) if (self.__worker_count > 0):
|
def shutdown(self, wait_for_workers_period = 1, clean_shutdown_reties = 5): if (not isinstance(clean_shutdown_reties, int)): raise TypeError("clean_shutdown_reties is not an int") if (not clean_shutdown_reties >= 0): raise ValueError('clean_shutdown_reties must be >= 0') if (not isinstance(wait_for_workers_period, int)): raise TypeError("wait_for_workers_period is not an int") if (not wait_for_workers_period >= 0): raise ValueError('wait_for_workers_period must be >= 0') logger = logging.getLogger("threadpool") logger.info("shutting down") with self.__active_workers_lock: self.__shutting_down = True self.__max_workers = 0 self.__kill_workers_after = 0 retries_left = clean_shutdown_reties while (retries_left > 0): with self.__active_workers_lock: logger.info("waiting for workers to shut down (%i), %i workers left"%(retries_left, self.__active_workers)) if (self.__active_workers > 0): retries_left -= 1 else: retries_left = 0 sleep(wait_for_workers_period) with self.__active_workers_lock: if (self.__active_workers > 0): logger.warning("shutdown stopped waiting. Still %i active workers"%self.__active_workers) clean_shutdown = False else: clean_shutdown = True logger.info("shutdown complete") return clean_shutdown
|
with self.__active_workers_lock: if (self.__active_workers > 0): logger.warning("shutdown stopped waiting. Still %i active workers"%self.__active_workers)
|
with self.__worker_count_lock: if (self.__worker_count > 0): logger.warning("shutdown stopped waiting. Still %i active workers"%self.__worker_count)
|
def shutdown(self, wait_for_workers_period = 1, clean_shutdown_reties = 5): if (not isinstance(clean_shutdown_reties, int)): raise TypeError("clean_shutdown_reties is not an int") if (not clean_shutdown_reties >= 0): raise ValueError('clean_shutdown_reties must be >= 0') if (not isinstance(wait_for_workers_period, int)): raise TypeError("wait_for_workers_period is not an int") if (not wait_for_workers_period >= 0): raise ValueError('wait_for_workers_period must be >= 0') logger = logging.getLogger("threadpool") logger.info("shutting down") with self.__active_workers_lock: self.__shutting_down = True self.__max_workers = 0 self.__kill_workers_after = 0 retries_left = clean_shutdown_reties while (retries_left > 0): with self.__active_workers_lock: logger.info("waiting for workers to shut down (%i), %i workers left"%(retries_left, self.__active_workers)) if (self.__active_workers > 0): retries_left -= 1 else: retries_left = 0 sleep(wait_for_workers_period) with self.__active_workers_lock: if (self.__active_workers > 0): logger.warning("shutdown stopped waiting. Still %i active workers"%self.__active_workers) clean_shutdown = False else: clean_shutdown = True logger.info("shutdown complete") return clean_shutdown
|
with self.__active_workers_lock: self.__active_workers -= 1
|
with self.__worker_count_lock: self.__worker_count -= 1
|
def punch_out(self): ''' Called by worker to update worker count when the worker is shutting down ''' with self.__active_workers_lock: self.__active_workers -= 1
|
with self.__active_workers_lock:
|
with self.__worker_count_lock:
|
def __new_worker(self): ''' Adding a new worker thread to the thread pool ''' with self.__active_workers_lock: ThreadPool.Worker(self) self.__active_workers += 1
|
self.__active_workers += 1
|
self.__worker_count += 1 def worker_active(self): with self.__worker_count_lock: self.__active_worker_count = self.__active_worker_count + 1 def worker_inactive(self): with self.__worker_count_lock: self.__active_worker_count = self.__active_worker_count - 1
|
def __new_worker(self): ''' Adding a new worker thread to the thread pool ''' with self.__active_workers_lock: ThreadPool.Worker(self) self.__active_workers += 1
|
with self.__active_workers_lock:
|
with self.__worker_count_lock:
|
def add_job(self, function, args = None, return_callback=None): ''' Put new job into queue ''' if (not callable(function)): raise TypeError("function is not a callable") if (not ( args == None or isinstance(args, list))): raise TypeError("args is not a list") if (not (return_callback == None or callable(return_callback))): raise TypeError("return_callback is not a callable") if (args == None): args = [] job = ThreadPool.Job(function, args, return_callback) with self.__active_workers_lock: if (self.__shutting_down): raise AddJobException("ThreadPool is shutting down") try: start_new_worker = False if (self.__active_workers < self.__max_workers): if (self.__active_workers == 0 or not self.__jobs.empty()): start_new_worker = True self.__jobs.put(job) if (start_new_worker): self.__new_worker() except Exception: raise AddJobException("Could not add job")
|
if (self.__active_workers < self.__max_workers): if (self.__active_workers == 0 or not self.__jobs.empty()):
|
if (self.__worker_count < self.__max_workers): if (self.__active_worker_count <= self.__worker_count):
|
def add_job(self, function, args = None, return_callback=None): ''' Put new job into queue ''' if (not callable(function)): raise TypeError("function is not a callable") if (not ( args == None or isinstance(args, list))): raise TypeError("args is not a list") if (not (return_callback == None or callable(return_callback))): raise TypeError("return_callback is not a callable") if (args == None): args = [] job = ThreadPool.Job(function, args, return_callback) with self.__active_workers_lock: if (self.__shutting_down): raise AddJobException("ThreadPool is shutting down") try: start_new_worker = False if (self.__active_workers < self.__max_workers): if (self.__active_workers == 0 or not self.__jobs.empty()): start_new_worker = True self.__jobs.put(job) if (start_new_worker): self.__new_worker() except Exception: raise AddJobException("Could not add job")
|
if (self.__active_worker_count <= self.__worker_count):
|
if (self.__active_worker_count == self.__worker_count):
|
def add_job(self, function, args = None, return_callback=None): ''' Put new job into queue ''' if (not callable(function)): raise TypeError("function is not a callable") if (not ( args == None or isinstance(args, list))): raise TypeError("args is not a list") if (not (return_callback == None or callable(return_callback))): raise TypeError("return_callback is not a callable") if (args == None): args = [] job = ThreadPool.Job(function, args, return_callback) with self.__worker_count_lock: if (self.__shutting_down): raise AddJobException("ThreadPool is shutting down") try: start_new_worker = False if (self.__worker_count < self.__max_workers): if (self.__active_worker_count <= self.__worker_count): start_new_worker = True self.__jobs.put(job) if (start_new_worker): self.__new_worker() except Exception: raise AddJobException("Could not add job")
|
dir_path = layoutmanager.get_instance().get_entry_path(uid) metadata_path = layoutmanager.get_instance().get_metadata_path(uid) os.makedirs(metadata_path)
|
def _migrate_metadata(root_path, old_root_path, uid): dir_path = layoutmanager.get_instance().get_entry_path(uid) metadata_path = layoutmanager.get_instance().get_metadata_path(uid) os.makedirs(metadata_path) old_metadata_path = os.path.join(old_root_path, uid + '.metadata') metadata = cjson.decode(open(old_metadata_path, 'r').read()) if 'uid' not in metadata: metadata['uid'] = uid if 'timestamp' not in metadata and 'mtime' in metadata: metadata['timestamp'] = \ time.mktime(time.strptime(metadata['mtime'], DATE_FORMAT)) for key, value in metadata.items(): try: f = open(os.path.join(metadata_path, key), 'w') try: if isinstance(value, unicode): value = value.encode('utf-8') if not isinstance(value, basestring): value = str(value) f.write(value) finally: f.close() except Exception: logging.exception( 'Error while migrating property %s of entry %s', key, uid)
|
|
if not layout_manager.index_updated:
|
if not layoutmanager.get_instance().index_updated:
|
def __init__(self, **options): bus_name = dbus.service.BusName(DS_SERVICE, bus=dbus.SessionBus(), replace_existing=False, allow_replacement=False) dbus.service.Object.__init__(self, bus_name, DS_OBJECT_PATH)
|
responseSize = unpack(responseSizePacked)
|
responseSize = unpackSize(responseSizePacked)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending %s bytes of data" % dataLen s.send(dataLenBytes) s.send(data) print "waiting on response" responseSizePacked = s.recv(packedSize) responseSize = unpack(responseSizePacked) response = '' while len(response) < responseSize: response += s.recv(responseSize - len(response)) print "Received %s bytes " % len(response) print "Got:" + response s.close() return response
|
clientsocket.send(filedata)
|
clientsocket.send(fileData)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending %s bytes of data" % dataLen s.send(dataLenBytes) s.send(data) print "waiting on response" responseSizePacked = s.recv(packedSize) responseSize = unpack(responseSizePacked) response = '' while len(response) < responseSize: response += s.recv(responseSize - len(response)) print "Received %s bytes " % len(response) print "Got:" + response s.close() return response
|
response = s.recv(999999)
|
responseSizePacked = s.recv(packedSize) responseSize = unpack(responseSizePacked) response = '' while len(response) < responseSize: response += s.recv(responseSize - len(response)) print "Received %s bytes " % len(response)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending %s bytes of data" % dataLen s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
clientsocket.send(file("results.key").read())
|
fileData = file("results.key").read() clientsocket.send(packSize(len(fileData))) clientsocket.send(filedata)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending %s bytes of data" % dataLen s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
os.system('sift < % | python process-sift > results.key' % filename)
|
os.system('sift < %s | python process-sift > results.key' % filename)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending data" s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
print "sending data"
|
print "sending %s bytes of data" % dataLen
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending data" s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending data" s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
|
print "received %s bytes" % len(imgData)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending data" s.send(dataLenBytes) s.send(data) print "waiting on response" response = s.recv(999999) print "Got:" + response s.close() return response
|
|
serversocket.bind(('0.0.0.0', settings.SERVER_PORT))
|
serversocket.bind(bindInfo)
|
def client(server,port,data): s = socket() print "connecting to %s:%s" % (server,port) s.connect((server, port)) print "connected" dataLen = len(data) dataLenBytes = packSize(dataLen) print "sending %s bytes of data" % dataLen s.send(dataLenBytes) s.send(data) print "waiting on response" responseSizePacked = s.recv(packedSize) responseSize = unpackSize(responseSizePacked) response = '' while len(response) < responseSize: response += s.recv(responseSize - len(response)) print "Received %s bytes " % len(response) print "Got:" + response s.close() return response
|
caller_allocates = '**' not in node.type.ctype
|
target = self._transformer.lookup_giname(node.type.target_giname) has_double_indirection = '**' in node.type.ctype is_structure_or_union = isinstance(target, (ast.Record, ast.Union)) caller_allocates = (not has_double_indirection and is_structure_or_union)
|
def _apply_annotations_param_ret_common(self, parent, node, tag): options = getattr(tag, 'options', {})
|
comment = '/**\n'
|
comment = '' comment += '/**\n'
|
def to_gtk_doc(self): lines = [self.name + ':'] tags = [] for name, tag in self.tags.iteritems(): if name in self.params: lines.append(tag.to_gtk_doc_param()) else: tags.append(tag)
|
positions=self.position)
|
self.position)
|
def validate(self): for option in self.options: value = self.options[option] if option == OPT_ALLOW_NONE: self._validate_option('allow-none', value, n_params=0) elif option == OPT_ARRAY: if value is None: continue for name, v in value.all().iteritems(): if name in [OPT_ARRAY_ZERO_TERMINATED, OPT_ARRAY_FIXED_SIZE]: try: int(v) except (TypeError, ValueError): if v is None: message.warn( 'array option %s needs a value' % ( name, ), positions=self.position) else: message.warn( 'invalid array %s option value %r, ' 'must be an integer' % (name, v, ), positions=self.position) continue elif name == OPT_ARRAY_LENGTH: if v is None: message.warn( 'array option length needs a value', positions=self.position) continue else: message.warn( 'invalid array annotation value: %r' % ( name, ), self.position)
|
tag.filename = block.position.offset(lineno)
|
tag.position = block.position.offset(lineno)
|
def _parse_comment(self, cmt): # We're looking for gtk-doc comments here, they look like this: # /** # * symbol: # # Or, alternatively, with options: # /** # * symbol: (name value) ... # # symbol is currently one of: # - function: gtk_widget_show # - signal: GtkWidget::destroy # - property: GtkWidget:visible # comment, filename, lineno = cmt comment = comment.lstrip() if not comment.startswith(_COMMENT_HEADER): return comment = comment[len(_COMMENT_HEADER):] comment = comment.strip() if not comment.startswith('* '): return comment = comment[2:]
|
parent_gitype = ast.Type(target_giname='GLib.Object')
|
parent_gitype = ast.Type(target_giname='GObject.Object')
|
def _create_gobject(self, node): type_name = 'G' + node.name if type_name == 'GObject': parent_gitype = None symbol = 'intern' elif type_name == 'GInitiallyUnowned': parent_gitype = ast.Type(target_giname='GLib.Object') symbol = 'g_initially_unowned_get_type' else: assert False gnode = glibast.GLibObject(node.name, parent_gitype, type_name, symbol, 'object', True) if type_name == 'GObject': gnode.fields.extend(node.fields) else: # http://bugzilla.gnome.org/show_bug.cgi?id=569408 # GInitiallyUnowned is actually a typedef for GObject, but # that's not reflected in the GIR, where it appears as a # subclass (as it appears in the GType hierarchy). So # what we do here is copy all of the GObject fields into # GInitiallyUnowned so that struct offset computation # works correctly. gnode.fields = self._namespace.get('Object').fields self._namespace.append(gnode, replace=True)
|
if child.private: continue
|
def _create_enum(self, symbol): prefix = self._enum_common_prefix(symbol) if prefix: prefixlen = len(prefix) else: prefixlen = 0 members = [] for child in symbol.base_type.child_list: if prefixlen > 0: name = child.ident[prefixlen:] else: if child.private: continue # Ok, the enum members don't have a consistent prefix # among them, so let's just remove the global namespace # prefix. try: name = self._strip_symbol(child) except TransformerException, e: message.warn_symbol(symbol, e) return None members.append(ast.Member(name.lower(), child.const_int, child.ident, None))
|
|
if girname in self._include_names:
|
if include in self._include_names:
|
def register_include_uninstalled(self, include_path): basename = os.path.basename(include_path) if not basename.endswith('.gir'): raise SystemExit(
|
% (param_name, parent.name, location_name))
|
% (param_name, location_name, parent.name))
|
def _get_parameter_index(self, parent, param_name, location_name): index = parent.get_parameter_index(param_name) if index is None: raise InvalidAnnotationError( "can't find parameter %s referenced by parameter %s of %r" % (param_name, parent.name, location_name))
|
name_offset = func.symbol.find(name_uscore)
|
name_offset = func.symbol.find(name_uscore + '_')
|
def _parse_method_common(self, func, is_method): # Skip _get_type functions, we processed them # already if func.symbol.endswith('_get_type'): return None if self._namespace_name == 'GLib': # No GObjects in GLib return None
|
def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): block = self._blocks.get(node.c_name) self._apply_annotations_callable(node, chain, block)
|
def _get_annotation_name(self, node):
|
def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): block = self._blocks.get(node.c_name) self._apply_annotations_callable(node, chain, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): if node.ctype is not None: block = self._blocks.get(node.ctype) else: block = self._blocks.get(node.c_name) self._apply_annotations_annotated(node, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union)): for field in node.fields: self._blocks.get('%s::%s' % (node.c_name, field.name)) self._apply_annotations_field(node, block, field) if isinstance(node, (ast.Class, ast.Interface)): for prop in node.properties: self._apply_annotations_property(node, prop) for sig in node.signals: self._apply_annotations_signal(node, sig) if isinstance(node, ast.Class): block = self._blocks.get(node.c_name) if block: tag = block.get(TAG_UNREF_FUNC) node.unref_func = tag.value if tag else None tag = block.get(TAG_REF_FUNC) node.ref_func = tag.value if tag else None tag = block.get(TAG_SET_VALUE_FUNC) node.set_value_func = tag.value if tag else None tag = block.get(TAG_GET_VALUE_FUNC) node.get_value_func = tag.value if tag else None return True
|
block = self._blocks.get(node.ctype) else: block = self._blocks.get(node.c_name) self._apply_annotations_annotated(node, block)
|
return node.ctype elif isinstance(node, ast.Registered) and node.gtype_name is not None: return node.gtype_name return node.c_name assert False, "Unhandled node %r" % (node, ) def _get_block(self, node): return self._blocks.get(self._get_annotation_name(node)) def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): self._apply_annotations_callable(node, chain, block = self._get_block(node)) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): self._apply_annotations_annotated(node, self._get_block(node))
|
def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): block = self._blocks.get(node.c_name) self._apply_annotations_callable(node, chain, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): if node.ctype is not None: block = self._blocks.get(node.ctype) else: block = self._blocks.get(node.c_name) self._apply_annotations_annotated(node, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union)): for field in node.fields: self._blocks.get('%s::%s' % (node.c_name, field.name)) self._apply_annotations_field(node, block, field) if isinstance(node, (ast.Class, ast.Interface)): for prop in node.properties: self._apply_annotations_property(node, prop) for sig in node.signals: self._apply_annotations_signal(node, sig) if isinstance(node, ast.Class): block = self._blocks.get(node.c_name) if block: tag = block.get(TAG_UNREF_FUNC) node.unref_func = tag.value if tag else None tag = block.get(TAG_REF_FUNC) node.ref_func = tag.value if tag else None tag = block.get(TAG_SET_VALUE_FUNC) node.set_value_func = tag.value if tag else None tag = block.get(TAG_GET_VALUE_FUNC) node.get_value_func = tag.value if tag else None return True
|
self._blocks.get('%s::%s' % (node.c_name, field.name))
|
def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): block = self._blocks.get(node.c_name) self._apply_annotations_callable(node, chain, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): if node.ctype is not None: block = self._blocks.get(node.ctype) else: block = self._blocks.get(node.c_name) self._apply_annotations_annotated(node, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union)): for field in node.fields: self._blocks.get('%s::%s' % (node.c_name, field.name)) self._apply_annotations_field(node, block, field) if isinstance(node, (ast.Class, ast.Interface)): for prop in node.properties: self._apply_annotations_property(node, prop) for sig in node.signals: self._apply_annotations_signal(node, sig) if isinstance(node, ast.Class): block = self._blocks.get(node.c_name) if block: tag = block.get(TAG_UNREF_FUNC) node.unref_func = tag.value if tag else None tag = block.get(TAG_REF_FUNC) node.ref_func = tag.value if tag else None tag = block.get(TAG_SET_VALUE_FUNC) node.set_value_func = tag.value if tag else None tag = block.get(TAG_GET_VALUE_FUNC) node.get_value_func = tag.value if tag else None return True
|
|
block = self._blocks.get(node.c_name)
|
block = self._get_block(node)
|
def _pass_read_annotations(self, node, chain): if not node.namespace: return False if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): block = self._blocks.get(node.c_name) self._apply_annotations_callable(node, chain, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): if node.ctype is not None: block = self._blocks.get(node.ctype) else: block = self._blocks.get(node.c_name) self._apply_annotations_annotated(node, block) if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union)): for field in node.fields: self._blocks.get('%s::%s' % (node.c_name, field.name)) self._apply_annotations_field(node, block, field) if isinstance(node, (ast.Class, ast.Interface)): for prop in node.properties: self._apply_annotations_property(node, prop) for sig in node.signals: self._apply_annotations_signal(node, sig) if isinstance(node, ast.Class): block = self._blocks.get(node.c_name) if block: tag = block.get(TAG_UNREF_FUNC) node.unref_func = tag.value if tag else None tag = block.get(TAG_REF_FUNC) node.ref_func = tag.value if tag else None tag = block.get(TAG_SET_VALUE_FUNC) node.set_value_func = tag.value if tag else None tag = block.get(TAG_GET_VALUE_FUNC) node.get_value_func = tag.value if tag else None return True
|
block = self._blocks.get('%s:%s' % (parent.c_name, prop.name))
|
prefix = self._get_annotation_name(parent) block = self._blocks.get('%s:%s' % (prefix, prop.name))
|
def _apply_annotations_property(self, parent, prop): block = self._blocks.get('%s:%s' % (parent.c_name, prop.name)) self._apply_annotations_annotated(prop, block) if not block: return transfer_tag = block.get(TAG_TRANSFER) if transfer_tag is not None: prop.transfer = transfer_tag.value else: prop.transfer = self._get_transfer_default(parent, prop) type_tag = block.get(TAG_TYPE) if type_tag: prop.type = self._resolve(type_tag.value, prop.type)
|
block = self._blocks.get('%s::%s' % (parent.c_name, signal.name))
|
prefix = self._get_annotation_name(parent) block = self._blocks.get('%s::%s' % (prefix, signal.name))
|
def _apply_annotations_signal(self, parent, signal): block = self._blocks.get('%s::%s' % (parent.c_name, signal.name)) self._apply_annotations_annotated(signal, block) # We're only attempting to name the signal parameters if # the number of parameter tags (@foo) is the same or greater # than the number of signal parameters if block and len(block.tags) > len(signal.parameters): names = block.tags.items() else: names = [] for i, param in enumerate(signal.parameters): if names: name, tag = names[i+1] param.name = name options = getattr(tag, 'options', {}) param_type = options.get(OPT_TYPE) if param_type: param.type = self._resolve(param_type.one(), param.type) else: tag = None self._apply_annotations_param(signal, param, tag) self._apply_annotations_return(signal, signal.retval, block)
|
if isinstance(parent, ast.Function):
|
if isinstance(parent, (ast.Function, ast.VFunction)):
|
def _apply_annotations_param(self, parent, param, tag): if tag: options = tag.options else: options = {} if isinstance(parent, ast.Function): scope = options.get(OPT_SCOPE) if scope: scope = scope.one() if scope not in [ast.PARAM_SCOPE_CALL, ast.PARAM_SCOPE_ASYNC, ast.PARAM_SCOPE_NOTIFIED]: message.warn_node( parent, "Invalid scope %r for parameter %r" % (scope, param.argname)) else: param.scope = scope param.transfer = ast.PARAM_TRANSFER_NONE
|
args.append(library)
|
libtool_args.append(library)
|
def _link(self, output, *sources): args = [] libtool = get_libtool_command(self._options) if libtool: args.extend(libtool) args.append('--mode=link') args.append('--tag=CC') args.append('--silent')
|
enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield
|
if block: enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield
|
def _apply_annotations_enum(self, node, block): enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield self._apply_annotations_annotated(node, block)
|
node.attributes.append((key, value.one()))
|
if value: node.attributes.append((key, value.one()))
|
def _parse_attributes(self, node, block): annos_tag = self._get_tag(block, TAG_ATTRIBUTES) if annos_tag is None: return for key, value in annos_tag.options.iteritems(): node.attributes.append((key, value.one()))
|
member.attrib['value'],
|
value,
|
def _introspect_enum(self, xmlnode): members = [] for member in xmlnode.findall('member'): # Keep the name closer to what we'd take from C by default; # see http://bugzilla.gnome.org/show_bug.cgi?id=575613 name = member.attrib['nick'].replace('-', '_') members.append(ast.Member(name, member.attrib['value'], member.attrib['name'], member.attrib['nick']))
|
type_name = xmlnode.attrib['name'] (get_type, c_symbol_prefix) = self._split_type_and_symbol_prefix(xmlnode) try: enum_name = self._transformer.strip_identifier(type_name) except TransformerException, e: message.fatal(e)
|
def _introspect_enum(self, xmlnode): members = [] for member in xmlnode.findall('member'): # Keep the name closer to what we'd take from C by default; # see http://bugzilla.gnome.org/show_bug.cgi?id=575613 name = member.attrib['nick'].replace('-', '_') members.append(ast.Member(name, member.attrib['value'], member.attrib['name'], member.attrib['nick']))
|
|
while parent and (not parent.create_type().target_giname == 'GObject.Object'):
|
while parent and (not parent.gi_name == 'GObject.Object'):
|
def _pair_constructor(self, func, subsymbol): if not (func.symbol.find('_new_') >= 0 or func.symbol.endswith('_new')): return False target = self._transformer.lookup_typenode(func.retval.type) if not isinstance(target, (ast.Class, glibast.GLibBoxed)): return False new_idx = func.symbol.rfind('_new') assert (new_idx >= 0) prefix = func.symbol[:new_idx] split = self._split_uscored_by_type(subsymbol) if split is None: # TODO - need a e.g. (method) annotation message.warn_node(func, "Can't find matching type for constructor; symbol=%r" % (func.symbol, )) return False (origin_node, funcname) = split if not isinstance(origin_node, (ast.Class, glibast.GLibBoxed)): return False if origin_node.namespace != self._namespace: return False if isinstance(target, ast.Class): parent = origin_node while parent and (not parent.create_type().target_giname == 'GObject.Object'): if parent == target: break if parent.parent: parent = self._transformer.lookup_typenode(parent.parent) else: parent = None if parent is None: message.warn_node(func, "Return value is not superclass for constructor; " "symbol=%r constructed=%r return=%r" % ( func.symbol, str(origin_node.create_type()), str(func.retval.type))) return False else: if origin_node != target: message.warn_node(func, "Constructor return type mismatch symbol=%r " "constructed=%r return=%r" % ( func.symbol, str(origin_node.create_type()), str(func.retval.type))) return False self._namespace.float(func) func.name = funcname func.is_constructor = True origin_node.constructors.append(func) # Constructors have default return semantics if not func.retval.transfer: func.retval.transfer = self._get_transfer_default_return(func, func.retval) return True
|
if parent is None:
|
if parent is None or parent.gi_name == 'GObject.Object':
|
def _pair_constructor(self, func, subsymbol): if not (func.symbol.find('_new_') >= 0 or func.symbol.endswith('_new')): return False target = self._transformer.lookup_typenode(func.retval.type) if not isinstance(target, (ast.Class, glibast.GLibBoxed)): return False new_idx = func.symbol.rfind('_new') assert (new_idx >= 0) prefix = func.symbol[:new_idx] split = self._split_uscored_by_type(subsymbol) if split is None: # TODO - need a e.g. (method) annotation message.warn_node(func, "Can't find matching type for constructor; symbol=%r" % (func.symbol, )) return False (origin_node, funcname) = split if not isinstance(origin_node, (ast.Class, glibast.GLibBoxed)): return False if origin_node.namespace != self._namespace: return False if isinstance(target, ast.Class): parent = origin_node while parent and (not parent.create_type().target_giname == 'GObject.Object'): if parent == target: break if parent.parent: parent = self._transformer.lookup_typenode(parent.parent) else: parent = None if parent is None: message.warn_node(func, "Return value is not superclass for constructor; " "symbol=%r constructed=%r return=%r" % ( func.symbol, str(origin_node.create_type()), str(func.retval.type))) return False else: if origin_node != target: message.warn_node(func, "Constructor return type mismatch symbol=%r " "constructed=%r return=%r" % ( func.symbol, str(origin_node.create_type()), str(func.retval.type))) return False self._namespace.float(func) func.name = funcname func.is_constructor = True origin_node.constructors.append(func) # Constructors have default return semantics if not func.retval.transfer: func.retval.transfer = self._get_transfer_default_return(func, func.retval) return True
|
mod = imp.load_module(name, open(realpath), realpath, ('.so', 'rb', 3))
|
platform_system = platform.system() if platform_system == 'Darwin': extension = '.dylib' elif platform_system == 'Windows': extension = '.dll' else: extension = '.so' mod = imp.load_module(name, open(realpath), realpath, (extension, 'rb', 3))
|
def load_module(self, name): realpath = extract_libtool(self.path) mod = imp.load_module(name, open(realpath), realpath, ('.so', 'rb', 3)) mod.__loader__ = self return mod
|
uscored = self._uscored_identifier_for_type(first.type)
|
if hasattr(target, 'c_symbol_prefix') and target.c_symbol_prefix is not None: uscored = target.c_symbol_prefix else: uscored = self._uscored_identifier_for_type(first.type)
|
def _pair_method(self, func, subsymbol): if not func.parameters: return False first = func.parameters[0] target = self._transformer.lookup_typenode(first.type) if not isinstance(target, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Boxed)): return False if target.namespace != self._namespace: return False
|
self.write_line('<%s%s>' % (tag_name, attrs))
|
self.write_line(u'<%s%s>' % (tag_name, attrs))
|
def _open_tag(self, tag_name, attributes=None): if attributes is None: attributes = [] attrs = collect_attributes( tag_name, attributes, self._indent, self._indent_char, len(tag_name) + 2) self.write_line('<%s%s>' % (tag_name, attrs))
|
self.write_line('</%s>' % (tag_name, ))
|
self.write_line(u'</%s>' % (tag_name, ))
|
def _close_tag(self, tag_name): self.write_line('</%s>' % (tag_name, ))
|
def write_line(self, line='', indent=True, do_escape=False):
|
def write_line(self, line=u'', indent=True, do_escape=False): if isinstance(line, str): line = line.decode('utf-8') assert isinstance(line, unicode)
|
def write_line(self, line='', indent=True, do_escape=False): if do_escape: line = escape(str(line))
|
line = escape(str(line))
|
line = escape(str(line)).decode('utf-8')
|
def write_line(self, line='', indent=True, do_escape=False): if do_escape: line = escape(str(line))
|
self._data.write('%s%s' % (line, self._newline_char))
|
self._data.write('%s%s' % (line.encode('utf-8'), self._newline_char))
|
def write_line(self, line='', indent=True, do_escape=False): if do_escape: line = escape(str(line))
|
prefix = '<%s' % (tag_name, )
|
prefix = u'<%s' % (tag_name, )
|
def write_tag(self, tag_name, attributes, data=None): if attributes is None: attributes = [] prefix = '<%s' % (tag_name, ) if data is not None: suffix = '>%s</%s>' % (escape(data), tag_name) else: suffix = '/>' attrs = collect_attributes( tag_name, attributes, self._indent, self._indent_char, len(prefix) + len(suffix)) self.write_line(prefix + attrs + suffix)
|
suffix = '>%s</%s>' % (escape(data), tag_name)
|
if isinstance(data, str): data = data.decode('UTF-8') suffix = u'>%s</%s>' % (escape(data), tag_name)
|
def write_tag(self, tag_name, attributes, data=None): if attributes is None: attributes = [] prefix = '<%s' % (tag_name, ) if data is not None: suffix = '>%s</%s>' % (escape(data), tag_name) else: suffix = '/>' attrs = collect_attributes( tag_name, attributes, self._indent, self._indent_char, len(prefix) + len(suffix)) self.write_line(prefix + attrs + suffix)
|
suffix = '/>'
|
suffix = u'/>'
|
def write_tag(self, tag_name, attributes, data=None): if attributes is None: attributes = [] prefix = '<%s' % (tag_name, ) if data is not None: suffix = '>%s</%s>' % (escape(data), tag_name) else: suffix = '/>' attrs = collect_attributes( tag_name, attributes, self._indent, self._indent_char, len(prefix) + len(suffix)) self.write_line(prefix + attrs + suffix)
|
if isinstance(parent, ast.Function):
|
if parent is not None and isinstance(parent, ast.Function):
|
def top_combiner(base, *rest): if orig_node is not None and isinstance(orig_node, ast.Type): base.is_const = orig_node.is_const return combiner(base, *rest)
|
text = parent.name
|
text = type_str
|
def top_combiner(base, *rest): if orig_node is not None and isinstance(orig_node, ast.Type): base.is_const = orig_node.is_const return combiner(base, *rest)
|
and node.type.name == 'List')):
|
and (node.type.name == 'List' or node.type.name == 'SList'))):
|
def _introspectable_analysis(self, node, stack): if isinstance(node, TypeContainer): parent = stack[-1] if isinstance(node.type, Varargs): parent.introspectable = False elif not isinstance(node.type, List) and \ (node.type.name == 'GLib.List' or (self._transformer._namespace.name == 'GLib' and node.type.name == 'List')): if isinstance(node, Parameter): self._transformer.log_node_warning(parent,
|
if block: enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield
|
enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield
|
def _apply_annotations_enum(self, node, block): if block: enum_type = block.options.get(OPT_TYPE) if enum_type and enum_type.one() == 'bitfield': node.__class__ = ast.Bitfield self._apply_annotations_annotated(node, block)
|
args.extend(['ldd', binary.args[0]])
|
if platform.system() == 'Darwin': args.extend(['otool', '-L', binary.args[0]]) else: args.extend(['ldd', binary.args[0]])
|
def _resolve_non_libtool(options, binary, libraries): if not libraries: return [] args = [] libtool = get_libtool_command(options) if libtool: args.extend(libtool) args.append('--mode=execute') args.extend(['ldd', binary.args[0]]) proc = subprocess.Popen(args, stdout=subprocess.PIPE) patterns = {} for library in libraries: patterns[library] = _ldd_library_pattern(library) shlibs = [] for line in proc.stdout: for library, pattern in patterns.iteritems(): m = pattern.search(line) if m: del patterns[library] shlibs.append(m.group(1)) break if len(patterns) > 0: raise SystemExit( "ERROR: can't resolve libraries to shared libraries: " + ", ".join(patterns.keys())) return shlibs
|
message.warn_symbol(node.symbol,
|
message.warn_node(node,
|
def _apply_annotations2_function(self, node, chain): # Handle virtual invokers parent = chain[-1] if chain else None block = self._blocks.get(node.symbol) if not (block and parent): return virtual = block.get(TAG_VFUNC) if not virtual: return invoker_name = virtual.value matched = False for vfunc in parent.virtual_methods: if vfunc.name == invoker_name: matched = True vfunc.invoker = node.name # Also merge in annotations self._apply_annotations_callable(vfunc, [parent], block) break if not matched: message.warn_symbol(node.symbol, "Virtual slot %r not found for %r annotation" % (invoker_name, TAG_VFUNC))
|
help="If true, the library is located on the system, not in the current directory")
|
help=("""If true, the library is located on the system,""" + """not in the current directory"""))
|
def _get_option_parser(): parser = optparse.OptionParser('%prog [options] sources') parser.add_option('', "--quiet", action="store_true", dest="quiet", default=False, help="If passed, do not print details of normal" \ + " operation") parser.add_option("", "--format", action="store", dest="format", default="gir", help="format to use, one of gidl, gir") parser.add_option("-i", "--include", action="append", dest="includes", default=[], help="Add specified gir file as dependency") parser.add_option("", "--include-uninstalled", action="append", dest="includes_uninstalled", default=[], help=("""A file path to a dependency; only use this " "when building multiple .gir files inside a " "single module.""")) parser.add_option("", "--add-include-path", action="append", dest="include_paths", default=[], help="include paths for other GIR files") parser.add_option("", "--program", action="store", dest="program", default=None, help="program to execute") parser.add_option("", "--program-arg", action="append", dest="program_args", default=[], help="extra arguments to program") parser.add_option("", "--libtool", action="store", dest="libtool_path", default=None, help="full path to libtool") parser.add_option("", "--no-libtool", action="store_true", dest="nolibtool", default=False, help="do not use libtool") parser.add_option("", "--external-library", action="store_true", dest="external_library", default=False, help="If true, the library is located on the system, not in the current directory") parser.add_option("-l", "--library", action="append", dest="libraries", default=[], help="libraries of this unit") parser.add_option("-L", "--library-path", action="append", dest="library_paths", default=[], help="directories to search for libraries") parser.add_option("-n", "--namespace", action="store", dest="namespace_name", help=("name of namespace for this unit, also " "used to compute --identifier-prefix and --symbol-prefix")) parser.add_option("", "--nsversion", action="store", dest="namespace_version", help="version of namespace for this unit") parser.add_option("", "--strip-prefix", action="store", dest="strip_prefix", help="""Option --strip-prefix is deprecated, please see --identifier-prefix
|
_error("""Option --strip-prefix has been replaced; see --identifier-prefix and --symbol-prefix.""")
|
print """g-ir-scanner: warning: Option --strip-prefix has been deprecated; see --identifier-prefix and --symbol-prefix.""" options.identifier_prefixes.append(options.strip_prefix)
|
def scanner_main(args): parser = _get_option_parser() (options, args) = parser.parse_args(args) if options.passthrough_gir: passthrough_gir(options.passthrough_gir, sys.stdout) if options.test_codegen: return test_codegen(options.test_codegen) if len(args) <= 1: _error('Need at least one filename') if not options.namespace_name: _error('Namespace name missing') if options.format == 'gir': from giscanner.girwriter import GIRWriter as Writer else: _error("Unknown format: %s" % (options.format, )) if not (options.libraries or options.program): _error("Must specify --program or --library") libraries = options.libraries if options.strip_prefix: _error("""Option --strip-prefix has been replaced;
|
self._namespace.float(func) func.name = funcname node.static_methods.append(func)
|
return True
|
def _pair_static_method(self, func, subsymbol): split = self._split_uscored_by_type(subsymbol) if split is None: return False (node, funcname) = split if not isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union, glibast.GLibBoxedOther)): return False self._namespace.float(func) func.name = funcname node.static_methods.append(func)
|
return False
|
return self._resolve_type_from_ctype_all_namespaces(typeval, pointer_stripped)
|
def _resolve_type_from_ctype(self, typeval): assert typeval.ctype is not None pointer_stripped = typeval.ctype.replace('*', '') try: matches = self.split_ctype_namespaces(pointer_stripped) except ValueError, e: return False target_giname = None for namespace, name in matches: target = namespace.get(name) if not target: target = namespace.get_by_ctype(pointer_stripped) if target: typeval.target_giname = '%s.%s' % (namespace.name, target.name) return True return False
|
ptype = ast.Type.create_type_gtype_name(pctype)
|
ptype = ast.Type.create_from_gtype_name(pctype)
|
def _introspect_signals(self, node, xmlnode): for signal_info in xmlnode.findall('signal'): rctype = signal_info.attrib['return'] rtype = ast.Type.create_from_gtype_name(rctype) return_ = ast.Return(rtype) parameters = [] for i, parameter in enumerate(signal_info.findall('param')): if i == 0: argname = 'object' else: argname = 'p%s' % (i-1, ) pctype = parameter.attrib['type'] ptype = ast.Type.create_type_gtype_name(pctype) param = ast.Parameter(argname, ptype) param.transfer = ast.PARAM_TRANSFER_NONE parameters.append(param) signal = glibast.GLibSignal(signal_info.attrib['name'], return_, parameters) node.signals.append(signal) node.signals = node.signals
|
os.unlink(c_path)
|
def run(self): tpl_args = {} tpl_args['init_sections'] = "\n".join(self._options.init_sections)
|
|
message.warn(
|
message.warn_node(
|
def _apply_annotations_param(self, parent, param, tag): if tag: options = tag.options else: options = {} if isinstance(parent, ast.Function): scope = options.get(OPT_SCOPE) if scope: scope = scope.one() if scope not in [ast.PARAM_SCOPE_CALL, ast.PARAM_SCOPE_ASYNC, ast.PARAM_SCOPE_NOTIFIED]: message.warn( parent, "Invalid scope %r for parameter %r" % (scope, param.name)) else: param.scope = scope param.transfer = ast.PARAM_TRANSFER_NONE
|
"Invalid scope %r for parameter %r" % (scope, param.name))
|
"Invalid scope %r for parameter %r" % (scope, param.argname))
|
def _apply_annotations_param(self, parent, param, tag): if tag: options = tag.options else: options = {} if isinstance(parent, ast.Function): scope = options.get(OPT_SCOPE) if scope: scope = scope.one() if scope not in [ast.PARAM_SCOPE_CALL, ast.PARAM_SCOPE_ASYNC, ast.PARAM_SCOPE_NOTIFIED]: message.warn( parent, "Invalid scope %r for parameter %r" % (scope, param.name)) else: param.scope = scope param.transfer = ast.PARAM_TRANSFER_NONE
|
name = self.remove_prefix(symbol.ident)
|
name = self._strip_namespace_func(symbol.ident)
|
def _create_const(self, symbol): # Don't create constants for non-public things # http://bugzilla.gnome.org/show_bug.cgi?id=572790 if (symbol.source_filename is None or not symbol.source_filename.endswith('.h')): return None name = self.remove_prefix(symbol.ident) if symbol.const_string is not None: type_name = 'utf8' value = symbol.const_string elif symbol.const_int is not None: type_name = 'int' value = symbol.const_int elif symbol.const_double is not None: type_name = 'double' value = symbol.const_double else: raise AssertionError()
|
return False if typeval.is_equiv(ast.TYPE_UNICHAR):
|
def _type_is_introspectable(self, typeval, warn=False): if not typeval.resolved: return False if isinstance(typeval, ast.TypeUnknown): return False if isinstance(typeval, (ast.Array, ast.List)): return self._type_is_introspectable(typeval.element_type) elif isinstance(typeval, ast.Map): return (self._type_is_introspectable(typeval.key_type) and self._type_is_introspectable(typeval.value_type)) if typeval.target_foreign: return True if typeval.target_fundamental: if typeval.is_equiv(ast.TYPE_VALIST): return False # Mark UCHAR as not introspectable temporarily until # we're ready to land the typelib changes if typeval.is_equiv(ast.TYPE_UNICHAR): return False # These are not introspectable pending us adding # larger type tags to the typelib (in theory these could # be 128 bit or larger) if typeval.is_equiv((ast.TYPE_LONG_LONG, ast.TYPE_LONG_ULONG, ast.TYPE_LONG_DOUBLE)): return False return True target = self._transformer.lookup_typenode(typeval) if not target: return False return target.introspectable and (not target.skip)
|
|
if self._namespace_name == 'GLib': return None
|
def _parse_method_common(self, func, is_method): # Skip _get_type functions, we processed them # already if func.symbol.endswith('_get_type'): return None if self._namespace_name == 'GLib': # No GObjects in GLib return None
|
|
elif isinstnace(node, GLibBoxed):
|
elif isinstance(node, GLibBoxed):
|
def _subwalk(subnode): self._walk(subnode, callback, chain)
|
if orig_node is not None:
|
if orig_node is not None and isinstance(orig_node, ast.Type):
|
def top_combiner(base, *rest): if orig_node is not None: base.is_const = orig_node.is_const return combiner(base, *rest)
|
element_type_node = self._resolve(element_type.one())
|
element_type_node = self._resolve(element_type.one(), parent)
|
def _apply_annotations_array(self, parent, node, options): array_opt = options.get(OPT_ARRAY) if array_opt: array_values = array_opt.all() else: array_values = {}
|
node.type.element_type = self._resolve(element_type[0])
|
node.type.element_type = self._resolve(element_type[0], parent)
|
def _apply_annotations_element_type(self, parent, node, options): element_type_opt = options.get(OPT_ELEMENT_TYPE) element_type = element_type_opt.flat() if isinstance(node.type, ast.List): assert len(element_type) == 1 node.type.element_type = self._resolve(element_type[0]) elif isinstance(node.type, ast.Map): assert len(element_type) == 2 node.type.key_type = self._resolve(element_type[0]) node.type.value_type = self._resolve(element_type[1]) elif isinstance(node.type, ast.Array): node.type.element_type = self._resolve(element_type[0]) else: message.warn_node(parent, "Unknown container %r for element-type annotation" % (node.type, ))
|
node.type.key_type = self._resolve(element_type[0]) node.type.value_type = self._resolve(element_type[1])
|
node.type.key_type = self._resolve(element_type[0], parent) node.type.value_type = self._resolve(element_type[1], parent)
|
def _apply_annotations_element_type(self, parent, node, options): element_type_opt = options.get(OPT_ELEMENT_TYPE) element_type = element_type_opt.flat() if isinstance(node.type, ast.List): assert len(element_type) == 1 node.type.element_type = self._resolve(element_type[0]) elif isinstance(node.type, ast.Map): assert len(element_type) == 2 node.type.key_type = self._resolve(element_type[0]) node.type.value_type = self._resolve(element_type[1]) elif isinstance(node.type, ast.Array): node.type.element_type = self._resolve(element_type[0]) else: message.warn_node(parent, "Unknown container %r for element-type annotation" % (node.type, ))
|
uscored = target.c_symbol_prefix else: uscored = self._uscored_identifier_for_type(first.type) if not subsymbol.startswith(uscored): return False
|
prefix_matches = subsymbol.startswith(target.c_symbol_prefix) if prefix_matches: uscored_prefix = target.c_symbol_prefix if not prefix_matches: uscored_prefix = self._uscored_identifier_for_type(first.type) if not subsymbol.startswith(uscored_prefix): return False
|
def _pair_method(self, func, subsymbol): if not func.parameters: return False first = func.parameters[0] target = self._transformer.lookup_typenode(first.type) if not isinstance(target, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Boxed)): return False if target.namespace != self._namespace: return False
|
func.name = func.symbol[(subsym_idx + len(uscored) + 1):]
|
func.name = func.symbol[(subsym_idx + len(uscored_prefix) + 1):]
|
def _pair_method(self, func, subsymbol): if not func.parameters: return False first = func.parameters[0] target = self._transformer.lookup_typenode(first.type) if not isinstance(target, (ast.Class, ast.Interface, ast.Record, ast.Union, ast.Boxed)): return False if target.namespace != self._namespace: return False
|
has_array = \ node.type.name in ['GLib.Array', 'GLib.PtrArray', 'GLib.ByteArray'] or \ node.type.ctype in ['GArray*', 'GPtrArray*', 'GByteArray*']
|
has_array = self._is_array_type(node)
|
def _extract_container_type(self, parent, node, options): has_element_type = OPT_ELEMENT_TYPE in options has_array = OPT_ARRAY in options
|
second_colon_index = line.rfind(':')
|
line_after_first_colon_space = line[first_colonspace_index + 2:] second_colon_index = line_after_first_colon_space.find(':') if second_colon_index >= 0: second_colon_index += first_colonspace_index + 2 assert line[second_colon_index] == ':'
|
def _parse_comment(self, cmt): # We're looking for gtk-doc comments here, they look like this: # /** # * symbol: # # Or, alternatively, with options: # /** # * symbol: (name value) ... # # symbol is currently one of: # - function: gtk_widget_show # - signal: GtkWidget::destroy # - property: GtkWidget:visible # comment, filename, lineno = cmt comment = comment.lstrip() if not comment.startswith(_COMMENT_HEADER): return comment = comment[len(_COMMENT_HEADER):] comment = comment.strip() if not comment.startswith('* '): return comment = comment[2:]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.