예제 #1
0
def receive_message():
  if request.method == 'GET':
    """Before allowing people to message your bot, Facebook has implemented a verify token
    that confirms all requests that your bot receives came from Facebook."""
    token_sent = request.args.get("hub.verify_token")
    return verify_fb_token(token_sent)
  # if the request was not get, it must be POST and we can just proceed with sending a message back to user
  else:
    # get whatever message a user sent the bot
    output = request.get_json()
    for event in output['entry']:
      messaging = event['messaging']
      for message in messaging:
        if message.get('message'):
          # Facebook Messenger ID for user so we know where to send response back to
          recipient_id = message['sender']['id']

          #initialize bot
          main.start(recipient_id)

          if message['message'].get('text'):
            user_message = message['message'].get('text')
            response_sent_text = get_message(user_message)
            send_message(recipient_id, response_sent_text)
          # if user sends us a GIF, photo,video, or any other non-text item
          if message['message'].get('attachments'):
            response_sent_nontext = "I'm sorry, I can only respond to text."
            send_message(recipient_id, response_sent_nontext)
  return "Message Processed"
예제 #2
0
파일: zeronet.py 프로젝트: shea256/ZeroNet
def main():
	print "- Starting ZeroNet..."
	import sys, os
	main = None
	try:
		sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Imports relative to src
		import main
		main.start()
		if main.update_after_shutdown: # Updater
			import update, sys, os, gc
			# Try cleanup openssl
			try:
				if "lib.opensslVerify" in sys.modules:
					sys.modules["lib.opensslVerify"].opensslVerify.close()
			except Exception, err:
				print "Error closing openssl", err

			# Update
			update.update()

			# Close log files
			logger = sys.modules["main"].logging.getLogger()

			for handler in logger.handlers[:]:
				handler.flush()
				handler.close()
				logger.removeHandler(handler)

	except Exception, err: # Prevent closing
		import traceback
		traceback.print_exc()
		traceback.print_exc(file=open("log/error.log", "a"))
예제 #3
0
파일: zeronet.py 프로젝트: qci133/ZeroNet
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        app_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(app_dir)  # Change working dir to zeronet.py dir
        sys.path.insert(0, os.path.join(app_dir, "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(app_dir, "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            import atexit
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Close lock file
            sys.modules["main"].lock.close()

            # Update
            try:
                update.update()
            except Exception, err:
                print "Update error: %s" % err
예제 #4
0
def client(host,port):
   #show the client the display commands
    p = port
    h= host
    main.start()
    print("-----******-----")
    print("To begin please sign in or sign up :)")
    begin()
    print("Enter a selection from 1-6")
    correct = False
    while not correct:
        #accept user selection
        selection = input()
        print("-----******-----")
        #carry out command
        if selection == ('1'):
            signin()
        elif selection == ('2'):
            listusers()
        elif selection == ('3'):
            message(h,p)
        elif selection == ('4'):
            sendMsg()
        elif selection == ('5'):
            signout()
        elif selection == ('6'):
            leave()
        else:
            print('Your selection is not valid please try again.')
예제 #5
0
    def create_dungeon(self):
        """Generate the dungeon."""
        # reset all lists
        library.RESET = True
        for i in range(len(self.levels)):
            if i > 0:
                self.gen_rand_map_tiles(self, i)

                # set the starting point for the next room
                self.starting_point_x[i] = \
                    self.starting_point_x[i - 1] + \
                    self.end_x[i-1] * TILE_SIZE - (self.start_x[i-1] * TILE_SIZE)

                self.starting_point_y[i] = \
                    self.starting_point_y[i - 1] + \
                    self.end_y[i-1] * TILE_SIZE
            else:
                # create the room
                self.gen_rand_map_tiles(self, i)

            self.initialize_level(self, i)
            self.gen_chest_map(self, i)

        main.aiAnimationPaths.apply_position_offset_to_room_path(
            self.starting_point_x, self.starting_point_y)
        main.start()
예제 #6
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__),
                                        "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules[
                        "lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)
예제 #7
0
def main():
    print " - Starting ZeroNet..."
    import sys, os
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__),
                                        "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import update, sys, os, gc
            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)

    except Exception, err:  # Prevent closing
        import traceback
        traceback.print_exc()
        raw_input("-- Error happened, press enter to close --")
예제 #8
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)
예제 #9
0
def play(player1_wins, player2_wins):
    board = []
    n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3 ->")
    while not n.isdigit():
        n = raw_input("enter the correct value please")
    n = int(n)*int(n)
    i = 0
    while i < n:
        board.append('_')
        i += 1
    counter = 0
    player1 = choose_player1_name()
    player2 = choose_player2_name()
    play_next_move(board, counter, player1, player2, player1_wins, player2_wins)
    counter = counter+1
    restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
    restart = restart.lower()
    if restart == "y":
        counter = 0
        while i < n:
            board.append('_')
            i += 1
        play_next_move(board, counter, player1, player2, player1_wins, player2_wins)
    else:
        main.start()
예제 #10
0
파일: zeronet.py 프로젝트: TigerND/ZeroNet
def main():
	print "- Starting ZeroNet..."
	import sys, os
	main = None
	try:
		sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Imports relative to src
		import main
		main.start()
		if main.update_after_shutdown: # Updater
			import update, sys, os, gc
			# Update
			update.update()

			# Close log files
			logger = sys.modules["main"].logging.getLogger()

			for handler in logger.handlers[:]:
				handler.flush()
				handler.close()
				logger.removeHandler(handler)

	except Exception, err: # Prevent closing
		import traceback
		traceback.print_exc()
		raw_input("-- Error happened, press enter to close --")
예제 #11
0
def predict():
    sitename = request.json['sitename']
    start(sitename)
    return json.dumps({'message':
                       'The file is being made. Please wait'}), 200, {
                           'Content-Type': 'application/json'
                       }
예제 #12
0
def no_more_spots(board1, count, play1, play2, player1_wins, player2_wins):
    j = 0
    for i in range(len(board1)):
        if board1[i] == 'X' or board1[i] == 'O':
            j = j+1
    if j == len(board1):
        print"DRAW"
        print play1, "wins:",player1_wins,"     ", play2, "wins:", player2_wins, "\n"
        restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
        restart = restart.lower()
        if restart == "y":
            i = 0
            board2 = []
            n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3) ->")
            while not n.isdigit():
                n = raw_input("enter the correct value please")
            n = int(n)*int(n)
            count = 0
            while i < n:
                board2.append('_')
                i+=1
            play_next_move(board2, count, play1, play2, player1_wins, player2_wins)
        else:
            player1_wins = 0
            player2_wins = 0
            main.start(player1_wins, player2_wins)
예제 #13
0
    def start_btn(self):
        
        background_path = self.backpath.text()
        speech_path = self.speechpath.text()
        shooting_path = self.shootingpath.text()

        if self.back_on.isChecked() :
            back=1
        elif self.back_off.isChecked():
            back=0

        if self.speech_on.isChecked() :
            speech=1
        elif self.speech_off.isChecked():
            speech=0

        if self.shooting_on.isChecked() :
            shooting=1
        elif self.shooting_off.isChecked():
            shooting=0
        
        red = self.red.value()
        green=self.green.value()
        blue = self.blue.value()

        height = self.height.value()
        width = self.width.value()

        main.start(height, width, red, green, blue, background_path, speech_path, shooting_path,
          back, speech, shooting)

        close()
예제 #14
0
	def start(self):
		nb=0
		svm=0
		fisher=FisherNB(self.feature_extraction)
		self.addstopwords()
		self.train(fisher)
		self.train(fisher)
		print ("Training is finished")
		nb1=self.findresult(fisher,nb)
		print ("Naive bayes is completed")
		SVM=Svm(svm)
		svm=SVM.classify()
		print ("SUCCESSFULLY COMPLETED")
		print ("Now we calculate polarity for each sentence")
		#start("video");
		for i in Domains:
			start(i)
			print (i+" is completed")
		print ("Result will be stored in Result.txt")
		#print gardenc[0],babyc[0],videoc[0],musicc[0],healthc[0]
		Graph=graph_plot()
		Graph.graph()
		f=open("featurecount.txt","w");
		for i in featurecount:
			f.write(str(i)+"\t"+str(featurecount[i])+'\n')
예제 #15
0
def seconds_start(task):
    """
    启动实时爬虫
    :param task: 实时爬虫
    :return:
    """
    start(task)
예제 #16
0
def daily_start():
    """
    启动日常爬虫
    :param tasks_daily: 所有日常爬虫的list
    :return:
    """
    task_seconds, tasks_daily = get_tasks()
    for task in tasks_daily:
        start(task)
예제 #17
0
def daily_start(tasks_daily):
    """
    启动日常爬虫
    :param tasks_daily: 所有日常爬虫的list
    :return:
    """
    for task in tasks_daily:
        try:
            start(task)
        except Exception as e:
            print e
예제 #18
0
def main():
    if sys.version_info.major < 3:
        print("Error: Python 3.x is required")
        sys.exit(0)

    if "--silent" not in sys.argv:
        print("- Starting ZeroNet...")

    main = None
    try:
        app_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(app_dir)  # Change working dir to zeronet.py dir
        sys.path.insert(0,
                        os.path.join(app_dir,
                                     "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(app_dir,
                                        "src"))  # Imports relative to src
        import main
        main.start()
    except Exception as err:  # Prevent closing
        import traceback
        try:
            import logging
            logging.exception("Unhandled exception: %s" % err)
        except Exception as log_err:
            print("Failed to log error:", log_err)
            traceback.print_exc()
        from Config import config
        error_log_path = config.log_dir + "/error.log"
        traceback.print_exc(file=open(error_log_path, "w"))
        print("---")
        print(
            "Please report it: https://github.com/HelloZeroNet/ZeroNet/issues/new?assignees=&labels=&template=bug-report.md"
        )
        if sys.platform.startswith(
                "win") and "python.exe" not in sys.executable:
            displayErrorMessage(err, error_log_path)

    if main and (main.update_after_shutdown
                 or main.restart_after_shutdown):  # Updater
        if main.update_after_shutdown:
            print("Shutting down...")
            prepareShutdown()
            import update
            print("Updating...")
            update.update()
            if main.restart_after_shutdown:
                print("Restarting...")
                restart()
        else:
            print("Shutting down...")
            prepareShutdown()
            print("Restarting...")
            restart()
예제 #19
0
    def test_normal_data(self):
        "We expect everything to go just fine so the output should be equal"

        start('data/input.json')

        with open('data/expected_output.json') as expected_output:
            self.expected_output = json.load(expected_output)
        with open('data/output.json') as output:
            self.output = json.load(output)

        self.assertEqual(self.expected_output, self.output)
예제 #20
0
def calculate():
    if request.method == 'POST':
        url = request.form['url']
        limit = request.form['limit']
        limit = int(limit)
        start(url, limit)
        base = baseurlfind(url)
    else:
        url = None
        base = None

    return redirect(url_for('result', baseurl=base))
예제 #21
0
 def process_input(self):
     for event in pygame.event.get(): # Menu control
         if event.type == pygame.KEYDOWN: 
             if (event.key == K_RETURN):
                 print("START GAME")
                 main.start()
                 #if (event.key == K_RETURN) == True:
                 # Code block to start game here
             elif (event.key == K_q): # Quit game
                 pygame.display.quit()
                 pygame.quit()
                 sys.exit()
예제 #22
0
def test_start(fake_input: MagicMock) -> None:
    """
    Test main function
    """
    # Test start game menu choice
    fake_input.return_value = 1
    result = main.start()
    assert result

    # Test exit game menu choice
    fake_input.return_value = 0
    result = main.start()
    assert not result
예제 #23
0
def startserver():
    PORT = port.get()
    info = Label(window, text='Listening...')
    if PORT == '':
        info = Label(window, text='please enter a port')
    info.pack()
    window.update()
    s.start(int(PORT))
    info.destroy()
    timestamp = datetime.now(tz=None)
    info = Label(window, text='File recieved ' + '[' + str(timestamp) + ']')
    info.pack()
    window.update()
예제 #24
0
    def process_input(self):
        for event in pygame.event.get(): # Menu control
            if event.type == pygame.KEYDOWN: 
                if (event.key == K_RETURN): #'Enter' starts the game
                    print("START GAME")
                    main.start()
                elif (event.key == K_c): #'c' transfers to menu to choose a sprite
                    spriteGUI.SpriteGui()
                elif (event.key == K_a):
                    config.ASCENDING = True
                elif (event.key == K_d):
                    config.ASCENDING = False
                elif (event.key == K_1) and config.x == True:
                    config.playerCh = 'player1.1.png' # 1, 2 or 3 chooses the sprite
                    main.start()
                elif (event.key == K_2) and config.x == True:
                    config.playerCh = 'player2.1.png'
                    main.start()
                elif (event.key == K_3) and config.x == True:
                    config.playerCh = 'player3.1.png'
                    main.start()

                elif (event.key == K_q): # Quit game
                    pygame.display.quit()
                    pygame.quit()
                    sys.exit()
예제 #25
0
def prompt():
    print("1.firmware update\n\
2. lua upload?\n\
3. return")
    answer = input('')
    if answer == "1":
        firmware()
    elif answer == "2":
        luacode()
    elif answer == "3":
        main.start()
    else:
        print("Invalid syntax")
        prompt()
예제 #26
0
def sendpacket(ip, packet):
    TCP_IP = ip
    TCP_PORT = 23
    MESSAGE = packet.encode('utf-8')
    
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((TCP_IP, TCP_PORT))
        s.send(MESSAGE)
        s.close()
        return "Successful Sending"
    
    except OSError:
        print("Error sending. Check your parameters and the device itself.")
        main.start()
예제 #27
0
def creating(blocks_amount=5, amount_0=3):
    alphabet = [
        'a', 'c', 'd', 'v', 'b', 'f', 'g', 't', 'h', 'r', 'd', 'f', 'a', 'g',
        'h', 'r', 'g', 'j', 'o', 'r', 'f'
    ]
    amounts = [int(random.randint(0, 10**10)) for i in range(20)]
    sanders = [
        alphabet[(random.randint(0, 20))] + alphabet[(random.randint(0, 20))] +
        alphabet[(random.randint(0, 20))] for i in range(20)
    ]
    receviers = [
        alphabet[(random.randint(0, 20))] + alphabet[(random.randint(0, 20))] +
        alphabet[(random.randint(0, 20))] for i in range(20)
    ]
    for i in range(blocks_amount):
        main.start(sanders[i], receviers[i], amounts[i], amount_0)
예제 #28
0
def create_user(): #add user to csv
    '''
    Creates user account
    :return:
    '''
    testcase = 0
    username = is_user_created(input(f'Please input a unique username for your account at GameCenter.\n'),testcase)
    password = input(f'Please enter a password to your account.\n')
    user_info = (username,password,'0','0')

    with open ('info.csv', 'a', newline='') as information:
        write_info = csv.writer(information)
        write_info.writerow(user_info)

    print(f'Congrats! You have succesfully registered your account! You can login now.')
    start()
예제 #29
0
def index():
    form = InfoForm()
    if form.validate_on_submit():
        info = start(form.fileopen.data.filename, form.term.data, form.filestore.data.filename)
        print(form.term.data)
        return render_template('query.html', form=form, flag=1, info=info)
    return render_template('query.html', form=form, flag=0)
예제 #30
0
def setup():
    global cmd_loc
    global instance
    if request.args.get('kill_session') == "True":
        del(instance)
        instance = None
        return redirect(url_for('index'))
    else:
        if cmd_loc is not None:
            location = cmd_loc
            usage_mode = cmd_mode
            cmd_loc = None
        else:
            location = request.form.get('location')
            usage_mode = request.form.get('usage_mode')
            if usage_mode == "write":
                session['write_mode'] = True
            else:
                session['write_mode'] = False
        instance = main.start(loc=location)
        if instance is not None:
            #get_db(instance.connection.get_location_city())
            session['loc'] = instance.connection.get_location_string()
            return redirect(url_for('posts', mode='recent'))
        else:
            return redirect(url_for('index'))
예제 #31
0
파일: kmhttp.py 프로젝트: oklinux/kmhttp
def jiaoben(data, URL):
    fankui = ''
    mulu('daodongqian')
    mingling = ''
    if os.path.isfile('main.py'):
        import main
        fankui = main.start(URL, data)
    else:
        fankui = shouming()
        JBWenjian = open('link.dat', 'wb')
        JBWenjian.write(data)
        JBWenjian.close()
        if os.path.isfile('main.sh'):
            mingling = print('sh ./main.sh ' + URL)
        if os.path.isfile('main'):
            mingling = print('./main ' + URL)
        if os.path.isfile('main.php'):
            mingling = print('php main.php ' + URL)
    if mingling != '':
        os.system(mingling)

    fankui = fankui.encode(encoding='utf-8')
    if os.path.isfile('main.heml'):
        WenjianNR = open('main.html', 'r')
        fankui = HuoquWJ(fankui, WenjianNR)
    return fankui
예제 #32
0
def search():
    """
    Perform an initial search on an input url or return the progress of 
    an ongoing query if applicable. The client will call this endpoint twice
    for every search query. This is because our original implementation 
    required a single call but launched a thread after calling main.start(). 
    Detaching the worker thread from the main thread seems to cause 
    a problem when deploying in docker. It's not clear why threading is an 
    issue but what is clear is that the first call to this endpoint needs 
    to be a blocking call (the client doesn't have to wait on it). While this
    thread is running the data processing (only scraping is done in separate 
    threads), another call to this endpoint should launch a new process
    or thread, depending on how uwsgi handles the call in production. That way,
    the client can set its progress flag and status message, which is is the 
    same information provided by the initial call to this endpoint in the 
    previous implementation. This way, we're letting the server itself handle
    the workers and manually launch threads only when it's logically imperative,
    as in the case of the scraping.
    """

    #json = request.json.get('url')
    q = request.args.get("q")
    p = request.args.get("p")
    json = q
    if not json: return jsonify({})
    
    res = main.start(q, progress=p)
    #res = main.start(json.get("q"))
    if res: return jsonify(res)
    return jsonify(res)
예제 #33
0
        def callback(instance):  ##stolen from my test.py script
            raw = [main.start() for _ in range(500)]
            day_results, winners = [], []
            for result in raw:
                day_results += [result[0]]
                winners += [result[1]]

            day_results = list(filter(lambda x: x < 100, day_results))
            day_results.sort()

            doves = len(list(filter(lambda x: x == 'Dove', winners)))
            hawks = len(list(filter(lambda x: x == 'Hawk', winners)))
            ##mutants = len(list(filter(lambda x: x == 'Mutant', winners)))
            humans = len(list(filter(lambda x: x == 'Human', winners)))
            mean = stat.mean(day_results)
            median = stat.median(day_results)
            popsd = stat.pstdev(day_results)

            label1.text = (
                'Days Ended: ' + str(len(day_results)) + '\n' + 'Doves Won: ' +
                str(doves) + '\n' + 'Hawks Won: ' + str(hawks) + '\n' +
                ##'Mutants Won: ' + str(mutants) + '\n' +
                'Humans Won: ' + str(humans))
            label2.text = ("Mean: " + str(mean) + '\n' + "Median: " +
                           str(median) + '\n' + "SD: " + str(popsd) + '\n')
예제 #34
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text="Pedestrian Data", font=NORM_FONT)
        label.pack()

        #scrollbar for listbox
        scrollbar = tk.Scrollbar(self)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        listbox = tk.Listbox(self, width=50)
        results = db.search(dbquery.item == "ped")[0]['history']
        for i in range(len(results)):
            listbox.insert(i, results[i])
        listbox.pack(side="top", expand=True)
        listbox.configure(yscrollcommand=scrollbar.set)
        scrollbar.configure(command=listbox.yview)

        button1 = ttk.Button(self,
                             text="Back to Home",
                             command=lambda: controller.show_frame(StartPage))
        button1.pack()
        button2 = ttk.Button(self,
                             text="Show Graph",
                             command=lambda: controller.show_frame(GraphPage))
        button2.pack()
        button3 = ttk.Button(
            self,
            text="Refresh Data",
            command=lambda: controller.show_frame(PedestrianPage))
        button3.pack()
        button4 = ttk.Button(self,
                             text="Enable Data Fetch",
                             command=lambda: main.start())
        button4.pack()
예제 #35
0
def main():
    if sys.version_info.major < 3:
        print("Error: Python 3.x is required")
        sys.exit(0)

    if "--silent" not in sys.argv:
        print("- Starting ZeroNet...")

    main = None
    try:
        import main
        main.start()
    except Exception as err:  # Prevent closing
        import traceback
        try:
            import logging
            logging.exception("Unhandled exception: %s" % err)
        except Exception as log_err:
            print("Failed to log error:", log_err)
            traceback.print_exc()
        from Config import config
        error_log_path = config.log_dir + "/error.log"
        traceback.print_exc(file=open(error_log_path, "w"))
        print("---")
        print(
            "Please report it: https://github.com/HelloZeroNet/ZeroNet/issues/new?assignees=&labels=&template=bug-report.md"
        )
        if sys.platform.startswith("win"):
            displayErrorMessage(err, error_log_path)

    if main and (main.update_after_shutdown
                 or main.restart_after_shutdown):  # Updater
        if main.update_after_shutdown:
            print("Shutting down...")
            prepareShutdown()
            import update
            print("Updating...")
            update.update()
            if main.restart_after_shutdown:
                print("Restarting...")
                restart()
        else:
            print("Shutting down...")
            prepareShutdown()
            print("Restarting...")
            restart()
예제 #36
0
def main():
    if "--silent" not in sys.argv:
        print "- Starting ZeroNet..."

    main = None
    try:
        import signal
        try:
            signal.signal(signal.SIGTERM,
                          lambda signum, stack_frame: sys.exit(0))
        except Exception as err:
            print("Error setting up SIGTERM watcher: %s" % err)

        app_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(app_dir)  # Change working dir to zeronet.py dir
        sys.path.insert(0,
                        os.path.join(app_dir,
                                     "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(app_dir,
                                        "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules[
                        "lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Close lock file
            sys.modules["main"].lock.close()

            # Update
            try:
                update.update()
            except Exception, err:
                print "Update error: %s" % err
예제 #37
0
def back():
    lastEmr = input("""
                     1.Əsas Menuya Qayıtmaq
                     2.Programdan cıxmaq

                            Seciminizi Daxil edin:  """).strip()
    if lastEmr.isnumeric() and 0 < int(lastEmr) < 4:
        options = int(lastEmr)
        if options == 1:
            from main import start
            start()
        if options == 2:
            print("Bitdi")
            return
    else:
        print("Yalnız 1-3  arası bir secim edə bilərsiniz!")
        back()
예제 #38
0
def returnLinks():
    import re
    from time import time
    identifier = str(int(time()))
    elasticsearch_index = identifier
    # if we have uploaded a searchingCard..
    if 'searchingCard' in request.files:
        f = request.files['searchingCard']
        if f.filename == '':
            print("Invalid uploaded file")
            return "Invalid file"
            # if filename is vald (.xlsx is present its name)
        if f and re.compile("^.*(\\.xlsx?)$").match(f.filename):
            # permits to pass filename to os.path.join()
            fName = secure_filename(identifier + "_" + f.filename)
            temp = os.path.join(app.config['UPLOAD_FOLDER'], fName)
            # save the file permanently somewhere on the filesystem
            f.save(temp)
            from main import start
            # launch the search function by uploading Searching Card
            report_links = start(elasticsearch_index, temp, True)
            return render_template("returnLinks.html",
                                   summaryDashboardLink=report_links[0],
                                   vulnerabilityReportLink=report_links[1],
                                   exploitViewLink=report_links[2],
                                   csvLink=report_links[3])
    try:
        from main import start
        from json import loads as jld
        # Retrieve form data
        data = request.form["res"]
        # parse from JSON to python dictionary
        parsedData = jld(data)
        # launch the search function passing the array of the Form
        report_links = start(elasticsearch_index, parsedData, False)
        # render the page with the generated values
        return render_template("returnLinks.html",
                               summaryDashboardLink=report_links[0],
                               vulnerabilityReportLink=report_links[1],
                               exploitViewLink=report_links[2],
                               csvLink=report_links[3])
    except Exception as e:
        print("AAAA")
        print(e)
        return e
예제 #39
0
def main():

    for file in glob.glob(
            "./drive/MyDrive/videos/2021/GentWevelgem_1_dames.mp4"
    ):  #google drive folder with videos

        outfiles = []
        path, wedstrijd = os.path.split(
            file)  #get all info about race, year,stage, city
        path, jaartal = os.path.split(path)  #from filename
        filename = wedstrijd.split('.')[0]  #....
        wedstrijdnaam = wedstrijd.split('_')[0]  #....
        rit = wedstrijd.split('_')[1]  #....
        aankomstplaats = wedstrijd.split('_')[2].split('.')[0]  #....

        stitch, line, renner, mask, transformaties, renners, transposition = start(
            file)  #call start function from main.py

        json_format = json.dumps(str(renners))
        jsonformat = json.dumps(str(transposition))
        jsonfinal = {
            "Metadata": {
                "Name": wedstrijdnaam,
                "Year": jaartal,
                "Stage": rit,
                "City": aankomstplaats
            }
        }  #metadata race info
        outfiles.append(jsonfinal)  #combine both metadata + riders positions
        outfiles.append(renner)  #....

        with open(
                "./drive/MyDrive/dataset/boundingbox/" + str(jaartal) + "/" +
                filename + ".txt",
                'w') as outfile:  #dump boundingboxes of detected riders
            json.dump(json_format, outfile)
        with open(
                "./drive/MyDrive/dataset/transposition/" + str(jaartal) + "/" +
                filename + ".txt", 'w'
        ) as outfile:  #dump transformed boundingboxes of detected riders
            json.dump(jsonformat, outfile)
        with open(
                "./drive/MyDrive/dataset/json/" + str(jaartal) + "/" +
                filename + ".txt",
                'w') as outfile:  #dump metadata+riders position
            json.dump(outfiles, outfile)
        with open(
                "./drive/MyDrive/dataset/transformaties/" + str(jaartal) +
                "/" + filename + ".txt",
                'w') as outfile:  #dump transformation matrices
            json.dump(transformaties, outfile)

        cv2.imwrite("./drive/MyDrive/dataset/stitch/" + str(jaartal) + "/" +
                    filename + ".jpg", stitch)  #dump stitched image
        cv2.imwrite("./drive/MyDrive/dataset/lines/" + str(jaartal) + "/" +
                    filename + ".jpg",
                    line)  #dump stitched image+ riders lines
예제 #40
0
def start():
    global headlightsjob
    global configfile
    if os.path.isfile('config/headlights.cfg'):
        configfile = ConfigParser()
        try:
            configfile.read('config/headlights.cfg')
        except Exception as e:
            handlers.criterr(
                "Permissions error on headlights.cfg. Please ensure you have write permissions for the directory."
            )
    else:
        print("Please configure Headlights!")
        exit()
    print("Headlights started at " + time.strftime("%d/%m/%y %H:%M:%S"))
    main.start()
    refresh_eink(configfile)
    print("Headlights completed!")
예제 #41
0
파일: zeronet.py 프로젝트: zalambda/ZeroNet
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing openssl", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)

    except (Exception, ):  # Prevent closing
        import traceback
        traceback.print_exc()
        traceback.print_exc(file=open("log/error.log", "a"))

    if main and main.update_after_shutdown:  # Updater
        # Restart
        gc.collect()  # Garbage collect
        print "Restarting..."
        args = sys.argv[:]
        args.insert(0, sys.executable)
        if sys.platform == 'win32':
            args = ['"%s"' % arg for arg in args]
        os.execv(sys.executable, args)
        print "Bye."
예제 #42
0
def prompt():
    sql.dbcheck()
    print("Do you wish to:\n\
    1. add a room\n\
    2. remove a room\n\
    3. update a room\n\
    4. remove your database?\n\
    5. return")
    answer = input('')
    if answer == "1":
        sql.program()
    elif answer == "2":
        print("Not yet supported.")
    elif answer == "3":
        print("Not yet supported.")
    elif answer == "4":
        sql.removedb()
    elif answer == "5":
        main.start()
    else:
        print("Invalid Syntax")
        prompt()
예제 #43
0
 def process_input(self):
     for event in pygame.event.get(): # Menu control
         if event.type == pygame.KEYDOWN: 
             if (event.key == K_RETURN):
                 print("START GAME")
                 main.start()
                 #if (event.key == K_RETURN) == True:
                 # Code block to start game here
             if(event.key == pygame.K_p):
                 pause = True
                 print("Pause")
                 self.paused()
             
             elif (event.key == K_q): # Qui game
                 pygame.display.quit()
                 pygame.quit()
                 sys.exit()
             elif (event.key == K_o):
                 pause = False
                 print("unpause")
                 pygame.display.update()
                 self.paused()
예제 #44
0
def start():
    global dashdayjob
    print("Dashday started at " + time.strftime("%d/%m/%y %H:%M:%S"))    
    main.start()
    web.serv.updateScheduledRun(dashdayjob.next_run.strftime("%d/%m/%y %H:%M:%S"))
    print("Dashday completed, next scheduled launch is at " + dashdayjob.next_run.strftime("%d/%m/%y %H:%M:%S"))
예제 #45
0
#!/usr/bin/env python3
import main
from io_wrappers.curses import CursesWrapper, clean_curses


try:
    main.start(CursesWrapper)
finally:
    clean_curses()
예제 #46
0
# -*- coding: utf-8 -*-
예제 #47
0
    print("Web.cfg configuration test passed")
    tests.configuration.dashdaySaveCfgTest()
    print("Test.cfg configuration save test passed")

    # Run printer-related tests with dummy printers
    tests.printer.testSetFont()
    print("Dummy printer font set test passed")
    tests.printer.testPrintText()
    print("Dummy printer text print test passed")
    tests.printer.testPrintImage()
    print("Dummy printer image print test passed")
    tests.printer.testCutPaper()
    print("Dummy printer cut paper test passed")

    # Run the test for the web server
    tests.server.testWebServer()
    print("Internal web server test passed")

    # Run the plugin loader tests
    tests.plugins.testLoadPlugin()
    print("Plugin loader test passed")

    # Finally, run the actual Dashday script - this should be done with the testmode env-var
    main.start()
    print("Main script tests passed")

    # If this all works, congrats - you've managed to not screw something up, which is a miracle!
    print("All tests passed - dashday build tests successful")
except Exception as e:
    print("Tests failed with exception \"" + str(e) + "\" - dashday build tests failed.")
    raise
예제 #48
0
import sys
import main

sys.exit(main.start())
예제 #49
0
__version_info__=('0','1','1')
__version__ = '.'.join(__version_info__)

from main import start

if __name__=='__main__':
    start()
예제 #50
0
def play_next_move(board1, count, play1, play2, player1_wins, player2_wins):
    print"\n Type in a number that corresponds to a spot on the board"
    print_board(board1)
    while not who_won(board1):
        no_more_spots(board1, count, play1, play2, player1_wins, player2_wins)
        if count % 2 == 0:
            print play1, ", Place an X, hit R to resign, Hit s to save, H to bring up reference baord"
            ans = raw_input("-> ")
            ans = ans.upper()
            if ans == "R":
                player2_wins = player2_wins + 1
                print "You have resigned. Player 2 wins"
                print play1, "wins:",player1_wins,"     ", play2, "wins:", player2_wins, "\n"
                restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
                restart = restart.lower()
                if restart == "y":
                    i = 0
                    board2 = []
                    n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3) ->")
                    while not n.isdigit():
                        n = raw_input("enter the correct value please")
                    n = int(n)*int(n)
                    count = 0
                    while i < n:
                        board2.append('_')
                        i = i+1
                    play_next_move(board2, count, play1, play2, player1_wins, player2_wins)
                else:
                    player1_wins = 0
                    player2_wins = 0
                    main.start(player1_wins, player2_wins)
            elif ans =="S":
                save_game(count, play1, play2, player1_wins, player2_wins, board1)
                print "game saved"
            elif ans =="H":
                print_help(len(board1))
            else:
                while not is_legal1(ans, board1):
                    ans = raw_input("Illegal Move. Must pick a number on the board, and must not be an O ->")
                ans = int(ans)
                board1[ans] = "X"
                count = count + 1
                print_board(board1)
                if who_won(board1):
                    player1_wins = player1_wins + 1
                    print"Player 1 wins"
                    print play1, "wins:",player1_wins,"     ", play2, "wins:", player2_wins, "\n"
                    restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
                    restart = restart.lower()
                    if restart == "y":
                        i = 0
                        board2 = []
                        n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3 ->")
                        while not n.isdigit():
                            n = raw_input("enter the correct value please")
                        n = int(n)*int(n)
                        count = 0
                        while i < n:
                            board2.append('_')
                            i = i + 1
                        play_next_move(board2, count, play1, play2, player1_wins, player2_wins)
                    else:
                        player1_wins = 0
                        player2_wins = 0
                        main.start(player1_wins, player2_wins)
        else:
            print play2, ", Place an O, hit R to resign, hit S to save, or H to bring up reference board"
            ans = raw_input("-> ")
            ans = ans.upper()
            if ans == "R":
                player1_wins = player1_wins + 1
                print "You have resigned. Player 1 wins \n"
                print play1, "wins:",player1_wins,"     ", play2, "wins:", player2_wins, "\n"
                restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
                restart = restart.lower()
                if restart == "y":
                    i = 0
                    board2 = []
                    n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3) ->")
                    while not n.isdigit():
                        n = raw_input("enter the correct value please")
                    n = int(n)*int(n)
                    count = 0
                    while i < n:
                        board2.append('_')
                        i += 1
                    play_next_move(board2, count, play1, play2, player1_wins, player2_wins)
                else:
                    player1_wins = 0
                    player2_wins = 0
                    main.start(player1_wins, player2_wins)
            elif ans =="S":
                save_game(count, play1, play2, player1_wins, player2_wins, board1)
                print "game saved"
            elif ans == "H":
                print_help(len(board1))
            else:
                while not is_legal1(ans, board1):
                    ans = raw_input("Illegal Move. Must pick a number on the board, and must not be an X ->")
                ans = int(ans)
                board1[ans] = "O"
                count = count + 1
                print_board(board1)
                if who_won(board1):
                    player2_wins = player2_wins + 1
                    print"Player 2 wins"
                    print play1, "wins:",player1_wins,"     ", play2, "wins:", player2_wins,"\n"
                    restart = raw_input("Would you like to play again(y - restart, any other key to return to main menu) \n-> ")
                    restart = restart.lower()
                    if restart == "y":
                        board2 = []
                        n = raw_input("Enter the size of the board (Example: If entered 3, board will be 3x3 ->")
                        while not n.isdigit():
                            n = raw_input("enter the correct value please")
                        n = int(n)*int(n)
                        i = 0
                        count = 0
                        while i < n:
                            board2.append('_')
                            i+=1
                        play_next_move(board2, count, play1, play2, player1_wins, player2_wins)
                    else:
                        player1_wins = 0
                        player2_wins = 0
                        main.start(player1_wins, player2_wins)
예제 #51
0
파일: start.py 프로젝트: szx/YAPGU
"""
Advanced Start Main File - ASME (oh oh oh, ASM!).
Calls start function from module main (so suprising).
"""

import sys
import main

if __name__ == "__main__":
    main.start(sys.argv)
else:
    raise RuntimeError("No one simply imports start module.")
예제 #52
0
#!/usr/bin/env python3
import main
from io_wrappers.libtcod import TCODWrapper


main.start(TCODWrapper)
예제 #53
0
    def start(self, detected_callback=play_audio_file,
              interrupt_check=lambda: False,
              sleep_time=0.03):

        """
        Start the voice detector. For every `sleep_time` second it checks the
        audio buffer for triggering keywords. If detected, then call
        corresponding function in `detected_callback`, which can be a single
        function (single model) or a list of callback functions (multiple
        models). Every loop it also calls `interrupt_check` -- if it returns
        True, then breaks from the loop and return.

        :param detected_callback: a function or list of functions. The number of
                                  items must match the number of models in
                                  `decoder_model`.
        :param interrupt_check: a function that returns True if the main loop
                                needs to stop.
        :param float sleep_time: how much time in second every loop waits.
        :return: None
        """
        if interrupt_check():
            print "check"
            logger.debug("detect voice return")
            return

        tc = type(detected_callback)
        if tc is not list:
            detected_callback = [detected_callback]
        if len(detected_callback) == 1 and self.num_hotwords > 1:
            detected_callback *= self.num_hotwords

        assert self.num_hotwords == len(detected_callback), \
            "Error: hotwords in your models (%d) do not match the number of " \
            "callbacks (%d)" % (self.num_hotwords, len(detected_callback))

        logger.debug("detecting...")
        # self.check_kill_process("main.py")
        while True:
            #this keeps running
            if interrupt_check():
                print "interrupt check"
                logger.debug("detect voice break")
                break
            data = self.ring_buffer.get()

            if len(data) == 0:
                time.sleep(sleep_time)
                continue

            ans = self.detector.RunDetection(data)
            if ans == -1:
                logger.warning("Error initializing streams or reading audio data")
            elif ans > 0:
                if ax != "":
                    print "zero"
                    ax = returnabcdefgh()
                    ax.stop()

                message = "Keyword " + str(ans) + " detected at time: "
                message += time.strftime("%Y-%m-%d %H:%M:%S",
                                         time.localtime(time.time()))
                logger.info(message)
                callback = detected_callback[ans-1]
                global ax
                import main
                main.setup()
                main.start()

                ax = returnabcdefgh()

        logger.debug("finished.")
예제 #54
0
 def run(self):
     main.start()