sqlite – Python: error al almacenar una tupla

Estoy intentando crear una función que me permita meter a modo de tupla los string de “piezas” en un query de SQLite. Para ello he creado anteriormente una base de datos que almacenan los valores de Piezas y Ordenes.
Después he creado esta función, que es donde tengo problemas.

    def orden_compra ():
        Vendedor_nombre = input('¿Quién eres?: ')
        numero = int(input('¿Número de artículos?: '))
        for i in range (0, numero):
            while True:
                pieza_nombre = input('Nombre de la pieza a comprar: ')
                try:
                    pieza = Piezas.get(Piezas.Nombre == pieza_nombre)
                    break
                except DoesNotExist:
                    print('Esta pieza no existe actualmente en el sistema, '
                        'por favor ingresa un nombre correcto.')
            ID = input('ID de la compra: ')
            for precio in Piezas.select().where(Piezas.Nombre == pieza_nombre):
                precio_ordenes = (precio.Precio)
            precio_ordenes+=precio_ordenes
            pieza=str(pieza)
            pieza=pieza.append(pieza)
            Ordenes.create(ID_compra_ordenes=ID, Fecha_compra_ordenes=datetime.now(),
                          Vendedor_ordenes=Vendedor_nombre, Piezas_ordenes = pieza,
                          Precio_ordenes=precio_ordenes)
            print('Pieza vendida satisfactoreamente')

La función me pide un nombre y el número de artículos para registrar, mediante un loop me pide el nombre de la pieza y lo comprueba si existe ya previamente en la base de datos creada anteriormente (tabla Precio).

Si es así me pide más opciones del producto si no, me pide de nuevo que meta un nombre válido.
Cuando existe una concordancia entre el objeto a registrar y el que está almacenado en la base de datos de Precio obtiene el precio de esa tabla y va sumando los precios acorde con el número total de productos adquiridos.

Mi problema es que esta función registra objeto a objeto y me gustaría que el total de objetos que una persona registre se queden almacenados a modo de tupla.
Para ello he hecho uso de la función append, como pueden ver y me da error:

     AttributeError: 'str' object has no attribute 'append'

En qué estoy fallando?
Gracias de antemano.

python – Delete all item contains word with regex

List = [‘aleksandre’, ‘shopify-ecommerce’, ‘php-ecommerce’, ‘html-code’, ‘css-code’, ‘sultan’, ‘november’]

New List = [‘aleksandre’, ‘sultan’, ‘november’]

How I can delete item contains ‘ecommerce’ and ‘code’ from list?

I try to delete with regex but i cant.

Thank you

python 3.x – Combining two pandas dataframes/tables of unequal lengths

I have two dataframes of different lengths.
df1: df2:

  Column1  Column2             ColumnA ColumnG ColumnSG
0    ab1       bc1                ab1      A      AA
1    ab2       ab5                bc1      B      BB   
2    ab3       bc4                ab3      C      CC
3    ab4       ab5                ab1      D      DD
4    ab5       ab1                ab5      E      EE 
                                  bc4      F      FF    
                                  ab2      G      GG
                                  ab4      H      HH

I would like an output that looks something like this:

df1:

OUTPUT

What I tried so far?

for row in df1, df2:
   if df1[Column1] == df2[ColumnA]:
      df1[ColumnG1] = df2[ColumnG]
      df1[ColumnSG1] = df2[ColumnSG]

But, this gave me an error saying,
ValueError: Can only compare identically-labeled Series objects

How can I solve this?

i want acces data from an application using python api

I have an application which has quiz with 10 question and all qts have radio buttons eg each qts has 
4 radio buttons and quiz results have to be mailed to teachers ,admin and parents so applications 
options Here are
1.email
2.run at server
Now I need this data from this application to have a seperate analytics dashboard so I have created 
Aws Ubuntu server,database ,table I need to know how can I get this data through python API kindly 
help its humble request.
import urllib.request
import json

url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'

def response(url):
    with urllib.request.urlopen(url) as response:
        return response.read()
res = response(url)
print(json.loads(res))

This is what I am getting every where I have tried this but I need a architecture where I shall get data from application I the application has send to server option where actually they need a server address how I can get this data because all API scripts says fetch from url or get from url kindly help

visual studio code – Python não reconhece novas bibliotecas

tive diversos problemas para instalar as novas bibliotecas como o kivy, o que funcionou foi o seguinte código no powershell na minha virtualenv: “kivy_examples –pre –extra-index-url https://kivy.org/downloads/simple/”.
porém agora nem o pycharm e nem o vscode reconhecem as novas bibliotecas.
-python 3.8.6
-kivy 1.11.1
nunca tive esse problema antes, a única coisa que muda é que meu pc foi formatado a pouco tempo.

Sumar claves diccionario python – Stack Overflow en español

estoy intentando sumar los valores de un diccionario siempre que se cumpla la condicion de que sea un numero y no un str, he usado el metodo isinstance tras iterar en el diccionario pero simplemente no he sabido continuar una vez localizados los str

magic_dict = dict(val1=44, val2='secret value', val3=55.0, val4=1)

for key in magic_dict:
  print(key, ":", magic_dict(key)) 
  result = isinstance(magic_dict(key), str)
  if result:
    print('Es str')
  else:
    print('No es str')

python – Implementing Convolutional Neural Network

Context

I was making a Convolutional Neural Network from scratch in Python. I completed making it …. It works fine … The only thing is that it takes a lot of time as the size of the input grows.

Code

import numpy as np
import math

class ConvolutionalNeuralNetwork():
    def __init__(self, num_of_filters, kernel_shape, stride):
        self.num_of_filters = num_of_filters
        self.kernel_shape = kernel_shape
        self.stride = stride
        self.kernels = ()

        # Initialize 
        for i in range(self.num_of_filters):
            self.kernel = np.random.uniform(-1, 1, size=(3,3))
            self.kernels.append(self.kernel)
        self.kernels = np.array(self.kernels)

    def ElementWiseAddition(self, images):
        if np.array(images).shape(0) == 1:
            return images(0)
        
        resultant_image = images(0)
        for image in images(1:):
            resultant_image = np.add(image, resultant_image)
            resultant_image = resultant_image.astype(float)
            resultant_image /= 2.0

        return resultant_image

    def GetOutput(self, x):
        filter_maps = ()
        for filter_n in range(self.num_of_filters):
            kernel_n_filter_maps = ()
            for image in x:
                filter_map = ()
                for i in range(0, (image.shape(0)-3)+1, self.stride):
                    row = ()
                    for j in range(0, (image.shape(1)-3)+1, self.stride):
                        piece = image(i:i+3, j:j+3)
                        value = np.sum(np.multiply(self.kernels(filter_n), piece))

                        # Apply Softmax Activation
                        if value < 0.0:
                            value = 0
                        row.append(value)
                    filter_map.append(row)
                kernel_n_filter_maps.append(filter_map)
            filter_maps.append(self.ElementWiseAddition(kernel_n_filter_maps))
        return np.array(filter_maps)

input = np.random.uniform(-1, 1, size=(512, 4, 4))

ConvolutionalNN = ConvolutionalNeuralNetwork(1028, (3,3), stride=1)
output = ConvolutionalNN.GetOutput(input)
print(output.shape)

How can I make this code consume less time and make it more efficient?

python – Premiação Vinculo – Django

Sou novato no Django,

Mas estava querendo uma ideia de como fazer o seguinte

Tenho um model de Prêmios, e nesse model esta vinculado com grupo de prêmios

Preciso pegar esse prêmios e coloca na ordem desejada pelo usuário.

Pela lista de prêmios que tive cadastrado:
Carro, Balinha,U$1.000.000.000, Casa, fogão, Viagem.

Premio: Carro – 3° Prêmio
Premio: Balinha – 1° Prêmio
Premio: U$1.000.000.000 – 2° Premio

Onde o usuário escolha ordem dos premiums já cadastrados em outro model.

Estou sem ideia de como criar isso, tanto model como form até a views para filtra isso tudo.. Se alguem puder ajudar.

python – script encoder for IDS test

It depends on what the IDS is designed to look for and what the exploit is. Is it looking for the script code? Or is it looking for the effects in the traffic?

If it is looking for the effects on the wire, then there will be little one can do to hide that from the IDS, no matter if it is a script or a compiled binary.

If the target needs to experience the traffic in a particular way in order for the exploit to work, then that particular way will be detectable on the wire.

performance – Sorting Algorithm (from scratch) in Python

I am attempting to write a Python program where I have to create a sorting algorithm without the assistance of the built-ins (like the sort() function). I used the def keyword to create the sorting_function() (the code bits in this paragraph will make more sense once you see my code) so all I have to do at the end is call the sorting_function(P.S. this is where the original_list needs to be passed as a parameter). My code (almost) works, but my concern is, how do I pass the original_list (or the user’s input) as a parameter of the function? Instead of having my program edited by the user (where they have to go to the bottom of the program to insert the numbers of their list) for it to work? Also, silly me, the user is still going to edit the program, but it’s easier and required to pass the original_list as a parameter of the sorting_algorithm function.

I also thought it would be helpful for you to know that I have no prior coding experience and that this is my first code in any programming language, so this may not be the most efficient code.

My code is as follows (my explanations might be too long, but I need to do this for clarity’s sake. If any of my explanations are wrong/vague, please don’t hesitate to correct me):

def sorting_algorithm(numbers):                                                         #this is the function in which the code will be written and upon completion, should be called on.
    sorted_list = ()                                                                    #the sorted_list variable is assigned to an empty list, which is where the sorted numbers will be stored.                                                               
    index = 0                                                                           #the index starts from zero because, to effectively sort the numbers, the counting must start from the first number in the list.
    comparison_number = 1                                                               #this is a comparison variable used for comparing the numbers in the list.

    while numbers:
        if numbers(index) == numbers(-1) and numbers(index) <= comparison_number:       #if the program reaches the last number in the list and it is smaller than the comparison_number (which is 1)
            sorted_list.append(numbers.pop(index))                                      #then that number is put into the sorted_list's '()'.
            index = 0                                                                   #the index stays at zero for each if, elif and else statements as only one of these conditions can be true.
        elif numbers(index) == numbers(-1):                                             #if the program reaches the last number in the list,
            index = 0                                                                   #then the position of the index should be returned to '0'.
            comparison_number += 1                                                      #the comparison number will also go up by one because numbers (from the list) are being compared to the comparison number (which, again is 1)
        elif numbers(index) <= comparison_number:                                       #if the number (under analysis) is less than or equals to comparison_number
            sorted_list.append(numbers.pop(index))                                      #then that number can be placed into the sorted_list's '()'.
            index = 0                                                                   #the index is again returned to the first number in the list so it (the number) can be analyzed.
            comparison_number += 1                                                      #the comparison_number goes up by one again because another number has been compared and added to the sorted_list's '()'.
        else:
            index += 1                                                                  #if none of the above conditions apply to the number(s) in the list,
    return sorted_list                                                                  #then the program will move onto the next number and the loop will restart! Also, I'm not entirely sure
                                                                                        #if the return sorted_list line is needed.


sorting_algorithm()                                                                     #this is how to call on the function, I believe.
original_list = (123, 85, 9587, 0, 453, 7, 63)                                          #this is where the user can/will input the numbers of their list.
print("The unsorted list: {}".format(original_list))                                    #I had to look at some examples of code to figure this out, I'm still not sure what '{}' is for...
original_list = sorting_algorithm(original_list)                                        ##but this will take the numbers of the list and go through the loop and put the numbers in ascending order.
print("And the sorted list: {}".format(original_list))                                  #at last, this line will print out the sorted list of numbers.

Note: I know that the names of my variables are really long (I used entire words to identify my vars), but it’s easier for me to go back and know what those variables do. I’m very sorry if this is annoying to some of you, but since this is my first Python code, I believe it is essential for me to do this to achieve optimal clarity.

I hope my question isn’t too vague, and if I can provide any further details, please let me know.