def __init__(self, engine, config, section, option, autoApply=False): ConfigChoice.__init__(self, config, section, option, autoApply) self.engine = engine self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("VolumeConfigChoice class init (Settings.py)...")
def __epollIn(self, fileno): try: # 取得当前链接对象 conn = self.__client_connections[fileno] # 取得当前内容 requests = self.__client_requests[fileno] # 取得头信息 header = self.__socket_parser.getHeader(conn) cmd = header["cmd"] if cmd == 0: self.__epoll_close(fileno) return False # 获取内容长度 body_info = self.__socket_parser.getBody(conn, header["body_len"]) # 获取处理程序 handler_name = self.__getHandler(cmd) if len(handler_name) > 0: send_list = eval(handler_name)(body_info) else: send_list = [0, {"error": "cmd not defined"}] self.__send_list = send_list # 处理程序的返回值发送回调用者,返回值格式为[标识符, {}] # self.__socket_parser.send(conn, send_list[0], send_list[1]) # 修改文件描述符为可读状态 self.__epoll.modify(fileno, select.EPOLLOUT) except: Log.error() self.__epoll_close(fileno) return False
def set(self, section, option, value): """ Set the value of a configuration key. @param section: Section name @param option: Option name @param value: Value name """ try: prototype[section][option] except KeyError: Log.warn("Config key %s.%s not defined while writing." % (section, option)) if not self.config.has_section(section): self.config.add_section(section) if type(value) == unicode: value = value.encode(encoding) else: value = str(value) self.config.set(section, option, value) f = open(self.fileName, "w") self.config.write(f) f.close()
def loadPackage(self,loadInfo): if self.package == None: return self.log(u'loadPackage Start') ff = FileLoader.load(self.package,loadData=False) if ff.state != FileLoader.idOk: return try: zf = zipfile.ZipFile(ff.target) for name in zf.namelist(): index = name.rfind('/') if index != -1: folder = name[:index] if name.endswith('.txt'): try: bundle = os.path.join(self.cache, name.replace('/','_')) self.log(u'Load {0}'.format(bundle)) with open(bundle, 'wb') as ff: ff.write(zf.read(name)) self.loadBundle(bundle,loadInfo) if loadInfo.isFetchAll(): return except Exception, ee: Log.log(Text.formatException(ee)) except Exception, ee: Log.log(Text.formatException(ee))
def keyName(value): if value in CONTROL1: name = "Controller 1" control = CONTROL1 n = 0 elif value in CONTROL2: name = "Controller 2" control = CONTROL2 n = 1 elif value in CONTROL3: name = "Controller 3" control = CONTROL3 n = 2 else: name = "Controller 4" control = CONTROL4 n = 3 for j in range(20): if value == control[j]: if self.type[n] == 2: return name + " " + drumkey4names[j] elif self.type[n] == 3: return name + " " + drumkey5names[j] else: return name + " " + guitarkeynames[j] else: Log.notice("Key value not found.") return "Error"
def disableScreensaver(self): if os.name == 'nt': # See the DisableScreensaver and RestoreScreensaver functions in # modules/video_output/msw/common.c in the source code for VLC. import win32gui import win32con import atexit Log.debug('Disabling screensaver.') old_lowpowertimeout = win32gui.SystemParametersInfo(win32con.SPI_GETLOWPOWERTIMEOUT) if old_lowpowertimeout != 0: atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETLOWPOWERTIMEOUT, old_lowpowertimeout)) win32gui.SystemParametersInfo(win32con.SPI_SETLOWPOWERTIMEOUT, 0) old_powerofftimeout = win32gui.SystemParametersInfo(win32con.SPI_GETPOWEROFFTIMEOUT) if old_powerofftimeout != 0: atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETPOWEROFFTIMEOUT, old_powerofftimeout)) win32gui.SystemParametersInfo(win32con.SPI_SETPOWEROFFTIMEOUT, 0) old_screensavetimeout = win32gui.SystemParametersInfo(win32con.SPI_GETSCREENSAVETIMEOUT) if old_screensavetimeout != 0: atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETSCREENSAVETIMEOUT, old_screensavetimeout)) win32gui.SystemParametersInfo(win32con.SPI_SETSCREENSAVETIMEOUT, 0) else: Log.debug('Screensaver disabling is not implemented on this platform.')
def get(self, section, option): """ Read a configuration key. @param section: Section name @param option: Option name @return: Key value """ try: type = self.prototype[section][option].type default = self.prototype[section][option].default except KeyError: Log.warn("Config key %s.%s not defined while reading." % (section, option)) type, default = str, None value = self.config.has_option(section, option) and self.config.get(section, option) or default if type == bool: value = str(value).lower() if value in ("1", "true", "yes", "on"): value = True else: value = False else: try: value = type(value) except: value = None #Log.debug("%s.%s = %s" % (section, option, value)) return value
def showTutorial(self): # evilynux - Make sure tutorial exists before launching #tutorialpath = self.engine.getPath(os.path.join("songs","tutorial")) tutorialpath = self.engine.tutorialFolder if not os.path.isdir(self.engine.resource.fileName(tutorialpath)): Log.debug("No folder found: %s" % tutorialpath) Dialogs.showMessage(self.engine, _("No tutorials found!")) return if self.engine.isServerRunning(): return players = Dialogs.activateControllers(self.engine, 1) #akedrou if players == 0: return Config.set("game","game_mode", 0) #MFH - ensure tutorial can work with new logic that depends on this mode variable Config.set("game","multiplayer_mode", 0) #MFH - ensure tutorial can work with new logic that depends on this mode variable Config.set("game", "players", 1) Config.set("game", "tut", True) #Config.set("game","game_mode", 1) #MFH - don't force practice mode.... this is problematic. self.engine.startServer() self.engine.resource.load(self, "session", lambda: self.engine.connect("127.0.0.1"), synch = True) if Dialogs.showLoadingScreen(self.engine, lambda: self.session and self.session.isConnected): self.launchLayer(lambda: Lobby(self.engine, self.session, singlePlayer = True))
def popLayer(self, layer): Log.debug("View: Pop: %s" % layer.__class__.__name__) if layer in self.incoming: self.incoming.remove(layer) if layer in self.layers and not layer in self.outgoing: self.outgoing.append(layer)
def __init__(self, engine, infoFileName, songTrackName, guitarTrackName, rhythmTrackName, noteFileName, scriptFileName = None, partlist = [parts[GUITAR_PART]]): self.engine = engine self.info = SongInfo(infoFileName) self.tracks = [[Track() for t in range(len(difficulties))] for i in range(len(partlist))] self.difficulty = [difficulties[AMAZING_DIFFICULTY] for i in partlist] self._playing = False self.start = 0.0 self.noteFileName = noteFileName self.bpm = None self.period = 0 self.parts = partlist self.delay = self.engine.config.get("audio", "delay") self.delay += self.info.delay self.missVolume = self.engine.config.get("audio", "miss_volume") #RF-mod skip if folder (not needed anymore?) #if self.info.folder == True: # return # load the tracks if songTrackName: self.music = Audio.Music(songTrackName) self.guitarTrack = None self.rhythmTrack = None try: if guitarTrackName: self.guitarTrack = Audio.StreamingSound(self.engine, self.engine.audio.getChannel(1), guitarTrackName) except Exception, e: Log.warn("Unable to load guitar track: %s" % e)
def convertToTexture(self, width, height): if self.texture: return e = "SVG drawing does not have a valid texture image." Log.error(e) raise RuntimeError(e)
def __init__(self, infoFileName): self.songName = os.path.basename(os.path.dirname(infoFileName)) self.fileName = infoFileName self.info = ConfigParser() self._difficulties = None try: self.info.read(infoFileName) except: pass # Read highscores and verify their hashes. # There ain't no security like security throught obscurity :) self.highScores = {} scores = self._get("scores", str, "") if scores: scores = Cerealizer.loads(binascii.unhexlify(scores)) for difficulty in scores.keys(): try: difficulty = difficulties[difficulty] except KeyError: continue for score, stars, name, hash in scores[difficulty.id]: if self.getScoreHash(difficulty, score, stars, name) == hash: self.addHighscore(difficulty, score, stars, name) else: Log.warn("Weak hack attempt detected. Better luck next time.")
def onINVITE(self, message): Log.logTest("rejecting received INVITE with 603") repl = self.createReply(603, "Decline") self.writeMessageToNetwork(self.neh, repl) ack = self.readRequestFromNetwork(self.neh) if ack is None: self.addResult(TestCase.TC_ERROR, "missing ACK on negative reply")
def run(self): try: return self.mainloop() except KeyboardInterrupt: sys.exit(0) except SystemExit: sys.exit(0) except Exception, e: def clearMatrixStack(stack): try: glMatrixMode(stack) for i in range(16): glPopMatrix() except: pass if self.handlingException: # A recursive exception is fatal as we can't reliably reset the GL state sys.exit(1) self.handlingException = True Log.error("%s: %s" % (e.__class__, e)) import traceback traceback.print_exc() clearMatrixStack(GL_PROJECTION) clearMatrixStack(GL_MODELVIEW) Dialogs.showMessage(self, unicode(e)) self.handlingException = False return True
def __init__(self): Task.__init__(self) self.mouse = pygame.mouse self.mouseListeners = [] self.keyListeners = [] self.systemListeners = [] self.priorityKeyListeners = [] self.controls = Controls() self.disableKeyRepeat() # Initialize joysticks pygame.joystick.init() self.joystickAxes = {} self.joystickHats = {} self.joysticks = [pygame.joystick.Joystick(id) for id in range(pygame.joystick.get_count())] for j in self.joysticks: j.init() self.joystickAxes[j.get_id()] = [0] * j.get_numaxes() self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats() Log.debug("%d joysticks found." % (len(self.joysticks))) # Enable music events Audio.Music.setEndEvent(MusicFinished) # Custom key names self.getSystemKeyName = pygame.key.name pygame.key.name = self.getKeyName
def create_path(self, ccpath): """ Creates a complete route of directories matching the given path. Raises CCError exception when the creation of any directory fails. """ Log.debug("Creating new path:" + ccpath) # Split path in directories dirs = ccpath.split(os.sep) # Because ccpath starts with os.sep the first element in dirs # will be the "" and must be deleted del dirs[0] current = os.sep for dir_name in dirs: current += dir_name # Create directory only if it did not exist previously if not os.path.isdir(current): try: self.create_dir(current) except: raise current += os.sep
def list_checkouts_in_all_vobs(self): """ List checkouts in all the configured vobs. """ colist_in_vobs = [] vobs = self._config.get_vobs() vobs_to_string = " ".join(str(x) for x in vobs) Log.debug("list_checkouts in all vobs : " + vobs_to_string) if not vobs: colist_in_vobs = self.list_checkouts("") else: for vob in vobs: colist_in_vobs.extend (self.list_checkouts(vob)) list_of_checkouts = " ".join(str(x) for x in colist_in_vobs) Log.debug("Final list_checkout in all vobs : " + vobs_to_string + " list of checkouts : " + list_of_checkouts) return colist_in_vobs
def exists_label(self, label, ccpath): """ Check if a label exists Raises CCError exception when the command fails. """ result = False prevdir = os.getcwd() parent = os.path.dirname(ccpath) os.chdir(parent) try: p = subprocess.Popen([self._config.get_cleartool_path(), "lstype", "lbtype:" + label], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() except: Log.error (ccpath + self._("exists_label_failed") + str(sys.exc_info())) os.chdir (prevdir) if p.returncode == 0 and out[1] != "Error:": result = True return result
def create_dir(self, ccpath): """ Creates a new directory in ClearCase. Raises CCError exception when the command fails. """ Log.debug("create_dir:"+ccpath) if not os.path.isdir(ccpath): parent = ccpath # Remove last / when necessary if parent[len(parent) - 1] == os.sep: parent = parent[:-1] # Get parent directory parent = os.path.dirname(parent) if not os.path.isdir(parent): raise CCError(parent + self._("not_in_CC")) # Only create dir if not versioned in CC if not self.is_versioned(ccpath): if not self.is_checkout(parent): # Check out parent directory self.checkout(parent, self._("CC_dir_modification_comment")) try: # Create new directory p = subprocess.Popen([self._config.get_cleartool_path(), "mkdir", "-c", self._("new_CC_folder"), ccpath], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() self.checkin(parent) self.checkin(ccpath) except: raise CCError(ccpath + self._("creation_failed") + str(sys.exc_info())) if p.returncode != 0: raise CCError(ccpath + self._("creation_failed") + str(err)) else: raise CCError(ccpath + self._("already_in_CC"))
def parse_methode_call_response(c, data): call = {} call["flags"] = get_number(data[0:4]) Log.info(" BinaryMethodeResponse:") Log.info(" Flags: %d" % call["flags"]) c["MethodeResponse"] = call return parse_methode_call_array(c, data[4:])
def add(self, surface, margin=0): w, h = surface.get_size() x, y = self.cursor w += margin h += margin if w > self.texture.pixelSize[0] or h > self.texture.pixelSize[1]: raise ValueError("Surface is too big to fit into atlas.") if x + w >= self.texture.pixelSize[0]: x = 0 y += self.rowHeight self.rowHeight = 0 if y + h >= self.texture.pixelSize[1]: Log.debug("Texture atlas %s full after %d surfaces." % (self.texture.pixelSize, self.surfaceCount)) raise TextureAtlasFullException() self.texture.loadSubsurface(surface, position=(x, y), alphaChannel=True) self.surfaceCount += 1 self.rowHeight = max(self.rowHeight, h) self.cursor = (x + w, y + h) # Return the coordinates for the uploaded texture patch w -= margin h -= margin return ( x / float(self.texture.pixelSize[0]), y / float(self.texture.pixelSize[1]), (x + w) / float(self.texture.pixelSize[0]), (y + h) / float(self.texture.pixelSize[1]), )
def main(): parser = argparse.ArgumentParser(description='Utility to take " \ + "snapshots of git repositories at specified (in months) interval') #project specific arguments parser.add_argument("config_file", \ help = "This is the path to your configuration file.") #logging and config specific arguments parser.add_argument("-v", "--verbose", default = 'w', nargs="?", \ help="increase verbosity: d = debug, i = info, w = warnings, e = error, c = critical. " \ "By default, we will log everything above warnings.") parser.add_argument("--log", dest="log_file", default='log.txt', \ help="file to store the logs, by default it will be stored at log.txt") args = parser.parse_args() Util.cleanup(args.log_file) Log.setLogger(args.verbose, args.log_file) config_info = ConfigInfoSZZ(args.config_file) downloadSnapshots(config_info)
def getOptions(self, section, option): """ Read the preset options of a configuration key. @param section: Section name @param option: Option name @return: Tuple of Key list and Values list """ try: options = self.prototype[section][option].options.values() keys = self.prototype[section][option].options.keys() type = self.prototype[section][option].type except KeyError: Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName)) raise optionList = [] if type != None: for i in range(len(options)): value = _convertValue(keys[i], type) optionList.append(value) return optionList, options
def __init__(self, engine, controlnum, samprate=44100): Task.__init__(self) self.engine = engine self.controlnum = controlnum devnum = self.engine.input.controls.micDevice[controlnum] if devnum == -1: devnum = None self.devname = pa.get_default_input_device_info()['name'] else: self.devname = pa.get_device_info_by_index(devnum)['name'] self.mic = pa.open(samprate, 1, pyaudio.paFloat32, input=True, input_device_index=devnum, start=False) if Config.get('game', 'use_new_pitch_analyzer') or not have_pypitch: self.analyzer = Analyzer(samprate) else: self.analyzer = pypitch.Analyzer(samprate) self.mic_started = False self.lastPeak = 0 self.detectTaps = True self.tapStatus = False self.tapThreshold = -self.engine.input.controls.micTapSensitivity[controlnum] self.passthroughQueue = [] passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum] if passthroughVolume > 0.0: Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100)) self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self) self.passthroughStream.setVolume(passthroughVolume) else: Log.debug('Microphone: not creating passthrough stream') self.passthroughStream = None
def __init__(self, config, section, option, autoApply = False): self.config = config Log.debug("ConfigChoice class init (Settings.py)...") self.section = section self.option = option self.changed = False self.value = None self.autoApply = autoApply o = config.prototype[section][option] v = config.get(section, option) if isinstance(o.options, dict): values = o.options.values() values.sort() try: valueIndex = values.index(o.options[v]) except KeyError: valueIndex = 0 elif isinstance(o.options, list): values = o.options try: valueIndex = values.index(v) except ValueError: valueIndex = 0 else: raise RuntimeError("No usable options for %s.%s." % (section, option)) Menu.Choice.__init__(self, text = o.text, callback = self.change, values = values, valueIndex = valueIndex)
def __init__(self, context, ImgData): self.ImgData = None self.texture = None self.context = context self.cache = None self.filename = ImgData # Detect the type of data passed in if type(ImgData) == file: self.ImgData = ImgData.read() elif type(ImgData) == str: self.texture = Texture(ImgData) elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in self.texture = Texture() self.texture.loadImage(ImgData) # Make sure we have a valid texture if not self.texture: if type(ImgData) == str: e = "Unable to load texture for %s." % ImgData else: e = "Unable to load texture for SVG file." Log.error(e) raise RuntimeError(e) self.pixelSize = self.texture.pixelSize self.position = [0.0,0.0] self.scale = [1.0,1.0] self.angle = 0 self.color = (1.0,1.0,1.0) self.rect = (0,1,0,1) self.shift = -.5 self.createArrays()
def collectData(db): global lock if db.connect(): try: Control.getSettings (db)#Control sistema calefaccio records=db.select("SELECT ipv6,thingToken FROM motes where type=0 and thingToken IS NOT NULL and thingToken !=''") lowTemp=False#Control sistema calefaccio for row in records: try: ipv6=str(row[0]) temp =ObjectCoAP.sendGET(ipv6,'temp' ) if temp is not None: tempValue = ConvertValue.getTemperature(temp) if not lowTemp: #Control sistema calefaccio lowTemp = Control.checkTemp(tempValue) #Control sistema calefaccio hum =ObjectCoAP.sendGET(ipv6,'hum' ) if hum is not None: humValue=ConvertValue.getHumidity(hum) if (tempValue or humValue) is not None: send=SendDataToServer(lock,tempValue,humValue,ipv6,str(row[1]))#Emmagatzematge a thethings.iO send.start()#Emmagatzematge a thethings.iO except: Log.writeError( "No hi ha comunicacio amb la mota "+ ipv6) pass Control.checkAction(lowTemp)#Control sistema calefaccio except: pass db.close()
def __init__(self, owner, name, number): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("Player class init (Player.py)...") self.owner = owner self.controls = Controls() self.reset() self.playerstring = "player" + str(number) self.whichPart = Config.get(self.playerstring, "part") self.bassGrooveEnableMode = Config.get("game", "bass_groove_enable") self.currentTheme = 1 #MFH - need to store selected practice mode and start position here self.practiceMode = False self.practiceSection = None self.startPos = 0.0 self.hopoFreq = None self.stars = 0 self.totalStreakNotes = 0 self.totalNotes = 0
def load_alarms(filename): # Dictionary from alarm names -> commands l = {} # Parse the file a line at a time (comment lines start with #) fh = open(filename, 'r') for line in fh: if len(line.strip()) > 0 and line[0] != '#': # Split on spaces or tabs split_chars = [' ', '\t'] found_split = False values = ['', []] for char in line.strip(): if char not in split_chars: # Characters before the first split are part of the name, characters after # the split are part of the command if not found_split: values[0] += char else: values[1][-1] += char else: found_split = True if len(values[1]) == 0 or len(values[1][-1]) > 0: values[1].append('') # First value is the alarm name, second is the command if values[0] not in l: l[values[0]] = values[1] Log.debug('Loaded alarm "%s" => "%s"' % (values[0], ' '.join(values[1]))) else: Log.warning('Multiple definitions for alarm "%s"; using first definition only.', values[0]) fh.close() return l
def parse_methode_call_record(data, start): record = {} r_type = ord(data[start]) if r_type == 1: # ClassWithId return parse_record_classwithid(data, start) elif r_type == 3: # ClassWithMembers return parse_record_classwithmembers(data, start) elif r_type == 4: # SystemClassWithMembersAndTypes return parse_record_systemclasswithmembersandtypes(data, start) elif r_type == 5: # ClassWithMembersAndTypes return parse_record_classwithmembersandtypes(data, start) elif r_type == 6: # BinaryObjectString return parse_record_binaryobjectstring(data, start) elif r_type == 7: # BinaryArray return parse_record_binaryarray(data, start) elif r_type == 8: # MemberPrimitiveType return parse_record_memberprimitivetype(data, start) elif r_type == 9: # MemberReference return parse_record_memberreference(data, start) elif r_type == 10: # ObjectNull return parse_record_objectnull(data, start) # 11 == messageend elif r_type == 12: # BinaryLibrary return parse_record_binarylibrary(data, start) # 13 == ObjectNullMultible256 # 14 == ObjectNullMultible elif r_type == 15: # ArraySinglePrimitive return parse_record_arraysingleprimitive(data, start) elif r_type == 16: # ArraySingleObject return parse_record_arraysingleobject(data, start) Log.error("Unkown Record Type: %d" % r_type) Log.print_hex(data[start:]) return None, start + 1
def sendMessage(self, receiverId, message): try: self.sessions[receiverId].sendMessage(message) except IndexError: Log.warning("Tried to send message to nonexistent session #%d." % receiverId)
def __init__(self, guitarScene, configFileName): self.scene = guitarScene self.engine = guitarScene.engine self.config = Config.MyConfigParser() self.backgroundLayers = [] self.foregroundLayers = [] self.textures = {} self.reset() self.wFull = None #MFH - needed for new stage background handling self.hFull = None # evilynux - imported myfingershurt stuff from GuitarScene self.mode = self.engine.config.get("game", "stage_mode") self.songStage = self.engine.config.get("game", "song_stage") self.animatedFolder = self.engine.config.get("game", "animated_stage_folder") # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs #MFH TODO - alter logic to accomodate separated animation and slideshow # settings based on seleted animated stage folder animationMode = self.engine.config.get("game", "stage_animate") slideShowMode = self.engine.config.get("game", "rotate_stages") if self.animatedFolder == _("None"): self.rotationMode = 0 #MFH: if no animated stage folders are available, disable rotation. elif self.animatedFolder == "Normal": self.rotationMode = slideShowMode else: self.rotationMode = animationMode self.imgArr = [] #QQstarS:random self.imgArrScaleFactors = [] #MFH - for precalculated scale factors self.rotateDelay = self.engine.config.get( "game", "stage_rotate_delay" ) #myfingershurt - user defined stage rotate delay self.animateDelay = self.engine.config.get( "game", "stage_animate_delay" ) #myfingershurt - user defined stage rotate delay self.animation = False self.indexCount = 0 #QQstarS:random time counter self.arrNum = 0 #QQstarS:random the array num self.arrDir = 1 #forwards self.config.read(configFileName) # evilynux - Improved stage error handling self.themename = self.engine.data.themeLabel self.path = os.path.join("themes", self.themename, "stages") self.pathfull = self.engine.getPath(self.path) if not os.path.exists(self.pathfull): # evilynux Log.warn("Stage folder does not exist: %s" % self.pathfull) self.mode = 1 # Fallback to song-specific stage suffix = ".jpg" # Build the layers for i in range(32): section = "layer%d" % i if self.config.has_section(section): def get(value, type=str, default=None): if self.config.has_option(section, value): return type(self.config.get(section, value)) return default xres = get("xres", int, 256) yres = get("yres", int, 256) texture = get("texture") try: drawing = self.textures[texture] except KeyError: drawing = self.engine.loadImgDrawing( self, None, os.path.join("themes", self.themename, texture), textureSize=(xres, yres)) self.textures[texture] = drawing layer = Layer(self, drawing) layer.position = (get("xpos", float, 0.0), get("ypos", float, 0.0)) layer.scale = (get("xscale", float, 1.0), get("yscale", float, 1.0)) layer.angle = math.pi * get("angle", float, 0.0) / 180.0 layer.srcBlending = globals()["GL_%s" % get( "src_blending", str, "src_alpha").upper()] layer.dstBlending = globals()["GL_%s" % get( "dst_blending", str, "one_minus_src_alpha").upper()] layer.color = (get("color_r", float, 1.0), get("color_g", float, 1.0), get("color_b", float, 1.0), get("color_a", float, 1.0)) # Load any effects fxClasses = { "light": LightEffect, "rotate": RotateEffect, "wiggle": WiggleEffect, "scale": ScaleEffect, } for j in range(32): fxSection = "layer%d:fx%d" % (i, j) if self.config.has_section(fxSection): type = self.config.get(fxSection, "type") if not type in fxClasses: continue options = self.config.options(fxSection) options = dict([(opt, self.config.get(fxSection, opt)) for opt in options]) fx = fxClasses[type](layer, options) layer.effects.append(fx) if get("foreground", int): self.foregroundLayers.append(layer) else: self.backgroundLayers.append(layer)
def __init__(self, engine): self.engine = engine self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("MainMenu class init (MainMenu.py)...") self.time = 0.0 self.nextLayer = None self.visibility = 0.0 self.active = False Player.practiceMode = False #myfingershurt: removing neck menu requirement: #self.neckMenuEnabled = False #self.neckMenuEnabled = Config.get("game", "neck_select_enabled") self.gfxVersionTag = Config.get("game", "gfx_version_tag") #self.tut = Config.get("game", "tut") self.chosenNeck = Config.get("game", "default_neck") exists = 0 #neck fallback to random if doesn't exist. try: # evilynux - first assume the chosenNeck contains the full filename engine.loadImgDrawing(self, "ok", os.path.join("necks",self.chosenNeck+".png")) except IOError: try: engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_"+self.chosenNeck+".png")) except IOError: pass else: exists = 1 else: exists = 1 #MFH - fallback logic now supports a couple valid default neck filenames #MFH - check for Neck_1 if exists == 0: try: engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_1.png")) except IOError: pass else: Config.set("game", "default_neck", "1") Log.warn("Default chosen neck not valid; fallback Neck_1.png forced.") exists = 1 #MFH - check for defaultneck if exists == 0: try: engine.loadImgDrawing(self, "ok", os.path.join("necks","defaultneck.png")) except IOError: #we don't really need to be accepting this except... ...yea, sorry. raise IOError, "Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!" else: Log.warn("Default chosen neck not valid; fallback defaultneck.png forced.") Config.set("game", "default_neck", "defaultneck") exists = 1 dPlayerConfig = None #Get theme self.theme = self.engine.data.theme self.themeCoOp = self.engine.data.themeCoOp self.themename = self.engine.data.themeLabel self.useSoloMenu = Theme.use_solo_submenu try: #blazingamer self.menux = Theme.menuX self.menuy = Theme.menuY except Exception, e: Log.warn("Unable to load Theme menuX / Y positions: %s" % e) self.menux = None self.menuy = None
def render(self, visibility, topMost): self.engine.view.setViewport(1,0) self.visibility = visibility if self.rbmenu: v = 1.0 - ((1 - visibility) ** 2) else: v = 1 if v == 1: self.engine.view.transitionTime = 1 if self.menu.active and not self.active: self.active = True t = self.time / 100 w, h, = self.engine.view.geometry[2:4] r = .5 if not self.useSoloMenu: if self.active: if self.engine.view.topLayer() is not None: if self.optionsBG != None: self.engine.drawImage(self.optionsBG, (self.opt_bkg_size[2],-self.opt_bkg_size[3]), (w*self.opt_bkg_size[0],h*self.opt_bkg_size[1]), stretched = 3) self.engine.drawImage(self.optionsPanel, (0.5,-0.5), (w/1.7, h/2)) else: self.engine.drawImage(self.engine.data.loadingImage, (0.5,-0.5), (w/2, h/2), stretched = 3) if self.menu.active: if self.background != None: #MFH - auto-scaling self.engine.drawImage(self.background, (1.0,-1.0), (w/2, h/2), stretched = 3) for i in range(0,6): #Item selected if self.menu.currentIndex == i: xpos = (.5,1) #Item unselected else: xpos = (0,.5) #which item? ypos = 1/6.0*i #============blazingamer============ #if menux and/or menuy are not set it will use the default positions for the main text if self.menux == None or self.menuy == None: if self.theme == 0: textcoord = (w*0.5,h*0.45-(h*self.main_menu_vspacing)*i) elif self.theme == 1: textcoord = (w*0.7,h*0.8-(h*self.main_menu_vspacing)*i) #if menux and menuy are set it will use those else: try: textcoord = (w*self.menux,h*self.menuy-(h*self.main_menu_vspacing)*i) except Exception, e: Log.warn("Unable to translate BGText: %s" % e) #=================================== self.engine.drawImage(self.BGText, (.5*self.main_menu_scale,-1/6.0*self.main_menu_scale), textcoord, rect = (xpos[0],xpos[1],ypos,ypos+1/6.0))
xpos = (.5,1) #Item unselected else: xpos = (0,.5) #which item? ypos = 1/5.0*i #============blazingamer============ #if menux and/or menuy are not set it will use the default positions for the main text if self.menux == None or self.menuy == None: textcoord = (w*0.2,(h*0.8-(h*self.main_menu_vspacing)*i)*v) #if menux and menuy are set it will use those else: try: textcoord = (w*self.menux,(h*self.menuy-(h*self.main_menu_vspacing)*i)*v) except Exception, e: Log.warn("Unable to translate BGText: %s" % e) #=================================== self.engine.drawImage(self.BGText, (.5*self.main_menu_scale,(-1/5.0*self.main_menu_scale)), textcoord, rect = (xpos[0],xpos[1],ypos,ypos+1/5.0)) #racer: added version tag to main menu: if self.version != None: wfactor = self.version.widthf(pixelw = 640.000) self.engine.drawImage(self.version, (0.5,-0.5),(w*Theme.versiontagposX, h*Theme.versiontagposY)) #worldrave - Added theme settings to control X+Y positions of versiontag.
def __init__(self, engine, choices, onClose=None, onCancel=None, pos=(.2, .66 - .35), viewSize=6, fadeScreen=False, font="font", mainMenu=None, textColor=None, selectedColor=None, append_submenu_char=True): self.engine = engine Log.debug("Menu class init (Menu.py)...") #Get theme themename = self.engine.data.themeLabel self.theme = self.engine.data.theme self.choices = [] self.currentIndex = 0 self.time = 0 self.onClose = onClose self.onCancel = onCancel self.viewOffset = 0 self.mainMenu = False self.textColor = textColor self.selectedColor = selectedColor self.sfxVolume = self.engine.config.get("audio", "SFX_volume") if pos == ( .2, .66 - .35 ): #MFH - default position, not called with a special one - this is a submenu: self.sub_menu_x = Theme.sub_menu_xVar self.sub_menu_y = Theme.sub_menu_yVar if engine.data.theme == 0: if self.sub_menu_x == None: self.sub_menu_x = .44 if self.sub_menu_y == None: self.sub_menu_y = .14 elif engine.data.theme == 1: if self.sub_menu_x == None: self.sub_menu_x = .38 if self.sub_menu_y == None: self.sub_menu_y = .15 elif engine.data.theme == 2: if self.sub_menu_x == None: self.sub_menu_x = .25 if self.sub_menu_y == None: self.sub_menu_y = .14 pos = (self.sub_menu_x, self.sub_menu_y) if viewSize == 6: #MFH - default viewsize if self.theme == 0 or self.theme == 1 or self.theme == 2: #8bit viewSize = 10 self.pos = pos self.viewSize = viewSize self.fadeScreen = fadeScreen self.font = font self.active = False self.mainMenu = mainMenu for c in choices: try: text, callback = c if isinstance(text, tuple): c = Choice(text[0], callback, values=text[2], valueIndex=text[1], append_submenu_char=append_submenu_char) else: c = Choice(text, callback, append_submenu_char=append_submenu_char) except TypeError: pass self.choices.append(c)
engine.setDebugModeEnabled(not engine.isDebugModeEnabled()) engine.debugLayer.debugOut(engine) engine.quit() break encoding = Config.get("game", "encoding") if encoding != None: reload(sys) sys.setdefaultencoding(encoding) engine.setStartupLayer(MainMenu(engine)) try: import psyco psyco.profile() except: Log.warn("Unable to enable psyco.") try: while engine.run(): pass except KeyboardInterrupt: pass if engine.restartRequested: Log.notice("Restarting.") engine.audio.close() try: # Determine whether were running from an exe or not if hasattr(sys, "frozen"): if os.name == "nt": os.execl("FretsOnFire.exe", "FretsOnFire.exe", *sys.argv[1:])
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### import Log import Audio import math from PitchAnalyzer import Analyzer import numpy import Config try: import pyaudio supported = True except ImportError: Log.warn('Missing pyaudio - microphone support will not be possible') supported = False try: import pypitch have_pypitch = True except ImportError: have_pypitch = False from Task import Task from Language import _ if supported: pa = pyaudio.PyAudio() # Precompute these in the interest of saving CPU time in the note analysis loop
#fp = open('/tmp/hexfilter','a') NET_SETTINGS = { 'mainnet': { 'log': '/media/vdb1/dclavijo/chaindb/addrscript.log', 'db': '/media/vdb1/dclavijo/chaindb' }, 'testnet3': { 'log': '/tmp/testtestscript.log', 'db': '/tmp/chaintest' } } MY_NETWORK = 'mainnet' SETTINGS = NET_SETTINGS[MY_NETWORK] log = Log.Log(SETTINGS['log']) #mempool = MemPool.MemPool(log) SKIP_TX = [] msg_start = "f9beb4d9".decode('hex') def chaindb_init(): chaindb = ChainDb.ChainDb(SETTINGS, SETTINGS['db'], log, "", NETWORKS[MY_NETWORK], True) chaindb.blk_cache.max = 1000 return chaindb def scan_tx(chaindb, tx, height):
def handleConnectionOpen(self, conn): Log.debug("Session #%d connected." % conn.id) self.sessions[conn.id] = conn self.engine.addTask(conn, synchronized=False)
def log_debug(info): global __debug_flag if __debug_flag: Log.log_trace(info, Log.DEBUG_LEVEL)
parser = OptionParser( usage="usage: %prog SerialNumber TestResult TestErrorCode", version="0.1") (options, args) = parser.parse_args() if len(args) != 3: sys.exit( "Usage: LocalSaveResult.py SerialNumber TestResult TestErrorCode") home_dir = os.environ['FT'] config = Configure(home_dir + '/BFTConfig.txt') config.Put('HOME_DIR', home_dir) #SN = 'fzhb30500040' config.Put('CanisterSN', args[0]) log = Log() log.Open('test.log') config.Put('TestResult', args[1]) config.Put('ErrorCode', args[2]) timeStampStart = datetime.now().strftime("%Y-%m-%d %H:%M:%S") time.sleep(10) timeStampEnd = datetime.now().strftime("%Y-%m-%d %H:%M:%S") config.Put('StartTime', timeStampStart) config.Put('EndTime', timeStampEnd) #config.Put('flexflow_group', [['2014-08-04 15:28:32', '0:00:44', 'BmcSelClear', '26010']]) config.Put('flexflow_group', []) print config.Get('PcbaSN') print config.Get('TestResult') print config.Get('ErrorCode') print config.Get('StartTime')
log_path = result_path + 'log.txt' def save_img(imgs, path): if not os.path.exists(result_path + path): os.mkdir(result_path + path) for i in range(imgs.shape[0]): plt.figure(figsize=(4.32, 2.88)) if i % 50 == 0: print('saving ' + path + ':', i) plt.imshow((imgs[i, :, :, 0]), cmap='gray', interpolation="bicubic") plt.savefig(result_path + path + '/' + str(i) + '.jpg') plt.close() Log.Log(log_path, 'w+', 1) # set log file fine_tfrecords_trainpath = '../transferlearning_dataset/mnist_train_data.tfrecords' fine_tfrecords_testpath = '../transferlearning_dataset/mnist_test_data.tfrecords' train_data_batch, train_label_batch = Get_data.read_and_decode( fine_tfrecords_trainpath, batch_size=Option.batch_size, data_name='train_data', label_name='train_label') test_data_batch, test_label_batch = Get_data.read_and_decode( fine_tfrecords_testpath, batch_size=Option.batch_size, data_name='test_data', label_name='test_label')
def database_handle(self, db_name, db_table, db_sql, db_opt_value, expect_value): index_value = db_name[-1:] file_name = 'mesh' table_name = db_table hdlNum = 0 if 21 == db_opt_value: hdlNum = 1 dataBaseCmd = db_sql opType = db_opt_value context = 6 #pdb.set_trace() fmt = '!24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24s24sB3000sBI' #fmt = '!24s24s460sB3000sBI' u16SrcSPID = 5002 u16DstSPID = 401 u16MsgType = 2006 sendMsgFmt = '4H24s480sB3000sBI' u16MsgLength = struct.calcsize(sendMsgFmt) - 8 sendMsgPacket = struct.Struct(sendMsgFmt) sendMsg = sendMsgPacket.pack(u16SrcSPID, u16DstSPID, u16MsgType, u16MsgLength, file_name, table_name, hdlNum, dataBaseCmd, opType, context) log_debug(sendMsg) sendList = struct.unpack(sendMsgFmt, sendMsg) log_debug(sendList) #pdb.set_trace() recMsgFmt = '!4HBIII500sI' socket_client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if os.path.exists('/tmp/socket_mesh_client' + index_value): # socket_mesh_client[int] os.unlink('/tmp/socket_mesh_client' + index_value) socket_client.bind('/tmp/socket_mesh_client' + index_value) socket_client.connect('/tmp/socket_mesh_server' + index_value) # socket_mesh_server[int] fmtlen = struct.calcsize(recMsgFmt) bufsize = struct.calcsize(recMsgFmt) log_debug(fmtlen) socket_client.send(sendMsg) data = socket_client.recv(bufsize) #pdb.set_trace() if not len(data): print 'data is error' else: rspList = struct.unpack('!4HBIII500sI', data) header1, header2, header3, header4, type, res, ctx, rown, errMsg, reslen = struct.unpack( '!4HBIII500sI', data) log_debug(rspList) #print header1, header2, header3, header4, type, res, ctx, rown, errMsg, reslen #pdb.set_trace() if 0 != reslen: data = socket_client.recv(reslen) if None != expect_value: rspList = struct.unpack('I', data) log_debug(rspList[0]) if int(expect_value) != rspList[0]: Log.log_trace( 'expect: ' + expect_value + ', which is: ' + str(rspList[0]), Log.ERROR_LEVEL) socket_client.close() return -1 socket_client.close() log_debug('database socke close')
import Log # 对应在linux下执行的shell语句 ls_command = "hadoop fs -ls /Backup/" if __name__ == "__main__": #参数检测,是否满足两个参数 if len(sys.argv) != 3: print( "ERROR:SCD-08011.LEVEL:4.Please input like eg:'AvailableDate.py filename id'" ) exit(1) #建立日志文件 log = Log.log("AvailableData", sys.argv[-1]) log.command(" ".join(sys.argv)) # 列出文件是否保存在hdfs之中 filename = sys.argv[1] ls_outcome = os.popen(ls_command + filename).read().split("\n") try: firstdate = ls_outcome[1][-10:] except: log.error( "Sorry,You didn't backup %s on the HDFS.Please check the filename!" % filename) print( "ERROR:SCD-08002.LEVEL:4.Sorry,You didn't backup %s on the HDFS.Please check the filename!" % filename) log.chaLogPath()
def main(): """Main thread""" try: opts, args = getopt.getopt(sys.argv[1:], "vdc:p:D:P:m:N:", [ "verbose", "debug", "config=", "play=", "diff=", "part=", "mode=", "nbrplayers=" ]) except getopt.GetoptError: print usage sys.exit(1) playing = None configFile = None debug = False difficulty = 0 part = 0 mode = 0 nbrplayers = 1 for opt, arg in opts: if opt in ["--verbose", "-v"]: Log.quiet = False if opt in ["--debug", "-d"]: debug = True if opt in ["--config", "-c"]: configFile = arg if opt in ["--play", "-p"]: playing = arg if opt in ["--diff", "-D"]: difficulty = arg if opt in ["--part", "-P"]: part = arg #evilynux - Multiplayer and mode selection support if opt in ["--mode", "-m"]: mode = int(arg) if opt in ["--nbrplayers", "-N"]: nbrplayers = int(arg) while True: if configFile != None: if configFile.lower() == "reset": fileName = os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".ini") os.remove(fileName) config = Config.load(Version.appName() + ".ini", setAsDefault=True) else: config = Config.load(configFile, setAsDefault=True) else: config = Config.load(Version.appName() + ".ini", setAsDefault=True) engine = GameEngine(config) engine.cmdPlay = 0 if playing != None: Config.set("game", "selected_library", "songs") Config.set("game", "selected_song", playing) engine.cmdPlay = 1 engine.cmdDiff = int(difficulty) engine.cmdPart = int(part) #evilynux - Multiplayer and mode selection support Config.set("game", "players", nbrplayers) Config.set("game", "game_mode", mode) Config.set("game", "multiplayer_mode", mode) if debug == True: engine.setDebugModeEnabled(not engine.isDebugModeEnabled()) engine.debugLayer.debugOut(engine) engine.quit() break encoding = Config.get("game", "encoding") if encoding != None: reload(sys) sys.setdefaultencoding(encoding) engine.setStartupLayer(MainMenu(engine)) #stump: make psyco optional if Config.get("performance", "use_psyco"): try: import psyco psyco.profile() except: Log.warn("Unable to enable psyco.") try: engine.ticksAtStart = pygame.time.get_ticks() while engine.run(): pass except KeyboardInterrupt: pass if engine.restartRequested: Log.notice("Restarting.") engine.audio.close() try: # Determine whether were running from an exe or not if hasattr(sys, "frozen"): if os.name == "nt": os.execl("FretsOnFire.exe", "FretsOnFire.exe", *sys.argv[1:]) elif sys.frozen == "macosx_app": import string import subprocess appname = string.join( string.split(sys.executable, '/')[:-1], '/') appname = appname + "/Frets on Fire" subprocess.Popen( ` appname `, shell=True) else: os.execl("./FretsOnFire", "./FretsOnFire", *sys.argv[1:]) else: # stump: sys.executable points to the active python interpreter os.execl(sys.executable, sys.executable, "FretsOnFire.py", *sys.argv[1:]) except: Log.warn("Restart failed.") raise break else: break # evilynux - MainMenu class already calls this - useless? engine.quit()
def onACK(self, message): Log.logTest("received ACK") self.connected = True Log.logTest("sleeping for 3 seconds...") time.sleep(3)
def __init__(self): self.log = Log.log('spyder') self.getDenyLink() # self.getVisitLink(); pass
def test_cant_change_name(self): new_path = Log.log_file(__name="new") path = Log.log_file() self.assertNotEqual(new_path, path) self.assertEqual(path, LOG)
def onBYE(self, message): self.addResult(TestCase.TC_PASSED, "received BYE over same connection") Log.logTest("sending 200 on BYE") repl = self.createReply(200, "OK", message) self.writeMessageToNetwork(self.neh, repl) self.end = True
def test_the_same(self): path_1 = Log.log_file() path_2 = Log.log_file() self.assertEqual(path_1, path_2) self.assertEqual(LOG, path_1)
def __init__(self): self.log = Log() self.log.update('PublicIP') self.success = False
def PackSingleAtals(root, dirName, outDir): fileDir = os.path.join(root, dirName) if not os.path.isdir(fileDir): print(fileDir + " not dir!!!") return Log.Info("打包目录 => " + fileDir) outFileName = "_".join(dirName.split("\\")) exePath = os.path.join( WORK, "..\\gen_version\\libs\\texturepack\\bin\\TexturePacker.exe") packImgList = [] fullPackImgList = [] imgList = [] # 目录包含image,不打包改目录图片 if fileDir.find("image") != -1: for fileName in os.listdir(fileDir): if fileName.endswith(".jpg") or fileName.endswith(".png"): filePath = os.path.join(fileDir, fileName) imgList.append(filePath) else: for fileName in os.listdir(fileDir): filePath = os.path.join(fileDir, fileName) if fileName.endswith(".jpg"): print("copy jpg => " + filePath) imgList.append(filePath) continue if not fileName.endswith(".png"): continue image = Image.open(filePath) # 太大的图片忽略 if image.width * image.height >= 450 * 200: imgList.append(filePath) print("ignore image ", filePath, image.size) continue packImgList.append(fileName) fullPackImgList.append(os.path.join(fileDir, fileName)) outSaveDir = fileDir.replace(root, outDir) Util.ClearDir(outSaveDir) Util.CheckDir(outSaveDir) if len(fullPackImgList) == 1: imgList.append(fullPackImgList[0]) fullPackImgList = [] if len(fullPackImgList) > 0: # 打包图集 jsonPath = os.path.join(outSaveDir, outFileName + ".json") pngPath = os.path.join(outSaveDir, outFileName + ".png") argsArray = [ "--disable-rotation", "--size-constraints AnySize", "--max-width 2048", "--max-height 2048", "--format json-array", ] command = exePath + " {0} --data {1} --sheet {2} {3}".format( " ".join(argsArray), jsonPath, pngPath, " ".join(packImgList)) # print(command) curDir = os.getcwd() os.chdir(fileDir) os.system(command) os.chdir(curDir) ParserSliceArea(jsonPath) # os.chdir(curDir) for file in imgList: shutil.copy2(file, file.replace(root, outDir))
def test_always_the_same(self): self.assertEqual(LOG, Log.log_file())
def _ignition_off(self): log.info('Ignition stopped for %s seconds' % self.getIgnitionOffTimeout()) with self._ignition_lock: self._ignition = False self.signal('ignition_off')
#!/usr/bin/env python # Written by: DGC # python imports import sys import logging import unittest # local imports sys.path.append("..") import Log LOG = Log.log_file() #============================================================================== class utest_Log(unittest.TestCase): def test_exception(self): thrown = False try: Log.__init_logfile() except AttributeError: thrown = True self.assertTrue(thrown) def test_the_same(self): path_1 = Log.log_file() path_2 = Log.log_file() self.assertEqual(path_1, path_2) self.assertEqual(LOG, path_1)
def __run(_bundlePath): # # Initializes the plugin framework, verifies the plugin & extracts information, then enters a # run loop for handling requests. # global BundlePath global ResourcesPath global Identifier global DataPath global Debug global __pluginModule global __prefs global __prefsPath global __databasePath global __logFilePath global __requestHandlers supportFilesPath = os.environ[ "HOME"] + "/Library/Application Support/Plex Media Server/Plug-in Support" logFilesPath = os.environ["HOME"] + "/Library/Logs/PMS Plugin Logs/" def checkpath(path): try: if not os.path.exists(path): os.makedirs(path) except: pass checkpath(supportFilesPath + "/Preferences") checkpath(supportFilesPath + "/Databases") checkpath(logFilesPath) # Set the bundle path variable BundlePath = _bundlePath.rstrip('/') ResourcesPath = BundlePath + "/Contents/Resources" # Add the bundle path to the system path if os.path.isdir(BundlePath + "/Contents"): sys.path.append(BundlePath + "/Contents") if os.path.isdir(BundlePath + "/Contents/Libraries"): sys.path.append(BundlePath + "/Contents/Libraries") else: print "Couldn't find bundle directory" return None # Open the Info.plist file infoplist = XML.ElementFromFile((BundlePath + "/Contents/Info.plist")) if infoplist is None: print "Couldn't load Info.plist file from plugin" return # Get the plugin identifier Identifier = infoplist.xpath( '//key[text()="CFBundleIdentifier"]//following-sibling::string/text()' )[0] if Identifier is None: print "Invalid Info.plist file in plugin" return None # Set up the log file __logFilePath = logFilesPath + Identifier + ".log" if os.path.exists(__logFilePath): if os.path.exists(__logFilePath + ".old"): os.remove(__logFilePath + ".old") os.rename(__logFilePath, __logFilePath + ".old") # Show a big warning message - Framework v0 is deprecated!! Log.Add( "(Framework) Deprecated version\n\nNOTICE: This version of the Plex Media Framework is deprecated and is no longer supported.\nPlease migrate your code to a newer version. More information can be found at http://dev.plexapp.com/\n" ) Log.Add("(Framework) Plugin initialized", False) # Check whether debugging is enabled try: _debug = infoplist.xpath( '//key[text()="PlexPluginDebug"]//following-sibling::string/text()' )[0] if _debug == "1": Debug = True Log.Add("(Framework) Debugging is enabled") except: pass # Create the data path if it doesn't already exist DataPath = supportFilesPath + "/Data/" + Identifier if not os.path.isdir(DataPath): os.makedirs(DataPath) # Change directory to the data path os.chdir(DataPath) # If a preference file exists, load it __prefsPath = supportFilesPath + "/Preferences/" + Identifier + ".xml" defaultsPath = BundlePath + "/Contents/Defaults.xml" if os.path.exists(__prefsPath): __prefs = XML.ElementFromFile(__prefsPath) Log.Add("(Framework) Loaded user preferences") # Otherwise, try to apply the defaults file elif os.path.exists(defaultsPath): __prefs = XML.ElementFromFile(defaultsPath) Log.Add("(Framework) Loaded default preferences") # If no preferences were loaded, create an empty preferences element else: __prefs = XML.Element("PluginPreferences") # Load the plugin's dictionary file LoadDict() # Load the plugin's localization strings Locale.__loadDefaults() # TODO: Retrieve locale info from PMS for overriding default dict strings # Locale.__loadLocale(loc) # Set the database file path __databasePath = supportFilesPath + "/Databases/" + Identifier + ".db" # Initialize the plugin's CookieJar HTTP.__loadCookieJar() Log.Add("(Framework) Loaded cookie jar") # Attempt to import the plugin module - if debugging is enabled, don't catch exceptions if Debug: import Code as _plugin Log.Add("(Framework) Imported plugin module") else: try: import Code as _plugin Log.Add("(Framework) Imported plugin module") except ImportError: Log.Add("(Framework) Couldn't import plugin from bundle") return __pluginModule = _plugin # Call the plugin's Start method Log.Add("(Framework) Attempting to start the plugin...") __call(_plugin.Start) Log.Add("(Framework) Plugin started", False) Log.Add("(Framework) Entering run loop") # Enter a run loop to handle requests while True: try: # Read the input path = raw_input() # Strip GET from the start of the path path = path.lstrip("GET ").strip() # Split the path into components and decode. pathNouns = path.split('/') pathNouns = [urllib.unquote(p) for p in pathNouns] # If no input was given, return an error if len(pathNouns) <= 1: sys.stdout.write("%s\r\n\r\n" % PMS.Error['BadRequest']) sys.stdout.flush() # Otherwise, attempt to handle the request else: Response['Content-Type'] = 'application/xml' Response['Status'] = '200 OK' Response["Headers"] = "" result = None pathNouns.pop(0) count = len(pathNouns) if pathNouns[count - 1] == "": count = count - 1 pathNouns.pop(len(pathNouns) - 1) Log.Add("(Framework) Handling request : " + path, False) # Check for a management request if pathNouns[0] == ":": result = __handlePMSRequest(pathNouns, count) else: # Check each request handler to see if it handles the current prefix handler = None for key in __requestHandlers: if handler is None: if path.count(key, 0, len(key)) == 1: # Remove the prefix from the path keyNounCount = len(key.split('/')) - 1 for i in range(keyNounCount): pathNouns.pop(0) count = count - keyNounCount # Find the request handler handler = __requestHandlers[key]["handler"] # Check whether we should handle the request internally handled = False if count > 0: if pathNouns[0] == ":": handled = True result = __handleInternalRequest(pathNouns, count) # If the request hasn't been handled, and we have a valid request handler, call it if not handled and handler is not None: result = handler(pathNouns, count) # If the request wasn't handled, return an error if result == None: Log.Add("(Framework) Request not handled by plugin", False) response = "%s\r\n\r\n" % PMS.Error['NotFound'] # If the plugin returned an error, return it to PMS elif result in PMS.Error.values(): Log.Add( "(Framework) Plug-in returned an error : %s" % result, False) response = result + "\r\n" # Otherwise, return the result else: Log.Add("(Framework) Response OK") response = "%s\r\nContent-Type: %s\r\nContent-Length: %i\r\n%s\r\n%s\r\n" % \ (Response["Status"], str(Response['Content-Type']), len(result), Response["Headers"], result) sys.stdout.write(response) sys.stdout.flush() # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin except KeyboardInterrupt: # Commit any changes to the database and close it if DB.__db is not None: DB.Commit() DB.__db.close() # Save the dictionary SaveDict() # Exit sys.exit() except EOFError: # Commit any changes to the database and close it if DB.__db is not None: DB.Commit() DB.__db.close() Log.Add("(Framework) Plugin stopped") sys.exit() # If another exception is raised, deal with the problem except: # If in debug mode, print the traceback, otherwise report an internal error if Debug: Log.Add("(Framework) An exception happened:\n%s" % traceback.format_exc()) else: Log.Add("(Framework) An internal error occurred", False) sys.stdout.write("%s\r\n\r\n" % PMS.Error['InternalError']) sys.stdout.flush() # Make sure the plugin's dictionary is saved finally: SaveDict()
def __init__(self, opts): self.logger = Log.Logger(opts)
def message(self, *args, **params): Log.info('*********************Message!************************') return
def test_logutil(self): cm = None master = None try: cm = Cm.CM("test_logutil") cm.create_workspace() pg = Pg.PG(0) # master --> master master = Pgs.PGS(0, 'localhost', 1900, cm.dir) pg.join(master, start=True) master.smr.wait_role(Smr.SMR.MASTER) # make some logs self.make_logs(master, 5) # get file sequences seqs = master.smr.getseq_log() file_seqs = [] seq = 0 while seq + 64 * 1024 * 1024 < seqs['max']: file_seqs.append(seq) seq = seq + 64 * 1024 * 1024 # get leading timestamp and sequence from each logs and peek one peeks = [] for seq in file_seqs: out, _ = Log.datadump_communicate(master.dir, seq, seq + 5 * 1024, 'Tsld32') lines = out.split('\n') assert len(lines) > 0 peek = lines[len(lines) / 2] peeks.append(peek) # find by time range and check peek is in the lines idx = 0 for seq in file_seqs: peek = peeks[idx] ts = int(peek.split()[0]) assert ts > 20160817000000000 out, _ = Log.dumpbytime_communicate(master.dir, ts, ts + 1, 'Tsld32') lines = out.split('\n') found = False for line in lines: if line == peek: found = True break assert found == True idx = idx + 1 # decachelog (just for coverage) out, _ = Log.decachelog_communicate(master.dir, file_seqs[-1], True) assert len(out) == 0 # mincorelog (just for coverage) out, _ = Log.mincorelog_communicate(master.dir) assert len(out.split('\n')) >= 5 finally: # Util.tstop('Check output!') if master is not None: master.kill_smr() master.kill_be() if cm is not None: cm.remove_workspace()