A
A
Alexander Alekseev2016-09-23 12:00:02
Programming
Alexander Alekseev, 2016-09-23 12:00:02

MODx How to add an option/setting to the whole site?

How to add an option/setting that will be visible on the entire site from all templates?
For example, in the admin panel, somewhere in the settings, there will be a select with a list of options
. When you change it, the class will change, for example, body

Answer the question

In order to leave comments, you need to log in

6 answer(s)
X
xmoonlight, 2016-09-11
@xmoonlight

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complex.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practically it beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one and preferably only one obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea let's do more of those!

R
Roman Sokolov, 2016-09-11
@jimquery

Read about the Caesar cipher - it might work.

M
MYMINKA, 2021-04-16
@MYMINKA

I did something like this, only here this "text" is read from a file, and the decrypted text is written to another file.
def read_file():
f = open("Cipher", "r")
cesar_cipher = f.read()
f.close()
return cesar_cipher
def create_new_string(message):
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
key = 1
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
if num < 0:
else:
translated = translated + symbol
return translated
def create_strings(string):
array_of_strings = string.split()
array_of_words = []
string = ""
for word in array_of_strings:
if not '/' in word:
string += word + " "
else:
string += word
array_of_words.append(string)
string = ""
return array_of_words
#This function will shuffle the sequence of symbols to the beginning of a word
def cesar_cipher_decode(array_of_words):
decoded_strings = []
shift = -3
for item in array_of_words:
decoded_strings.append(decode_string(item, shift))
shift -= 1
return decoded_strings
def decode_string(string, shift):
separated_string = string.split()
string = ""
decoded_string = ""
for word in separated_string:
string = word[(len(word) + shift) % len(word):] + word[:(len(word) + shift) % len(word)]
decoded_string += string + " "
string = ""
return decoded_string
def write_information_to_the_file():
f = open("Cipher_decode", "w")
f.write(convert_to_string(cesar_cipher_decode(create_strings(create_new_string((read_file()))))))
f.close()
return 0
def convert_to_string(arr):
s = ""
for item in arr:
s += item + '\n'
return s
if __name__ == "__main__":
write_information_to_the_file()

D
Denis, 2021-09-13
@denisstfu

Somehow like this. It's a two-step cipher. First, the Caesar cipher is applied, and then the shift within the word, which increases with each sentence.

LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'


def get_encrypted_word(message, key):
    translated_step_1 = ''
    translated_step_2 = ''
    for symbol in message:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            translated_step_1 += LETTERS[num-key]
        else:
            translated_step_1 += symbol
    replace_index = 3
    for word in translated_step_1.split(' '):
        new_word = ''
        for index in range(len(word)):
            new_word += (word[index - replace_index % len(word)])
        if new_word.endswith('/'):
            replace_index += 1
        translated_step_2 += new_word + ' '
    translated_step_2 = translated_step_2.replace('/', '\n')
    return translated_step_2


crypted_string = 'тут ваш зашифрованный текст'

print(get_encrypted_word(crypted_string, 1))

C
chubinmax, 2022-04-16
@chubinmax

Good day!
preamble ...
In the cart I am in the Python smoking room group. From time to time I help growing pythons deal with their problems. Nothing but entertainment and brain food. Then one guy threw a problem and asked for help to solve it.
Problem 10. Truth
What to do
You have received a ciphertext, which means a big truth for many Python programmers. Write a program that implements an algorithm for decrypting this text. Decipher the text with your program, and then search for it on the Internet.

I don’t cite the text here, it is below in the source code below.
Moreover, after 10 minutes the guy said - thank you, my colleague helped me solve it and flashed a screenshot with the source code. I saw a nesting doll of three cycles nested in each other and decided to assert itself. To do this, I sat down to write something compact and without "matryoshkas". It was then that interesting things began ...
I did not begin to rewrite the implementation of the Caesar encryption algorithm, but the second encryption algorithm by shifting letters seemed interesting to me and the "matryoshka" was in it.
Guys, this is not an easy task. It didn’t work out on her knee .. Take a closer look.
I even recorded a video here with reasoning about the solution and demonstrating the pitfalls.
I would be glad to hear your opinion, criticism and suggestions.
I have questions about the assignment as a whole:
1. How, looking at the source text, could it be understood that the Caesar algorithm should be applied to it?
2. In order to select the displacement step in Caesar, it was necessary to have an introductory type:

  • English text
  • the decrypted text must 100% contain a certain word, for example, there is the word "better"

under such conditions, I could cyclically apply the Caesar algorithm to the text, changing the offset step, and at each iteration search in the resulting text for one or more words that are known to be present in it. But as it turned out, the text deciphered by Caesar turned out to be encrypted in another way, and those words that could serve as a sign of successful decryption for me can be (almost certainly) distorted by the second layer of encryption.
those. now, in order to understand that the text was finally decrypted, after each iteration of decryption by Caesar, I would immediately apply the decryption cycle according to the second algorithm and look for the given words ... The cycle in the cycle ...
The fact that this is long is one side of the issue. But answer me, how should I understand what type of the second encryption algorithm is?!!??!
Solutions posted on the Internet from somewhere immediately know this information. OK. Let's say I had an incomplete task and somewhere in the original one there really was a hint.
It was probably also given in the hint that the string starts with a capital letter and ends with a "/" character. Even though I didn't say anything about it.
But the pitfalls were not found where expected. It turned out that even a text split into lines, when shifting letters in all the words of a line at the same time, can produce funny and unexpected results. Those. Some of the words may already be collected, while others are not yet. For example:
I begin to decipher by moving the letters in each word by the same step:
parseS si etterb ntha ense / d 1:
Sparse is better anth dense/ 2 : *** " than "
spelled incorrectly etterb hant ense/d 7: Sparse is better than dense/ 8: YES! Search termination condition: 1. In the first word, the first letter must be capitalized 2. In the last word, the last character must be the "/" character, everything would seem simple, but in automatic mode, the decryption cycle would stop at the second step. In this case, one word in the line would have formed incorrectly !!! Here are those times!
And here is another line from the text for the correct assembly of all the words in which as many as 20 iterations are required.
Moreover, the first coincidence of our conditions occurs at iteration 9, but some of the words are distorted
: /id 2:
If het plementationim is hard to explain- it(sa adb dea/i 3:
fI the plementationi si dhar ot -explain sit( a bad idea/ 4:
If eth implementation is rdha to n-explai (sit a dba /idea 5:
fI het nimplementatio si ardh ot in-expla t(si a adb a/ide 6:
If the onimplementati is hard to ain-expl it(sa bad ea/id 7:
fI eth ionimplementat si dhar ot lain-exp sit( a dba dea/i 8:
If hetionimplementa is rdha to plain-ex (sit a adb idea/ 9: *** Although the first and last words are correct, the remaining words are mangled
fI the ationimplement si ardh ot xplain-e t(si a bad /idea 10:
If eth tationimplemen is hard to explain- it(sa dba a/ide 11:
fI het ntationimpleme si dhar ot -explain sit( a adb ea/id 12:
If the entationimple is rdha to n-explai (sit a bad dea/i 13 :
fI eth mentationimple si ardh ot in-expla t(si a dba idea/ 14:
If het mentationimpl is hard to ain-expl it(sa adb /idea 15:
fI the lementationimp si dhar ot lain-exp sit( a bad a /ide 16:
If eth plementationim is rdha to plain-ex (sit a dba ea/id 17:
fI het plementationi si ardh ot xplain-e t(si a adb dea/i 18:
If the implementation is hard to explain- it(sa bad idea/ 19: YES!
In general, I didn’t come up with a universal way to fully automatically decode the text. Suggest some options for solving the problem. Below I’ll spend my version of solving the problem with an interactive mode. : -)
# Max Chubin 2022-04-16

# алгоритм цезаря
def encrypt(message, key):
  translated = ''
  for symbol in message:
    if symbol in LETTERS:
      num = LETTERS.find(symbol)
      translated = translated + LETTERS[num - key]
    else:
      translated = translated + symbol
  return translated

# исходный текст
txt = '''
vujgvmCfb tj ufscfu ouib z/vhm jdjuFyqm jt fscfuu uibo jdju/jnqm fTjnqm tj scfuuf ibou fy/dpnqm yDpnqmf jt cfuufs boui dbufe/dpnqmj uGmb tj fuufsc ouib oftufe/ bstfTq jt uufscf uibo otf/ef uzSfbebcjmj vout/dp djbmTqf dbtft (ubsfo djbmtqf hifopv up csfbl ifu t/svmf ipvhiBmu zqsbdujdbmju fbutc uz/qvsj Fsspst tipvme wfsof qbtt foumz/tjm omfttV mjdjumzfyq odfe/tjmf Jo fui dfgb pg hvjuz-bncj gvtfsf fui ubujpoufnq up ftt/hv Uifsf vmetip fc pof.. boe sbcmzqsfgf zpom pof pvt..pcwj xbz pu pe ju/ Bmuipvhi uibu bzx bzn puo cf wjpvtpc bu jstug ttvomf sfzpv( i/Evud xOp tj scfuuf ibou /ofwfs uipvhiBm fsofw jt fopgu cfuufs boui iu++sjh x/op gJ ifu nfoubujpojnqmf tj eibs pu mbjo-fyq tju( b bec /jefb Jg fui foubujpojnqmfn jt fbtz up bjo-fyqm ju znb cf b hppe jefb/ bnftqbdftO bsf pof ipoljoh sfbuh efbj .. fu(tm pe psfn gp tf"uip/
'''
# используемый в шифровании набор символов
LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

# удаление дублей в списке
def clean_doubles(param):
  clean_list = []
  counter = 0
  for item in param:
    if item in clean_list:
      counter += 1
      continue
    else:
      clean_list.append(item)
  return clean_list

# дешифровка слов методом сдвига букв по принципу стэка
def shift(text, iterations = 35):
  txt = text.split(' ') # разбиваем исходный текст по словам
  # ищем слова со слэшами. по условию строка имеет вид "Beautiful is better than ugly/"
  # т.е. слэш должен стоять в конце последнего слова. добавляем перевод строки.
  txt = ' '.join(map(lambda x: x+'\n' if '/' in x else x, txt))
  txt = txt.split('\n') # снова разбиваем текст уже по переводам строк
  result = ''
  for line in txt: # перебираем строки 
    words = line.split() # разбиваем строки на слова
    new_line = ''
    key = 1 # величина сдвига букв в слове
    if len(words) == 0: 
      continue
    results_list = [] 
    while key < iterations:
      words_new = list(map(lambda x:  x[-key%len(x):] + x[:-key%len(x)], words)) # сдвиг букв на шаг key
      # print(' '.join(words_new), key, end='')
      # if ' ' in input(':'): 
      # 	key += 1
      # 	continue
      # если в первом слове первая буква заглавная и в последнем слове в конце символ '/'
      if words_new[0][0].isupper() and words_new[-1].endswith('/'): 
        results_list.append(' '.join(words_new)) # добавляем этот вариант строки в список вариантов
      key += 1
    clean_list = clean_doubles(results_list) # чистим дубли в списке
    select = 0
    if len(clean_list) != 1:
      print('Выберите строку, которая не содержит ошибок:')
      for num, item in enumerate(clean_list):
        print(num, ':', item)
      while True: # добиваемся от пользователя выбора доступного варианта из списка предложенных
        select = input(':')
        if select.isnumeric():
          select = int(select)
          if 0 <= select < len(clean_list):
            break

    result += clean_list[select] + '\n' # собираем новый дешифрованный текст

  return result

if __name__ == "__main__":
  # дешифровка цезарем
  text = encrypt(txt, 1)
  print(text)

  # дешифровка сдвигом
  result = shift(text)
  print(result)

O
Oleg Shchavelev, 2016-09-23
@shure348

Well, there are two ways.
The first way is standard. Add a parameter to the standard settings prntscr.com/cld6u0
Then output it to a template or chunk
Or a more convenient option through the ConfigClient
component There is a convenient interface.
We output the template in the same way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question