The socket.send
description indicates that it takes bytes. Try encoding your string to bytes as part of your log
function.
def log(socket, sock_message):
sock_bytes = bytes(sock_message, 'UTF-8')
socket.send(sock_bytes)
I have a function that takes in a string, sends it via a socket, and prints it to the console. Sending strings to this function yields some warnings that turn into other warnings when attempting to fix them. , The socket.send description indicates that it takes bytes. Try encoding your string to bytes as part of your log function. , EDIT: As explained below, an str can't have both decode and encode and I'm confusing my IDE by doing both on the same variable. I fixed it by maintaining a separate variable for the bytes version, and this fixes the issue. , Also I tried a loop then using the mentioned functions and adding each element of th array
Function:
def log(socket, sock_message):
sock_message = sock_message.encode()
socket.send(sock_message)
print(sock_message.decode())
I'm attempting to call my function this way:
log(conn, "BATT " + str(random.randint(1, 100)))
And also, for simplicity:
log(conn, "SIG: 100%")
The
socket.send
description indicates that it takes bytes. Try encoding your string to bytes as part of your
log
function.
def log(socket, sock_message):
sock_bytes = bytes(sock_message, 'UTF-8')
socket.send(sock_bytes)
Here's how I would do it using C++11:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
const std::string target{"graph:"};
if (argc < 2) {
std::cout << "Usage: graph filename\n";
return 0;
}
std::string line;
std::size_t t1;
std::size_t t2;
std::string output;
std::vector<std::string> answers;
bool emitting = false;
for (std::ifstream in(argv[1]); std::getline(in, line); ) {
t1 = 0;
for (t2=line.find(target); t2 != std::string::npos;
t2 = line.find(target,t1))
{
if (emitting) {
output += line.substr(t1,t2-t1);
answers.push_back(output);
output.clear();
// emitting = false;
} else {
emitting = true;
}
t1 = t2+target.size();
}
if (emitting) {
output += line.substr(t1);
output += '\n';
}
}
for (const auto &s : answers)
std::cout << "[" << s << "]";
std::cout << '\n';
}
If your file contents is:
graph: Q R J A graph: P L L A graph: A B C D graph:
this program will print:
[Q R J A][P L L A][A B C D]
var $rows = $('table tbody tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
var regular_expression = new RegExp(escapeRegExp(val));
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !text.match(regular_expression);
}).hide();
});
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search">
<table>
<tbody>
<tr>
<td>google</td>
<td>Bing</td>
<td>Search Engine</td>
</tr>
<tr>
<td>Opera</td>
<td>Chrome</td>
<td>FireFox</td>
</tr>
</tbody>
</table>
Use
memcpy
:
memcpy(ptr, Array1, sizeof(Array1));
Create a function, iterate the array, return once found
function findPlayer(id) {
for (var i = 0; i < player.length; i++) {
if (player[i].id == id) return player[i];
}
}
There is a new function parameter syntax / to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments. This is the same notation shown by help() for C functions annotated with Larry Hastings’ Argument Clinic tool.,Here’s an example that alters the statistics.mean() function to prevent the data parameter from being used as a keyword argument:,This greatly simplifies the implementation of functions and methods that need to accept arbitrary keyword arguments. For example, here is an excerpt from code in the collections module:,The itertools.accumulate() function added an option initial keyword argument to specify an initial value:
if (n: = len(a)) > 10:
print(f "List is too long ({n} elements, expected <= 10)")
discount = 0.0
if (mo: = re.search(r '(\d+)% discount', advertisement)):
discount = float(mo.group(1)) / 100.0
# Loop over fixed length blocks
while (block: = f.read(256)) != '':
process(block)
[clean_name.title() for name in names
if (clean_name: = normalize('NFC', name)) in allowed_names
]
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
f(10, 20, 30, d = 40, e = 50, f = 60)
The indexing operator ([ ]) selects a single element from a sequence. The expression inside brackets is called the index, and must be an integer value. The index indicates which element to select, hence its name.,One of the parts that make up a sequence type (string, list, or tuple). Elements have a value and an index. The value is accessed by using the index operator ([*index*]) on the sequence.,The interval between successive elements of a linear sequence. The third (and optional argument) to the range function is called the step size. If not specified, it defaults to 1.,A subsequence of a sequence is called a slice and the operation that extracts a subsequence is called slicing. Like with indexing, we use square brackets ([ ]) as the slice operator, but instead of one integer value inside we have two, seperated by a colon (:):
[10, 20, 30, 40, 50]
["spam", "bungee", "swallow"]
(2, 4, 6, 8)
("two", "four", "six", "eight")[("cheese", "queso"), ("red", "rojo"), ("school", "escuela")]
>>> thing = 2, 4, 6, 8
>>> type(thing)
<class 'tuple'>
>>> thing
(2, 4, 6, 8)
>>> singleton = (2,)
>>> type(singleton)
<class 'tuple'>
>>> not_tuple = (2)
>>> type(not_tuple)
<class 'int'>
>>> empty_tuple = ()
>>> type(empty_tuple)
<class 'tuple'>
>>> fruit = "banana" >>>
fruit[1]
'a' >>>
fruits = ['apples', 'cherries', 'pears'] >>>
fruits[0]
'apples' >>>
prices = (3.99, 6.00, 10.00, 5.25) >>>
prices[3]
5.25
>>>
pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>>
pairs[2]
('school', 'escuela')
>>> len('banana')
6
>>> len(['a', 'b', 'c', 'd'])
4
>>>
len((2, 4, 6, 8, 10, 12))
6
>>>
pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>>
len(pairs)
3
To write the regex pattern \d+ (one or more digits) in a Python regular string, you need to write '\\d+'. This is cumbersome and error-prone.,Python's solution is using raw string with a prefix r in the form of r'...'. It ignores interpretation of the Python's string escape sequence. For example, r'\n' is '\'+'n' (two characters) instead of newline (one character). Using raw string, you can write r'\d+' for regex pattern \d+ (instead of regular string '\\d+').,On the other hand, Python' regular strings also use backslash for escape sequences, e.g., \n for newline, \t for tab. Again, you need to write \\ for \.,For simple text string operations such as string search and replacement, you can use the built-in string functions (e.g., str.replace(old, new)). For complex pattern search and replacement, you need to master regular expression (regex).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_copy: Copy file line-by-line from source to destination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: file_copy <src> <dest>
"""
import sys
import os
def main():
# Check and retrieve command-line arguments
if len(sys.argv) != 3:
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
fileIn = sys.argv[1]
fileOut = sys.argv[2]
# Verify source file
if not os.path.isfile(fileIn):
print("error: {} does not exist".format(fileIn))
sys.exit(1)
# Verify destination file
if os.path.isfile(fileOut):
print("{} exists. Override (y/n)?".format(fileOut))
reply = input().strip().lower()
if reply[0] != 'y':
sys.exit(1)
# Process the file line-by-line
with open(fileIn, 'r') as fpIn, open(fileOut, 'w') as fpOut:
lineNumber = 0
for line in fpIn:
lineNumber += 1
line = line.rstrip() # Strip trailing spaces and newline
fpOut.write("{}: {}\n".format(lineNumber, line))
# Need \n, which will be translated to platform-dependent newline
print("Number of lines: {}\n".format(lineNumber))
if __name__ == '__main__':
main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_list_oswalk.py - List files recursively from a given directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: files_list_oswalk.py [<dir>|.]
"""
import sys
import os
def main():
# Process command-line arguments
if len(sys.argv) > 2: # Command-line arguments are kept in a list 'sys.argv'
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
elif len(sys.argv) == 2:
dir = sys.argv[1] # directory given in command-line argument
else:
dir = '.' # default current directory
# Verify dir
if not os.path.isdir(dir):
print('error: {} does not exists'.format(dir))
sys.exit(1)
# Recursively walk thru from dir using os.walk()
for curr_dir, subdirs, files in os.walk(dir):
# os.walk() recursively walk thru the given "dir" and its sub-directories
# For each iteration:
# - curr_dir: current directory being walk thru, recursively from "dir"
# - subdirs: list of sub-directories in "curr_dir"
# - files: list of files/symlinks in "curr_dir"
print('D:', os.path.abspath(curr_dir)) # print currently walk dir
for subdir in sorted(subdirs): # print all subdirs under "curr_dir"
print('SD:', os.path.abspath(subdir))
for file in sorted(files): # print all files under "curr_dir"
print(os.path.join(os.path.abspath(curr_dir), file)) # full filename
if __name__ == '__main__':
main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_list_glob.py - List files recursively from a given directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: files_list [<dir>|.]
"""
import sys
import os
import glob # Python 3.5
def main():
# Process command-line arguments
if len(sys.argv) > 2: # Command-line arguments are kept in a list 'sys.argv'
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
elif len(sys.argv) == 2:
dir = sys.argv[1] # directory given in command-line argument
else:
dir = '.' # default current directory
# Check dir
if not os.path.isdir(dir):
print('error: {} does not exists'.format(dir))
sys.exit(1)
# List *.txt only
for file in glob.glob(dir + '/**/*.txt', recursive=True):
# ** match any files and zero or more directories and subdirectories
print(file)
print('----------------------------')
# List all files and subdirs
for file in glob.glob(dir + '/**', recursive=True):
# ** match any files and zero or more directories and subdirectories
if os.path.isdir(file):
print('D:', file)
else:
print(file)
if __name__ == '__main__':
main()