|
|
Write some code to de-serialise TCP data from 4different scales (different IP address) to be visualise
as digital LED object. The value that is being read is weight [40]. Anyone who can assist in this question please
|
|
|
|
|
|
Me enviaron hacer que el algorimo heruistico que esta de forma lineal sea dinamico, osea que el cambio de posicion lo genere de forma dinamica mediante el ingreso del tamaño del array, pero no me sale me podrian ayudar??? solo he logrado que imprima el array pero no me sale el cambio de posicion
Google translate: They sent me to make the heruistic algorithm that is linearly dynamic, that is, the change of position is generated dynamically by entering the size of the array, but it doesn't work out, could you help me??? I have only managed to print the array but I do not get the change of position
from re import I
from ClaseNodo import Nodo
def buscar_solucion_heuristica(nodo_inicial, solucion, visitados):
visitados.append(nodo_inicial.get_datos())
if nodo_inicial.get_datos() == solucion:
return nodo_inicial
else:
dato_nodo = nodo_inicial.get_datos()
i=0
while i < tamaño :
hijo=[]
hijo.append(dato_nodo)
i=i+1
hijo=[dato_nodo[1], dato_nodo[0], dato_nodo[2], dato_nodo[3], dato_nodo[4], dato_nodo[5]]
hijo_izquierdo = Nodo(hijo)
hijo=[dato_nodo[1], dato_nodo[0], dato_nodo[3], dato_nodo[2], dato_nodo[4], dato_nodo[5]]
hijo_central = Nodo(hijo)
hijo=[dato_nodo[1], dato_nodo[0], dato_nodo[3], dato_nodo[2], dato_nodo[5], dato_nodo[4]]
hijo_derecho = Nodo(hijo)
nodo_inicial.set_hijos([hijo_izquierdo, hijo_central, hijo_derecho])
for nodo_hijo in nodo_inicial.get_hijos():
if not nodo_hijo.get_datos() in visitados and mejora(nodo_inicial, nodo_hijo):
sol= buscar_solucion_heuristica(nodo_hijo, solucion, visitados)
if sol != None:
return sol
return None
def mejora(nodo_padre, nodo_hijo):
calidad_padre=0
calidad_hijo=0
dato_padre = nodo_padre.get_datos()
dato_hijo = nodo_hijo.get_datos()
for n in range(1,len(dato_padre)):
if (dato_padre[n]>dato_padre[n-1]):
calidad_padre = calidad_padre + 1;
if (dato_hijo[n]>dato_hijo[n-1]):
calidad_hijo = calidad_hijo + 1;
if calidad_hijo>=calidad_padre:
return True
else:
return False
if __name__ == "__main__":
i=0
j=0
estado_inicial=[]
tamaño =int(input("Por Favor, Introduzca el tamaño del array"))
while i < tamaño:
inicio =int(input("Por Favor, Introduzca un numero"))
estado_inicial.append(inicio)
i=i+1
solucion=[]
while j < tamaño:
final =int(input("Por Favor, Introduzca el solucion"))
solucion.append(final)
j=j+1
nodo_solucion = None
visitados=[]
nodo_inicial = Nodo(estado_inicial)
nodo = buscar_solucion_heuristica(nodo_inicial, solucion, \
visitados)
resultado=[]
while nodo.get_padre() != None:
resultado.append(nodo.get_datos())
nodo = nodo.get_padre()
resultado.append(estado_inicial)
resultado.reverse()
print(resultado)
|
|
|
|
|
This is an English language site, and we can only accept and answer questions in that language.
I have run this through Google Translate to produce a probably-good version, but you should check it and make sure it does say what you are actually asking.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I want to secure my python app using an online license key. Consider the following simple example:
import requests
def license():
keys = requests.get("http://yourlink.com/licensekeys.txt").text
keyfromuser = "mykey"
for key in keys.splitlines():
if key == keyfromuser:
return
exit()
license()
Anybody can open my code in notepad and make some changes to disable the license key requirement.
What is the best strategy to implement license approach to make it harder to beginner and intermediate level programmers to reverse engineer my app?
|
|
|
|
|
You put the functionality in a web service. No service without a valid key.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
I have a ready python project. how can I set inside of it an activation system and only be activated by myself? can you provide me any code or library examples
|
|
|
|
|
|
import re
def creation_of_dictionary(message):
print(f"In creation_of_dictionary: message= {message}")
m = {}
l = []
z4 = {}
mc = ['r', 'o', 't', 'e']
for i in message:
if i.isalpha():
b = i.lower()
l.append(b)
print(f"creation_of_dictionary:l={l}")
for g in range(len(l)):
f = l.count(l[g])
m[l[g]] = f
tuples = m.items()
tuples = sorted(tuples, key=lambda tuples: tuples[1])
print(f"tuples = {tuples}")
for e in [-4, -3, -2, -1]:
z4[mc[m]] = tuples[e][0]
z4[tuples[e][0]] = mc[e]
print(z4)
return (z4)
def decode(message, dict):
lists = []
for m in message:
l = m.lower()
lists.append(l)
for s in range(len(lists)):
if lists[s] in dict.keys():
lists[s] = dict[lists[s]]
b = ''.join(lists)
return b
def txt_decode(path):
lines = []
newdic = {}
m = open(path, 'r')
q = m.readlines()
m.close()
for i in range(len(q)):
q[i] = q[i].rstrip()
newdic = creation_of_dictionary(''.join(q))
for t in range(len(q)):
lines.append(decode(q[t], newdic))
f = open(path, 'a')
f2 = open("result.txt", 'w')
f.write("\n The encryption for the above text is:\n")
for n in range(len(lines)):
f.write(lines[n])
f2.write(lines[n])
f.write('\n')
f2.write('\n')
f.close()
def long_word(message_file):
register = re.compile('[^a-zA-Z]')
with open(message_file, 'r') as infile:
messages = infile.read().split()
max_option = len(max(messages, key=len))
word = [word for word in messages if len(word) == max_option]
final_word = []
for z in range(0, len(word)):
word[z] = register.sub('', word[z])
if len(word[z]) == max_option:
final_word.append(word[z])
return final_word
def file_length(f_mean):
with open(f_mean) as f:
for o, p in enumerate(f):
pass
return o + 1
def main():
txt_decode("message.txt")
f = open("message.txt", 'a')
long = long_word("result.txt")
num_of_try = file_length("result.txt")
for m in range(0, num_of_try):
f.write(long[0] + "")
f.write("\n")
f.close()
if __name__ == '__main__':
main()
Part 1
replace 4 most common letters in the text with 4 most common letters in the English language ‘e’,’t’,’o’,’r’.
in example: 'a' is most common - replace it with 'e', and 'e' with 'a'
in example: abcd most common chars in text: a <-> e, b <-> t, c <-> o, d <-> r
Create a function replace_common_occurences(str) -> replaced_dict - that will include the most common letters and their replacements.
The function needs to find the most common chars (count occurences)
The function will receive a text as a string and will return the relevant dictionary - replaced_dict
{'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'}
1. The dictionary will include only letters that were changed.
2. include only letters - not numbers, spaces, etc.
3. code must be case insensitive - dictionary only lower case
4. check:
a. There are at least four different letters in your text
b. for for every popular letter - there is no letter that appears the same number of times.
c. the most popular letters are not 'e', 't', 'o', 'r'
"""
"""
Part 2
1. Write a function replace_chars_in_text(text to change, replaced_dict) -> changed str
2. The function will iterate over the str and for each char
if there is a replaced_dict[key] - replace with the value, otherwise do not change.
3. Example: str = ///bha Taa3add, bha Tdaer, enr b7ha Fdcccccbbb
replaced_dict = {'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'}
replaced_str = ///the bee3err, the bread, and t7he frooooottt
"""
"""
Part 3
Create a function: decode_text(path to encrypted text file) to update the message text file
call:
1. replace_common_occurences(str) -> replaced_dict
2. replace_chars_in_text(text to change, replaced_dict) -> changed str
add to message.txt file: 'the encryption for the above text is:' ....decrypted text....
create another text file - results.txt - include only the decrypted results.
notes: common chars should be done over all text file, not line by line.
ignore \n.
"""
"""
Part 4
Create a function find_longest_word(path to results.txt) -> list of longest words.
return the longest word in result.txt file (decrypted text) - count only alphabetical chars.
Removing all non alpha chars - import re, regex=re.compile("[^a-zA-Z]") list[i]=regex.sub(", your string)
Create a function count_num_of_lines(path to results.txt) -> num of lines.
main()
1. decrypt message - part 1,2,3
2. write to the original message (append) the first value of the longest words list return from find_longest_word(path to results.txt)
times the number of lines in results.txt file.
Example: Your longest word is "BOOBOBA", The number of lines is 2.
Add to original message.txt - BOOBOBA BOOBOBA
"""
'Puackich, hvhnkrally oaths phufhck. All ymr nhhd is Pykemn.'
J.U.U.U Kmltin.
mmps iks nmk eio; ---> hkmu
"""
hi guys pls advise i added the code i managed to write and the H.W description below basically the code supposed to receive and than decode string message but i am getting errors such as message.txt file doesnt exist etc
|
|
|
|
|
אנטון מוטרוק 2021 wrote: errors such as message.txt file doesnt exist etc If you get errors then you need to provide the exact text, and explain which line they occurred on. Remember we have never seen this code before, have no idea what is is supposed to do or what data it is processing.
Also, instead of trying to write the entire application in one go, stop and look at the task(s) you have been set. Go by the numbers in your questions: write the code just for that step, and test it until it works successfully. Only then should you move on to the next step, and so on, until you complete the entire application.
|
|
|
|
|
As a new Python user, I got such an error as
'module' object has no attribute 'askopenfilename' in the piece of code below:
def getfile(title, filetype, ext):
root = tkinter.Tk()
root.withdraw()
# open window on top of other windows
root.attributes("-topmost", True)
filename = filedialog.askopenfilename(initialdir=r"C:\Users\...\Testing\AHCS Map Update\2022_Test",
title= title,
filetypes=(("{}".format(filetype),
"*.{}".format(ext)),
("all files","*.*")))
return filename
Referring to Python Examples of tkinter.filedialog.askopenfilename[^] the
attribute 'askopenfilename' is used. How can this
'askopenfilename' be properly called? Thanks.
|
|
|
|
|
|
Using Python 2.7 and run in VS2019, my Python script has errors. Mycode is below
import os
import arcpy
import numpy as np
import pandas as pd
import tkinter
from tkinter import filedialog
import time
import zipfile
...
def getfile(title, filetype, ext):
root = tkinter.Tk() root.withdraw()
...
A red wave-line is below the
root.withdraw() , and the error message is
Unexpected token 'root' .
In my CPU, the
Anaconda3 is installed
C:\Users\...\Anaconda3\Lib\site-packages\jedi\third_party\typeshed\stdlib\3\tkinter . In my Environmental Variables, there is such an item as
C:\Users\...\Anaconda3
How to debug it? Thanks if you can help.
|
|
|
|
|
That is not valid Python, it should be:
def getfile(title, filetype, ext):
root = tkinter.Tk()
root.withdraw()
|
|
|
|
|
What do you mean? Could you hint me clearly? Thanks.
|
|
|
|
|
It could not be any clearer, what do you not understand?
|
|
|
|
|
Seriously?
You cannot have two statements on the same line!
|
|
|
|
|
|
def ListOfLists(list):
'''
This function receives a list, which can contain elements that are themselves lists and
returns those items separately in a single list.
If the parameter is not of type list, it must return null.
Receive an argument:
list: The list that can contain other lists and is converted to a
list of unique or non-iterable elements.
Ex:
ListOfLists([1,2,['a','b'],[10]]) should return [1,2,'a','b',10]
ListOfLists(108) should return null.
ListOfLists([[1,2,[3]],[4]]) should return [1,2,3,4]
|
|
|
|
|
|
A tad late to the party but a recursive approach seems to work.
def Collapse(lst):
result = []
for item in lst:
if type(item) == list:
result.extend(Collapse(item))
else:
result.append(item)
return result
a = [1, [2, 3, [3.1, 3.2]], 4]
b = Collapse(a)
print(a)
print(b)
|
|
|
|
|
We're curious. A virtual environment can use system wide resources, but can a virtual environment lean on an existing venv and only have the extra bits, or overide bits, that are specific to that new venv?
cheers
Chris Maunder
|
|
|
|
|
I'm curious: Is any VM implementation programmed in Python? (Recursive virtualization or not!)
|
|
|
|
|
The virtual environment just puts itself (i.e its version of Python and associated libraries) at the front of the search path. So anything called after you run activate , will load first from the .venv locations, before looking at the system folders. I guess that if you then activate another .venv then the search path would be venv2 -> venv1 -> system installation . Which could be fun.
|
|
|
|
|