Posts by fernandosavio • 9,013 points
290 posts
-
0
votes2
answers15
viewsA: DRF/Django - How to send an attribute value instead of sending a JSON object
You can use the attribute source of Fields of the Django Rest Framework to say where to find the data serialize will put on JSON. Assuming you’re using a Modelserializer, your example would look…
-
1
votes1
answer23
viewsA: How to change 2 values by changing the [input type=range] to be rendered on the page? VUEJS
You can use computed_properties to calculate the discounted value and the pages, because both depend on the variable value. Honestly, there’s not much to explain because what I’ve changed is just…
-
3
votes2
answers36
viewsA: How to use a function inside variable on out of function?
You need to study better on the scope of variables (this article, for example). Its variable v1 is created within the function test, that is, it exists only within this function. When you do return…
-
2
votes4
answers1335
viewsA: How to use . replace() to remove Python strings
TL;DR Using str.translate is performatic but works only if the received strings are only 1 character. chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] texto = 'Lorem: "ipsum" \'dolor\', sit!…
-
2
votes1
answer45
viewsA: Calculate the chargeback in percentage of the final value C#
If you have the formula: resultado = valor * (1 + juros) Using your example we would have: var resultado = 100 * (1 + 0.15) // resultado = 115 If we have only interest and result and we have no…
-
7
votes1
answer49
viewsA: Python Any checks too many elements even returning a True option with the first
When you do: variavel = None any([not variavel, variavel.get("chave1"), variavel.get("chave2")]) It’s "the same" that you’ve done: variavel = None lista = [not variavel, variavel.get("chave1"),…
pythonanswered fernandosavio 9,013 -
4
votes3
answers79
viewsA: Select right line with Split in TXT
To select the correct line of the file just iterate line by line and count on which line you are, so get to the desired line just return the words that are in it. You can iterate over the line…
pythonanswered fernandosavio 9,013 -
1
votes1
answer36
viewsA: How to convert the expires token to a date
The key expires_in is not a "Registered Claim", I mean, there is no standardization and you need to find out who generated this number to know what it means. Below I first explain the standard JWT…
-
2
votes2
answers66
viewsA: VIEW DICTIONARY ALPHABETICALLY - PYTHON
I think more important than the algorithm, you need to understand that the structure you chose for your data is not suitable. I’ll try to make a comparison here to see if it’s clear how much better:…
-
4
votes4
answers143
viewsA: Show days of the week
There’s a lot of unused code in your algorithm. From what I understand you want to print in "Have a good XXX-Friday" or "Have a good Saturday/Sunday" but you create and not use variables or create…
-
2
votes2
answers51
viewsA: Product between vectors
There is no sequence multiplication implementation in python, so the error message. You can calculate the scalar product using the function zip to iterate over the two lists "at the same time" and…
-
0
votes2
answers28
viewsA: How to do procedure in Pyhton Jupyter lab with a number list and not just with a list item
You can separate the logic into a function and apply within the comprehensilist on as your IF applies to each iteration and not to the final result: import math def calculate_theta(x, y): t = 180 *…
pythonanswered fernandosavio 9,013 -
4
votes4
answers197
viewsA: Python, how to calculate the average of a list of 5 in 5 elements?
The session "Itertools Recipes" in module documentation itertools contains an example of a function called grouper which makes the grouping of N into N elements of an iterable (efficiently). Just…
-
3
votes3
answers114
viewsA: How to remove only spaces between words/letters?
You can use Regular Expressions to delete only spaces between words. For this you can use \b to match the limit of words (see documentation). So if we do a regex to match 1 or more spaces between…
-
2
votes3
answers63
viewsA: Vue JS - How to display a list interspersed between property and value?
If you’re not going to show tabular data, theoretically you wouldn’t even need to use a table to show your data side by side. But if you need it the same way, or someone who gets here needs it, you…
-
4
votes3
answers155
viewsA: How do I remove the last "," that appears in the print?
If you have an integer list, just use method str.join() to join them. num_inteiros = int(input()) numeros = [str(2 ** i) for i in range(num_inteiros)] print(", ".join(numeros)) I’m converting the…
-
1
votes1
answer102
viewsA: Read/manipulate file name error: Attributeerror: 'list' Object has no attribute 'Seek'
To documentation states that the first parameter of ZipFile must be: A string with the path to a ZIP archive import zipfile zf = zipfile.Zipfile("path/para/arquivo.zip") An object file-like import…
-
2
votes2
answers29
viewsA: Show only second field of the field choises
As demonstrated in documentation of template for you can unpack (unpacking) the items you are iterating on. As in your case, each item is a tuple, you could unpack the tuple into two values and use…
-
2
votes1
answer33
viewsA: Selecting information that repeats many times
You can create an object that with the count of each fruit using Array.reduce() and passing an object as accumulator. There at each step you increment the key containing the fruit found inside the…
-
1
votes3
answers52
viewsA: How to fill out a list?
If the values of the second list are always a arithmetic progression, you don’t need to create it in memory, just use a range() to iterate by values and print only values that are contained in your…
-
4
votes1
answer55
viewsA: Loop of python repetition
You are assigning 1 to the value at each step of your loop, that is, the program is adding correctly, but you are "zeroing" the value that was added to each step of the loop. To solve you can create…
-
3
votes2
answers85
viewsA: Analyze Data with python
Apparently the pandas is not recognizing the second column as numerical data. Assuming the pandas must recognize the "." (dot) as decimal separator, instead of comma, you may only need to inform the…
pythonanswered fernandosavio 9,013 -
3
votes5
answers626
viewsA: Select between month and year only dates
Assuming the dates are 2010-09-15 and 2020-04-08, you could use DATE_FORMAT to replace the day of the initial date by 01 and the function LAST_DAY to replace the end date day with the biggest day of…
mysqlanswered fernandosavio 9,013 -
0
votes2
answers230
viewsA: When selecting a checkbox, disable other checkboxes
A very simple way to enable/disable multiple elements at the same time is to use the attribute disabled of fieldset, because they disable all child inputs. Then it becomes much simpler to activate…
jqueryanswered fernandosavio 9,013 -
3
votes2
answers66
viewsA: Receive items from an ordered list in a variable - Python
TL;DR nums = [2, 5, 7, 9] valor = "".join(nums) print(valor) # "2579" Motive By checking the job documentation print you will note the following sentence: All non-keyword Arguments are converted to…
-
8
votes4
answers727
viewsA: Check Object inside an Array using index()
To use index you would need to test if it is the same object. Note that, just because an object has the same keys and values, doesn’t mean that they are the same object. Therefore: let obj_1 =…
javascriptanswered fernandosavio 9,013 -
4
votes3
answers131
viewsA: Break string every 4 positions - Python
In the session "recipes" module itertools has a function called grouper who picks up a sequence and iterates "to pieces": from itertools import zip_longest def grouper(iterable, n, fillvalue=None):…
-
2
votes3
answers222
viewsA: re.error: bad escape c at position 0
termos = ['brasil', 'argentina', 'chile', 'canada'] palavras = ['brasil.sao_paulo', 'chile', 'argentina'] for termo in termos: for palavra in palavras: if termo.casefold() in palavra.casefold():…
-
11
votes1
answer1867
viewsA: Python integer split operator
If you check the documentation of numerical types will see that the operator // contains the following description and observation: x // y: floored quotient of x and y *...The result is Always…
pythonanswered fernandosavio 9,013 -
2
votes2
answers107
viewsA: How to partition people in a network of friends?
I created a solution using set and for...else... Yes, that for...else may seem very strange but when you understand what it’s for it can be very useful, as is the case... Steps to solving the…
-
2
votes2
answers149
viewsA: How to extract only words from any text, ignoring punctuation and uppercase letters?
You can use the function re.finditer from the native Python regex module. Using the pattern \w+ in Unicode strings you will match 1 or more characters that should be part of a Unicode word (this…
-
0
votes4
answers87
viewsA: Show/Hide Information by clicking
If you just want to toggle text and asterisks, there is no reason why you have a div separate, or any very complex structure... You could simply save the original text in an attribute and toggle the…
-
1
votes2
answers225
viewsA: Logic test inside the Python array
You could create the list with all fields and filter the result later. The module itertools has the function itertools.compress that "removes" the elements of an iterable based on the boolean value…
-
4
votes4
answers2743
viewsA: Javascript has a xor operator?
If you analyze the XOR truth table, also known as "Or exclusive", you will see that the output is true only when the inputs are different. ┌───────────┬───────────┬───────┐ │ entrada_a │ entrada_b │…
javascriptanswered fernandosavio 9,013 -
0
votes4
answers353
viewsA: Doubt with error - comparisons against strings
The remark is trying to tell you that you should convert numerical values to numbers before using them in comparisons. You can use the function parseint to convert strings to integer numbers.…
javascriptanswered fernandosavio 9,013 -
1
votes1
answer42
viewsA: How to ensure that Promise is resolved?
Its function this.$root.login need to return to Promise’s axios, in that way await can take the returns of Fulfill and Reject of your Prime correctly. See the example below: /* Se `success` for true…
-
3
votes2
answers1733
viewsA: Function that returns all combinations of a string
TL:DR Use itertools.permutations instead of itertools.combinations for permutations will return the possibilities of a Arrangement while combinations the possibilities of a Combining. That is, in…
pythonanswered fernandosavio 9,013 -
1
votes2
answers659
viewsA: summation multiplication algorithm
TL;DR def mul_to_add(x, y): if x == 0 or y == 0: return '0' negativo = (x * y) < 0 x, y = abs(x), abs(y) x, y = min(x, y), max(x, y) op = '-' if negativo else '+' result = f'-{y}' if negativo…
pythonanswered fernandosavio 9,013 -
2
votes2
answers100
viewsA: What is wrong with python below? Any suggestions for another solution?
TL;DR Knowing a little the modules that Python provides and some language functionality you can do it in a simpler way: from random import randint from itertools import chain def constroi_matriz(m,…
-
1
votes2
answers526
viewsA: Apply a function to each element of a python matrix
If you just want to apply mathematical operations to all elements of your array it is much easier for you to simply add the number you want to your array: import numpy as np array = np.array([[1, 2,…
-
2
votes3
answers1598
viewsA: Break lines in a certain Python character space
I’m posting my answer as a complement to reply by @Woss. Your question specifies that you want to handle your result string to have a maximum of 100 so that your content fits on the screen. My…
pythonanswered fernandosavio 9,013 -
0
votes2
answers1309
viewsA: How to make Redirect on the page with Django
Apparently its problem is the structure of views that you’re thinking about. It would be much simpler for you to pass resultado or None for the template, and in the template you show the result only…
-
1
votes1
answer179
viewsA: Move subfolders with python
You can use pathlib.Path to browse the folders and pathlib.Path.rename to move its contents to the root folder. Take an example: from pathlib import Path # path da pasta root root = Path('./root')…
-
1
votes3
answers147
viewsA: Delete copied array item without deleting the item from its source - Vuejs
There are several ways to copy an array, but you need to know if you want a shallow copy (Shallow copy) or a deep copy (deep copy) 1. If you’re just working with primitive types like Number, String…
-
1
votes1
answer265
viewsA: Click on checkbox option deselect other options
One way for you to solve your problem is to treat the "No alternative" option as a special option. That is, it will not be included in data.options or data.checkeds because it has a special…
-
1
votes1
answer79
viewsA: Challenge in python. Doubt
If you check the documentation you’ll see that it says: A set Object is an unordered Collection of distinct hashable Objects. Free translation: An object set (set) is an unordered collection of…
pythonanswered fernandosavio 9,013 -
5
votes2
answers114
viewsA: A function stores specific elements of a list in another list
TL;DR import bisect def intervalo(lista, i, j): left = bisect.bisect_left(lista, i) right = bisect.bisect(lista, j) return lista[left:right] Explanation Notice this section of your code: if el >=…
-
0
votes2
answers160
viewsA: Comparison between Dictionary and List
TL;DR Change: usuarios = list({'nome': 'marcelo', 'senha': 'marcelo123'}) # por: usuarios = [{'nome': 'marcelo', 'senha': 'marcelo123'}] And: if usuario['nome'] not in usuarios['nome']: # por: if…
-
2
votes1
answer377
viewsA: in Sqlalchemy what is the difference between filter and filter_by
filter If you check the method documentation Query.filter(*criterions) you will see that it receives a variable number of positional parameters. Examples of use would be:…
-
4
votes3
answers844
viewsA: How to initialize a list of empty lists?
Only by complementing the reply by @Woss... Sequence multiplication In the sequence documentation, the description of the operator of addition and multiplication between sequences and integers…