Python

A python game in easy way


“I have a small code of python its very easy to implement for a small game,I have refered it from somewhere and posting for is there any more easiest way for tic tac toe game I have a small code of python its very easy to implement for a small game,I have refered it from somewhere and posting for is there any more easiest way for tic tac toe game”

#Import
import os
import time
import random

#Define the board
board = ["", " ", " ", " ", " ", " ", " ", " ", " ", " "]

#Print the header
def print_header():
    print"""

 To play Tic-Tac-Toe, you need to get three in a row...
 Your choices are defined, they must be from 1 to 9...

"""

#Define the print_board function 
def print_board():
    print "   |   |   "
    print " "+board[1]+" | "+board[2]+" | "+board[3]+"  "
    print "   |   |   "
    print "---|---|---"
    print "   |   |   "
    print " "+board[4]+" | "+board[5]+" | "+board[6]+"  "
    print "   |   |   "
    print "---|---|---"
    print "   |   |   "         
    print " "+board[7]+" | "+board[8]+" | "+board[9]+"  "
    print "   |   |   "

def is_winner(board, player):
    if (board[1] == player and board[2] == player and board[3] == player) or 
        (board[4] == player and board[5] == player and board[6] == player) or 
        (board[7] == player and board[8] == player and board[9] == player) or 
        (board[1] == player and board[4] == player and board[7] == player) or 
        (board[2] == player and board[5] == player and board[8] == player) or 
        (board[3] == player and board[6] == player and board[9] == player) or 
        (board[1] == player and board[5] == player and board[9] == player) or 
        (board[3] == player and board[5] == player and board[7] == player):
        return True
    else:
        return False

def is_board_full(board):
    if " " in board:
        return False
    else:
        return True

while True:
    os.system("clear")
    print_header()
    print_board()

    #Get Player X Input
    choice = raw_input("Please choose an empty space for X. ")
    choice = int(choice)

    #Check to see if the space is empty first
    if board[choice] == " ":
        board[choice] = "X"
    else:
        print "Sorry, that space is not empty!"
        time.sleep(1)

    #Check for X win
    if is_winner(board, "X"):
        os.system("clear")
        print_header()
        print_board()
        print "X wins! Congratulations"
        break

    os.system("clear")
    print_header()
    print_board()

    #Check for a tie (is the board full)
    #If the board is full, do something
    if is_board_full(board):
        print "Tie!"
        break

    #Get Player O Input
    choice = raw_input("Please choose an empty space for O. ")
    choice = int(choice)

    #Check to see if the space is empty first
    if board[choice] == " ":
        board[choice] = "O"
    else:
        print "Sorry, that space is not empty!"
        time.sleep(1)

    #Check for O win
    if is_winner(board, "O"):
        os.system("clear")
        print_header()
        print_board()
        print "O wins! Congratulations"
        break

    #Check for a tie (is the board full)
    #If the board is full, do something
    if is_board_full(board):
        print "Tie!"
        break



لینک منبع

python – lexical dispersion-plot with matplotlib


I need to plot a graph (of which I am not sure, if it has a specific name: some call it (lexical) “dispersion”-plot (NLTK), others “barcode” (matplotlib)). I have a text, which I split in words and I want the graph to draw a thin line every time the word appears in the text. I want to do this with the matplotlib in python3. (The post “Lexical dispersion plot is seaborn” is very similiar to my question, but it uses stripplot from seaborn, but I want to do it with matplotlib.)

I wrote a code, but it needs an unbelievable amount of time to draw it. My question is, how to improve this code or how to make it right in the first place. Here is a MWE:

import matplotlib.pyplot as plt
text = open("file.txt", "r", encoding="utf-8").read()
words = re.split("W", text.lower())
WORD = "rabbit"
x = [i for i in range(0,len(words))]
y = [1 if w == WORD else 0 for w in words]
fig, ax = plt.subplots()
ax.bar(x, y, width=0, edgecolor="red")
ax.set_xticks([])
ax.set_yticks([])

example dispersion- or barcode-plot



لینک منبع

Python How to extract specific string into multiple variable


i am trying to extract a specific line as variable in file.

this is content of my test.txt

#first set
Task Identification Number: 210CT1
Task title: Assignment 1
Weight: 25
fullMark: 100
Description: Program and design and complexity running time.

#second set
Task Identification Number: 210CT2
Task title: Assignment 2
Weight: 25
fullMark: 100
Description: Shortest Path Algorithm

#third set
Task Identification Number: 210CT3
Task title: Final Examination
Weight: 50
fullMark: 100
Description: Close Book Examination

this is my code

with open(home + '\Desktop\PADS Assignment\test.txt', 'r') as mod:
    for line in mod:
        taskNumber , taskTile , weight, fullMark , desc = line.strip(' ').split(": ") 
        print(taskNumber)
        print(taskTile)
        print(weight)
        print(fullMark)
        print(description)

here is what i’m trying to do:

taskNumber is 210CT1 
taskTitle is Assignment 1
weight is 25
fullMark is 100
desc is Program and design and complexity running time

and loop until the third set 

but there’s an error occurred in the output

ValueError: not enough values to unpack (expected 5, got 2)



لینک منبع

IOError: [Errno 0] Error, in python file handling



    with open(host_temp,'r+') as file:
            content=file.read()
            print(content)
            file.write(redirect+ " "+web + "n")

This Code always shows :


    Traceback (most recent call last):
      File "./website_blocker.py", line ۴, in 
        file.write(redirect+ " "+web + "n")
    IOError: [Errno ۰] Error

How can solve this problem???



لینک منبع

python iterate over a list and remove any duplicates found within lists inside a dictionary and remove the duplicates


i have a list of numbers and a dictionary with names(key) and numbers(values)
i need to iterate over the list called lotto and and then check them against the values of the names in the dictionary and if i get a match remove that number from the dictionary value.

heres what i have so far but it just prints out the origanal dictionary keys and values

players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto =[1,2,3,4,5,6,]

for i in players.values():  
    if i in lotto:
       players.values.remove(i)  

print (players)

any help appriciated



لینک منبع

python – Splunk download using dask delayed


I am trying to download data from a splunk instance for a period of time using delayed. I have created a function that works like this:

@delayed
def _execute_query(query, time_period):
    spl_service = Service(username, password, host, port)
    return spl_service(query, time_period)

def execute_splunk_query(query, time_period):
    time_periods = time_period.split(timedelta(minutes=10)
    delayed = []
    for tm_per in time_periods:
        results = _execute_query(query, tm_per)
        delayed.append(results)
    return delayed

Assume data are larger than my laptops memory for that period of time so I want to use dask for it. I use the distributed scheduler so I set up a local cluster like this

from dask.distributed import Client
client = Client()
# setup query and time_period

results = execute_splunk_query(query, time_period)

# i do the following to convert to dataframe
results_bag = dask.bag.from_delayed(results)
data_df = results_bag.to_dataframe()
data_df.persist() # works with client and local cluster

Then this process takes too long and I get a MemoryError. So I have some questions on that:

  1. Doesn’t dask take care of that (Memory) by moving data from memory to disk? Does this work when persisting data.
  2. I see that when the delayed tasks are executed I don’t see any performance boost, like they are executed sequenctially and not in parallel. I can see that is true also in dask dashboard.

Could you please explain the above a little more in details?



لینک منبع

python – Filtering on pgcrypto encrypted column in SQLAlchemy


In SQLAlchemy custom types documentation there is example of custom column that encrypts data with pgcrypto in transparent fashion. It generally works well, minus filtering/sorting that doesn’t. Example code is as following:

from sqlalchemy import create_engine, String, Integer, func, 
    Column, type_coerce

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session

from sqlalchemy.dialects.postgresql import BYTEA


Base = declarative_base()


class PGPString(BYTEA):
    def __init__(self, passphrase, length=None):
        super(PGPString, self).__init__(length)
        self.passphrase = passphrase

    def bind_expression(self, bindvalue):
        # convert the bind's type from PGPString to
        # String, so that it's passed to psycopg2 as is without
        # a dbapi.Binary wrapper
        bindvalue = type_coerce(bindvalue, String)
        return func.pgp_sym_encrypt(bindvalue, self.passphrase)

    def column_expression(self, col):
        return func.pgp_sym_decrypt(col, self.passphrase)


class ColumTest(Base):
    __tablename__ = 'columntest'

    id = Column(Integer, primary_key=True)
    message = Column('message', PGPString(
        "this is my passphrase"))


e = create_engine('postgres://postgres:password@WSX@localhost:5432/testdb', echo='debug')

Base.metadata.create_all(e)

s = Session(e)

o = ColumTest(message='test')
s.add(o)
s.commit()
s.query(ColumTest).filter(ColumTest.message == 'test').all()

The problem is that SQLAlchemy generates SQL on filter as such:

s.query(ColumTest).filter(ColumTest.message == 'test').all()
۲۰۱۷-۰۸-۱۷ ۱۱:۱۵:۰۸,۹۱۵ INFO sqlalchemy.engine.base.Engine SELECT columntest.id AS columntest_id, pgp_sym_decrypt(columntest.message, %(pgp_sym_decrypt_1)s) AS columntest_message 
FROM columntest 
WHERE columntest.message = pgp_sym_encrypt(%(message_1)s, %(pgp_sym_encrypt_1)s)
۲۰۱۷-۰۸-۱۷ ۱۱:۱۵:۰۸,۹۱۵ INFO sqlalchemy.engine.base.Engine {'message_1': 'test', 'pgp_sym_decrypt_1': 'this is my passphrase', 'pgp_sym_encrypt_1': 'this is my passphrase'}
۲۰۱۷-۰۸-۱۷ ۱۱:۱۵:۰۸,۹۱۷ DEBUG sqlalchemy.engine.base.Engine Col ('columntest_id', 'columntest_message')

Filtering doesn’t work because pgp_sym_encrypt value is salted. And I would like to use aliased columntest_message that holds decrypted message instead because that would allow me to sort data, too. How can it be achieved, preferably on column definition level so there would be no necessity to rewrite existing queries? Thanks!



لینک منبع

I wanted to download videos in bulk from Tutsplus.com using python. I have a legit subscription


Below is the the section for downloading videos from a given course. Now the information is printed perfectly on the terminal but the videos do not get downloaded. Please help!!

def download_binary(_file_name_, _url_):
print "Downloading %s " % _file_name_
response = urllib.request.urlopen(_url_)
# req = urllib2.urlopen(_url_)
output = open(_filename_,"wb")
output.write(response.read())
CHUNK = 16 * 1024
with open(_file_name_, 'wb') as fp:
while True:
chunk = response.read(CHUNK)
if not chunk:
break
fp.write(chunk)



لینک منبع

python – OperationalError at /admin/login/ FATAL: password authentication failed for user – Django & Postgres &


Heyy, I have been struggling with this for a while now..

I have hosted a website on Digital Ocean using ubuntu, nginx, gunicorn, virtualenv, Postgres and Django and while the site is visible and working, logging into the admin page gives me this error:

OperationalError at /admin/login/
FATAL:  password authentication failed for user "usr"
FATAL:  password authentication failed for user "usr"
Request Method: POST
Request URL:    https://www.***.com/admin/login/?next=/admin/
Django Version: 1.11
Exception Type: OperationalError
Exception Value:    
FATAL:  password authentication failed for user "usr"
FATAL:  password authentication failed for user "usr"
Exception Location: /***/lib/python3.5/site-packages/psycopg2/__init__.py in connect, line 130
Python Executable:  ***
Python Version: 3.5.2

Note: for privacy reasons I have replaced the user for postgres with “usr” ,the websites address with “***” and the database name with “db”.

The connection is not happening between my Postgres user and Postgres database.

When I run:sudo -u postgres psql -U usr db I get the same error.


I use environment variables for the passwords as you can see below:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db',
        'USER': 'usr',
        'PASSWORD': os.environ["DB_PASSWORD"],
        'HOST': 'localhost',
    }
}

My environment variables are in the .bashrc file:

export DB_PASSWORD="*******"

export SECRET_KEY="******************************"

when I run the python shell and print the DB_PASSWORD that I import from the OS library, the password is correct.

What could be the cause of this problem? Thank you in advance!



لینک منبع