Ada - case/switch invalid token - switch-statement

I am trying to read from a file line by line using a code at the beginning of the line as a condition for a case statement to determine which operation to perform with the rest of the data in the same line.
The file text is as follows:
IL Sales Mary Sales_person 1378 25.46
IL Sales Mary Sales_person 1364 20.13
IR Sales Vallerie Manager 1358 27.15
IL Media Marty Manager 1444 25.17
IR Media Bob spokesperson 1416 10.13
IL Crew Sally Pilot 675 35.11
IR Media David Designer 1412 20.76
DL Media
DR Media
PA
PD Media
DD Sales
PD Sales
I have the codes (IL, IR, DL, DR, PA, PD, DD) as enumeration types here:
type CodeType is(IL, IR, DL, DR, PA, PD, DD);
package CodeTypeIO is new Ada.Text_IO.Enumeration_IO(CodeType);
use CodeTypeIO;
My case/switch is as follows:
Open(File => fileIn, Mode => In_File, Name => "input.txt");
Create(File => fileOut, Mode => Out_File, Name => "output.txt");
loop
get(fileIn, code);
case code is
when IL =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inLeftNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when IR =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when DL =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when DR =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when PA =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when PD =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
when DD =>
get(fileIn, deptIn);
get(fileIn, eNameIn);
get(fileIn, titleIn);
get(fileIn, IDIn);
FloatIO.get(fileIn, payrateIn);
inRightNode(deptIn, eNameIn, titleIn, IDIn, payrateIn);
end case;
end loop;
I am getting an "invalid token" error at every "when 'whatever code' ->" line. I've tried a few adjustments and googled about invalid tokens but haven't found quite what I'm looking for to fix my issue.
Errors were corrected by changing all " -> " to " =>" and changing "get(fileIn, line);" & "case line is" to "get(fileIn, code);" & "case code is".
The corrections are reflected in the sample code above.

Related

How does my server know that a client has disconnected?

So i have a TCP connection with a select, to handle multiple clients.
These multiple clients chat between each other having a UDP connection independent of the server.
The server keeps a list with all connected clients and notifies each one of them when a new client arrives or when one disconnects.
I have a working code.
I do not understand how, where in the code of the client, does it send the disconnection information to the server. Because the server receives the information that a client disconnects. BUT HOW
server.py:
import pickle
import select
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('0.0.0.0', 7000)
server.bind(address)
print('Starting up on %s port %s' % address)
input_sockets = [server]
output_sockets = []
clients = []
server.listen(10)
i = 0
while True:
readable, writable, exceptional = select.select(input_sockets, output_sockets, input_sockets)
for s in readable:
if s is server:
i = i+1
client_socket, client_address = s.accept()
print('New connection from client ' + str(i) + ' with address: ' + str(client_address))
client_socket.send(pickle.dumps(clients))
for client in input_sockets:
if client is not server:
client.send(pickle.dumps(client_address))
input_sockets.append(client_socket)
clients.append(client_address)
else:
client_address = s.getpeername()
print("Client with address '" + str(client_address) + "' disconnected")
clients.remove(client_address)
input_sockets.remove(s)
for client in input_sockets:
if client is not server:
client.send(pickle.dumps(client_address))
s.close()
client.py
import socket
import pickle
import threading
import select
def chat(udp_sock):
global done
while not done:
message = input()
if message == "QUIT":
done = True
else:
for client in clients:
udp_sock.sendto(message.encode('utf-8'), client)
done = False
server_address = ('127.0.0.1', 7000)
s_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s_tcp.connect(server_address)
clients_data = s_tcp.recv(1024)
clients = pickle.loads(clients_data)
s_udp.bind(s_tcp.getsockname())
reading = threading.Thread(target=chat, args=(s_udp,))
reading.start()
while not done:
r, w, e = select.select([s_tcp, s_udp], [], [], 1)
for s in r:
if s == s_tcp:
addr = s_tcp.recv(1024)
addr = pickle.loads(addr)
if addr in clients:
clients.remove(addr)
print("Client " + str(addr) + " has disconnected.")
else:
clients.append(addr)
print("Client " + str(addr) + " is now connected.")
if s == s_udp:
msg, addr = s_udp.recvfrom(1024)
msg = msg.decode()
print("[" + str(addr) + "]: " + str(msg))
reading.join()
s_tcp.close()
s_udp.close()
enter code here
for s in readable:
if s is server:
...
else:
client_address = s.getpeername()
print("Client with address '" + str(client_address) + "' disconnected")
clients.remove(client_address)
input_sockets.remove(s)
The server simply disconnects a client when select shows that it could read from the client socket. Since the client never sends anything to the server on the TCP connection, the only case where the client socket is readable is when the client disconnects. In this case a recv on the client socket would return '', i.e. no data as a sign that the socket has been disconnected. T
The client thus just needs to disconnect the TCP connection in order to signal to the server that the client is done. This is explicitly done in the code by closing the socket, but would also be implicitly done when the client exits.
s_tcp.close()

'list' object has no attribute 'encode

Can somebody help me?
i want to attach a excel file for an email sender in python but gives everytime an error. I looked online and everywhere it said it like it is in my code. can somebody tell me whats wrong
thank you verry much
message = MIMEMultipart()
message['Subject'] = 'Maandelijks rapport'
message['To'] = receiver_email
message['From'] = sender_email
message.attach(MIMEText('In de bijlage vind je het maandrapport terug!'))
part = MIMEBase('application', "octet-stream")
part.set_payload(open('test.xls', "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Desposition', 'attachment; filename="test.xls"')
message.attach(part)
#send the email
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login(sender_email, password)
print('connecting with smtp server...')
smtp.login(sender_email, password)
smtp.sendmail(sender_email, receiver_email, message.as_string())
print('connection succeed!')
print('email has been sent!')
smtp.quit()

How can I configure SSL for an IRC bot in Python?

How can I fix this error :
ERROR :NON-SSL command received on SSL-only port. Check your
connection settings
My code:
import socket
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "server"
channel = "#channel"
ircsock.connect((server, 6697))
ircsock.send(bytes("USER "+ botnick +" "+ botnick +" "+ botnick + " " + botnick + "n", "UTF-8"))
ircsock.send(bytes("NICK "+ botnick +"n", "UTF-8"))
ircsock.send(bytes("JOIN "+ channel +"n", "UTF-8"))
ircmsg = ircsock.recv(4096).decode("UTF-8")
print(ircmsg)
Wrap the connection socket with an SSL socket.
For example:
import ssl
import socket
port = 6697
server = "server" # Replace me with real address
ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock = ctx.wrap_socket(sock)
ircsock.connect((server, port))
ircsock.send(bytes("USER "+ botnick +" "+ botnick +" "+ botnick + " " + botnick + "n", "UTF-8"))
...

can't send data from react-native app to python server

I'm doing an application that send and recieve data with python socket server. The application written with react-native. Everytime i connect and try send/recieve data it give that error: GET /socket.io/?EIO=3&transport=polling&t=Mlquqm0 HTTP/1.1
actually ı send a data like "hello server" but server recieve that error.
python socket working in a ubuntu server. i tried this on a python client and it's work but not react-native client.
server.py:
import socket
import sys
import ast
import os
import time
HOST = ip
PORT = port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# socket.socket: must use to create a socket.
# socket.AF_INET: Address Format, Internet = IP Addresses.
# socket.SOCK_STREAM: two-way, connection-based byte streams.
print('socket created')
# Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print
'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print('Socket Bind Success!')
# listen(): This method sets up and start TCP listener.
s.listen(10)
print('Socket is now listening')
while 1:
conn, addr = s.accept()
print('Connect with ' + addr[0] + ':' + str(addr[1]))
buf = conn.recv(64)
buf = buf.decode()
command = str(buf)
print(command)
nickname,password,command = command.split()
gazoz = str(nickname) + " " + str(password) + " " + str(command)
input = open("input.txt","a+",encoding="utf-8")
input.write(str(gazoz) + "\n")
input.close()
print(nickname)
time.sleep(2)
if os.path.isfile("connection/us_" + nickname + ".txt"):
data = open("connection/us_" + nickname + ".txt","r",encoding="utf-8")
msg = data.read()
print(msg)
data.close()
os.remove("connection/us_" + nickname + ".txt")
msg = str.encode(msg)
if len(msg) == 0:
msg = "pek bisi yok"
msg = str.encode(msg)
conn.send(msg)
s.close()
react native client
import io from 'socket.io-client';
const socket = io("ip:port");
socket.connect();
socket.emit("hello server");
socket.close();
can you try this ?
import SocketIOClient from "socket.io-client/dist/socket.io";
const socket = await SocketIOClient(url);
socket.on("connect", () => { console.log("connected") });

How can we use microphone in google colab?

OSError Traceback (most recent call last)
<ipython-input-21-4159a88154c9> in <module>()
7 response = google_images_download.googleimagesdownload()
8 r = sr.Recognizer()
----> 9 with sr.Microphone() as source:
10 print("Say something!")
11 audio = r.listen(source)
/usr/local/lib/python3.6/dist-packages/speech_recognition/init.py in init(self, device_index, sample_rate, chunk_size)
84 assert 0 <= device_index < count, "Device index out of range ({} devices available; device index should be between 0 and {} inclusive)".format(count, count - 1)
85 if sample_rate is None: # automatically set the sample rate to the hardware's default sample rate if not specified
---> 86 device_info = audio.get_device_inf o_by_index(device_index) if device_index is not None else audio.get_default_input_device_info()
87 assert isinstance(device_info.get("defaultSampleRate"), (float, int)) and device_info["defaultSampleRate"] > 0, "Invalid device info returned from PyAudio: {}".format(device_info)
88 sample_rate = int(device_info["defaultSampleRate"])
Here's an example that shows how to access a user's camera and microphone:
https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=2viqYx97hPMi
The snippet you linked above attempts to access a microphone in Python. That won't work because there's no microphone attached to the virtual machine which executes Python code in Colab.
Instead, you want to access the microphone of the computer running the web browser. Then, capture data there, and pass it back to the virtual machine for processing in Python.
That's what's shown in the snippet linked above.
Here is a simple snippet
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
from scipy.io.wavfile import read as wav_read
import io
import ffmpeg
AUDIO_HTML = """
<script>
var my_div = document.createElement("DIV");
var my_p = document.createElement("P");
var my_btn = document.createElement("BUTTON");
var t = document.createTextNode("Press to start recording");
my_btn.appendChild(t);
//my_p.appendChild(my_btn);
my_div.appendChild(my_btn);
document.body.appendChild(my_div);
var base64data = 0;
var reader;
var recorder, gumStream;
var recordButton = my_btn;
var handleSuccess = function(stream) {
gumStream = stream;
var options = {
//bitsPerSecond: 8000, //chrome seems to ignore, always 48k
mimeType : 'audio/webm;codecs=opus'
//mimeType : 'audio/webm;codecs=pcm'
};
//recorder = new MediaRecorder(stream, options);
recorder = new MediaRecorder(stream);
recorder.ondataavailable = function(e) {
var url = URL.createObjectURL(e.data);
var preview = document.createElement('audio');
preview.controls = true;
preview.src = url;
document.body.appendChild(preview);
reader = new FileReader();
reader.readAsDataURL(e.data);
reader.onloadend = function() {
base64data = reader.result;
//console.log("Inside FileReader:" + base64data);
}
};
recorder.start();
};
recordButton.innerText = "Recording... press to stop";
navigator.mediaDevices.getUserMedia({audio: true}).then(handleSuccess);
function toggleRecording() {
if (recorder && recorder.state == "recording") {
recorder.stop();
gumStream.getAudioTracks()[0].stop();
recordButton.innerText = "Saving the recording... pls wait!"
}
}
// https://stackoverflow.com/a/951057
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var data = new Promise(resolve=>{
//recordButton.addEventListener("click", toggleRecording);
recordButton.onclick = ()=>{
toggleRecording()
sleep(2000).then(() => {
// wait 2000ms for the data to be available...
// ideally this should use something like await...
//console.log("Inside data:" + base64data)
resolve(base64data.toString())
});
}
});
</script>
"""
def get_audio():
display(HTML(AUDIO_HTML))
data = eval_js("data")
binary = b64decode(data.split(',')[1])
process = (ffmpeg
.input('pipe:0')
.output('pipe:1', format='wav')
.run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
)
output, err = process.communicate(input=binary)
riff_chunk_size = len(output) - 8
# Break up the chunk size into four bytes, held in b.
q = riff_chunk_size
b = []
for i in range(4):
q, r = divmod(q, 256)
b.append(r)
# Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
riff = output[:4] + bytes(b) + output[8:]
sr, audio = wav_read(io.BytesIO(riff))
return audio, sr
then run this
audio, sr = get_audio()
you might need to install this one
!pip install ffmpeg-python

Resources