Exemplo n.º 1
0
    def process_window_event(self, evt):
        """Processes a window event."""

        # Exit when the X button is clicked.
        if evt.type == pygame.QUIT:
            sys.exit()

        # Add other events here.
        if evt.type == pygame.MOUSEBUTTONDOWN:
            JCSPyGm_Input.mouseDownThisFrame = True
            JCSPyGm_Input.mouseIsDown = True

        if evt.type == pygame.MOUSEBUTTONUP:
            JCSPyGm_Input.mouseUpThisFrame = True
            JCSPyGm_Input.mouseIsDown = False

        if evt.type == pygame.MOUSEMOTION:
            JCSPyGm_Input.mousePosition = pygame.mouse.get_pos()

        if evt.type == pygame.KEYDOWN:
            JCSPyGm_Input.keysPressedThisFrame.append(evt.key)
            JCSPyGm_Input.keysDown.append(evt.key)

        if evt.type == pygame.KEYUP:
            JCSPyGm_Input.keysReleasedThisFrame.append(evt.key)

            # remove any occurence of this key in the keysDown array.
            JCSPyGm_Input.keysDown.remove(evt.key)
Exemplo n.º 2
0
def choose_pokemon(isComp):
    global curr_comp_pokemon
    global curr_user_pokemon
    global computerPokemon
    if not isComp:
        if len(myPokemon) == 0:
            print("You lost!")
            sys.exit(0)
        print("Which Pokemon do you choose to call?")
        choice = int(input())
        curr_user_pokemon = kb.get_pokemon(myPokemon[choice-1])
        print("Go ", curr_user_pokemon.get_name())
        return;
    else:
        if len(computerPokemon) == 0:
            print("You won!")
            sys.exit(0)
        str = []
        compStrengths = curr_user_pokemon.get_weaknesses()
        for i in range(1, len(computerPokemon)-1):
            tempPokemon = kb.get_pokemon(computerPokemon[i-1])
            for j in range(0, len(compStrengths)):
                str.append(compStrengths[i])
                tempstr =  tempPokemon.get_strengths()
                for i in range(0, len(tempstr)):
                    if i in str:
                        curr_comp_pokemon = tempPokemon
                        print("The computer chose ", curr_comp_pokemon.get_name())
                        return;
        curr_comp_pokemon = kb.get_pokemon(computerPokemon[len(computerPokemon)-1])
        print("The computer chose ", curr_comp_pokemon.get_name())
        return
Exemplo n.º 3
0
def argParser():
	# Parsing command-line arguments
	" parse command line options into args and options "
	parser = optparse.OptionParser (
		"""usage: %prog [options] [referenceDb] [datasetName] filename(s) - import VCF, complete genomics or BED files into the beacon database.""")

	(options, args) = parser.parse_args ()

	if len (args) == 0:
		parser.print_help ()
		sys.exit (0)
	return args, options
Exemplo n.º 4
0
def main():
	args, options = argParser ()
	refDB = args[0]
	datasetName = args[1]
	fileName = args[2]
	if len (args) < 3:
		print ("Specify refdb, datasetname, and vcf filename")
		sys.exit (1)
	if refDB not in list_references ():
		print ("The reference assembly '%s' is not valid." % refDB)
		print ("Please specify one of these reference assemblies:")
		print (list_references ())
		sys.exit (1)
	importFiles (refDB, fileName, datasetName)
Exemplo n.º 5
0
def process(commands):
    if len(commands) > 1:
        if commands[0].lower() == "-d":
            process_decompile(commands[1:])
        elif commands[0].lower() == "-cn":
            process_compare(commands[1:], "normal")
        elif commands[0].lower() == "-co":
            process_compare(commands[1:], "obfuscated")
        elif commands[0].lower() == "-da":
            decompile_all(commands[1])
        elif commands[0].lower() == "-dq":
            process_decompile_quality(commands[1:])
        elif commands[0].lower() == "-h":
            help()
        elif commands[0].lower() == "-exit":
            sys.exit(0)
Exemplo n.º 6
0
def get_opt(argv):
    inputfile = ''
    env = 'local'
    try:
        opts, _ = getopt.getopt(argv, "hn:e:", ["ifile="])
    except getopt.GetoptError:
        print 'main.py -n <nodefile> -e local|prod|test '
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'main.py -n <nodefile> -e local|prod|test'
            sys.exit()
        elif opt in ("-n"):
            inputfile = arg
        elif opt in ("-e") and arg in ['prod', 'test', 'local']:
            env = arg
    return inputfile, env
Exemplo n.º 7
0
	def run(self):
		try:
			while True:
				self.currentState.run()
				self.currentState = self.currentState.next()
				
				if self.parameterHandler.stopProgram == True:
					self.frameHandler.release()
					self.serialHandler.close()
					break
				
				if self.parameterHandler.resume == True:
					self.parameterHandler.resume = False
					self.currentState = self.standBy
			sys.exit(0)
		except:
			print (sys.exc_info())
			self.frameHandler.release()
			self.serialHandler.close()
Exemplo n.º 8
0
def checkStock(inStock, pageNumber, item, openBrowser):
    if (inStock == True):
        # Play audio alert
        currentTime = datetime.datetime.now()
        newLine()
        print(currentTime)
        print("*** " + item.capitalize() + " found ***\n")
        print("Slickdeals page:", pageNumber)
        notification.notify(title="SlickAlerts",
                            message=str(item.capitalize()) + " found",
                            app_name="SlickAlerts",
                            timeout=10,
                            ticker="test")
        playsound("alert.mp3")
        if (openBrowser == True):
            print("Your default web browser will now open.")
            time.sleep(1)  # pause thread so user can read message
            wb.open(
                "https://slickdeals.net/forums/forumdisplay.php?f=9&page=" +
                str(pageNumber))  # opens web browser when found
        sys.exit(-1)
Exemplo n.º 9
0
def prepare_content(configuration, github_token, extract_dir):
    """
    Prepares the content for the documentation build. It checks for all content whether or
    not it's available locally or if it should be downloaded.
    :param configuration: Documentation build configuration file path.
    :param github_token: A valide Github token to download content with the Github Class
    :param extract_dir: Directory into which to put all content downloaded.
    """
    try:
        list_of_contents = local_or_upstream(github_token, extract_dir,
                                             extract_config(configuration))
    except:
        if getenv("LOCAL") == 'True':
            print(
                "\x1b[33mWARNING\x1b[0m: Downloading files failed, documentation is now in degraded mode."
            )
        else:
            print(
                "\x1b[31mERROR\x1b[0m: Downloading files failed, stoping build."
            )
            sys.exit(1)
    return list_of_contents
Exemplo n.º 10
0
def readAllelesVcf(ifh):
	rows = []
	skipCount = 0
	emptyCount = 0
	for chunk in ifh.chunks ():
		for line in chunk.decode ('utf-8').splitlines ():
			if line.startswith ("#"):
				continue
			fields = str.split (line.rstrip ("\n"), "\t", maxsplit=5)
			chrom, pos, varId, ref, alt = fields[:5]
			if chrom.startswith ("chr"):
				chrom = chrom.replace ("chr", "")
			pos = int (pos) - 1
			if alt == ".":
				emptyCount += 1
				continue
			refIsOne = len (ref) == 1
			altIsOne = len (alt) == 1

			if refIsOne and altIsOne:
				allele = alt
			elif not refIsOne and altIsOne:
				allele = "D" + str (len (ref) - 1)
				pos += 1
			elif refIsOne and not altIsOne:
				allele = "I" + alt[1:]
				pos += 1
			elif not refIsOne and not altIsOne:
				skipCount += 1
			else:
				print ("Invalid VCF fields:", fields)
				sys.exit (1)
			dataRow = (chrom, pos, allele)
			rows.append (dataRow)
		print ("Skipped %d lines with empty ALT alleles" % emptyCount)
		print ("Skipped %d lines with both ALT and REF alleles len!=1, cannot encode as queries" % skipCount)
	return rows
Exemplo n.º 11
0
def main():
    print('NetflixBot v1.3 by u/yoalan')

    # Check for config file
    if not os.path.exists('config.cfg'):
        print('No config file.')
        sys.exit()

    # Fetch config settings
    config = ConfigParser.ConfigParser()
    config.read('configCustom.cfg')
    USERNAME = config.get('Configuration', 'Username')
    PASSWORD = config.get('Configuration', 'Password')
    USERAGENT = config.get('Configuration', 'Useragent')

    # Login to reddit
    r = praw.Reddit(USERAGENT)
    r.login(USERNAME, PASSWORD)

    running = True
    while running:
        try:
            mentions = r.get_mentions()
            mentions = list(mentions)

            # Check mentions
            for c in mentions:
                print c.author.name
                if not c.new:
                    continue

                bodysplit = c.body.lower().split('\n\n')
                if len(bodysplit) <= REQUEST_LIMIT:
                    text = ''
                    for line in bodysplit:
                        # Comment
                        if 'director:' in line.lower():
                            director = parse_name(line, 'director:')
                            text += build_reply(director, QUERY['director'])
                        elif 'actor:' in line.lower():
                            actor = parse_name(line, 'actor:')
                            text += build_reply(actor, QUERY['actor'])
                        else:
                            movie_titles = parse_movies(line)
                            text += build_reply(movie_titles, QUERY['movie'])

                    text = add_signature(text)
                    print text
                    replyto(c, text)

            sleep(SLEEP_TIME)
        except KeyboardInterrupt:
            running = False
        except Exception as e:
            now = datetime.datetime.now()
            print now.strftime("%m-%d-%Y %H:%M")
            print traceback.format_exc()
            print 'ERROR:', e
            print 'Going to sleep for 30 seconds...\n'
            sleep(SLEEP_TIME)
            continue
Exemplo n.º 12
0
    def generer(self,
                jeu,
                nb,
                j,
                moidejouer,
                alphaBeta,
                test=None,
                h=None,
                useAB=True):
        """"
        l désigne la liste des fils
        nb nonbre de coup possible
        j designe le joueur
        moidejouer désigne celui qui commence le jeu
        
        
        
        """

        if jeu.verifiewin(j):

            a = Arbre(noeud=Noeud(10000000, 0, 0, 0), fils=[])
            a.nbNoeud = 1
            return a

        if j == 0:
            j1 = 1
        else:
            j1 = 0

        if jeu.verifiewin(j1):
            a = Arbre(noeud=Noeud(-10000000, 0, 0, 0), fils=[])
            a.nbNoeud = 1
            return a

        if nb == 0:

            if test != None:

                n = Noeud(self.test[test], 0, 0, 0)

                a = Arbre(noeud=n, fils=[])
                a.nbNoeud = 1
            else:
                n = Noeud(jeu.notation(j), 0, 0, 0)

                a = Arbre(noeud=n, fils=[])
                a.nbNoeud = 1
            return a
        else:
            if test == None:
                if (j == 0 and moidejouer) or (j == 1 and not moidejouer):

                    rangee = range(0, 6)
                else:
                    rangee = range(6, 12)
            else:
                rangee = range(0, 3)
            l = []
            maxx = -1000000000
            minn = 1000000000
            meilleurCoupMin = []
            meilleurCoupMax = []
            valeurMoyenne = 0
            nbNoeud = 0

            for i in rangee:

                if jeu.plateau.cases[i].graines > 0:

                    if (j == 0 and moidejouer) or (j == 1 and not moidejouer):
                        j1 = 1

                    else:
                        j1 = 0

                    passer = False
                    j2 = jeu.clone()

                    if j2.jouer(i) == 0:
                        j2.plateau.printC()

                        sys.exit(-1)
                    if test != None and not j2.plateau.verifie(j1):
                        nbAux = j2.plateau.cases[i].graines

                        if nbAux < 6:
                            k = i + 1

                            while nbAux > 0:
                                if j2.plateau.cases[k].graines != 12:
                                    nbAux = nbAux - 1

                                k = k + 1
                                if k >= 12:
                                    k = 0

                            if k == 0:
                                arrive = 11
                            else:
                                arrive = k - 1

                            if (j1 == 1 and arrive < 6) or (j1 == 0
                                                            and arrive >= 6):
                                passer = True

                    if not passer:

                        if moidejouer:
                            newalphaBeta = maxx
                        else:
                            newalphaBeta = minn

                        if test != None:

                            a = self.generer(jeu,
                                             nb - 1,
                                             j,
                                             not moidejouer,
                                             newalphaBeta,
                                             i + 3 * (h - nb) * test,
                                             h,
                                             useAB=useAB)
                        else:

                            a = self.generer(j2,
                                             nb - 1,
                                             j,
                                             not moidejouer,
                                             newalphaBeta,
                                             useAB=useAB)
                        nbNoeud = nbNoeud + a.nbNoeud
                        val = a.noeud.chiffre

                        valeurMoyenne = valeurMoyenne + val

                        if val > maxx:
                            maxx = val
                            meilleurCoupMax = [[
                                i, a.noeud.valeurMoyenne, a.noeud.valeurExteme
                            ]]
                        elif val == maxx:
                            meilleurCoupMax.append([
                                i, a.noeud.valeurMoyenne, a.noeud.valeurExteme
                            ])
                        if val < minn:
                            minn = val
                            meilleurCoupMin = [[
                                i, a.noeud.valeurMoyenne, a.noeud.valeurExteme
                            ]]
                        elif val == minn:
                            meilleurCoupMin.append([
                                i, a.noeud.valeurMoyenne, a.noeud.valeurExteme
                            ])

                        l.append(a)

                        if useAB:
                            if alphaBeta != None:
                                if moidejouer:

                                    if val > alphaBeta:

                                        break
                                else:
                                    if val < alphaBeta:

                                        break

            if len(l) == 0:
                jeu.plateau.printC()
                print(j)
                sys.exit(-1)

                a = Arbre(noeud=Noeud(10000000, 0, 0, 0), fils=[])

                return a

            valeurMoyenne = valeurMoyenne / len(l)

            mmax = 0
            bestMoy = -100000000
            mmin = 0
            wostMoy = 1000000000
            for jaux in meilleurCoupMax:
                moy = jaux[1]
                if moy > bestMoy:
                    bestMoy = moy
                    mmax = jaux[0]

            for jaux in meilleurCoupMin:
                moy = jaux[1]

                if moy < wostMoy:
                    wostMoy = moy
                    mmin = jaux[0]

            if moidejouer:

                a = Arbre(noeud=Noeud(maxx, mmax, valeurMoyenne, minn), fils=l)

            else:
                a = Arbre(noeud=Noeud(minn, mmin, valeurMoyenne, maxx), fils=l)

            a.nbNoeud = nbNoeud
            return a
def main():
    print("ProfanityCountBot v.01 by u/KilometersFan")
    #Check for config file
    if not os.path.exists('configCustom.cfg'):
        print("No config file exists")
        sys.exit()
    #Grab config settings
    config = configparser.ConfigParser()
    config.read("configCustom.cfg")
    #Set config values
    USERNAME = config.get("Configuration", "Username")
    PASSWORD = config.get("Configuration", "Password")
    USERAGENT = config.get("Configuration", "Useragent")
    CLIENT_ID = config.get("Configuration", "Client_ID")
    CLIENT_SECRET = config.get("Configuration", "Client_Secret")
    SLEEP_TIME = 60
    #Login
    reddit = praw.Reddit(client_id=CLIENT_ID,
                         client_secret=CLIENT_SECRET,
                         user_agent=USERAGENT,
                         username=USERNAME,
                         password=PASSWORD)
    running = True
    profanity_list = parse_list()
    db = pymysql.connect("localhost", "root", "root", "reddithistory")
    cursor = db.cursor()
    while running:
        try:
            # get mentions
            inbox = reddit.inbox
            mentions = list(inbox.mentions())
            frequent_words = {}
            mention_count = 0
            #iterate over mentions
            for mention in mentions:
                count = 0
                counted_before = False
                update_freq_words = False
                if not mention.new:
                    break
                mention_count += 1
                # get author of parent comment the user mentioned the bot from or the submission if the comment was top-level
                mention_body = mention.body.lower().split(" ")
                user = ""
                if len(mention_body) > 1:
                    user = parse_specific_user(reddit, mention_body)
                if not user:
                    user = mention.parent().author
                # get previous user data from database
                sql = "SELECT * FROM userhistory WHERE UserID = '" + user.id + "'"
                cursor.execute(sql)
                lastcomment, newcomment, lastsubmission, newsubmission, lastprofanity = 0, 0, 0, 0, 0
                freq_words_string = ""
                # update info if the user had their profanities counted
                if cursor.rowcount == 0:
                    print(user.name +
                          " has not had their profanities counted!")
                else:
                    results = cursor.fetchone()
                    lastcomment = results[1]
                    lastsubmission = results[2]
                    lastprofanity = results[3]
                    freq_words_string = results[4]
                    # parse the string and add the counts to the frequent_words dict
                    if freq_words_string:
                        frequent_words = json.loads(freq_words_string)
                        if (lastprofanity > len(frequent_words)):
                            lastprofanity -= lastprofanity - len(
                                frequent_words)
                    counted_before = True

                comments = list(user.comments.new(limit=None))
                if comments:
                    newcomment = comments[0].created_utc
                # go through user's comments
                for comment in comments:
                    if comment.created_utc <= lastcomment:
                        break
                    words = comment.body.split(" ")
                    for word in words:
                        if word.lower() in profanity_list:
                            update_freq_words = True
                            count += 1
                            if frequent_words.get(word.lower()):
                                frequent_words[word.lower(
                                )] = frequent_words[word.lower()] + 1
                            else:
                                frequent_words[word.lower()] = 1
                # go through user's submissions
                submissions = list(user.submissions.new(limit=None))
                if submissions:
                    newsubmission = submissions[0].created_utc
                for submission in submissions:
                    if submission.created_utc <= lastsubmission:
                        break
                    # check submission title
                    words = submission.title.split(" ")
                    for word in words:
                        if word in profanity_list:
                            update_freq_words = True
                            count += 1
                            if frequent_words.get(word.lower()):
                                frequent_words[word.lower(
                                )] = frequent_words[word.lower()] + 1
                            else:
                                frequent_words[word.lower()] = 1
                    # check submission text
                    words = submission.selftext.split(" ")
                    for word in words:
                        if word in profanity_list:
                            update_freq_words = True
                            count += 1
                            if frequent_words.get(word.lower()) != None:
                                frequent_words[word.lower(
                                )] = frequent_words[word.lower()] + 1
                            else:
                                frequent_words[word.lower()] = 1
                count = lastprofanity + count
                # print out the user's profanity data and reply to the mentioner
                if mention_count > 0:
                    # temp variables
                    creation_date = str(
                        datetime.datetime.utcfromtimestamp(
                            int(user.created_utc)).strftime('%m-%d-%Y'))
                    message = "Hello comrade. "
                    num_comments = len(comments)
                    num_submissions = len(submissions)
                    # message creation logic

                    if count > 1:
                        print(
                            "%s has used %d profanity since %s over %d comments and %d submissions."
                            % (user.name, count, creation_date, num_comments,
                               num_submissions))
                        message += "%s has used %d profanity since %s over %d comments and %d submissions." % (
                            user.name, count, creation_date, num_comments,
                            num_submissions)
                    elif count == 1:
                        print(
                            "%s has used %d profanities since %s over %d comments and %d submissions."
                            % (user.name, count, creation_date, num_comments,
                               num_submissions))
                        message += "%s has used %d profanities since %s over %d comments and %d submissions." % (
                            user.name, count, creation_date, num_comments,
                            num_submissions)
                    else:
                        print(
                            "%s has never used a profanity since %s over %d comments and %d submissions."
                            % (user.name, creation_date, num_comments,
                               num_submissions))
                        message += "%s has never used a profanity since %s over %d comments and %d submissions." % (
                            user.name, creation_date, num_comments,
                            num_submissions)
                    # generate table of proanities
                    profanities_list = list(frequent_words.keys())
                    profanities_list.sort()
                    if (len(profanities_list)):
                        message += "\n\nProfanities used: (NSFW)\n\nProfanity|Count\n:--|:--\n"
                        for key in profanities_list:
                            # remove word from user history and update profanity counts if that word was taken off the profnaity list beforehand
                            if key not in profanity_list:
                                old_count = count
                                count -= frequent_words.pop(key)
                                update_freq_words = True
                                message = message.replace(
                                    str(old_count), str(count))
                            else:
                                if (frequent_words[key] == 0):
                                    frequent_words.pop(key, None)
                                    continue
                                print(key + ": " + str(frequent_words[key]))
                                message += key + "|" + str(
                                    frequent_words[key]) + "\n"
                    temp_copy = frequent_words
                    # clear the dict for the next mentioner
                    frequent_words = {}
                    message += "\n\nNote: Reddit limits comment/submission getting by bots to 1000.\n\n*Beep boop, I'm a bot! I am currently under development and may not be working. If you have any suggestions for profanities to add or remove, send a message to /u/KilometersFan.*"
                    mention.reply(message)
                # mark mention as read
                mention.mark_read()
                # update the database
                if not counted_before:
                    sql = "INSERT INTO userhistory(UserID, LastCommentCreationTime, LastSubmissionCreationTime, LastProfanityCount) \
                            VALUES ('%s', %d, %d, %d)" % (user.id, newcomment,
                                                          newsubmission, count)
                else:
                    sql = "UPDATE userhistory SET LastCommentCreationTime = %d, LastSubmissionCreationTime = %d, \
                        LastProfanityCount = %d WHERE UserID = '%s'" % (
                        newcomment, newsubmission, count, user.id)
                cursor.execute(sql)
                db.commit()
                if update_freq_words:
                    sql = "UPDATE userhistory SET profanities = '%s' WHERE UserID = '%s'" % (
                        json.dumps(temp_copy), user.id)
                    cursor.execute(sql)
                    db.commit()

        except KeyboardInterrupt:
            running = False
        except Exception as e:
            now = datetime.datetime.now()
            print(now.strftime("%m-%d-%Y %H:%M"))
            print(traceback.format_exc())
            print('ERROR:', e)
            print('Going to sleep for 60 seconds...\n')
            db.rollback()
            sleep(SLEEP_TIME)
            continue
Exemplo n.º 14
0
def main():
	print('GoddamnBatmanBot v1.0 by u/yoalan')
	
	#Check for config file
	if not os.path.exists('config.cfg'):
		print('No config file.')
		sys.exit()

	#Fetch config settings
	config = ConfigParser.ConfigParser()
	config.read('config.cfg')
	USERNAME  = config.get('Configuration', 'Username')
	PASSWORD  = config.get('Configuration', 'Password')
	USERAGENT = config.get('Configuration', 'Useragent')
	SUBREDDITS = config.get('Configuration', 'Subreddit').split(',')
	
	if str(SUBREDDITS[0]) != 'all':
		combined_subs = ('%s') % '+'.join(SUBREDDITS)
		print('Looking at the following subreddits: "' + combined_subs + '".')
	else:
		comments = praw.helpers.comment_stream(r, 'all', limit=None)
		print('Looking at r/all.')

	#login to reddit
	r = praw.Reddit(USERAGENT)
	r.login(USERNAME,PASSWORD)

	#Set up our cache and completed work set
	cache = deque(maxlen=200) # double-ended queue
	already_done = set()

	running = True
	while running:    
	
		if str(SUBREDDITS[0]) != 'all':
			try:
				subs = r.get_subreddit(combined_subs)
				comments = subs.get_comments()
			except Exception as e:
				print("[ERROR]:", e)
				print("blindly handling error")
				print("sleeping 30 sec")
				sleep(30)       
				continue
	
		#Check comments
		for c in comments:
			
			#Did we recently check it? If so fetch new comments
			if c.id in cache:
				break
			
			#Add this to our cache
			cache.append(c.id)
			
			#Check if we need to reply
			if check_comment(c):
				
				#Check if we already replied
				for reply in c.replies:
					if reply.author.name == USERNAME:
						already_done.add(c.id)
				
				if c.id not in already_done:
				
					#Is it one our comments since we use a quote of the phrase?
					if c.author.name == USERNAME:
						already_done.add(c.id)
					
					#reply
					else:
						try:
							replyto(c, already_done)
							
						except KeyboardInterrupt:
							running = False
						except praw.errors.APIException as e:
							print("[ERROR]:", e)
							print("sleeping 30 sec")
							sleep(30)                
						except Exception as e: # In reality you don't want to just catch everything like this, but this is toy code.
							print("[ERROR]:", e)
							print("blindly handling error")
							continue
Exemplo n.º 15
0
def main():
    print('NetflixBot v1.3 by u/yoalan')
    
    # Check for config file
    if not os.path.exists('config.cfg'):
        print('No config file.')
        sys.exit()

    # Fetch config settings
    config = ConfigParser.ConfigParser()
    config.read('configCustom.cfg')
    USERNAME  = config.get('Configuration', 'Username')
    PASSWORD  = config.get('Configuration', 'Password')
    USERAGENT = config.get('Configuration', 'Useragent')

    # Login to reddit
    r = praw.Reddit(USERAGENT)
    r.login(USERNAME,PASSWORD)

    running = True
    while running:    
        try:
            mentions = r.get_mentions()
            mentions = list(mentions)

            # Check mentions 
            for c in mentions:
                print c.author.name
                if not c.new:
                    continue;
            
                bodysplit = c.body.lower().split('\n\n')
                if len(bodysplit) <= REQUEST_LIMIT:
                    text = ''
                    for line in bodysplit:
                        # Comment
                        if 'director:' in line.lower():
                            director = parse_name(line, 'director:')
                            text += build_reply(director, QUERY['director'])
                        elif 'actor:' in line.lower():
                            actor = parse_name(line, 'actor:')
                            text += build_reply(actor, QUERY['actor'])
                        else:
                            movie_titles = parse_movies(line)
                            text += build_reply(movie_titles, QUERY['movie'])

                    text = add_signature(text)
                    print text
                    replyto(c, text)

            sleep(SLEEP_TIME)
        except KeyboardInterrupt:
            running = False
        except Exception as e:
            now = datetime.datetime.now()
            print now.strftime("%m-%d-%Y %H:%M")
            print traceback.format_exc()
            print 'ERROR:', e
            print 'Going to sleep for 30 seconds...\n'
            sleep(SLEEP_TIME)
            continue
Exemplo n.º 16
0
 def __check_term_signal__(self):
     if (self.caught_term_signal):
         print "Got term signal. Exit."
         sys.exit()
Exemplo n.º 17
0
Arquivo: App.py Projeto: spiricn/ssc
    logger = logging.getLogger(__name__)

    exampleDir = os.path.dirname(__file__)

    container = ServletContainer('', 8080, os.path.join(exampleDir, 'root'), os.path.join(exampleDir, 'tmp'))

    container.start()

    container.addRestAPI()

    container.rest.addHandler(RestHandler('sample', sampleRest, 'This is a sample help doc', chunked=False))

    container.rest.addHandler(RestHandler('stream', streamRest, 'This is a stream help doc', chunked=True))

    logger.debug('sample started')
    logger.debug('Try accessing http://localhost:8080/rest/sample from your browser for a simple REST call')
    logger.debug('Try accessing http://localhost:8080/rest/stream from your browser, for a chunked REST call')
    logger.debug('press [ENTER] to stop')

    input()

    container.stop()

    logger.debug('sample stopped')

    return 0


if __name__ == '__main__':
    sys.exit(main())
def set_env_2():
    #2. Create logging dir
    if not os.path.exists(TX_ADDR_INFO_UPDATE_DAEMON_LOG_DIR):
        os.makedirs(TX_ADDR_INFO_UPDATE_DAEMON_LOG_DIR) 
        
if __name__ == '__main__':
    set_env_2()
    if len(sys.argv) == 3:
        env_setting = sys.argv[2]
        daemon = TransactionAddrInfoUpdaterProcessDaemon(pidfile=TX_ADDR_INFO_UPDATE_DAEMON_PID_FILE, 
                              stdout=TX_ADDR_INFO_UPDATE_DAEMON_STDOUT, 
                              stderr=TX_ADDR_INFO_UPDATE_DAEMON_STDERR)
        query_session = set_session(env_setting=env_setting)
        update_session = set_session(env_setting=env_setting)
        daemon.set_session(query_session = query_session, update_session = update_session)
        if 'start' == sys.argv[1]:
            print "start"
            daemon.start()
        elif 'stop' == sys.argv[1]:
            print "stop"
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            print "restart"
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart local|test|prod" % sys.argv[0]
        sys.exit(2)
Exemplo n.º 19
0
def main():
	print('Mnemosyne reborn by /u/ITSigno')

	# verify that the config file exists
	if not os.path.exists('mnemosyne.cfg'):
		print('No config file.')
		sys.exit() #bail

	# parse the config file
	config = ConfigParser.ConfigParser();
	config.read('mnemosyne.cfg')

	# get the basic info for the bot user
	USERNAME = config.get('Bot', 'username')
	PASSWORD = config.get('Bot', 'password')
	USERAGENT = config.get('Bot', 'useragent')

	# Get our reddit settings
	SUBREDDIT = config.get('Reddit', 'subreddit')
	REQ_LIMIT = config.get('Reddit', 'request_limit')

	# other misc. config options
	SUBMIT_URL = config.get('Config', 'submit_url')
	SLEEP_TIME = config.getint('Config', 'sleep_time')

	# TODO Move exclusions into confiog file
	EXCLUDE = re.compile('youtube\.com|archive\.is|web\.archive\.org')

	# Login to reddit
	# TODO setup OAuth method
	r = praw.Reddit(USERAGENT)
	r.login(USERNAME,PASSWORD, disable_warning=True)

	# get our designated sub
	s = r.get_subreddit(SUBREDDIT);

	# based on legacy message header
	d_head = "Archive links for this discussion: \n\n"
	p_head = "Archive links for this post: \n\n"

	# BotLivesMatter
	foot = "----\n\nI am Mnemosyne reborn. 418 I'm a teapot. ^^^/r/botsrights"

	# initialize our array of "already_done" posts, so we don't repeat work
	if not os.path.exists('replied_to.txt'):
		already_done = []
	else:
		with open('replied_to.txt', "r") as f:
			already_done = f.read()
			already_done = already_done.split("\n")
			already_done = filter(None, already_done)

	# loop forever and ever and ever and ever and ever and ever
	while True:
		try:
			# loop over every post returned by get_new
			# p is a Submission object
			for p in s.get_new(limit=REQ_LIMIT):
				#verify that the the post isn't already done...
				if p.id not in already_done:
					# Add the post id to the current array and the file
					already_done.append(p.id)
					with open('replied_to.txt', 'a') as f:
						f.write(p.id + "\n")

					# parse the url, get the domain, and run our exlude regex
					parsed_uri = urlparse(p.url)
					if EXCLUDE.search(parsed_uri.netloc) is not None:
						continue

					url = get_archive_url(SUBMIT_URL,p.url)
					
					if not url:
						log("Failed to archive: " + p.permalink + "\nurl: " + url, file="failed.txt")
						continue #failed to get url

					# use the right head based on post type
					head = d_head if p.is_self else p_head

					c = head + "* **Archive:** " + url + "\n\n" + foot
					p.add_comment(c)
					# done
						
			sleep(SLEEP_TIME)
		except Exception as e:
			log(traceback.format_exc() + "\n" + 'ERROR: ' + str(e) + "\n", file="error_log.txt")
			sleep(SLEEP_TIME)
			continue
Exemplo n.º 20
0
# Source and background files
if args.src == None :
    lccorr = '{0}/{1}/lcurve_{2}/{3}_lccorr_{2}.lc'.format(args.path, args.obs,
            args.tw, args.name)
    print(args.name)
    if path.exists(lccorr) :
        args.src = lccorr
    else :
        args.src = '{0}/{1}/lcurve_{2}/{3}_lc_{2}_src.lc'.format(args.path,
                args.obs, args.tw, args.name)
        args.bgd = '{0}/{1}/lcurve_{2}/{3}_lc_{2}_bgd.lc'.format(args.path,
                args.obs, args.tw, args.name)
        if not path.exists(args.src) :
            print('ERROR: Source File {0} does not exist'.format(args.src))
            sys.exit()
        if not path.exists(args.bgd) :
            print('ERROR: Background File {0} does not exist'.format(args.bgd))
            sys.exit()

# GTI file
if args.gti == None :
    args.gti = '{0}/{1}/PN_gti.fits'.format(args.path, args.obs)
    if not path.exists(args.gti) :
        print('ERROR: File {0} does not exist'.format(args.gti))
        sys.exit()

# Output file
src = (args.name).replace("_", "+")
out='{0}/{1}/lcurve_{2}/{3}_lc_{2}.pdf'.format(args.path, args.obs,
        args.tw, args.name)
Exemplo n.º 21
0
        config_section
        ,config.getint(config_section, "loop_count")
        ,config.get(config_section, "login_id")
        ,config.get(config_section, "login_pw")
        ,config.get(config_section, "reserve_month")
        ,literal_eval(config.get(config_section, "reserve_days"))
        ,literal_eval(config.get(config_section, "seat_nominees"))
        ,config.get(config_section, "percent_str")
        ,config.get(config_section, "birth_ymd")
        ,config.get(config_section, "bank_name")
        ,config.get(config_section, "user_agent")
        )
    reserv.process_reservation()
    del reserv
    
def getConfig():
    config = configparser.ConfigParser()
    config.read("reservation_second.conf", encoding="utf-8")
    print("config : {}".format(config))
    return config


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print('usage : python main.py [Execute Envirenment - limjaeho/kimjoojin]')
        sys.exit(0)
    else:
        print('command line arguments : {}'.format(sys.argv))
        config_section = sys.argv[1]
    main()
Exemplo n.º 22
0
env_setting = 'local'
if __name__ == '__main__':

    try:
        env_setting = sys.argv[1]
        if env_setting not in ["local", "prod"]:
            raise ValueError

        if len(sys.argv) > 2:
            count = int(sys.argv[2])
        else:
            count = 1000
    except StandardError:
        print >> stderr, "wrong input arguments"
        print >> stderr, "usage: ./mainchain_update.py <local|prod> [count]"
        sys.exit(2)

    print "Set up environment to", env_setting
    if is_process_running():
        print "Process is already running. Skip this round"
        print "Program terminated normally"
        sys.exit()

    try:
        make_lock_file()
    except IOError as e:
        sys.exit("Can't open lock file")

    try:
        session = set_session(env_setting=env_setting)
        updater = MainchainUpdater(session=session,
Exemplo n.º 23
0
def main():
    print('reallygoodbot v1.0 by /u/thetrny')
    
    #Check for config file
    if not os.path.exists('config.cfg'):
        print('No config file.')
        sys.exit()

    #Fetch config settings
    config = configparser.ConfigParser()
    config.read('config.cfg')
    USERNAME  = config.get('Configuration', 'Username')
    PASSWORD  = config.get('Configuration', 'Password')
    USERAGENT = config.get('Configuration', 'Useragent')
    SUBREDDITS = config.get('Configuration', 'Subreddit').split(',')

    #login to reddit
    r = praw.Reddit(USERAGENT)
    r.login(USERNAME,PASSWORD)

    thing_limit = int(input("Number of comments to look back: "))
    user_name = "reallygoodbot"
    user = r.get_redditor(user_name)
    gen = user.get_comments(limit=thing_limit)
    karma_by_subreddit = {}
    for thing in gen:
        subreddit = thing.subreddit.display_name
        karma_by_subreddit[subreddit] = (karma_by_subreddit.get(subreddit, 0)
                                         + thing.score)
    import pprint
    pprint.pprint(karma_by_subreddit)

    cache = deque(maxlen=CACHE_SIZE) # double-ended queue
    already_done = set()

    #Setup subreddits
    if str(SUBREDDITS[0]) != 'all':
        combined_subs = ('%s') % '+'.join(SUBREDDITS)
        print('Looking at the following subreddits: "' + combined_subs + '".')
    else:
        comments = praw.helpers.comment_stream(r, 'all', limit=None)
        print('Looking at /r/all.')

    running = True
    while running:    
        try:
            if str(SUBREDDITS[0]) != 'all':
                subs = r.get_subreddit(combined_subs)
                comments = subs.get_comments(limit=None)

            #Check comments 
            for c in comments:
                
                #Did we recently check it? If so fetch new comments
                if c.id in cache:
                    break
                
                #Add this to our cache
                cache.append(c.id)
                
                #Check if we need to reply
                if check_comment(c):
                    
                    #Check if we already replied
                    for reply in c.replies:
                        if reply.author.name == USERNAME:
                            already_done.add(c.id)
                    
                    if c.id not in already_done:
                        text = "Wow, that's a really good bot. \n\n"
                        text = add_signature(text)
                        replyto(c, text, already_done)

        except KeyboardInterrupt:
            running = False
        except Exception as e:
            now = datetime.datetime.now()
            print (now.strftime("%m-%d-%Y %H:%M"))
            print (traceback.format_exc())
            print ('ERROR:', e)
            print ('Going to sleep for 30 seconds...\n')
            sleep(SLEEP_TIME)
            continue