Password Generator Python – Code Review Stack Exchange

I decided to make a password generator to get more familiar with Python.

I had to break up the code into two boxes due to weird Stack Exchange highlighting with the triple quotes.

How would you improve this program on the grounds of:

  • Readability/cleanness,
  • Performance, and
  • Security.

Feel free to include any other comments you have on it that may not fit into those three categories.

import string
import random
import secrets
import argparse
import MyFormatter

alphaL = list(string.ascii_lowercase)
alphaU = list(string.ascii_uppercase)
numeric = list(string.digits)
special = list("!@#$%^&*")
special2 = list("""~`!@#$%^&*()+=_-{}()|:;"'?/<>,.""")

parser = argparse.ArgumentParser(
    formatter_class=MyFormatter.MyFormatter,
    description="Generates a password",
    usage="",
)

parser.add_argument("-lc", "--lower", type=int, default=1, help="Minimum number of lowercase alpha characters")
parser.add_argument("-uc", "--upper", type=int, default=1, help="Minimum number of uppercase alpha characters")
parser.add_argument("-n", "--numeric", type=int, default=1, help="Minimum number of numeric characters")
parser.add_argument("-s", "--special", type=int, default=1, help="Minimum number of special characters")
parser.add_argument("-se", "--extended", action = 'store_const', default = False, const= True, help="Toggles the extendard special character subset. Passwords may not be accepted by all services")
parser.add_argument("-l", "--length", type=int, default=20, help="Length of the generated password")

args = parser.parse_args()

length = args.length

minimums = (
    args.lower,
    args.upper,
    args.numeric,
    args.special,
)

password = ""

for i in range(0, minimums(0)) :
    password += secrets.choice(alphaL)
    
for i in range(0, minimums(1)) :
    password += secrets.choice(alphaU)

for i in range(0, minimums(2)) :
    password += secrets.choice(numeric)

if args.extended :
    subset = alphaL + alphaU + numeric + special2
    for i in range(0, minimums(3)) :
        password += secrets.choice(special2)
elif minimums(3) :
    subset = alphaL + alphaU + numeric + special
    for i in range(0, minimums(3)) :
        password += secrets.choice(special)

for i in range(0, 100) :
    random.shuffle(subset)
            
for i in range(len(password), length) :
    password += secrets.choice(subset)

for i in range(0, 100) :
    password = ''.join(random.sample(password, len(password)))

print("Password: ", password)

python – Optimization for data storage

I’d like your advice on the design of my application.

I use websockets to receive new data and the request module to retrieve older data.
Then I use pyqtgraph to display data and tables etc with pyqt5.

There are some data that I don’t keep in memory, I just display them on screen without the possibility to interact with them, and I have other data that I keep in memory, with which I do some processing.

I would like to know if I should use dictionaries to store and process data or create a database with SQL or use pandas.
There will be a lot of inserting, extracting, deleting and a lot of calculations.

Potentially, when there are big moves, I could have thousands of messages per second to process, which I would have to add to my database, process and then display them on screen or do whatever I wanted with them.

If you have any questions, don’t hesitate.

Example of connection:

import websockets
import asyncio
import json

async def capture_data():
    subscriptions = (sub for sub in ("quote", "trade", "instrument"))
    uri = "wss://www.bitmex.com/realtime?subscribe=" + ",".join(subscriptions)

    async with websockets.connect(uri) as websocket:
        while True:
            data = await websocket.recv()
            print(json.loads(data))


asyncio.get_event_loop().run_until_complete(capture_data())

Strings in python

How to find a specified letter follows an another letter or not.
eg;
the input is : ‘hi, how are you?’,’h’,’i’
then the output is true, because i followed by h at least one time .

object oriented – Multiprocessing OOP procedure python

Follow up question Image processing using Python OOP library

I want to use multiprocessing to analyze several images in parallel:

segmenter_class = {
'hsv': HSV_Segmentation,
'lab': LAB_Segmenter
}.get(procedure)

if not segmenter_class:
    raise ArgumentError("Invalid segmentation method '{}'".format(procedure))

for img in images:
    os.chdir(img_dir)
    processor =  = segmenter_class(img, img_dir, procedure)
    processor.start_pipeline()

What I tried so far:

image_lst = os.listdir(my_image_path)

# We split the list into sublist with 5 elements because of 512 GB RAM limitation
if len(image_lst) > 4:
    nr_of_sublists = (int(len(image_lst)/2.5))
    image_sub_lst  =(np.array_split(image_lst, nr_of_sublists))
else:
    image_sub_lst = (image_lst)

# We do the analysis for each sublist
for sub_lst in image_sub_lst:
    print (sub_lst)
    pool = multiprocessing.Pool(8)
    
    # Call the processor 
    processor =  = segmenter_class(img, img_dir, procedure)
    processor.start_pipeline()
    # How to call map???
    pool.map(?, sub_lst)
    pool.terminate()
    

python – How the basic structure of a simple messaging app works?

How the messaging apps works?
What is the Basic algorithm of it?
I tried the following method to make a messaging app.

  1. I enters message
  2. Message converts to a text file
  3. Text text file uploads to the ftp server
  4. My friend gets the text file from ftp and reads it

Is this method correct?
Do needed to use FTP server?
I found it is very slow and sometimes it gets timeout Error.
What is wrong here? Is my method wrong or the problem is the server?

python – How do i return the result of all regular expression? I need to return results of all android phones from “description” and “product”

“def searchbybrand(string):
if string == “android”:
return (collected_data(collected_data(‘description’).astype(str).str.contains(‘(Aa)ndroid’)))
elif string == “android”:
return (collected_data(collected_data(‘product’).astype(str).str.contains(‘(Aa)ndroid|(Aa)mazon’)))
else:
return collected_data(collected_data(‘product’).astype(str).str.contains(‘(Aa)pple|(Ii)Pad|(Rr)etina|(Aa)ir’))

searchbybrand(‘android’)

python – Cloud user registration

I developed an app that stores user-generated content in a local sql-lite database.

I would now provide the feature to the user to sync automagically its database with a cloud service. Ideally, I would like to set-up a framework that is easily up-scalableand that could provide a “serious” interface to the external world.

My issue is: I have really and totally NO IDEA on how this should be done. I mean, I am able to write a code in java or python that allows a someone to register to my service using username and password; but I would let it run on my raspberry py on my local network and not expose to the Internet.

I read names online about Django, Flask, Ruby… I have no idea on the differences between all of them and I don’t knbow what’s the best practice to provide such kind of design I would like to create.
Furthermore, I want my app to be able to sync with my service so I suppose that forms to fill are not way to go. I understand that these are web-based methods, so I have to rely on POST and GET methods, so I have to expose some API. But again, I am launching fancy words here and there.

So, question here:

How do I create a cloud-based service that requires user registration to sync user data with a mobile app?

Bonus question: what should I expose/provide to allow 3rd part services like Alexa to access a user database and perform operations on that (like reading it aloud)?

Please, note that also some pointer to keywords to study, or wathever else would be gladly appreciated.

Kind Regards

python – Scraping (Selenium) – Code Review Stack Exchange

I can’t seem to figure out how to click throw the load more until there is no more results.
I’ve managed to scroll to the button in various ways. Can’t seem to load to it and actually click.

Help?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time, requests
from bs4 import BeautifulSoup


def search_agent(zip):
    location = bot.find_element_by_name('hheroquotezip')
    time.sleep(3)
    location.clear()
    location.send_keys(zip)
    location.submit()


def load_all_agents():
    # click more until no more results to load
    while True:
        try:
            #more_button = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'results.length'))).click()
            more_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*(@id="searchResults")/div(3)/button'))).click()
        except TimeoutException:
            break

    # wait for results to load
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.seclection-result .partners-detail')))

    print ("Complete")
    bot.quit()

#define Zip for search query
zip = 20855

bot = webdriver.Safari()
wait = WebDriverWait(bot, 10)

#fetch agents page
bot.get('https://www.erieinsurance.com/find-an-insurance-agent')

search_agent(zip)
load_all_agents()

python – Optimize function that returns length of a subarray

I did an exercise today on where the task is to write a function that returns the length of the longest subarray where the difference between the smallest and biggest value in the subarray is no more than 1. I had a solution that works but it’s too slow to pass the tests that have big arrays. What is it about my solution that makes it very slow with huge arrays?

def longestSubarray(arr):
    longest = 0
    arr_len = len(arr)
    for i in range(arr_len):
        for j in range(i, arr_len):
            sub = arr(i: j+1)
            if max(sub) - min(sub) > 1:
                continue
            length = len(sub)
            if length > longest:
                longest = length
    return longest

python – Are set values faster than using variables

Using variables more convenient when values like MARGIN need to be changed

pygame.draw.line(screen, WHITE, (x - MARGIN, y - MARGIN), (x + TILESIZE, y - MARGIN), MARGIN)
pygame.draw.line(screen, WHITE, (x - MARGIN, y + TILESIZE), (x + TILESIZE, y + TILESIZE), MARGIN)
pygame.draw.line(screen, WHITE, (x - MARGIN, y - MARGIN), (x - MARGIN, y + TILESIZE), MARGIN)
pygame.draw.line(screen, WHITE, (x + TILESIZE, y - MARGIN), (x + TILESIZE, y + TILESIZE), MARGIN)

But if they were already set, would it be faster to do:

pygame.draw.line(screen, WHITE, (x - 1, y - 1), (x + 20, y - 1), 1)#Top
pygame.draw.line(screen, WHITE, (x - 1, y + 20), (x + 20, y + 20), 1)#Bottom
pygame.draw.line(screen, WHITE, (x - 1, y - 1), (x - 1, y + 20), 1)#Left
pygame.draw.line(screen, WHITE, (x + 20, y - 1), (x + 20, y + 20), 1)#Right