Posts by hkotsubo • 55,826 points
1,422 posts
-
1
votes3
answers119
viewsA: How to remove a link from a string in Javascript?
For the question URL, the other answers serve well, but remember that a URL can be much more complicated than the examples cited. For example, it can be something like…
-
1
votes2
answers64
viewsA: Is it possible to perform an overload (Overload) with Arrow functions?
Complementing the another answer, it is worth mentioning that in the end, the Typescript code is transposed into Javascript, which can help explain why it is not possible to do the Overload with…
-
3
votes1
answer91
viewsA: Doubt in variable manipulation in C
If you only want to make one printf in the end, then you have to take all the information that changes (in this case, the name of the operation and the result) and set it according to the chosen…
-
0
votes1
answer71
viewsA: Return "block" text with a keyword from a txt file
Regex is probably not the best option. Maybe you should read the file line by line, and for each line you see if it is at the beginning or end of a coupon, or if there is an extract on that line,…
-
0
votes1
answer33
viewsA: How to remove field to field from a String starting from left and bounded by a size desired by the user
Your solution is not ideal, but first we will fix your code, and then we will see a simpler solution. The problem is that you increase the i. That is, in the first iteration, you take substring(0)…
-
2
votes1
answer58
viewsA: Find values in blocks that extend across multiple lines
I think you’re complicating for nothing. Instead of sweeping the string looking for the beginning and end of each coupon, you can simply go reading line by line, and for each line you see if you are…
-
2
votes3
answers94
viewsA: String validation using while in Python
The reason one code worked, but the other one didn’t, is very simple. In the while, the condition serves to indicate whether it will continue performing or not. As long as the condition is true, it…
-
4
votes2
answers91
viewsA: How do iterators created from lists rescue "random" values in Python?
First, a little terminology/concepts. According to the documentation, one iterator (or "iterator") is any object that implements the methods __next__ and __iter__ (and the latter must return the…
-
1
votes2
answers76
viewsA: Even Number Counting (c language)
Like looks like an exercise, it may be "mandatory" to iterate one by one and use the operator % (and there the another answer I’ve told you how to do). But you can do a little better. Just make sure…
-
1
votes2
answers59
viewsA: Function in C that counts how many times the string appears in a file
Well, you only call once fgets(conteudo, 98, arquivo). What if the file has more than 98 characters? If so, you should make one loop and read until there is nothing left to read. Something like…
-
0
votes1
answer68
viewsA: Can I do better code than this in Python? I’m a beginner in the language and would like to know if I’m on the right track
Yes, it can be simpler. For example, you convert the raio for float several times: first to see if it is even number, then to see if it is less than 1, and then to calculate the area. Instead, why…
-
1
votes1
answer37
viewsA: Extract joint data from a JSON using PHP
For each key starting with "Trophy", simply extract the "name"/"desc" section and the respective code, and then set the values accordingly: $json = json_decode(file_get_contents("texts.json"));…
-
1
votes1
answer67
viewsA: Combination of a numerical list with limiter (Python)
You can simplify this code a lot. From what I understand, the idea is to search all combinations, but the order of the elements doesn’t seem to matter. That is, if you already have [2, 10] in the…
-
1
votes2
answers321
viewsA: How to emulate the regular expression reset branch in Java
To date the current version of Java is 16, and we still do not have available the branch reset. Therefore, another alternative - still far from ideal - is to use lookarounds: Pattern pattern =…
-
1
votes1
answer39
viewsA: word_tokenize creating tokens with only one character instead of words
read() takes the entire contents of the file and returns in a single string. That is, texts is a string. In doing for text in texts you are traversing the characters of texts, one by one. That is,…
-
5
votes2
answers114
viewsA: Is there a way to interpolate strings in Java?
In Java, one option is to use printf: String nome = "Fulano"; int idade = 20; System.out.printf("%s tem %d anos\n", nome, idade); // Fulano tem 20 anos The format string syntax is inspired by C, so…
-
3
votes1
answer64
viewsA: What is the best way to check if a string has any of these words?
An alternative is to use split to break the string into words, and see if each of the words is in the list: def verificar_nome(frase): for palavra in frase.split(): if palavra in nomes_proibidos:…
-
2
votes1
answer47
viewsA: Sorted function referencing keys in a dictionary to define the sort criteria
if I put dict[1] it starts sorting considering the second letter of the key string It’s not like that. First, let’s see what items() returns: for item in dict.items(): print(item, type(item)) Exit:…
-
3
votes3
answers157
viewsA: How to add digits from a number to "1" digit?
On the algorithm to sum the digits, you can choose any one from here. Having this, just go calculating the sum, until it is less than 10 (which is when it has only one digit). Something like this: n…
-
1
votes2
answers63
viewsA: How to use split() inside a Java loop?
First, you need to define the problem well: is to read only the first 10 lines of the file? or is to read the file until you find 10 numbers, regardless of the number of lines? or some other option?…
-
1
votes2
answers164
viewsA: How to format a double number to N decimals without rounding?
they round up the number, and that’s not what I wish Good, String.format also round: // quarta casa decimal é >= 5, arredonda para cima System.out.println(String.format("%.3f", 1.2225)); // 1,223…
-
3
votes3
answers1939
viewsA: Separate integer and decimal part into a number using Javascript
I just wanted to add a few details on the definition of the problem and the solutions of the other answers. It’s not that they’re wrong, but there’s a few you pay attention to. First, if the numbers…
javascriptanswered hkotsubo 55,826 -
2
votes3
answers77
viewsA: Generate multiple different arrays containing random numbers
Deep down you want to "generate N random things without repeating" (several different arrays), so an alternative is to follow this idea: generate all possibilities (assuming the total amount is 'X')…
-
4
votes2
answers73
viewsA: Is there documentation in the Ecmascript standard that ensures that an array when passed as a property advisor has a defined format?
This is not unique to arrays. Any object, when used in a property provider, ends up having its method toString called, and this string is used as key. Ex: var k = { toString: function() {…
javascript characteristic-language software-engineering documentation ecmascriptanswered hkotsubo 55,826 -
0
votes3
answers917
viewsA: Formatting String with Dateformat using a Timezone is not working
From Java 8 (or, if on Android, from the Level 26 API (required minSdkVersion >= 26, it is not enough to have compileSdkVersion >= 26)), you can use the API java.time. In this case, you do not…
-
6
votes1
answer73
viewsA: How to format a string to add spaces to the right in a printed table?
In the documentation of format there is a link to the page "Format String Syntax", that describes all possible options. There we find this table: Flag General Character Integral Floating Point…
-
7
votes2
answers141
viewsA: How to Split by Capital Letters and Numbers at the same time?
Your criterion is basically: a capital letter followed optionally by a lowercase letter, or one or more numbers So just do it: import re r = re.compile(r'[A-Z][a-z]?|\d+') composto1 = 'H2SO4'…
-
4
votes1
answer63
viewsA: How to align numbers on the left using str.format?
In the method format, you must use < to align to the left: for x in range(1, 11): print('{0:<2d} {1:<3d} {2:<4d} {3:<6d}'.format(x, x**2, x**3, x**4)) Exit: 1 1 1 1 2 4 8 16 3 9 27 81…
-
1
votes1
answer168
viewsA: How to take back a date formatted in MMM/yyyy format for yyyy-MM format with date-fns
First of all, new Date('abr/2017') doesn’t work the way you expect: // cada browser dá um resultado (Chrome: 01/01/2017 - Firefox: null/invalid date) console.log(new Date('abr/2017')); Testing on…
-
1
votes1
answer32
viewsA: Simpledateformat am/pm format returns "afternoon" instead of "PM"
I could not reproduce (tested in Java 8 and 11, with different locales) but it’s probably because of default locale of the JVM (see which one is yours, with System.out.println(Locale.getDefault())).…
-
3
votes1
answer93
viewsA: Is it possible to pass an Enum value on your call?
Short answer You are using enum wrong way. Create a class and you’re done. Long answer You can’t use it enum the way you intend it, and there are several reasons for it. First, when you do this:…
-
1
votes1
answer44
viewsA: What is the CSS selector to change a particular parent class only if it has a certain daughter class
Currently (May/2021) it is not possible to do this with CSS. There is a this proposal for the pseudo-selector :has. With him it would be possible to have something like: /* seleciona os elementos…
-
5
votes4
answers120
viewsA: How to filter an HTML tag and its contents with regular expressions in Shell Bash?
Do not use regex to manipulate HTML Generally, regex is not meant to work with HTML (may even "work" in many cases, but is not the most suitable tool for the task). The regex of another answer may…
-
1
votes3
answers188
viewsA: Two classes or more in the same element in HTML
According to the specification of WHATWG, an attribute cannot appear more than once in the same element: There must Never be two or more Attributes on the same start tag Whose Names are an ASCII…
-
1
votes1
answer36
viewsA: Numpy copy method does not create a deep copy?
The expected behavior is the same. To documentation cites that ndarray.copy is similar to numpy.copy, and the documentation of numpy.copy says the following: np.copy is a Shallow copy and will not…
-
4
votes1
answer49
viewsA: Remove Javascript comments from the script tag of an HTML, ignoring content from other tags (e.g., base 64 images)
Instead of using regex across HTML, you can use DOMDocument to get only the tags script, and apply the regex only to them. This way you guarantee that you will replace only the Javascript code,…
-
1
votes7
answers15010
viewsA: Print "n" natural odd numbers
Just to record another alternative (and I admit that maybe it’s a half Overkill, since the other solutions with range are simpler), you can use the module itertools: from itertools import islice,…
-
3
votes4
answers143
viewsA: Show days of the week
Yes, it can be simpler. See that you create 3 times today’s date (date.today() is called 3 times), but only need to call once. And then you take the day, month and year of today’s date and create…
-
3
votes1
answer56
viewsA: Doubt with the counter at the while
Make a table test would help to understand better. But anyway, let’s see what happens: Supposing it was typed primeiro_termo = 1 and razao = 2. The other variables will be: variable value accountant…
-
2
votes3
answers104
viewsA: Syntactic difference between classes and constructor functions in Javascript?
A construction function is still a function like any other, which can have whichever valid code, not only constant declaration. For example: function Teste(x, y) { // posso ter código "normal" que…
-
2
votes2
answers82
viewsA: Sort two lists based on the order of the first
An alternative is to create a list of indices, and sort these indices according to their value in x. Then you use these indexes to sort the lists: x = [7, 5, 9, 4, 2, 3, 8, 1, 6, 10] y = ['sete',…
-
1
votes2
answers67
viewsA: Problem when declaring 2 variables
The problem is that the program also needs to understand that the user can put only 1 number or none Good, for this you need to analyze what was typed, before converting to int and go out doing the…
-
0
votes3
answers405
viewsA: Make a program that reads an integer N and then print the N first odd natural numbers
it presents only the next odd number and for The problem is here: while(imp<n){ imp=n+2; In fact, the problem starts a little earlier because you did not assign any value to imp before using it,…
-
2
votes2
answers109
viewsA: What does the computer do with 2 distinct values that need to be returned and are in the same memory scope?
First, follow a reading suggestion that can help in understanding functions in general: What happens when we call a function?. That said, I think we can first see how it would be if the funcao nay…
-
5
votes4
answers150
viewsA: What regular expression to use to replace symbols in a string?
Complementing the other responses - and reinforcing for nay use regex, since solutions proposed by others are more suitable than regular expressions - see how it would be unnecessarily more…
-
2
votes1
answer108
viewsA: How to get binary code from a string without ASCII characters in Python?
The method encode returns an instance of bytes. And an object of the kind bytes, according to the documentation is a sequence of numbers, whose values are in the range between 0 and 255. And a…
-
1
votes1
answer82
viewsA: Use Regex to replace text
At first, you could simply create HTML with the text and the input, but if the idea is that it is dynamic, an alternative would be: var p = document.querySelector('#texto');…
-
1
votes2
answers11683
viewsA: What is the difference between Arrays.asList and List.of?
Complementing the another answer, there are several differences between these two methods (reference). One has already been quoted: Arrays.asList returns a list that can be modified (but with…
-
4
votes1
answer34
viewsA: Sort with Selection Sort by size and alphabetically
Simply include an additional check on if: def nome_ordena(nomes): for i in range(len(nomes)): i_menor = i for j in range(i + 1, len(nomes)): # se tamanho é diferente, ou se o tamanho é igual, usa a…
-
2
votes1
answer26
viewsA: Filter two lines of the file at the same time show only the second?
For this file format, an option would be: grep Cidade -A 1 info.txt | grep Title | awk -F: '{gsub(" +","");print $2}' The first grep takes the lines that have "City", and the option -A 1 also picks…