- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
// Это означает что, например, поведение следующего кода не определено:
fn cast(x: f32) -> u8 {
    x as u8
}
fn main() {
    let f = 300.0;
    let x = cast(f);
    println!("x: {}", x);
}Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
// Это означает что, например, поведение следующего кода не определено:
fn cast(x: f32) -> u8 {
    x as u8
}
fn main() {
    let f = 300.0;
    let x = cast(f);
    println!("x: {}", x);
}
            https://habr.com/ru/post/511546/
> Это мы называем ошибкой «корректности» (ведь unsafe кода тут нет) — то есть ошибка, когда компилятор делает неправильные вещи. Мы отмечаем их в нашем трекере как I-unsound, и относимся к ним очень серьёзно.
        
+1
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static java.lang.System.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class Rep implements CharSequence
{
    String str = null;
    int    len;
    char  base;
    public Rep(char x, int count)
    {
        this.len  = count;
        this.base = x;
    }
    @Override
    public int length()
    {
        return len;
    }
    @Override
    public char charAt(int index)
    {
        return base;
    }
    @Override
    public CharSequence subSequence(int beginIndex, int endIndex)
    {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > this.len) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == this.len)) ? this
                : new Rep(this.base, subLen);
    }
    @Override
    public String toString()
    {
        return null!=str ?  str : (this.str  = new String(new char[]{base}).repeat(len));
    }
    public static void main(String... args)
    {
        long ns = 0L;
        Pattern lazy   = Pattern.compile("^(11+?)\\1+$");
        Pattern greedy = Pattern.compile("^(11+?)\\1+$");
        ns=nanoTime();  lazy  .matcher(new Rep('1',100160079)).matches(); out.println( NANOSECONDS.toMillis(nanoTime()-ns));
        ns=nanoTime();  greedy.matcher(new Rep('1',100160079)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
        ns=nanoTime();  greedy.matcher(new Rep('1',1165139)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
        ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+?)\\1+$") ; out.println("Lazy String:"+ NANOSECONDS.toMillis(nanoTime()-ns));
        ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+)\\1+$") ; out.println("Greedy String:"+ NANOSECONDS.toMillis(nanoTime()-ns)); 
    }
}
            Так как в «Йажа» регулярки работают не на строках, а на интерфейсе CharSequence https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/CharSequence.html
Решил что можно сделать тупую реализацию CharSequence для строк из повторяющегося символа.
https://ideone.com/8eYFU7
        
+1
SIGRed (CVE-2020-1350) is a wormable, critical vulnerability (CVSS base score of 10.0) in the Windows DNS server
that affects Windows Server versions 2003 to 2019, and can be triggered by a malicious DNS response.
As the service is running in elevated privileges (SYSTEM), if exploited successfully, an attacker is granted Domain Administrator
rights, effectively compromising the entire corporate infrastructure.https://research.checkpoint.com/2020/resolving-your-way-into-domain-admin-exploiting-a-17-year-old-bug-in-windows-dns-servers/
+1
IT Оффтоп #50
#1: https://govnokod.ru/18142 https://govnokod.xyz/_18142
#2: https://govnokod.ru/18378 https://govnokod.xyz/_18378
#3: https://govnokod.ru/19667 https://govnokod.xyz/_19667
#4: https://govnokod.ru/21160 https://govnokod.xyz/_21160
#5: https://govnokod.ru/21772 https://govnokod.xyz/_21772
#6: (vanished) https://govnokod.xyz/_24063
#7: https://govnokod.ru/24538 https://govnokod.xyz/_24538
#8: (vanished) https://govnokod.xyz/_24815
#9: https://govnokod.ru/24867 https://govnokod.xyz/_24867
#10: https://govnokod.ru/25328 https://govnokod.xyz/_25328	
#11: (vanished) https://govnokod.xyz/_25436
#12: (vanished) https://govnokod.xyz/_25471
#13: (vanished) https://govnokod.xyz/_25590
#14: https://govnokod.ru/25684 https://govnokod.xyz/_25684
#15: https://govnokod.ru/25694 https://govnokod.xyz/_25694
#16: https://govnokod.ru/25725 https://govnokod.xyz/_25725
#17: https://govnokod.ru/25731 https://govnokod.xyz/_25731
#18: https://govnokod.ru/25762 https://govnokod.xyz/_25762
#19: https://govnokod.ru/25767 https://govnokod.xyz/_25767
#20: https://govnokod.ru/25776 https://govnokod.xyz/_25776
#21: https://govnokod.ru/25798 https://govnokod.xyz/_25798
#22: https://govnokod.ru/25811 https://govnokod.xyz/_25811
#23: https://govnokod.ru/25863 https://govnokod.xyz/_25863
            #24: https://govnokod.ru/25941 https://govnokod.xyz/_25941
#25: https://govnokod.ru/26026 https://govnokod.xyz/_26026
#26: https://govnokod.ru/26050 https://govnokod.xyz/_26050
#27: https://govnokod.ru/26340 https://govnokod.xyz/_26340
#28: https://govnokod.ru/26372 https://govnokod.xyz/_26372
#29: https://govnokod.ru/26385 https://govnokod.xyz/_26385
#30: https://govnokod.ru/26413 https://govnokod.xyz/_26413
#31: https://govnokod.ru/26423 https://govnokod.xyz/_26423
#32: https://govnokod.ru/26440 https://govnokod.xyz/_26440
#33: https://govnokod.ru/26449 https://govnokod.xyz/_26449
#34: https://govnokod.ru/26456 https://govnokod.xyz/_26456
#35: https://govnokod.ru/26463 https://govnokod.xyz/_26463
#36: https://govnokod.ru/26508 https://govnokod.xyz/_26508
#37: https://govnokod.ru/26524 https://govnokod.xyz/_26524
#38: https://govnokod.ru/26539 https://govnokod.xyz/_26539
#39: https://govnokod.ru/26556 https://govnokod.xyz/_26556
#40: https://govnokod.ru/26568 https://govnokod.xyz/_26568
#41: https://govnokod.ru/26589 https://govnokod.xyz/_26589
#42: https://govnokod.ru/26600 https://govnokod.xyz/_26600
#43: https://govnokod.ru/26604 https://govnokod.xyz/_26604
#44: https://govnokod.ru/26627 https://govnokod.xyz/_26627
#45: https://govnokod.ru/26635 https://govnokod.xyz/_26635
#46: (vanished) https://govnokod.xyz/_26646
#46: (vanished) https://govnokod.xyz/_26654
#47: https://govnokod.ru/26671 https://govnokod.xyz/_26671
#48: https://govnokod.ru/26707 https://govnokod.xyz/_26707
#49: https://govnokod.ru/26750 https://govnokod.xyz/_26750
#49: https://govnokod.ru/26776 https://govnokod.xyz/_26776
        
+1
private void checkButton_Click(object sender, EventArgs e)
    {
      if (this.passportTextbox.Text.Trim() == "")
      {
        int num1 = (int) MessageBox.Show("Введите серию и номер паспорта");
      }
      else
      {
        string rawData = this.passportTextbox.Text.Trim().Replace(" ", string.Empty);
        if (rawData.Length < 10)
        {
          this.textResult.Text = "Неверный формат серии или номера паспорта";
        }
        else
        {
          string commandText = string.Format("select * from passports where num='{0}' limit 1;", (object) Form1.ComputeSha256Hash(rawData));
          string connectionString = string.Format("Data Source=" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\db.sqlite");
          try
          {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            connection.Open();
            SQLiteDataAdapter sqLiteDataAdapter = new SQLiteDataAdapter(new SQLiteCommand(commandText, connection));
            DataTable dataTable1 = new DataTable();
            DataTable dataTable2 = dataTable1;
            sqLiteDataAdapter.Fill(dataTable2);
            if (dataTable1.Rows.Count > 0)
            {
              if (Convert.ToBoolean(dataTable1.Rows[0].ItemArray[1]))
                this.textResult.Text = "По паспорту «" + this.passportTextbox.Text + "» доступ к бюллетеню на дистанционном электронном голосовании ПРЕДОСТАВЛЕН";
              else
                this.textResult.Text = "По паспорту «" + this.passportTextbox.Text + "» доступ к бюллетеню на дистанционном электронном голосовании НЕ ПРЕДОСТАВЛЯЛСЯ";
            }
            else
              this.textResult.Text = "Паспорт «" + this.passportTextbox.Text + "» в списке участников дистанционного голосования НЕ НАЙДЕН";
            connection.Close();
          }
          catch (SQLiteException ex)
          {
            if (ex.ErrorCode != 1)
              return;
            int num2 = (int) MessageBox.Show("Файл db.sqlite не найден. Положите файл в папку вместе с exe.");
          }
        }
      }
    }
            https://habr.com/post/510512/
Медуза, паспорта и говнокод — почему номера паспортов всех участников интернет-голосования попали в Интернет
        
+1
public static bool found13 = false;
public static bool found11 = false;
// ...
public List<int> Children = new List<int>(); //index of children
public List<int> Children13 = new List<int>(); //index of children
            Код бота-автора подавляющего большинства статей на нескольких языках. В основном Шведский (автор бота — швед) и, наверное, Себуанский, не знаю как правильно по-русски, короче язык океании, где-то на Филиппинах на нем говорят. На последнем, между прочим, бот нахерачил столько, что вывел себуанскую Википедию на второе место по количеству статей вообще.
Потрясающий пример говнокода, написанного учёным для дела, и приемлемо решающий свою задачу. На основе отрытых баз знаний о таксонах биологических видов и географических объектах (реки, горы, населенные пункты), генерит статьи-заглушки с краткой информационной сводкой.
https://sv.wikipedia.org/wiki/Wikipedia:Projekt_DotNetWikiBot_Framewor  k/Lsjbot/Makespecies
Сори, если баян.
        
+1
if (feet_yaw <= 58)
	{
		if (-58 > feet_yaw)
			player->EyeAngles()->y = body_max_rotation + player->EyeAngles()->y;
	}
	else
	{
		player->EyeAngles()->y = body_max_rotation - player->EyeAngles()->y;
	}
	if (player->GetAnimOverlay(6)->m_flPlaybackRate > 0.1)
	{
		for (int resolve_delta = 58.f; resolve_delta < -58.f; resolve_delta = resolve_delta - 20.f)
		{
			player->EyeAngles()->y = resolve_delta;
		}
	}ресольвер
+1
if (UpdateLBY)
			{
				auto m_flDelta = csgo->local->GetPlayerAnimState()->m_flGoalFeetYaw - csgo->local->GetPlayerAnimState()->m_flEyeYaw;
				if (m_flDelta >= 35.0 && m_flDelta <= -35.0) {
					// the first lby break is left.
					csgo->cmd->viewangles.y -= 122.f;
				}
				else {
					if (m_flDelta <= -35.0) {
						// the second lby break is right.
						csgo->cmd->viewangles.y += 122.f;
					}
					if (m_flDelta >= 35.0) {
						// the loop.
						csgo->cmd->viewangles.y -= 122.f;
					}
				}
				csgo->send_packet = false;
				return;
			}
+1
package literatePrimes;
import java.util.ArrayList;
public class PrimeGenerator {
  private static int[] primes;
  private static ArrayList<Integer> multiplesOfPrimeFactors;
  protected static int[] generate(int n) {
    primes = new int[n];
    multiplesOfPrimeFactors = new ArrayList<Integer>();
    set2AsFirstPrime();
    checkOddNumbersForSubsequentPrimes();
    return primes;
  }
  private static void set2AsFirstPrime() {
    primes[0] = 2;
    multiplesOfPrimeFactors.add(2);
  }
  private static void checkOddNumbersForSubsequentPrimes() {
    int primeIndex = 1;
    for (int candidate = 3;
         primeIndex < primes.length;
         candidate += 2) {
      if (isPrime(candidate))
        primes[primeIndex++] = candidate;
    }
  }
  private static boolean isPrime(int candidate) {
    if (isLeastRelevantMultipleOfNextLargerPrimeFactor(candidate)) {
      multiplesOfPrimeFactors.add(candidate);
      return false;
    }
    return isNotMultipleOfAnyPreviousPrimeFactor(candidate);
  }
  private static boolean
  isLeastRelevantMultipleOfNextLargerPrimeFactor(int candidate) {
    int nextLargerPrimeFactor = primes[multiplesOfPrimeFactors.size()];
    int leastRelevantMultiple = nextLargerPrimeFactor * nextLargerPrimeFactor;
    return candidate == leastRelevantMultiple;
  }
  private static boolean
  isNotMultipleOfAnyPreviousPrimeFactor(int candidate) {
    for (int n = 1; n < multiplesOfPrimeFactors.size(); n++) {
      if (isMultipleOfNthPrimeFactor(candidate, n))
        return false;
    }
    return true;
  }
  private static boolean
  isMultipleOfNthPrimeFactor(int candidate, int n) {
   return
     candidate == smallestOddNthMultipleNotLessThanCandidate(candidate, n);
  }
  private static int
  smallestOddNthMultipleNotLessThanCandidate(int candidate, int n) {
    int multiple = multiplesOfPrimeFactors.get(n);
    while (multiple < candidate)
      multiple += 2 * primes[n];
    multiplesOfPrimeFactors.set(n, multiple);
    return multiple;
  }
}
            https://habr.com/ru/post/508876/
Вероятно, хватит рекомендовать «Чистый код»
> Я остановлюсь на ещё одном вопиющем примере кода. Это генератор простых чисел из главы 8:
        
+1
from selenium import webdriver
import time
import telegram
def A():
    код парсера
while True:
    browser = webdriver.Chrome()
    browser.maximize_window()
    browser.get('ссылка')
    try:
        BOT_TOKEN = 'токен'
        number2 = browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[5]/div/div[1]/div[1]/div').text
        SS = number2.split()
        if SS[0] == '0' and SS[1] == '0':
            browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[5]/div/div[1]/div[1]/a').click()
            time.sleep(5)
            A()
    except Exception:
        pass
    try:
        BOT_TOKEN = 'токен'
        number2 = browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[4]/div/div[1]/div[1]/div').text
        SS = number2.split()
        if SS[0] == '0' and SS[1] == '0':
            browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[4]/div/div[1]/div[1]/a').click()
            time.sleep(5)
            A()
    except Exception:
        pass
    try:
        BOT_TOKEN = 'токен'
        number2 = browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[3]/div/div[1]/div[1]/div').text
        SS = number2.split()
        if SS[0] == '0' and SS[1] == '0':
            browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[3]/div/div[1]/div[1]/a').click()
            time.sleep(5)
            A()
    except Exception:
        pass
    try:
        BOT_TOKEN = 'токен'
        number2 = browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[6]/div/div[1]/div[1]/div').text
        SS = number2.split()
        if SS[0] == '0' and SS[1] == '0':
            browser.find_element_by_xpath('//*[@id="games_content"]/div/div[1]/div/div/div[6]/div/div[1]/div[1]/a').click()
            time.sleep(5)
            A()
    except Exception:
        pass
    browser.close()
    time.sleep(15)Вопросик с хабра)