def __init__(self, base_dir, lib_name): self.app = None self.lib_name = lib_name self.base_dir = base_dir self.static_handler = StaticHandler(self.base_dir) self.template_handler = TemplateHandler() self.force_overwrite = False self.config = ConfigHandler(self.get_conf_path())
def __init__(self, url): ConfigHandler.__init__(self) FileHandler.__init__(self) self.url = url self.http = None self.filepath = None self.filesize = None self.filename = None logging.getLogger("urllib3").setLevel(logging.WARNING)
def merge_multithreaded_download_parts(self): # merging parts with open(self.filepath, 'wb') as wfd: for f in range(ConfigHandler.get_threads(self)): tempfilepath = ConfigHandler.get_temp_dir( self) + "/temp" + str(f) with open(tempfilepath, "rb") as fd: shutil.copyfileobj(fd, wfd) # delete copied segment FileHandler.delete_file(self, tempfilepath)
def __init__(self): logging.info('Creating RESTHandler'); self.lock = threading.RLock() self.since_id = None # Get Config and set since_id self.config = ConfigHandler() self.since_id = self.config.mention_id() # Attempt to get OAuth Client self.oauthhandler = OAuthHandler(self.config) if(self.verify_credentials()): logging.info('OAuth Client created successfully') else: logging.critical('Unable to birth OAuth Client')
def get_download_sizes_list(self): # no of bytes per thread size_per_thread = self.filesize // ConfigHandler.get_threads(self) # stores size to be downloaded by each thread sizes_list = [size_per_thread] * ConfigHandler.get_threads(self) # remaining size not assigned to any thread rem = self.filesize % ConfigHandler.get_threads(self) # loop to equally assign sizes to download, to each thread index = 0 while rem != 0: sizes_list[index] += 1 rem -= 1 index += 1 return sizes_list
def __init__(self): app_name = 'dbhandler_test' logfile = 'system' log_level = 10 screendump = True # log.info('Starting DentrixReporting logger...', # app_name = app_name, # logfile = logfile, # log_level = log_level, # screendump = screendump # ) self.config = ConfigHandler( self, app_name=app_name, logfile=logfile, log_level=log_level, screendump=screendump, config_file= "/Users/mikes/Documents/Eclipseworkspace/Telemend/Telemend-Dentrix-Reporting/conf/DentrixReporting.conf" ) DBO = DBHandler.handler('mssql') print 'DBO = ', DBO
def __init__(self, *args, **kwargs): self.config = ConfigHandler() self.args = args self.kwargs = kwargs self.default = DBHandler_defaults() self._check_host() self._check_db_name() self._check_db_port() # Sets database parameters from dbvars.cfg # self._set_db_vars() # # # Check for overriding vars passed into __init__ # if host is not None: self.dbvars['host'] = str(host) # if database is not None: self.dbvars['database'] = str(database) # if port is not None: self.dbvars['port'] = str(port) # if user is not None: self.dbvars['user'] = str(user) # if password is not None: self.dbvars['password'] = str(password) # # # Actually create the DB connection and cursor # self._set_db() # # self.values = {} log.debug("DBHandler set successfully.")
def make_request(self, headers=None): try: resp = self.http.request("GET", self.url.replace("https", "http"), retries=ConfigHandler.get_retries(self), timeout=ConfigHandler.get_timeouts(self), preload_content=False, headers=headers) except urllib3.exceptions.NewConnectionError: # if failed to create connection print("Connection Failed!") except urllib3.exceptions.SSLError: # if failed to establish secure connection (https) print("SSL Error!") return resp
def multithreaded_download(self, ranges_list): # downloading each segment for f in range(ConfigHandler.get_threads(self)): # calling seg_handler() for each thread t = threading.Thread(target=self.seg_handler, kwargs={ 'tempfilepath': ConfigHandler.get_temp_dir(self) + "/temp" + str(f), 'range_left': ranges_list[f][0], 'range_right': ranges_list[f][1] }) t.setDaemon(True) t.start() # except main_thread, calling join() for each thread # it ensures that merging of parts occur only after each thread has completed downloading main_thread = threading.current_thread() for t in threading.enumerate(): if t is main_thread: continue t.join()
def download(self): ConfigHandler.parse_config(self) if ConfigHandler.get_proxy(self): self.http = urllib3.ProxyManager(ConfigHandler.get_proxy(self)) else: self.http = urllib3.PoolManager() # make sure that download path and temp directory exists FileHandler.create_dir(self, ConfigHandler.get_download_dir(self)) FileHandler.create_dir(self, ConfigHandler.get_temp_dir(self)) # extracting filename from URL self.filename = os.path.basename(self.url.replace("%20", "_")) # getting complete filepath self.filepath = ConfigHandler.get_download_dir( self) + "/" + self.filename #making an initial request to get header information resp = self.make_request() # extracting the size of file to be downloaded in bytes, from header self.filesize = int(resp.headers['Content-Length']) # if server supports segmented download if self.range_download_support(resp): # get ranges for download for each thread ranges_list = self.get_download_ranges_list() # perform multithreaded download on single system self.multithreaded_download(ranges_list) # merge multithreaded download parts self.merge_multithreaded_download_parts() else: print('''Server doesn't support multithreaded downloads! Download will be performed using single thread, on master system.''') self.seg_handler(self.filepath, 0, self.filesize - 1) # perform final cleaning after download completion self.final_clean(interrupted=False)
class RESTHandler: # End points for REST calls PLACES_EP = "https://api.twitter.com/1.1/trends/place.json?id=" #GET VERIFY_CREDS_EP = "https://api.twitter.com/1.1/account/verify_credentials.json" #GET UPDATE_STATUS_EP = "https://api.twitter.com/1.1/statuses/update.json" #POST QUERY_SEARCH_EP = "https://api.twitter.com/1.1/search/tweets.json?q=" #GET MENTIONS_EP = "https://api.twitter.com/1.1/statuses/mentions_timeline.json?count=" #GET # Constants GLOBAL_WOEID = 1 # I'll grab trends from a global perspective for now JSON_DATA_INDEX = 0 # I have a feeling that Twitter nests most of its response data MAX_TWEET_LEN = 140 MAX_MENTIONS = 5 # Number of mentions to get at one time TWEET_SEARCH_LIMIT = "&count=20" # Additional, optional parameter for Query Search to limit returned tweets HTTP_SUCCESS = '200' TRENDS_KEY = 'trends' PROMOTED_CONTENT_KEY = 'promoted_content' NAME_KEY = 'name' NONE_STR = 'None' QUERY_KEY = 'query' STATUS_KEY = 'status' STATUSES_KEY = 'statuses' SCREEN_NAME_KEY = 'screen_name' USER_KEY = 'user' SINCE_ID_KEY = '&since_id=' ID_KEY = 'id' TEXT_KEY = 'text' ID_STR_KEY = 'id_str' USER_MENTIONS_KEY = 'user_mentions' # ctor def __init__(self): logging.info('Creating RESTHandler'); self.lock = threading.RLock() self.since_id = None # Get Config and set since_id self.config = ConfigHandler() self.since_id = self.config.mention_id() # Attempt to get OAuth Client self.oauthhandler = OAuthHandler(self.config) if(self.verify_credentials()): logging.info('OAuth Client created successfully') else: logging.critical('Unable to birth OAuth Client') # Gets a list of mentions and will use the since_id if it exists def get_user_from_mention(self): logging.info('Attempting to get list of mentions') mentions_ep = self.MENTIONS_EP +str(self.MAX_MENTIONS) # if a since_id exists, attach it if self.since_id is not None and self.since_id != '': logging.info('since_id found: %s' % self.since_id) mentions_ep += self.SINCE_ID_KEY + str(self.since_id) logging.info('Getting mentions at %s' % mentions_ep) # With the constructed endpoint, make the callable resp, data = self.get_request(mentions_ep) if self.resp_success(resp[self.STATUS_KEY]): mentions_data = json.loads(data) # Pick a mention out of the list numMentions = len(mentions_data) if numMentions > 0: logging.info('Grabbing random mention') rndIndex = randint(0, (numMentions - 1)) mention = mentions_data[rndIndex] self.since_id = mention[self.ID_STR_KEY] logging.info('Storing id: %s' % self.since_id) self.config.set_value(self.config.MENTION_SECTION, self.config.MENTION_ID, self.since_id) user = mention[self.USER_KEY][self.SCREEN_NAME_KEY] text = mention[self.TEXT_KEY] logging.info('Mention to respond to: %s by: %s' % (text, user)) return (user, text) else: logging.info('No mentions were found') return None else: logging.error('There was an issue fetching the list of mentions') return None # Gets a list of trends, picks a random one and returns the query def get_trend_query(self): # Take lock to do work with self.lock: places_ep = self.PLACES_EP + str(self.GLOBAL_WOEID) logging.info('Attempting to get list of places from ' + places_ep) resp, data = self.get_request(places_ep) if self.resp_success(resp[self.STATUS_KEY]): jsonData = json.loads(data) # With the list of trends, pick a random index trends = jsonData[self.JSON_DATA_INDEX][self.TRENDS_KEY] numTrends = len(trends) if numTrends > 0: logging.info('Grabbing random trend') rndIndex = randint(0, (numTrends - 1)) trend = trends[rndIndex] logging.info('Getting tweets for %s' % trend[self.NAME_KEY]) return trend[self.QUERY_KEY] else: logging.error('No trends were returned') return None else: logging.error('There was an issue getting the list of locales') return None # From the trend query, select a random tweet. Return the user who posted it def get_tweet_user(self, query): # Take lock to do work with self.lock: logging.info('Attempting to get list of tweets for trend') tweets_ep = self.QUERY_SEARCH_EP + query + self.TWEET_SEARCH_LIMIT resp, data = self.get_request(tweets_ep) if self.resp_success(resp[self.STATUS_KEY]): tweet_data = json.loads(data) tweets = tweet_data[self.STATUSES_KEY] logging.info('Selecting a random tweet') numTweets = len(tweets) if numTweets > 0: rndIndex = randint(0, numTweets - 1) tweet = tweets[rndIndex] logging.info('Grabbing user info') user = tweet[self.USER_KEY][self.SCREEN_NAME_KEY] return user else: logging.warning('No tweets were returned') return None else: logging.error('There was an issue fetching the list of tweets') return None # Updates status with a tweet. Takes in the status. def update_status(self, status): # Take lock to do work with self.lock: # Verify that status is under 140 characters if len(status) <= self.MAX_TWEET_LEN: status_ep = self.UPDATE_STATUS_EP logging.info('Attempting to post tweet') resp, data = self.post_request(status_ep, status) if self.resp_success(resp[self.STATUS_KEY]): logging.info('Post successful') else: logging.error('There was an error posting the tweet') else: logging.error('Tweet is too long to post') # Used to verify that our credentials are still authorized def verify_credentials(self): with self.lock: logging.info('Attempting to verify credentials') try: resp, data = self.get_request(self.VERIFY_CREDS_EP) return self.resp_success(resp[self.STATUS_KEY]) except socket.error as ex: if ex.errno == errno.ETIMEDOUT: logging.warning('The connection to the Twitter API timed out') except Exception as e: logging.warning('There was an issue verifying the credentials') logging.warning(e) # Checks HTTP response code for success def resp_success(self, status_val): return status_val == self.HTTP_SUCCESS # Executes a GET request and returns the response & data def get_request(self, endpoint): with self.lock: return self.oauthhandler.client.request(endpoint) # Executes a POST request and returns the response & data def post_request(self, endpoint, post_body): with self.lock: return self.oauthhandler.client.request( endpoint, method='POST', body=urllib.urlencode({'status':post_body}), )
def final_clean(self, interrupted=False): FileHandler.delete_dir(self, ConfigHandler.get_temp_dir(self)) if interrupted == True: ''' delete the partially downloaded file if user interrupted the download ''' FileHandler.delete_file(self, self.filepath)
#Apparently all the scripts ran by extention of this have this in their paths, huh. sys.path.extend( ["modules/stockfunctions", "modules/stockclasses", "extern_modules"]) from entity import EntityGroup from floor import Floor from devtools import DevMenu from state import PlayState from confighandler import ConfigHandler cfg = ConfigHandler('thm.cfg') cfg.readConfig() #from modules import * timer = pygame.time.Clock() if int(cfg.getVal('fullscreen')) == 1: screen = pygame.display.set_mode((cfg.getWidth(), cfg.getHeight()), pygame.FULLSCREEN) else: screen = pygame.display.set_mode((cfg.getWidth(), cfg.getHeight())) cheatScreen = pygame.Surface((800, 600)).convert() #pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])
def __init__(self, cut_file, config_file): self.cut_file = open(cut_file, 'r') self.config_reader = ConfigHandler(config_file)
class PlayState: """ The PlayState class. Maintains a list of all entity groups, can update them all, draw them all, return a list of all their sprites, and run the collision system.""" def __init__( self ): self.cfg = ConfigHandler( 'thm.cfg' ) self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = ( 0.0, 0.0 ) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler( 1, 2, callSpeshulEffect ) self.space.add_collision_handler( 2, 2, callSpeshulEffect ) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager( self ) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder={} self.curInputDict = {} self.playersGroup = None self.namedGroups = { 'playersGroup':self.playersGroup } self.lineVisualiser = LineVisualiser( self ) self.rerenderEverything = False self.soundManager = SoundManager( self ) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None def initNetworking( self ): if not self.networkingStarted: #pygnetic.init(logging_lvl=logging.DEBUG) pygnetic.init(logging_lvl=logging.ERROR) self.networkingStarted = True registerMessages() def hostGame( self ): if self.isHost: del self.networkNode._server gc.collect() else: self.isHost = True self.initNetworking() self.networkNode = NetworkServer( self, "", int( self.cfg.getVal("port") ), networkingMode=1 ) self.addGroup( EntityGroup( 'networkPlayers' ), name='networkPlayers' ) print "Beginning hosting..." def connectToGame( self, addr, port ): if self.isClient: del self.networkNode._client gc.collect() else: self.isClient = True self.initNetworking() self.networkNode = NetworkClient( self, networkingMode=1 ) self.networkNode.connect( addr, port ) self.addGroup( EntityGroup( 'networkPlayers' ), name='networkPlayers' ) print "Connecting..." def addBoundary( self, point1, point2 ): newSeg = pymunk.Segment( self.boundaryBody, point1, point2, 1 ) self.boundaries.append( newSeg ) self.space.add( newSeg ) def removeBoundary( self, givenSeg ): self.boundaries.remove( givenSeg ) self.space.remove( givenSeg ) def swap( self, newState ): self.stateToSwap = newState def addInterweaveGroup( self, group, index ): if self.interweaveOrder.get( index, None ) is None: self.interweaveOrder[index] = [group] else: self.interweaveOrder[index].append( group ) def addGroup(self, group, indexValue=None, isPlayerGroupBool=False, name=None, interweaveWithFloor=False): """Add's an entity group to the PlayState. If indexValue specifies the draw-order, defaults to last. isPlayerGroupBool specifies if the group is a group of players (ie, a group that will be sent input dictionaries). If a "name" is given, set PlayState.name = group. interweaveWithFloor means that the entityGroup is drawn with the floor layers instead, drawn after the layer of it's index. Multiple entgroups can share a interweave number, and they'll be drawn according to order of their addition. an interweave index of 0 means it will be drawn AFTER layer 1, the first layer above the background floor""" group.playState = self self.groups.append( group ) if not interweaveWithFloor: newIndex = len( self.groups ) - 1 if indexValue is None: self.drawOrder.append( newIndex ) else: self.drawOrder.insert( indexValue, newIndex ) else: newIndex = len( self.floor.layers ) - 1 if indexValue is None: self.addInterweaveGroup( group, newIndex ) else: self.addInterweaveGroup( group, indexValue ) if isPlayerGroupBool: self.namedGroups['playersGroup'] = group self.playersGroup = group if name is not None: self.namedGroups[name] = group setattr( self, name, group ) def checkForFocus( self ): lostFocus = ( not pygame.mouse.get_focused() ) and self.checkFocus self.pausedByFocus = lostFocus def pause( self ): self.paused = True def unpause( self ): self.paused = False def togglePaused( self ): self.paused = not self.paused def processNetworkEvents( self, dt ): self.gameLogicManager.preNetworkTick( dt ) if self.isHost or self.isClient: if self.networkTicker >= int(60.0/self.networkRate): self.networkNode.update( dt ) self.networkTicker = -1 self.networkNode.updateTime( dt ) self.networkTicker += 1 self.gameLogicManager.postNetworkTick( dt ) def update( self, dt ): """A generic update function. Sends input dictionaries to playerGroups. Updates all the child groups, runs the collision system.""" self.floor.update( self.panX, self.panY ) self.checkForFocus() if self.paused or self.pausedByFocus: self.processNetworkEvents( dt ) return None #Game logic self.gameLogicManager.preTick( dt ) if not self.hardBlockInput: #I'm doing the same thing even if the host or client is the same, to force identical player behaviour for either. if self.isClient or self.isHost: self.inputDictLog.append( self.curInputDict ) if self.networkTicker >= int(60.0/self.networkRate): for eachDict in self.inputDictLog: if self.playersGroup is not None and len( eachDict ) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput( eachDict ) for eachElement in self.hudList: eachElement.sendInput( eachDict ) self.inputDictLog = [] if self.isClient: self.networkNode.sendInput( self.curInputDict ) else: if self.playersGroup is not None and len( self.curInputDict ) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput( self.curInputDict ) for eachElement in self.hudList: eachElement.sendInput( self.curInputDict ) self.curInputDict = {} self.space.step( 1.0/60.0 ) for eachTriplet in self.postStepQueue: eachTriplet[0]( eachTriplet[1], eachTriplet[2] ) self.postStepQueue = [] for eachGroup in self.groups: eachGroup.update( dt ) for eachElement in self.hudList: eachElement.update( dt ) self.soundManager.update( dt ) self.processNetworkEvents( dt ) self.gameLogicManager.postTick( dt ) def setPan( self, x, y ): screenW, screenH = getResolution() if self.limitX1 is not None: x = min( -self.limitX1, x ) if self.limitX2 is not None: x = max( -(self.limitX2-screenW), x ) if self.limitY1 is not None: y = min( -(self.limitY1), y ) if self.limitY2 is not None: y = max( -(self.limitY2-screenH), y ) self.panX, self.panY = x, y def sendInput( self, inputDict ): """Simply sets PlayState.curInputDict to a given input dictionary, for use in PlayState.update()""" self.curInputDict = inputDict def sprites( self ): """Returns a list of all the sprites in all the entity groups in the PlayState.""" sumList = [] for eachSpriteList in [ someGroup.sprites() for someGroup in self.groups ]: sumList.extend( eachSpriteList ) return sumList def draw( self, surface ): """Draw all the child entity groups in PlayState, returning changed area rects""" changeRects = [] changeRects.append( surface.blit( self.floor.layers[0].image, self.floor.layers[0].rect.topleft ) ) if not self.drawByFeet: for eachVal in self.drawOrder: changeRects.extend( self.groups[eachVal].draw( surface ) ) allInterweaveGroups = self.interweaveOrder.values() for eachVal in range( 1, len( self.floor.layers ) ): eachLayer = self.floor.layers[eachVal] changeRects.append( surface.blit( eachLayer.image, eachLayer.rect.topleft ) ) groupsToDraw = self.interweaveOrder.get( eachVal-1, None ) if groupsToDraw is not None: allInterweaveGroups.remove( groupsToDraw ) [ changeRects.extend( each.draw( surface ) ) for each in groupsToDraw ] #Draw anything left over for eachGroupSet in allInterweaveGroups: [ changeRects.extend( eachGroup.draw( surface ) ) for eachGroup in eachGroupSet ] else: yTuples = [] for eachSprite in self.sprites(): if eachSprite.flatInDrawByFeet: y = eachSprite.rect.top else: y = eachSprite.rect.bottom yTuples.append( (y, eachSprite) ) yTuples.extend( [ (each.rect.bottom, each) for each in self.floor.layers[1:] ] ) renderList = [ each[1] for each in sorted( yTuples, lambda x, y: cmp( x[0], y[0] ) ) ] #I probably shouldn't be doing this. tmpDrawGroup = pygame.sprite.LayeredDirty( self.floor.layers[0], renderList ) changeRects.extend( tmpDrawGroup.draw( surface ) ) tmpDrawGroup.empty() del tmpDrawGroup changeRects.extend( self.lineVisualiser.draw( surface, (self.panX, self.panY) ) ) if len( self.gameLogicManager.lasers ) > 0: pt1, pt2 = self.gameLogicManager.getCurAimLine() pygame.draw.line( surface, darkGreen, pt1, pt2 ) for eachShot in self.gameLogicManager.preparedShots: pygame.draw.line( surface, green, eachShot[1][0], eachShot[1][1] ) #for eachMissile in [ each for each in self.genericStuffGroup.sprites() if each.__class__.__name__ == "Missile" ]: #pygame.draw.line( surface, darkRed, eachMissile.getPosition(), eachMissile.startPos, 4 ) for eachElement in self.hudList: eachElement.draw( surface ) changeRects.extend( [ each.rect for each in self.hudList ] ) if self.rerenderEverything: w, h = surface.get_width(), surface.get_height() changeRects.extend( [ pygame.Rect( 0, 0, w, h ) ] ) self.rerenderEverything = False return changeRects # # # This function, __getitem__, takes a value, if that value is a string, it looks for a group in PlayState.groups that has that string as entityGroup.name. # If that value is an int, it returns the group at that index value in self.groups. # def __getitem__( self, value ): if type( value ) == str: for eachGroup in self.groups: if eachGroup.name == value: return eachGroup raise Exception("No group in PlayState by name: " + value) elif type( value ) == int: return self.groups[value] else: raise Exception("PlayState.__getitem__ only takes strs or ints, got: " + str(type( value )) )
class PlayState: """ The PlayState class. Maintains a list of all entity groups, can update them all, draw them all, return a list of all their sprites, and run the collision system.""" def __init__(self): self.cfg = ConfigHandler('thm.cfg') self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = (0.0, 0.0) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler(1, 2, callSpeshulEffect) self.space.add_collision_handler(2, 2, callSpeshulEffect) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager(self) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder = {} self.curInputDict = {} self.playersGroup = None self.namedGroups = {'playersGroup': self.playersGroup} self.lineVisualiser = LineVisualiser(self) self.rerenderEverything = False self.soundManager = SoundManager(self) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None def initNetworking(self): if not self.networkingStarted: #pygnetic.init(logging_lvl=logging.DEBUG) pygnetic.init(logging_lvl=logging.ERROR) self.networkingStarted = True registerMessages() def hostGame(self): if self.isHost: del self.networkNode._server gc.collect() else: self.isHost = True self.initNetworking() self.networkNode = NetworkServer(self, "", int(self.cfg.getVal("port")), networkingMode=1) self.addGroup(EntityGroup('networkPlayers'), name='networkPlayers') print "Beginning hosting..." def connectToGame(self, addr, port): if self.isClient: del self.networkNode._client gc.collect() else: self.isClient = True self.initNetworking() self.networkNode = NetworkClient(self, networkingMode=1) self.networkNode.connect(addr, port) self.addGroup(EntityGroup('networkPlayers'), name='networkPlayers') print "Connecting..." def addBoundary(self, point1, point2): newSeg = pymunk.Segment(self.boundaryBody, point1, point2, 1) self.boundaries.append(newSeg) self.space.add(newSeg) def removeBoundary(self, givenSeg): self.boundaries.remove(givenSeg) self.space.remove(givenSeg) def swap(self, newState): self.stateToSwap = newState def addInterweaveGroup(self, group, index): if self.interweaveOrder.get(index, None) is None: self.interweaveOrder[index] = [group] else: self.interweaveOrder[index].append(group) def addGroup(self, group, indexValue=None, isPlayerGroupBool=False, name=None, interweaveWithFloor=False): """Add's an entity group to the PlayState. If indexValue specifies the draw-order, defaults to last. isPlayerGroupBool specifies if the group is a group of players (ie, a group that will be sent input dictionaries). If a "name" is given, set PlayState.name = group. interweaveWithFloor means that the entityGroup is drawn with the floor layers instead, drawn after the layer of it's index. Multiple entgroups can share a interweave number, and they'll be drawn according to order of their addition. an interweave index of 0 means it will be drawn AFTER layer 1, the first layer above the background floor""" group.playState = self self.groups.append(group) if not interweaveWithFloor: newIndex = len(self.groups) - 1 if indexValue is None: self.drawOrder.append(newIndex) else: self.drawOrder.insert(indexValue, newIndex) else: newIndex = len(self.floor.layers) - 1 if indexValue is None: self.addInterweaveGroup(group, newIndex) else: self.addInterweaveGroup(group, indexValue) if isPlayerGroupBool: self.namedGroups['playersGroup'] = group self.playersGroup = group if name is not None: self.namedGroups[name] = group setattr(self, name, group) def checkForFocus(self): lostFocus = (not pygame.mouse.get_focused()) and self.checkFocus self.pausedByFocus = lostFocus def pause(self): self.paused = True def unpause(self): self.paused = False def togglePaused(self): self.paused = not self.paused def processNetworkEvents(self, dt): self.gameLogicManager.preNetworkTick(dt) if self.isHost or self.isClient: if self.networkTicker >= int(60.0 / self.networkRate): self.networkNode.update(dt) self.networkTicker = -1 self.networkNode.updateTime(dt) self.networkTicker += 1 self.gameLogicManager.postNetworkTick(dt) def update(self, dt): """A generic update function. Sends input dictionaries to playerGroups. Updates all the child groups, runs the collision system.""" self.floor.update(self.panX, self.panY) self.checkForFocus() if self.paused or self.pausedByFocus: self.processNetworkEvents(dt) return None #Game logic self.gameLogicManager.preTick(dt) if not self.hardBlockInput: #I'm doing the same thing even if the host or client is the same, to force identical player behaviour for either. if self.isClient or self.isHost: self.inputDictLog.append(self.curInputDict) if self.networkTicker >= int(60.0 / self.networkRate): for eachDict in self.inputDictLog: if self.playersGroup is not None and len(eachDict) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput(eachDict) for eachElement in self.hudList: eachElement.sendInput(eachDict) self.inputDictLog = [] if self.isClient: self.networkNode.sendInput(self.curInputDict) else: if self.playersGroup is not None and len( self.curInputDict) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput(self.curInputDict) for eachElement in self.hudList: eachElement.sendInput(self.curInputDict) self.curInputDict = {} self.space.step(1.0 / 60.0) for eachTriplet in self.postStepQueue: eachTriplet[0](eachTriplet[1], eachTriplet[2]) self.postStepQueue = [] for eachGroup in self.groups: eachGroup.update(dt) for eachElement in self.hudList: eachElement.update(dt) self.soundManager.update(dt) self.processNetworkEvents(dt) self.gameLogicManager.postTick(dt) def setPan(self, x, y): screenW, screenH = getResolution() if self.limitX1 is not None: x = min(-self.limitX1, x) if self.limitX2 is not None: x = max(-(self.limitX2 - screenW), x) if self.limitY1 is not None: y = min(-(self.limitY1), y) if self.limitY2 is not None: y = max(-(self.limitY2 - screenH), y) self.panX, self.panY = x, y def sendInput(self, inputDict): """Simply sets PlayState.curInputDict to a given input dictionary, for use in PlayState.update()""" self.curInputDict = inputDict def sprites(self): """Returns a list of all the sprites in all the entity groups in the PlayState.""" sumList = [] for eachSpriteList in [ someGroup.sprites() for someGroup in self.groups ]: sumList.extend(eachSpriteList) return sumList def draw(self, surface): """Draw all the child entity groups in PlayState, returning changed area rects""" changeRects = [] changeRects.append( surface.blit(self.floor.layers[0].image, self.floor.layers[0].rect.topleft)) if not self.drawByFeet: for eachVal in self.drawOrder: changeRects.extend(self.groups[eachVal].draw(surface)) allInterweaveGroups = self.interweaveOrder.values() for eachVal in range(1, len(self.floor.layers)): eachLayer = self.floor.layers[eachVal] changeRects.append( surface.blit(eachLayer.image, eachLayer.rect.topleft)) groupsToDraw = self.interweaveOrder.get(eachVal - 1, None) if groupsToDraw is not None: allInterweaveGroups.remove(groupsToDraw) [ changeRects.extend(each.draw(surface)) for each in groupsToDraw ] #Draw anything left over for eachGroupSet in allInterweaveGroups: [ changeRects.extend(eachGroup.draw(surface)) for eachGroup in eachGroupSet ] else: yTuples = [] for eachSprite in self.sprites(): if eachSprite.flatInDrawByFeet: y = eachSprite.rect.top else: y = eachSprite.rect.bottom yTuples.append((y, eachSprite)) yTuples.extend([(each.rect.bottom, each) for each in self.floor.layers[1:]]) renderList = [ each[1] for each in sorted(yTuples, lambda x, y: cmp(x[0], y[0])) ] #I probably shouldn't be doing this. tmpDrawGroup = pygame.sprite.LayeredDirty(self.floor.layers[0], renderList) changeRects.extend(tmpDrawGroup.draw(surface)) tmpDrawGroup.empty() del tmpDrawGroup changeRects.extend( self.lineVisualiser.draw(surface, (self.panX, self.panY))) if len(self.gameLogicManager.lasers) > 0: pt1, pt2 = self.gameLogicManager.getCurAimLine() pygame.draw.line(surface, darkGreen, pt1, pt2) for eachShot in self.gameLogicManager.preparedShots: pygame.draw.line(surface, green, eachShot[1][0], eachShot[1][1]) #for eachMissile in [ each for each in self.genericStuffGroup.sprites() if each.__class__.__name__ == "Missile" ]: #pygame.draw.line( surface, darkRed, eachMissile.getPosition(), eachMissile.startPos, 4 ) for eachElement in self.hudList: eachElement.draw(surface) changeRects.extend([each.rect for each in self.hudList]) if self.rerenderEverything: w, h = surface.get_width(), surface.get_height() changeRects.extend([pygame.Rect(0, 0, w, h)]) self.rerenderEverything = False return changeRects # # # This function, __getitem__, takes a value, if that value is a string, it looks for a group in PlayState.groups that has that string as entityGroup.name. # If that value is an int, it returns the group at that index value in self.groups. # def __getitem__(self, value): if type(value) == str: for eachGroup in self.groups: if eachGroup.name == value: return eachGroup raise Exception("No group in PlayState by name: " + value) elif type(value) == int: return self.groups[value] else: raise Exception( "PlayState.__getitem__ only takes strs or ints, got: " + str(type(value)))
def config(self): return ConfigHandler(self.beets)
import os from confighandler import ConfigHandler if os.path.exists('settings.json') and os.path.exists('settings_default.json'): CONFIG = ConfigHandler('settings.json', os.environ, 'settings_default.json') else: CONFIG = ConfigHandler(os.environ)
class Library: def __init__(self, base_dir, lib_name): self.app = None self.lib_name = lib_name self.base_dir = base_dir self.static_handler = StaticHandler(self.base_dir) self.template_handler = TemplateHandler() self.force_overwrite = False self.config = ConfigHandler(self.get_conf_path()) def exists(self): for file_name in os.listdir(self.base_dir): if file_name == 'library__' + self.lib_name: return True return False def get_lib_path(self): return os.path.join(self.base_dir, 'library__' + self.lib_name) def get_conf_path(self): path = os.path.join(self.get_lib_path(), 'parse_settings.json') if not os.path.isfile(path): raise Exception('Could not find parse_settings.json file.', path) return path def create_folder(self, *args): target = os.path.join(*args) if os.path.isdir(target): return True os.makedirs(target, exist_ok=True) return True def create_file(self, content, *args): target = os.path.join(*args) with open(target, 'w+') as f: f.seek(0) f.write(content) f.truncate() return True def copy_lib_to_target(self, target_path, source_path): target = os.path.join(target_path, self.app['name']) if os.path.exists(target): shutil.rmtree(target) shutil.copytree(source_path, target) return True def parse_file(self, *args): target = os.path.join(*args) if not os.path.exists(target): return False with open(target, 'r+') as f: content = f.read() f.seek(0) f.write( self.template_handler.render_string( content, app=app, current_year=datetime.utcnow().year)) f.truncate() return True def remove_file(self, *args): target = os.path.join(*args) if os.path.exists(target): os.remove(target) return True def generate(self, app, target_folder): self.app = app self.target_folder = target_folder source = self.get_lib_path() # check if lib exists if not self.exists(): raise Exception('Could not find lib.', self.lib_name) # rendering ## license - get self.app['license_content'] = self.template_handler.render_string( self.static_handler.get_file('license', self.app['license_type']), app=app, current_year=datetime.utcnow().year) # check if lib already exists if os.path.exists(os.path.join(self.target_folder, self.app['name'])): overwrite_app = input( 'App {0} already exists. Do you want to overwrite it? (y/N): '. format(self.app['name'])) or 'n' if overwrite_app.upper() == 'N': return False # create file structure self.copy_lib_to_target(target_folder, source) # generate base folder if self.config.get('create_base_folder'): self.app["name_available"] = input( 'Available Name for {}*: '.format(self.app['name'])) if self.app["name_available"] == "": print('Available name is empty. Please try again.') sys.exit('Available name is empty. Please try again.') self.create_folder(target_folder, self.app['name'], *self.app["name_available"].split('.')) # generate content for dynamic files for file_name in self.config.get('files_to_parse'): self.parse_file(target_folder, self.app['name'], file_name.strip()) # create static files for obj in self.config.get('static_files'): instructions = obj.strip().split('>') # get static file content self.create_file(self.static_handler.get_file(instructions[0]), target_folder, self.app['name'], instructions[1]) # remove files for file_name in self.config.get('files_to_delete'): self.remove_file(target_folder, self.app['name'], file_name.strip()) return True
def __init__(self): self.cfg = ConfigHandler('thm.cfg') self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = (0.0, 0.0) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler(1, 2, callSpeshulEffect) self.space.add_collision_handler(2, 2, callSpeshulEffect) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager(self) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder = {} self.curInputDict = {} self.playersGroup = None self.namedGroups = {'playersGroup': self.playersGroup} self.lineVisualiser = LineVisualiser(self) self.rerenderEverything = False self.soundManager = SoundManager(self) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None
pygame.init() #Apparently all the scripts ran by extention of this have this in their paths, huh. sys.path.extend( ["modules/stockfunctions", "modules/stockclasses", "extern_modules"] ) from entity import EntityGroup from floor import Floor from devtools import DevMenu from state import PlayState from confighandler import ConfigHandler cfg = ConfigHandler( 'thm.cfg' ) cfg.readConfig() #from modules import * timer = pygame.time.Clock() if int(cfg.getVal('fullscreen')) == 1: screen = pygame.display.set_mode( (cfg.getWidth(), cfg.getHeight()), pygame.FULLSCREEN ) else: screen = pygame.display.set_mode( (cfg.getWidth(), cfg.getHeight()) ) cheatScreen = pygame.Surface( (800, 600) ).convert() #pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])
def __init__( self ): self.cfg = ConfigHandler( 'thm.cfg' ) self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = ( 0.0, 0.0 ) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler( 1, 2, callSpeshulEffect ) self.space.add_collision_handler( 2, 2, callSpeshulEffect ) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager( self ) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder={} self.curInputDict = {} self.playersGroup = None self.namedGroups = { 'playersGroup':self.playersGroup } self.lineVisualiser = LineVisualiser( self ) self.rerenderEverything = False self.soundManager = SoundManager( self ) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None
class BrocReader(object): """Controls the reading of the output files from the broc""" def __init__(self, cut_file, config_file): self.cut_file = open(cut_file, 'r') self.config_reader = ConfigHandler(config_file) def readfile(self): file_content = [] processes = [] accepted = {} overall = {} line = self.cut_file.readline() # Read over all non-empty lines in the input txt file while line != '': if '=-----------IMPOSED-CUTS-----------=' in line: line = self.cut_file.readline() values = {} while not '=----------------------------------=' in line: if 'identifier:' in line: process,channel,cutset = line.strip('identifier: ').split('|') values['process'] = process+'_'+channel values['cutset'] = cutset.strip('\n') elif 'cuts_passed' in line: values['cuts_passed'] = line.strip('cuts_passed: ').strip('\n') elif 'cuts_overall' in line: values['cuts_overall'] = line.strip('cuts_overall: ').strip('\n') line = self.cut_file.readline() accepted[values['process']] = [] overall[values['process']] = [] file_content.append(values) line = self.cut_file.readline() # Append the read-in values for cuts passed and overall to a dictionary with the process as the key for i in range(0,len(file_content)): accepted[file_content[i]['process']].append(float(file_content[i]['cuts_passed'])) overall[file_content[i]['process']].append(float(file_content[i]['cuts_overall'])) scaled_processes = {} scaled_processes_unc = {} sel_effs = {} # Loop over all processes and calculate the number of events at each cutstep for a given luminosity for process in accepted.keys(): scaled_processes[process] = [] scaled_processes_unc[process] = [] try: preselection = self.config_reader.get_preselection(process) except: # If no defined preselection in config, assume there is none (efficiency = 1) preselection = 1.0 lumi = self.config_reader.get_lumi() # Set the cross section for data so that the PhysicsProcess class knows not to scale it if 'Data' in process: cross_section = -1 else: cross_section = self.config_reader.get_cross_section(process) proc = PhysicsProcess(process) proc.events_accepted(accepted[process]) proc.events_overall(overall[process]) proc.preselection(preselection) proc.cross_section(cross_section) scaled_events,scaled_uncertainties = proc.get_scaled_events(lumi) scaled_processes[process] = scaled_events scaled_processes_unc[process] = scaled_uncertainties sel_effs[process] = [] for i in range(0,len(accepted[process])): sel_effs[process].append(accepted[process][i]/overall[process][i]) return scaled_processes, scaled_processes_unc, sel_effs