Beispiel #1
0
 def eachGrid(self, image):
     width, height = image.shape
     cell_size = int(width / 9)
     count = 0
     each_row = list()
     sudoku = list()
     for w in range(0, width, cell_size):
         for h in range(0, height, cell_size):
             current_cell = image[w + 5:w + cell_size - 5,
                                  h + 5:h + cell_size - 5]
             contours, _ = cv2.findContours(current_cell, cv2.RETR_LIST,
                                            cv2.CHAIN_APPROX_SIMPLE)
             if contours:
                 conts = sorted(contours, key=cv2.contourArea, reverse=True)
                 cnt = conts[0]
                 if cv2.contourArea(cnt) > cell_size * cell_size * 0.03:
                     count += 1
                     helper.showImage(helper.randomString(2), current_cell)
                     #cv2.imwrite('src\digit detection\data2' + '\\' + helper.randomString(2) + '.jpg', current_cell)
                     pred_digit = recognizeDigit(current_cell)
                 else:
                     pred_digit = 0
             else:
                 pred_digit = 0
             each_row.append(pred_digit)
             if len(each_row) == 9:
                 sudoku.append(each_row)
                 each_row = list()
     print(count)
     print(sudoku)
    def register(self, email: str, username: str, password: str) -> User:
        if self.db.find_user(username=username):
            raise Exception({"error_message": "Username is already taken"})

        if self.db.find_user(email=email):
            raise Exception({"error_message": "Email is already registered"})

        salt = randomString(32)
        hashed_password = hash_password(password, salt)
        user = User(None, username, email, None, hashed_password, salt)
        self.db.add_user(user)
        return self.get_user(username=username)
def set_password_lost(self, user_id, empty=False):
    db, cursor = self._connect()
    if empty:
        token = None
    else:
        randStr = randomString(stringLength=12)
        token = bcrypt.generate_password_hash(randStr).decode()
    update_user = "******"
    try:
        cursor.execute(update_user, (token, user_id))
        db.commit()
        return token if cursor.rowcount == 1 else None
    finally:
        db.close()
Beispiel #4
0
def register():
    post_data = request.get_json()

    # Check if the username already exist
    if User.query.filter(User.email == post_data['email']).count():
        return jsonify({"error_message": "Email is already registered"}), 403

    if User.query.filter(User.username == post_data['username']).count():
        return jsonify({"error_message": "Username is already taken"}), 403

    salt = randomString(32)
    hashed_password = hash_password(post_data['password'], salt)
    new_user = User(username=post_data['username'],
                    email=post_data['email'],
                    password=hashed_password,
                    password_salt=salt)

    try:
        db.session.add(new_user)
        db.session.commit()
    except:
        db.session.rollback()

    return jsonify({"status": "OK"})
Beispiel #5
0
class SimpleClient:
    "Simple client that communicats with a socket server."

    server_public_key = ""
    # append a random string to client secret for each connection.
    client_secret = "This is Client Secret - UniqueKey=" + randomString(10)

    def __init__(self, host='127.0.0.1', port=9500):
        self._server = host
        self._port = port

    def create_socket(self):
        try:
            return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as err:
            print("socket creation failed with error")

    def connect_to_server(self):
        # Initial communication with server
        msg = input("Type in 'Hello' to get Hi response from server: ")
        server_response = self.sendToServer("Sending msg: ", msg)
        print('1. Response received: ', server_response)

        #Check if response has Certificate marker in msg.
        if server_response.find("CA:") > -1 or server_response.find(
                "DB:") > -1:
            response_cert = server_response

            print("Sending cert to CA server .....")
            # Verify Cert. with CA
            CA_status = self.checkWithCA('127.0.2.1', 9000, response_cert)

            if CA_status == True:
                print("Certificate is valid. You may proceed")
                print("Recieved public key for CA server...")
                print("Public Key = " + self.server_public_key)
                # TODO: Send Secret using "server public key"
                print("Sending Secret using server public key")

                # Create Secret.
                encrypt_client_secret = simpleCipher(
                    self.server_public_key + "~" + self.client_secret, 1, 'e')

                # Send Secret
                server_response = self.sendToServer(
                    "2. Encrypted Secret = " + encrypt_client_secret,
                    encrypt_client_secret)

                # Check if response uses secret
                if server_response.find("VojrvfLfz") > -1:
                    print('- Received secret response: ' + server_response)
                    print("- Deciphered: '" +
                          simpleCipher(server_response, 1, 'd') + "'")

                    # Now communication can proceed in a secure manner
                    # Create a second enccrypted message
                    encrypt_client_msg = simpleCipher(
                        "Here is a test message!! :)" + "~" +
                        self.client_secret, 1, 'e')
                    server_response = self.sendToServer(
                        "3. Test Secret Msg = " + encrypt_client_msg,
                        encrypt_client_msg)

                    print('- Server response to secret msg:  ' +
                          server_response)
                    print('- Server response decrypted: ' +
                          simpleCipher(server_response, 1, 'd'))
            else:
                print("Warning: Certificate is invalid!!!")

    def sendToServer(self, announce, msg):
        """ Creates a socket and send a message.

        Parameters:
            announce(str): Announcement to display before message sent.
            msg (str): Message to send.
            return (byte): Returns the response messaage received.
        """
        response_msg = ""
        try:
            sock = self.create_socket()
            sock.connect((self._server, self._port))

            print(announce + "....")

            sock.sendall(msg.encode())

            result = sock.recv(4096)

            response_msg = result.decode()

        except Exception as err:
            print("Msg Send Error:\n {0}".format(err))

        return response_msg

    def checkCA(self, cert):
        """ Creates a socket and send a message to CA Server.

        Parameters:
            cert (str): certificate to send to CA server. 

        Return:
            status (bool): If CA validates cert or not.           
        """
        status = False
        try:
            sock = self.create_socket()
            sock.connect((self._server, self._port))

            print("Sending CA cert for verification....")

            sock.sendall(cert.encode())

            result = sock.recv(4096)

            response_msg = result.decode()
            print('Response received: ', response_msg)

            if response_msg != 'INVALID':
                status = True
                self.server_public_key = response_msg

        except Exception as err:
            print("CheckCA() Connection Error:\n {0}".format(err))

        return status

    def checkWithCA(self, host, port, cert):
        """ A certificate has been received, Check with CA if it's valid 
        
        Parameters:
            host (str): server ip address.
            port (int): Port number used by server.
            cert (str): Server certificate.

        Return:
            ca_response (byte): Server response.
        """
        ca_client = SimpleClient(host, port)
        ca_response = ca_client.checkCA(cert)
        # Bring public key over from CA server instance.
        self.server_public_key = ca_client.server_public_key
        return ca_response
Beispiel #6
0
    print('Evaluation weight is: ' + str(evalWeight))
    print('Alpha-beta: ' + str(pruning))
    print('These parameters can be passed as command line arguments\n')

if __name__ == '__main__':
   main(sys.argv[1:])

# Initialize game
gameState = gameState.GameState()
gameController = gameController.GameController()
socketHandler = socketHandler.SocketHandler(const.IP, const.PORT)
messageHandler = messageHandler.MessageHandler(gameState, gameController, socketHandler)
messageDispatcher = messageDispatcher.MessageDispatcher(gameState, gameController, socketHandler)

# TODO: handle case when failed to connect
username = helper.randomString()
messageDispatcher.connect()
messageDispatcher.login(username, gameId)

if not gameState.isFinished():
    messageHandler.receiveAndProcessMessages()

if not gameState.isFinished():
    print('[INFO] Waiting for game to start...\n')
    messageHandler.receiveAndProcessMessages()

# Strategy functions
bestMaxMove = []
calculationTimes = []
nodesEvaluated = 0
allNodesEvaluated = []
Beispiel #7
0
def clientSendMessage(event=None):
  global ip, port
  message = h.randomString(256)
  print "call EchoClient with long message", ip, port
  client = EchoClient(ip, port, message)
def user_settings():
    """User settings"""
    id = get_jwt_identity()
    message = error = ''

    if request.method == 'POST':
        form = request.form.to_dict()

        # Avatar
        file = request.files['avatar']
        if file and file.filename != '':
            if allowed_file(file.filename):
                filename = secure_filename(file.filename)
                os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
                img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(img_path)
                generate_miniatures(img_path, id)
                os.remove(img_path)
        if form['remove_avatar'] == '1':
            remove_miniatures(id)

        # Ensure checkbox are boolean and not 'on'
        form['share_email'] = False if form.get(
            'share_email') is None else True
        form['share_phone'] = False if form.get(
            'share_phone') is None else True
        form['has_whatsapp'] = False if form.get(
            'has_whatsapp') is None else True
        form['notif_new_event'] = False if form.get(
            'notif_new_event') is None else True
        form['notif_event_change'] = False if form.get(
            'notif_event_change') is None else True
        form['notif_tomorrow_events'] = False if form.get(
            'notif_tomorrow_events') is None else True

        # Remove extra fields that would break UserAPI.put_from_dict()
        del form['csrf_token']
        del form['remove_avatar']

        code, result = UserAPI.put_from_dict(id, form)
        if code == 200:
            message = lang['saved']

            # Regenerate new token so that new infos are stored in claims
            claims = get_jwt()
            claims['id'] = id
            claims['firstname'] = form['firstname']
            claims['lastname'] = form['lastname']
            claims['theme'] = form['theme']
            claims['notif_event_change'] = int(form['notif_event_change'])

            # message is lost... but we have to redirect for csrf_token variable
            return regenerate_claims(claims, '/settings')
        else:
            #print(result)
            error = lang['saved_error']

    header = render_template('header.html',
                             **lang,
                             is_connected=id is not None)

    #user_item = api_user.get(id) # can't get theme
    user_item = database.manager.db.get_user(user_id=id)

    themes = settings.themes.copy()
    if user_item['theme'] != settings.default_theme:
        themes[settings.default_theme] += ' (' + lang['default'] + ')'

    csrf_token = get_jwt().get("csrf")
    return render_template('user_settings.html',
                           **lang,
                           header=header,
                           user=user_item,
                           themes=themes,
                           csrf_token=csrf_token,
                           message=message,
                           error=error,
                           user_id=id,
                           random=randomString())
import socket
import helper as h
import sys

thp = (socket.gethostname(), 5555)
tbo = ("<broadcast>", 5555)
cid = h.randomString(10)
# create an INET, UDP socket
udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
udpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
udpsocket.settimeout(5)

# bind the socket to a public host Server
#udpsocket.bind(thp)

if len(sys.argv) == 2:
  msg = sys.argv[1]
else:
  msg = h.randomString(5)

try:
  udpsocket.sendto(msg, tbo)
  #(msg,ipp) = udpsocket.recvfrom(1024)
  print "Response: %s" % udpsocket.recv(1024)  
except socket.timeout:
    print "No server found"

while msg != "stop":
  try:
    (msg,ipp) = udpsocket.recvfrom(1024)
    print msg
import socket
from time import time
import helper as h

clientname = h.randomString(6)
print "My Name is",clientname
#create an INET, STREAMing socket
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM) # tcp SOCK_STREAM | udp SOCK_DGRAM

s.connect((socket.gethostname(),5555))

s.send(clientname+" "+ str(time()))
msg = s.recv(1024)
print "1 "+msg+" back on "+ str(time())
msg = s.recv(1024)
print "2 "+msg
msg = s.recv(1024)
print "3 "+msg
msg = s.recv(1024)
print "4 "+msg



s.shutdown(1)