def _command_LS(self, matchObj):
		"""Handler for LS command: Retrieves a listing of file names and sizes
		on the server."""
		
		sendStr(self._connSock, "LS\n")
		result = recvLine(self._connSock)
		if isError(result):
			return
		
		getSize = re.match(r"^OK (?P<size>\d+)$", result)
		if not getSize:
			if not self._isSocketClosed(result):
				debugPrint("CLIENT FAILURE: Malformed LS reply from server.")
			return
		
		numBytes = int(getSize.group("size"))
		listing = recvAll(self._dataSock, numBytes).decode()
		if len(listing) < numBytes:
			if not self._isSocketClosed(listing):
				debugPrint("CLIENT FAILURE: Incomplete reply from server.")
			return

		theList = [fileLine.split(maxsplit=1) for fileLine in listing.splitlines()]
		dirs = [entry[1] for entry in theList if entry[0] == "DIR"]
		files = [entry for entry in theList if entry[0] != "DIR"]

		# Get the maximum field width of the file sizes, for alignment when printing.
		maxSizeWidth = len(max(next(zip(*files)), key=len))
		print("Directories:")
		for name in dirs:
			print(" "*maxSizeWidth, name)
		print("Files:")
		for (size, name) in files:
			print("{{fsize: >{width}}} {{fname}}".format(width=maxSizeWidth).format(
					fsize=("" if size == "DIR" else size), fname=name))
	def handleClientConnection(self):
		"""The workhorse function of this server implementation.
		Repeatedly processes client commands one-by-one until the client
		exits."""
		
		while self._continueHandling:
			try:
				ctrlLine = recvLine(self._connSock)
			except socket.error:
				ctrlLine = None
							
			if not ctrlLine:
				debugPrint("SERVER: EOF from client socket.")
				break # Stop 
			for (regex, handler) in self._protocolHandlers.items():
				matchObj = re.match("^"+regex+"$", ctrlLine)
				if matchObj:
					(handlerFunc, needData, closeData, args, kwargs) = handler
					if needData and not self._dataSock:
						sendStr(self._connSock, "ERR NO DATA CONNECTION\n")
						break
					handlerFunc(matchObj, *args, **kwargs)
					if not self._config["persistent"] and closeData and self._dataSock:
						self._dataSock.close()
						self._dataSock = None
					break
			else:
				sendStr(self._connSock, "ERR BAD REQUEST\n")
		self._connSock.close()
		if self._dataSock:
			self._dataSock.close()
		debugPrint("SERVER: Client disconnected.")
示例#3
0
 def setMissilePause(self):
     num_bad_hits = 0
     for h in self.bad_hit_queue:
         num_bad_hits += h
     mp = ANIMATION_FRAME_COUNT * (1 + num_bad_hits)
     utils.debugPrint("%s bad hits, setting missile pause to %s" % (num_bad_hits, mp))
     self.missile_pause = mp
     self.current_missile_pause = mp
	def _command_QUIT(self, matchObj):
		"""Handler for the QUIT command: Signals the termination of the
		connection."""
		
		sendStr(self._connSock, "GO AWAY\n")
		result = recvLine(self._connSock)
		if result == "OK BYE":
			self._connSock.close()
			self._isFinished = True
		else:
			if not self._isSocketClosed(result):
				debugPrint("CLIENT FAILURE: Malformed QUIT reply from server.")
示例#5
0
def typeString(s, timeInterval=0.1):
    '''
    Type the string s. Wait timeInterval secs between each char.
    String s should only contains lower english letters and digits.
    length of s should <= 30.
    '''
    if len(s) > 30:
        debugPrint("Error in typeString(s) @cur.py: \n \t len of s > 30 \n")

    if not all(c.isdigit() or c.islower() for c in s):
        debugPrint("Error in typeString(s) @cur.py: \n \t s should only contains lower english letters and digits.\n")
    
    for c in s:
        typeChr(c, timeInterval)
	def registerCommandHandler(self, regex, handlerFunc, needData, *args, **kwargs):
		"""Register handlerFunc with the connection so that if a client command
		matches the given regex, that function is called with its appropriate
		re.match object and any other arguments. The needData flag denotes if
		the handler function needs a data connection. Attempting to add a regex
		which is already matched by an existing rule will fail with an error
		message."""
		
		for handler in self._commandHandlers.keys():
			if re.match("^"+handler+"$", regex):
				debugPrint("CLIENT: Invalid rule {rule}: Already matched by {old}.".format(
						rule=regex, old=handler))
				break
		else:
			self._commandHandlers[regex] = (handlerFunc, needData, args, kwargs)
	def _command_CHUNK(self, matchObj):
		"""Handler for CHUNK command: sets the transfer chunk size (bytes)."""
		
		chunkSize = int(matchObj.group("size"))
		if chunkSize < 1:
			print("FAILURE: Chunk size must be positive!")
			return
		sendStr(self._connSock, "SETCONFIG CHUNKSIZE {size}\n".format(size=chunkSize))
		result = recvLine(self._connSock)
		if result == "OK CHUNKSIZE {size}".format(size=chunkSize):
			self._config["chunk_size"] = chunkSize
			print("SUCCESS: Chunk size is now {size} byte{s}.".format(
					size=chunkSize, s=("s" if chunkSize > 1 else "")))
		else:
			if not self._isSocketClosed(result):
				debugPrint("CLIENT FAILURE: Malformed CHUNK response from server.")
	def registerProtocolHandler(self, regex, handlerFunc, needData, closeData, *args, **kwargs):
		"""Register handlerFunc with the connection so that if a client command
		matches the given regex, that function is called with its appropriate
		re.match object and any other arguments. The needData and closeData
		flags denote, respectively, if the handler function needs a data
		connection, and whether that data connection should be closed when it
		isfinished. Attempting to add a regex which is already matched by an
		existing rule will fail with an error message.)"""
		
		for handler in self._protocolHandlers.keys():
			if re.match("^"+handler+"$", regex):
				debugPrint("SERVER: Invalid rule {rule}: Already matched by {old}.".format(
						rule=regex, old=handler))
				break
		else:
			self._protocolHandlers[regex] = (handlerFunc, needData, closeData, args, kwargs)
示例#9
0
 def setMeteors(self, meteors_to_reset, excluded_rows):
     data.GlobalGameStatus.value.checkNewQueue()
     data.GlobalGameStatus.value.checkWrongQueue()
     data.GlobalGameStatus.value.printQueues()
     data.GlobalGameStatus.value.printReport()
     for i in meteors_to_reset:
         j = data.GlobalGameStatus.value.pick(excluded_rows)
         utils.debugPrint("resetting meteor #%s, got row %s" % (i, j))
         if j == data.BAD_ROW:
             self.meteors.getMeteor(i).setContent("?", data.BAD_ROW)
         else:
             excluded_rows.append(j)
             c = data.GlobalContentData.value.getRow(j).char
             self.meteors.getMeteor(i).setContent(c, j)
     for i in range(0, self.meteors.size()):
         m = self.meteors.getMeteor(i)
         utils.debugPrint("meteor #%s has row index %s, which has status %s"
                          % (i, m.row_ind, data.GlobalGameStatus.value.getStatus(m.row_ind)))
	def _protocol_GET(self, matchObj):
		"""Handler for the GET command: Downloads a file from the server."""
		
		fileName = matchObj.group("filename")
		if isdir(fileName):
			sendStr(self._connSock, "ERR FILE IS A DIRECTORY\n")
		elif not isfile(fileName):
			sendStr(self._connSock, "ERR FILE DOES NOT EXIST\n")
		else:
			fileSize = getsize(fileName)
			debugPrint("SERVER: Sending {fname}".format(fname=fileName))
			try:
				sendStr(self._connSock, "READY {size}\n".format(size=fileSize))
				sendFile(self._dataSock, fileName, self._config["chunk_size"])
			except (PermissionError, IOError):
				sendStr(self._connSock, "ERR CANNOT READ FILE\n")
			else:
				sendStr(self._connSock, "OK {size}\n".format(size=fileSize))
	def _command_GET(self, matchObj, overwriteFlag):
		"""Handler for GET command: Downloads a file from the server."""
		
		fileName = matchObj.group("filename")
		
		if isdir(fileName):
			print("FAILURE: A directory with that name already exists.")
			return
			
		if isfile(fileName) and not overwriteFlag:
			print("FAILURE: That file already exists.")
			return
			
		sendStr(self._connSock, "GET {name}\n".format(name=fileName))
		result = recvLine(self._connSock)
		if isError(result):
			return

		getSize = re.match("^READY (?P<size>\d+)$", result)
		if not getSize:
			if not self._isSocketClosed(result):
				debugPrint("CLIENT FAILURE: Malformed GET reply from server.")
			return
			
		fileSize = int(getSize.group("size"))
		chunkSize = self._config["chunk_size"]
		try:
			with Timer() as xferTime:
				numBytesWritten = recvFile(self._dataSock, fileSize, fileName, "wb", chunkSize)
		except (PermissionError, IOError):
			print("FAILURE: Cannot write to file.")
		else:
			if numBytesWritten < fileSize:
				print("FAILURE: Incomplete file data written.")
			else:
				isOK = recvLine(self._connSock)
				if isOK == "OK {size}".format(size=numBytesWritten):
					print("SUCCESS: {name} ({size} byte{s}) retrieved in {secs} seconds.".format(
							name=fileName, size=fileSize, secs=xferTime.elapsedTime(), 
							s=("s" if fileSize > 1 else "")))
				elif not self._isSocketClosed(isOK):
					print("CLIENT FAILURE: Malformed GET reply from server after transfer.")
示例#12
0
def getImgLoc(imgName, numPts=4000):
    targetImg = cv2.imread(imgName, cv2.IMREAD_GRAYSCALE)
    screenImg = cv2.cvtColor(np.asarray(ig.grab()), cv2.COLOR_RGB2GRAY)

    sift = cv2.SIFT_create(nfeatures=numPts)
    kp1, des1 = sift.detectAndCompute(targetImg, None)
    kp2, des2 = sift.detectAndCompute(screenImg, None)
    _, good_kp2 = flannMatch(kp1, des1, kp2, des2)

    if len(good_kp2) <= IMG_FOUND_THRES:
        debugPrint("getImgLoc:", imgName, "not found. #pts =", len(good_kp2))
        return None

    sumX, sumY = 0, 0
    for i in range(len(good_kp2)):
        sumX += good_kp2[i][0]
        sumY += good_kp2[i][1]

    debugPrint("getImgLoc:", imgName, "found. #pts =", len(good_kp2))
    return int(sumX / len(good_kp2)), int(sumY / len(good_kp2))
	def handleCommand(self, command):
		"""The workhorse function of this client implementation. """

		if not command:
			return False # Stop 
		for (regex, handler) in self._commandHandlers.items():
			matchObj = re.match("^"+regex+"$", command)
			if matchObj:
				(handlerFunc, needData, args, kwargs) = handler
				if needData and not self._dataSock:
					if not self._openDataConnection():
						debugPrint("CLIENT FAILURE: Could not establish data connection.")
						return False
				handlerFunc(matchObj, *args, **kwargs)
				if not self._config["persistent"] and self._dataSock:
					self._dataSock.close()
					self._dataSock = None
				return True
		else:
			print("Error: Invalid command! Type 'HELP' for a list of commands.")
			return False
示例#14
0
def main():

    MULTI_REDDIT = configs["MULTI_REDDIT"]
    for submission in reddit.subreddit(MULTI_REDDIT).stream.submissions():

        if submission.saved:
            debugPrint("Skipping Saved: " + submission.id)
            continue

        signalHandler.loopStart()

        debugPrint()
        print("Discovered: " + submission.id)

        if not submission.is_self:
            config = configs[submission.subreddit.display_name.lower()]
            if not isVideoOfAccepatableLength(submission, config):
                submission.mod.remove(reason_id=config.REASON_ID)
                submission.mod.send_removal_message(config.REMOVAL_MESSAGE)
                print("Removed: " + submission.permalink)

        submission.save()
        signalHandler.loopEnd()
	def _command_PERSIST(self, matchObj):
		"""Handler for PERSIST command: Enables or disables a persistent data
		connection."""
		
		option = matchObj.group("option")
		if option == "YES":
			sendStr(self._connSock, "SETCONFIG PERSISTENTDATA YES\n")
			result = recvLine(self._connSock)
			if result != "OK PERSISTENTDATA ENABLED":
				if not self._isSocketClosed(result):
					debugPrint("CLIENT FAILURE: Malformed PERSIST reply from server.")
			else:
				self._config["persistent"] = True
				print("Persistent data connection enabled.")
		else:
			sendStr(self._connSock, "SETCONFIG PERSISTENTDATA NO\n")
			result = recvLine(self._connSock)
			if result != "OK PERSISTENTDATA DISABLED":
				if not self._isSocketClosed(result):
					debugPrint("CLIENT FAILURE: Malformed PERSIST reply from server.")
			else:
				self._config["persistent"] = False
				print("Persistent data connection disabled.")
	def _command_PASV(self, matchObj):
		"""Handler for PASV command: Enables or disables passive data transfer
		mode."""
		
		option = matchObj.group("option")
		if option == "YES":
			sendStr(self._connSock, "SETCONFIG PASSIVE YES\n")
			result = recvLine(self._connSock)
			if result != "OK PASSIVE ENABLED":
				if not self._isSocketClosed(result):
					debugPrint("CLIENT FAILURE: Malformed PASV reply from server.")
			else:
				self._config["passive"] = True
				print("Passive data transfer mode enabled.")
		else:
			sendStr(self._connSock, "SETCONFIG PASSIVE NO\n")
			result = recvLine(self._connSock)
			if result != "OK PASSIVE DISABLED":
				if not self._isSocketClosed(result):
					debugPrint("CLIENT FAILURE: Malformed PASV reply from server.")
			else:
				self._config["passive"] = False
				print("Passive data transfer mode disabled.")
示例#17
0
 def parseFinStat(self):
     accounts = self.rawJSON['list']
     self.stockCode = accounts[0]['stock_code']
     for account in accounts:
         # print('parseFinStat:' + account['account_nm'])
         if account['account_nm'] == '유동자산':
             self.currentAssets = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '비유동자산':
             self.nonCurrentAssets = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '자산총계':
             self.totalAssets = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '유동부채':
             self.currentLiabilities = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '비유동부채':
             self.nonCurrentLiabilities = commasToInt(
                 account['thstrm_amount'])
         elif account['account_nm'] == '부채총계':
             self.totalLiabilities = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '자본금':
             self.equityCapital = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '이익잉여금':
             self.retainedEarnings = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '자본총계':
             self.totalEquity = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '매출액':
             self.revenues = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '영업이익':
             self.incomeFromOperations = commasToInt(
                 account['thstrm_amount'])
         elif account['account_nm'] == '법인세차감전 순이익':
             self.incomeBeforeTax = commasToInt(account['thstrm_amount'])
         elif account['account_nm'] == '당기순이익':
             self.netIncome = commasToInt(account['thstrm_amount'])
         else:
             debugPrint('Unknown account_nm {0}'.format(
                 account['account_nm']))
	def _command_PUT(self, matchObj):
		"""Handler for PUT command: Uploads a file to the server."""
		
		fileName = matchObj.group("filename")
		chunkSize = self._config["chunk_size"]
		
		if isdir(fileName):
			print("FAILURE: Cannot upload a directory.")
		elif not isfile(fileName):
			print("FAILURE: The file does not exist.")
		else:
			fileSize = getsize(fileName)
			sendStr(self._connSock, "PUT {size} {name}\n".format(size=fileSize, name=fileName))
			isReady = recvLine(self._connSock)
			if isError(isReady):
				return
			
			if isReady != "READY {size}".format(size=fileSize):
				if not self._isSocketClosed(isReady):
					debugPrint("CLIENT FAILURE: Malformed PUT reply from server.")
					return
			
			try:
				with Timer() as xferTime:
					sendFile(self._dataSock, fileName, chunkSize)
			except (PermissionError, IOError):
				print("CLIENT FAILURE: Cannot read from file.")
			else:
				isSent = recvLine(self._connSock)
				if isSent != "OK {size}".format(size=fileSize):
					if not self._isSocketClosed(isSent):
						debugPrint("CLIENT FAILURE: Malformed PUT reply from server.")
				else:
					print("SUCCESS: {name} ({size} byte{s}) uploaded in {secs:.4f} seconds.".format(
							name=fileName, size=fileSize, secs=xferTime.elapsedTime(), 
							s=("s" if fileSize > 1 else "")))
示例#19
0
 def setCorrectIndex(self, c):
     utils.debugPrint("correct index is %s" % c)
     row_ind = self.meteors.getMeteor(c).row_ind
     self.correct_text = "%s" % data.GlobalContentData.value.getRow(row_ind).reading
     self.correct_meteor_indices = []
     for i in range(0, self.meteors.size()):
         m = self.meteors.getMeteor(i)
         alt_ind = data.GlobalContentData.value.findAlternateReadingRow(m.row_ind, self.correct_text)
         if alt_ind != data.BAD_ROW:
             utils.debugPrint("for meteor %s, alt_ind = %s" % (i, alt_ind))
             utils.debugPrint("adding index %s to correct answers" % i)
             self.correct_meteor_indices.append(i)
             if alt_ind != m.row_ind:
                 m.setContent(data.GlobalContentData.value.getRow(alt_ind).char, alt_ind)
示例#20
0
    def stateGameOver(self):
        rects = []
        if not self.end_screen.isReady():
            utils.debugPrint("mastered = ")
            utils.debugPrint(self.mastered)
            utils.debugPrint("unmastered = ")
            utils.debugPrint(self.unmastered)
            num_mastered = 0
            for r in self.mastered:
                already_mastered = data.GlobalSaveFile.value.get(r)
                data.GlobalSaveFile.value.set(r, True)
                if not already_mastered:
                    num_mastered += 1
            for r in self.unmastered:
                data.GlobalSaveFile.value.set(r, False)

            self.end_screen.init(num_mastered,
                                 len(self.unmastered),
                                 self.shot_history.getCorrectPercentage(),
                                 self.getPlayTimeText())
            data.GlobalSaveFile.value.addPlayTime(self.getPlayTime())
            self.end_screen.visible = True
        self.end_screen.increment()
        return (GAMEPLAY_GAME_OVER, rects)
示例#21
0
    def getFinStatJSON(self):
        assert (self.reprt_code in ['11013', '11012', '11014', '11011'])
        url = 'https://opendart.fss.or.kr/api/fnlttSinglAcnt.json'
        params = {
            'crtfc_key': config.crtfc_key,
            'corp_code': self.corp_code,
            'bsns_year': self.bsns_year,
            'reprt_code': self.reprt_code
        }

        debugPrint('Connecting to {0}...'.format(url))
        res = requests.get(url, params=params)
        if res.status_code != 200:
            print('getFinStatJSON: {0} returned status code {1}'.format(
                url, res.status_code))
            return None
        debugPrint('Downloaded account as a JSON format')
        # print(str(res.content, 'utf-8'))
        accountJson = json.loads(res.content)
        debugPrint('Transformed into a JSON object')
        return accountJson
def forkingServer_listenForever(servPort, connHandlerType):
	"""Given a ServerConnectionHandler type, uses forking to implement a
	parallel server which listens for (possibly concurrent) client connections
	and handle them in child processes."""

	assert issubclass(connHandlerType, ServerConnectionHandler)
	
	workerProcs = []
	try:
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as servSock:
			servSock.bind(("", servPort))
			debugPrint("SERVER ({addr}) : Listening for incoming connections on port {p}.".format(
					addr=servSock.getsockname()[0], p=servPort))
			debugPrint("SERVER: Press Ctrl+C to quit.")
			servSock.listen(2)
			while True:		
				try:
					(clientSock, clientAddr) = servSock.accept()
				except KeyboardInterrupt:
					debugPrint("SERVER: Received exit signal. Waiting for workers to finish...")
					for workerPID in workerProcs:
						waitpid(workerPID, 0)
					debugPrint("SERVER: Shutting down.")
					servSock.close()
					exit(0)
				childPID = fork()
				# NB: fork() returns 0 to child; and the child PID to the parent.
				if childPID == 0:
					try:
						handler = connHandlerType(clientSock, clientAddr)
						handler.handleClientConnection()
					except KeyboardInterrupt:
						# The break will be handled by the main server process.
						pass
					finally:
						_exit(0)
				else:
					debugPrint("SERVER: Client ({addr}) connected -- handler PID {pid}...".format(
						addr=clientAddr, pid=childPID))
					workerProcs.append(childPID)
					debugPrint("SERVER: Main loop running, accepting more connections...")
	except socket.error as socketError:
		debugPrint("SERVER: Could not creating listening socket. Reason: {err}".format(
				err=socketError))
		exit(1)
def threadingServer_listenForever(servPort, connHandlerType):
	"""Given a ServerConnectionHandler type, uses threading to implement a
	parallel server which listens for (possibly concurrent) client connections
	and process them in child threads."""
	
	assert issubclass(connHandlerType, ServerConnectionHandler)
	
	workerThreads = []
	try:
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as servSock:
			servSock.bind(("", servPort))
			debugPrint("SERVER ({addr}) : Listening for incoming connections on port {p}.".format(
					addr=servSock.getsockname()[0], p=servPort))
			debugPrint("SERVER: Press Ctrl+C to quit.")
			servSock.listen(2)
			while True:		
				(clientSock, clientAddr) = servSock.accept()
				handler = connHandlerType(clientSock, clientAddr)
				clientThread = threading.Thread(target=handler.handleClientConnection)
				workerThreads.append(clientThread)
				debugPrint("SERVER: Client ({addr}) connected -- handler thread {tid}...".format(
						addr=clientAddr, tid=clientThread.name))
				clientThread.start()
				debugPrint("SERVER: Main loop running, accepting more connections...")
	except socket.error as socketError:
		debugPrint("SERVER: Could not creating listening socket. Reason: {err}".format(
				err=socketError))
		exit(1)
	except (KeyboardInterrupt, SystemExit):
		debugPrint("SERVER: Received exit signal. Waiting for workers to finish...")
		for childThread in workerThreads:
			childThread.join()
		debugPrint("SERVER: Shutting down.")
		servSock.close()
		exit(0)
示例#24
0
 def updateBadHitQueue(self, hit_type):
     utils.debugPrint("updateHitQueue")
     self.bad_hit_queue.append(hit_type)
     if len(self.bad_hit_queue) > BAD_HIT_QUEUE_SIZE:
         self.bad_hit_queue = self.bad_hit_queue[1:]
示例#25
0
 def recordIncorrect(self):
     utils.debugPrint("recordIncorrect")
     self.updateBadHitQueue(1)
     self.setMissilePause()
     self.num_shots += 1
示例#26
0
def loadCorpCodes():
    # Check if pickle already exists
    corpCode = loadCorpCodesCached()
    if corpCode is not None:
        debugPrint('corpCode cache hit!')
        return corpCode

    # Fetch Zipped XML from OPEN DART
    baseUrl = 'https://opendart.fss.or.kr/api/corpCode.xml'
    params = {'crtfc_key': config.crtfc_key}
    res = requests.get(baseUrl, params=params)
    debugPrint('Downloading corpcode zip file...')
    if res.status_code != 200:
        debugPrint('{0} returned status code {1}'.
                   format(baseUrl, res.status_code))
        return None
    debugPrint('Downloaded corpcode zip file')

    # Save zip file
    debugPrint('Saving corpcode zip file...')
    if not os.path.exists(config.dataPath):
        os.mkdir(config.dataPath)
    with open(config.corpCodeZipPath, 'wb') as f:
        for chunk in res.iter_content(chunk_size=128):
            f.write(chunk)
    debugPrint('Saved corpcode zip file')

    # Extract zip file and save it as an XML file
    debugPrint('Extracting corpcode zip file...')
    with zipfile.ZipFile(config.corpCodeZipPath) as zf:
        zf.extractall(config.dataPath)
    debugPrint('loadCorpCodes', 'Extracted corpcode zip file')

    # Transfrom XML as an dictionary
    debugPrint('Transforming XML into dictionary...')
    corpCode = dict()
    tree = elemTree.parse(config.corpCodeXmlPath)
    for elem in tree.iter('list'):
        code = elem.find('corp_code').text
        name = elem.find('corp_name').text
        corpCode[name] = code
    debugPrint('Transformed XML into dictionary')

    # Cache the dictionary as a pickle object
    debugPrint('Saving dictonary as a pickle object...')
    with open(config.corpCodePklPath, 'wb') as f:
        pickle.dump(corpCode, f)
    debugPrint('Saved dictonary as a pickle object')

    return corpCode
from collections import defaultdict
import argparse
from cbid_cuda import correlation_cbid
from utils import debugPrint

# parse argument to get the program name and path
parser = argparse.ArgumentParser(description="Sort events")
parser.add_argument("--input_trace", help="set the input trace")
parser.add_argument("--output_trace", help="set the output trace destination")
parser.add_argument(
    "--gpu_log",
    help=
    "log file created by HC with GPU information (kernels, barriers, memcpy)")
args = parser.parse_args()

debugPrint("SORT EVENTS")
# Add the input trace to the collection
collection = btr.TraceCollection()

# Set the input traces
if args.input_trace == None:
    directory = os.getcwd() + "/../lttng-traces/"
    path = max([os.path.join(directory, d) for d in os.listdir(directory)],
               key=os.path.getmtime)
else:
    path = args.input_trace
if path[-1] == "/":
    path = path[:-1]
collection.add_trace(path + "/ust/uid/1000/64-bit", 'ctf')

# Set the output trace
示例#28
0
 def recordUnmaster(self, row_ind):
     utils.debugPrint("recordUnmaster")
     add_set = set([row_ind])
     self.unmastered |= add_set
     self.mastered -= add_set
示例#29
0
def getCurrentCursorPos():
    setDPI()
    x, y = win32gui.GetCursorPos()
    debugPrint("CurPos: ", (x, y))
    return x, y
示例#30
0
        pass

    ffree= consts.maxIno-files
    # f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_namemax
    self.log ("sftats!")
    return (consts.fragmentSize, blocks, free, consts.maxIno, ffree, 255)

if __name__ == '__main__':
  (opts, args)= parseOpts ([
    Option ('b', 'broadcast-to', True, default=''),
    Option ('c', 'connect-to', True),
    Option ('l', 'log-file', True, default='virtue.log'),
  ], argv[1:])
  debugPrint (1, 'parsed args: %s, left args: %s' % (
    ", ".join (
      map (
        lambda x: "%s: %s" % (x, opts[x].value),
        opts.keys ()
      ))
    , args))

  net= opts['b'].asString ()
  url= opts['c'].asString ()

  server= Virtue (url, net, fileName=opts['l'].asString ())
  server.flags= 0
  # server.multithreaded= 1;

  server.main ()
  server.saveLog ()
示例#31
0
from collections import defaultdict
import argparse
from utils import debugPrint
import math

# parse argument to get the program name and path
parser = argparse.ArgumentParser(description="Sort events")
parser.add_argument("--input_trace", help="set the input trace")
parser.add_argument("--output_trace", help="set the output trace destination")
parser.add_argument(
    "--gpu_log",
    help=
    "log file created by HC with GPU information (kernels, barriers, memcpy)")
args = parser.parse_args()

debugPrint("SORT EVENTS")
# Add the input trace to the collection
collection = btr.TraceCollection()

# Set the input traces
if args.input_trace == None:
    directory = os.getcwd() + "/../lttng-traces/"
    path = max([os.path.join(directory, d) for d in os.listdir(directory)],
               key=os.path.getmtime)
else:
    path = args.input_trace
if path[-1] == "/":
    path = path[:-1]
collection.add_trace(path + "/ust/uid/1000/64-bit", 'ctf')

# Set the output trace
	def _openDataConnection(self):
		"""Opens a data connection to the server. The existing data connection
		(if any) is closed."""
		
		if self._dataSock:
			self._dataSock.close()
			self._dataSock = None
			
		if self._config["passive"]:
			sendStr(self._connSock, "DATA\n")
			result = recvLine(self._connSock).rstrip()
			if isError(result):
				return False
			
			getPort = re.match(r"^READY (?P<port>\d+)$", result)
			if not getPort:
				if not self._isSocketClosed(result):
					debugPrint("CLIENT FAILURE: Malformed DATA reply from server. 2")
				return False
			
			port = int(getPort.group("port"))
			try:
				self._dataSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				self._dataSock.connect((self._remoteAddr[0], port))
			except socket.error as err:
				debugPrint("CLIENT FAILURE: Socket error: {errmsg}".format(errmsg=err))
				self._dataSock = None
				return False
			else:
				result = recvLine(self._connSock).rstrip()
				if isError(result):
					self._dataSock = None
					return False
				elif result == "OK {port}".format(port=port):
					return True
				else:
					if not self._isSocketClosed(result):
						debugPrint("CLIENT FAILURE: Malformed DATA reply from server. 3")
					self._dataSock = None
					return False
		
		else: # Not passive
			dataConn = None
			try:
				dataConn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				dataConn.bind(("", 0))
				dataConn.settimeout(60)
				dataConn.listen(1)
				dataPort = dataConn.getsockname()[1]
				sendStr(self._connSock, "DATA {p}\n".format(p=dataPort))
				while True:	
					(serverDataSock, serverAddr) = dataConn.accept()
					if serverAddr[0] == self._remoteAddr[0]:
						result = recvLine(self._connSock).rstrip()
						if result == "OK {port}".format(port=dataPort):
							self._dataSock = serverDataSock
							return True
						else:
							if not self._isSocketClosed(result):
								debugPrint("CLIENT FAILURE: Malformed DATA reply from server. 1")
							self._dataSock = None
							serverDataSock.close()
							return False
					else:
						serverDataSock.close()						
			except socket.timeout as err:
				return False