# -*- coding: utf-8 -*-
"""
# Самый простой пример окна.
# Отсюда: https://wiki.wxpython.org/Getting%20Started
import wx
# Create a new app, don't redirect stdout/stderr to a window.
app = wx.App(False)
# A Frame is a top-level window.
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True) # Show the frame.
app.MainLoop()
"""
import wx
class MyFrame(wx.Frame):
"""Главное окно."""
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200, 100))
# текстовое многострочное поле
self.text_input = wx.TextCtrl(
self,
style=wx.TE_MULTILINE,
size=(400, 200),
)
# кнопка
self.exit_button = wx.Button(
self,
label="Exit",
pos=(300, 300),
size=(100, 100)
)
self.Size = (500, 500)
# Привязка нажатия кнопки к запуску метода главного окна
self.Bind(wx.EVT_BUTTON, self.my_exit, self.exit_button)
self.Show(True)
def my_exit(self, param):
"""Самодельный метод - Закрыть главное окно."""
# quit() # раскоментировать чтоб выход заработал
print(f"param: {dir(param)}") # что во втором параметре
self.text_input.SetValue("Exit") # изменить текст
app = wx.App(False)
frame = MyFrame(None, 'Small editor - Тестовый редактор')
app.MainLoop()
Архив рубрики: Без рубрики
Python matplotlib быстро нарисовать график
Сборка Python из исходников в Linux
Имеем распакованный архив с исходниками, например Python-3.10.0.tar.xz
1490 cd Python-3.10.0
1491 ls
1492 mkdir debug
1493 cd debug/
1498 make -C ".." clean
1499 ../configure --with-pydebug
1500 make
1502 ./python
Последней командой запустится собранный из исходников python, можно пользоваться
Как узнать код активации Windows из Linux
В «современных» компьютерах код активации windows обычно зашивается производителями в железо. Чтобы узнать код активации, например для переустановки винды, нужно загрузиться с загрузочной флэшки с Linux и выполнить команду:
sudo cat /sys/firmware/acpi/tables/MSDM
Pygame перехват событий с джойстика
Код для вывода информации обо всех событиях, происходящих с джойстиком:
import pygame
pygame.joystick.init()
pygame.init()
clock = pygame.time.Clock()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
while True:
for event in pygame.event.get():
print(event)
clock.tick(60)
Пример вывода информации о происходящих с джойстиком событиях:
pygame 2.0.1 (SDL 2.0.14, Python 3.8.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
<Event(1541-JoyDeviceAdded {'device_index': 0, 'guid': '030000004c050000da0c000011010000'})>
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 0})>
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 1})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': 0.0})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': -1.000030518509476})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': 0.0})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 3})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 3})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 0})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 0})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 2})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 2})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 1})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 1})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 5})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 5})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 4})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 4})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 7})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 7})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 6})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 6})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 9})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 9})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 8})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 8})>
Программа для проверки джойстика — человек ходит влево-вправо:
import pygame
pygame.joystick.init()
pygame.init()
clock = pygame.time.Clock()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
hero_sprite = (
"_o_\n"
"(_)\n"
"/ \\\n"
)
def render_object(x: int, sprite: str):
lines = sprite.split("\n")
print("\n" * 50)
for line in lines:
print(" " * x + line)
hero_x = 10
hero_vx = 0
while True:
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
print("it works!")
if event.axis == 0:
hero_vx = int(event.value)
hero_x += hero_vx
render_object(hero_x, hero_sprite)
clock.tick(60)
Python ctypes и вызов функций
>>> from ctypes import *
>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle 7f8318993000 at 0x7f8317e7f730>
>>> libc = CDLL("libc.so.6")
>>> libc.printf(b"spam")
4
spam>>>
>>> c_int()
c_int(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140201018456432)
>>> c_wchar_p("Hello, World")
c_wchar_p(140201018456688)
>>> c_ushort(-3)
c_ushort(65533)
>>> c_uint(-3)
c_uint(4294967293)
>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(140201018456432)
>>> print(c_s.value)
Hello, World
Сборка из исходников и запуск игры Minetest в Ubuntu
По порядку выполнял команды в консоли, всё получилось с первого раза, игра minetest запустилась:
cd MyPets/
mkdir 2022-05-18_minetest_from_scratch
cd 2022-05-18_minetest_from_scratch
sudo apt install g++ make libc6-dev cmake libpng-dev libjpeg-dev libxxf86vm-dev libgl1-mesa-dev libsqlite3-dev libogg-dev libvorbis-dev libopenal-dev libcurl4-gnutls-dev libfreetype6-dev zlib1g-dev libgmp-dev libjsoncpp-dev libzstd-dev libluajit-5.1-dev
ls
sudo apt install git
git clone --depth 1 https://github.com/minetest/minetest.git
ls
cd minetest/
ls
git clone --depth 1 https://github.com/minetest/minetest_game.git games/minetest_game
git clone --depth 1 https://github.com/minetest/irrlicht.git lib/irrlichtmt
cmake . -DRUN_IN_PLACE=TRUE
make -j$(nproc)
./bin/minetest
Теперь в игре можно легко править и добавлять всё что угодно и пересобирать.
Быстрая настройка прокси-сервера privoxy в Ubuntu-образном линуксе за 10 минут
Предупреждение: не для продакшна!
Установка:
$ sudo apt-get install privoxy
Настройка:
- /etc/privoxy/config
...
debug 512
...
listen-address 192.168.0.88:8118
...
- /etc/privoxy/user-action: дописать в самый конец
...
# как блокировать вообще всё пока не нашёл, поэтому такой стыд из звёздочек
{+block}
*
*.*
*.*.*
*.*.*.*
*.*.*.*.*
# белый список куда можно
{-block}
linux.org.ru
*.linux.org.ru
Просмотр логов:
$ tail -f /var/log/privoxy/logfile
Идея здесь такая, что никуда нельзя. Смотрим лог, выбираем адреса, которые нужны, добавляем в конец user-action.
Из плюсов:
- все левые сайты блокируются
- работает для HTTPS без колдовства с сертификатами (соединение остаётся нормально зашифрованным)
Из минусов — читать логи и ручками дописывать конфиг. Ещё не разобрался как нормально заблокировать вообще все сайты. В примере конфига блокируются все поддомены до 5 уровня. Сайты с доменами 6 уровня и больше не блокируются.
Почти весь C# за 2 часа
Материал для тех, кто уже на чём-то писать умеет, и кому надо срочно что-то написать на C#. Это не шпаргалка для экзаменов, а набор примеров кода. Приведённых здесь примеров достаточно для 80% всего, что можно написать на C# даже без использования IDE (достаточно блокнота). Поехали.
= c#
== Самая короткая программа на C#, которая ничего не делает
class test {static void Main(){}}
== выход из программы
Quit();
return из Main
== компиляция
=== csc
csc form.cs
на выходе появится экзешник
=== mcs
mcs form.cs -r:System.Windows.Forms.dll
== консоль
Console.Write("Press any key to exit . . . ");
Console.ReadKey(true);
== подключение dll
[DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true, CharSet = CharSet.Unicode,
ThrowOnUnmappableChar = true)]
private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags);
== перебор массивов циклом
=== объявление
==== многомерный массив
int[] nums1 = new int[] { 0, 1, 2, 3, 4, 5 };
int[,] nums2 = { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums1;
int[,] nums2 = new int[2, 3];
int[,] nums3 = new int[2, 3] { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums4 = new int[,] { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums5 = new [,]{ { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums6 = { { 0, 1, 2 }, { 3, 4, 5 } };
==== массив массивов
int[][] nums = new int[3][];
nums[0] = new int[2] { 1, 2 }; // выделяем память для первого подмассива
nums[1] = new int[3] { 1, 2, 3 }; // выделяем память для второго подмассива
nums[2] = new int[5] { 1, 2, 3, 4, 5 }; // выделяем память для третьего подмассива
=== for
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = numbers[i] * 2;
Console.WriteLine(numbers[i]);
}
=== foreach
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int i in numbers)
{
Console.WriteLine(i);
}
=== длина массива
int[] numbers = { 1, 2, 3, 5 };
Console.WriteLine(numbers.Length); // 4
=== элементы с конца
int[] numbers = { 1, 2, 3, 5};
Console.WriteLine(numbers[^1]); // 5 - последний элемент с конца
Console.WriteLine(numbers[^2]); // 3 - предпоследний элемент с конца
== чтение и запись файлов
=== чтение
string text = System.IO.File.ReadAllText(@"C:\tmp\Text.txt");
=== запись
var file = new System.IO.StreamWriter(this.textBoxOutputDir.Text + "\\log.txt", true);
file.WriteLine(OutText);
file.Close();
== http-запросы
using System.Net;
...
private static string POST(string Url, string Data)
{
WebRequest req = WebRequest.Create(Url);
req.Method = "POST";
req.Timeout = 100000;
req.ContentType = "application/x-www-form-urlencoded";
byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
req.ContentLength = sentData.Length;
Stream sendStream = req.GetRequestStream();
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
WebResponse res = req.GetResponse();
Stream ReceiveStream = res.GetResponseStream();
StreamReader sr = new StreamReader(ReceiveStream, Encoding.UTF8);
//Кодировка указывается в зависимости от кодировки ответа сервера
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
...
}
== Обработка исключений
static double SafeDivision(double x, double y)
{
if (y == 0)
throw new DivideByZeroException();
return x / y;
}
...
try
{
result = SafeDivision(a, b);
Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
}
catch (DivideByZeroException)
{
Console.WriteLine("Attempted divide by zero.");
}
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do
== обработка аргументов
public static int Main(string[] args) {
if(args.Length > 1){
string Data="arg1:" + args[1];
...
}
}
== окна
=== создание окна
using System;
using System.Windows.Forms;
public class HelloWorld : Form {
static public void Main () {
Application.Run (new HelloWorld ());
}
public HelloWorld () {
Text = "Hello Mono World";
}
}
=== добавление кнопки
this.button1 = new System.Windows.Forms.Button();
this.button1.Location = new System.Drawing.Point(192, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(88, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Browse";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.Controls.Add(this.button1);
...
private void button1_Click(object sender, System.EventArgs e)
{
...
}
=== всё вместе
public class MainWindow : System.Windows.Controls.Window
{
private Button button1;
public MainWindow()
{
button1 = new Button();
button1.Text = "Click me!";
button1.ClickEvent += button1_OnClick;
}
protected void button1_OnClick(object sender, MouseEventArgs e)
{
MessageBox.Show("Clicked!");
}
}
== лямбды
(input-parameters) => expression
(input-parameters) => { <sequence-of-statements> }
Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25
== xml
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
// Save the document to a file.
doc.Save("data.xml");
}
}
== sql
using System.Data.SqlClient;
string query = @"select 1";
using (
var connection = new SqlConnection(
"user id=Vasya;password=P@$$w0rd;server=MyServer;database=MyBase;connection timeout=10;"
)
) {
connection.Open();
using (var command = new SqlCommand(query, connection)){
command.CommandTimeout = 290;
using(SqlDataReader reader = command.ExecuteReader()){
int rowcounter = -1;
while (reader.Read()) {
rowcounter++; //счётчик строк в результате запроса
//заполняем значения в сохранённой строке
if (reader["My_Column"] is int) {
int n = (int)reader["My_Column "];
}
//…
}
reader.Close();
}
}
}
//добавить обработчики исключений
Для подключения к базе не под логином и паролем, а через доменную авторизацию
using (var connection = new SqlConnection("server=MyServer;database=MyBase;connection timeout=10; Integrated Security=True;")) {}
== Linq
using System.Linq;
using System.DirectoryServices;
...
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry
in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
foreach (var name in userNames)
Console.WriteLine(name);
}
var list = new List<int>{ 2, 7, 1, 3, 9 };
var result = from i in list
where i > 1
select i;
== операции со строками
// Declare without initializing.
string message1;
string message2 = null;
string message3 = System.String.Empty;
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";
System.String greeting = "Hello World!";
var temp = "I'm still a strongly-typed System.String!";
const string message4 = "You can't get rid of me!";
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);
=== сложение
s1 += s2;
=== подстроки
string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"
=== поиск
int index = s3.IndexOf("C");
=== замена
System.Console.WriteLine(s3.Replace("C#", "Basic"));
=== перебор символов
s5[s5.Length - i - 1]
=== ToLower ToUpper
if (System.Char.IsLower(sb[j]) == true)
sb[j] = System.Char.ToUpper(sb[j]);
else if (System.Char.IsUpper(sb[j]) == true)
sb[j] = System.Char.ToLower(sb[j]);
=== форматированные строки
var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) * 100d} years old today.");
string name = "Vynn";
string greetings = string.Format("Hello {0}!", name);
string name = "Vjor";
string greeting = $"Hello, {name}!";
=== многострочные строки
string query = @"
SELECT *
FROM some_table
"
@"C:\tmp\Text.txt"
=== unicode
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
== Словари
var jh = (
firstName: "Jupiter",
lastName: "Hammon",
born: 1711,
published: 1761
);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
var numbers = new Dictionary<int, string>
{
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
foreach (KeyValuePair<string, List<string>> group in rudimentaryMultiValuedDictionary1){
...
}
== задержка времмени в программе
System.Threading.Thread.Sleep(50);
== многопоточность
public async Task<int> RetrieveDocsHomePage()
{
var client = new HttpClient();
byte[] content = await client.GetByteArrayAsync("https://docs.microsoft.com/");
Console.WriteLine($"{nameof(RetrieveDocsHomePage)}: Finished downloading.");
return content.Length;
}
Thread synchronization
C# provides the lock statement, which is yet another example of beneficial syntactic sugar. It works by marking a block of code as a critical section by mutual exclusion of access to a provided object. Like the using statement, it works by the compiler generating a try ... finally block in its place.
private static StreamWriter _writer;
public void ConcurrentMethod()
{
lock (_writer)
{
_writer.WriteLine("Line 1.");
_writer.WriteLine("Followed by line 2.");
}
}
== асинхронность
static IEnumerable<int> MyIterator()
{
try
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
yield return i;
}
}
finally
{
Thread.Sleep(200);
Console.WriteLine("finally");
}
}
static async IAsyncEnumerable<int> MyIterator()
{
try
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(1000);
yield return i;
}
}
finally
{
await Task.Delay(200);
Console.WriteLine("finally");
}
}
IAsyncEnumerable<string> result = from url in urls
where item % 2 == 0
select SomeAsyncMethod(item);
async ValueTask<int> SomeAsyncMethod(int item)
{
await Task.Yield();
return item * 2;
}
public static class SomeAsyncCode
{
public static Task<XDocument> GetContentAsync()
{
HttpClient httpClient = new HttpClient();
return httpClient.GetStringAsync("www.contoso.com").ContinueWith((task) => {
string responseBodyAsText = task.Result;
return XDocument.Parse(responseBodyAsText);
});
}
}
var t = SomeAsyncCode.GetContentAsync().ContinueWith((task) => {
var xmlDocument = task.Result;
});
t.Start();
Here is the same logic written in the async-await syntax:
public static class SomeAsyncCode
{
public static async Task<XDocument> GetContentAsync()
{
HttpClient httpClient = new HttpClient();
string responseBodyAsText = await httpClient.GetStringAsync("www.contoso.com");
return XDocument.Parse(responseBodyAsText);
}
}
var xmlDocument = await SomeAsyncCode.GetContentAsync();
// The Task will be started on call with await.
== Запуск команд CMD из кода программы
using System.Diagnostics;
Process.Start("calc");
Process.Start("explorer", "d:");
Так же можно запускать программы от имени другого пользователя, см. вамианты перегрузки .Start()
== тесты
[TestMethod]
public void Debit_WithValidAmount_UpdatesBalance()
{
double beginningBalance = 11.99;
double debitAmount = 4.55;
double expected = 7.44;
BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);
account.Debit(debitAmount);
double actual = account.Balance;
Assert.AreEqual(expected, actual, 0.001, "Account not debited correctly");
}
[TestMethod]
public void Debit_WhenAmountIsMoreThanBalance_ShouldThrowArgumentOutOfRange()
{
double beginningBalance = 11.99;
double debitAmount = 20.0;
BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);
try {
account.Debit(debitAmount);
}
catch (System.ArgumentOutOfRangeException e) {
// Assert
StringAssert.Contains(e.Message, BankAccount.DebitAmountExceedsBalanceMessage);
return;
}
Assert.Fail("The expected exception was not thrown.");
}
== прочее
=== пространства имён
using forwpf = System.Windows;
...
public static forwpf::Point Convert(forwinforms::Point point) => new forwpf::Point(point.X, point.Y);
=== узнать текущее имя пользователя
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
=== какая вкладка открыта в tabControl
this.tabControl1.SelectedTab – сама выбранная вкладка
this.tabControl1.SelectedTab.Text – её заголовок
tabControl1.SelectTab(1); — выбрать вкладку по номеру
=== get, set
public int Y
{
get { return y; }
set { y = value; }
}
struct Point
{
int X;
int Y {get; set;}
}
=== операторы
System.Index operator ^(int fromEnd);
=== обход файлов и папок
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
System.Console.WriteLine(s);
}
=== stdin, out, err
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
=== HEX
byte[] array = { 0x64, 0x6f, 0x74, 0x63, 0x65, 0x74 };
string hexValue = Convert.ToHexString(array);
/*Output:
646F74636574
*/
=== списки
System.Collections.Generic.List<string> strings = new System.Collections.Generic.List<string>();
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};
.at(...)
=== операторы
Primary expressions Primary x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
Unary operators Unary + - ! ~ ++x --x (T)x
Arithmetic operators Multiplicative * / %
Arithmetic operators Additive + -
Shift operators Shift << >>
Relational and type-testing operators Relational and type testing < > <= >= is as
Relational and type-testing operators Equality == !=
Logical operators Logical AND &
Logical operators Logical XOR ^
Logical operators Logical OR |
Conditional logical operators Conditional AND &&
Conditional logical operators Conditional OR ||
The null coalescing operator Null coalescing ??
Conditional operator Conditional ?:
Assignment operators, Anonymous function expressions Assignment and lambda expression = *= /= %= += -= <<= >>= &= ^= |= =>
=== колбэки
public static void MethodWithCallback(int param1, int param2, Del callback)
{
callback("The number is: " + (param1 + param2).ToString());
}
=== if else
int statusCode = condition ? 1 : 2;
=== switch
switch (condition)
{
case 1:
//do something
break;
case 2:
//do something
break;
case 3:
//do something
break;
default:
//do something else
break;
}
=== Tuples
public (string FirstName, string LastName) GetName()
{
return ("Vincent", "Durano");
}
=== делегаты
class Program
{
// Delegate type:
delegate int Operation(int a, int b);
static int Add(int i1, int i2)
{
return i1 + i2;
}
static int Sub(int i1, int i2)
{
return i1 - i2;
}
static void Main()
{
// Instantiate the delegate and assign the method to it.
Operation op = Add;
// Call the method that the delegate points to.
int result1 = op(2, 3); // 5
op = Sub;
int result2 = op(10, 2); // 8
}
}
=== указатели
static void Main(string[] args)
{
unsafe
{
int a = 2;
int* b = &a;
Console.WriteLine("Address of a: {0}. Value: {1}", (int)&a, a);
Console.WriteLine("Address of b: {0}. Value: {1}. Value of *b: {2}", (int)&b, (int)b, *b);
// Will output something like:
// Address of a: 71953600. Value: 2
// Address of b: 71953596. Value: 71953600. Value of *b: 2
}
}
=== анонимные типы
var carl = new { Name = "Carl", Age = 35 }; // Name of the type is only known by the compiler.
=== Boxing and unboxing
int foo = 42; // Value type.
object bar = foo; // foo is boxed to bar.
int foo2 = (int)bar; // Unboxed back to value type.
=== модификаторы
Class modifiers
abstract - Specifies that a class only serves as a base class. It must be implemented in an inheriting class.
sealed - Specifies that a class cannot be inherited.
Class member modifiers
const - Specifies that a variable is a constant value that has to be initialized when it gets declared.
event - Declares an event.
extern - Specifies that a method signature without a body uses a DLL-import.
override - Specifies that a method or property declaration is an override of a virtual member or an implementation of a member of an abstract class.
readonly - Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class.
unsafe - Specifies an unsafe context, which allows the use of pointers.
virtual - Specifies that a method or property declaration can be overridden by a derived class.
volatile - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.
static modifier
=== интерфейсы
public class Adder : IBinaryOperation
{
double IBinaryOperation.A { get; set; }
double IBinaryOperation.B { get; set; }
double IBinaryOperation.GetResult()
{
return ((IBinaryOperation)this).A + ((IBinaryOperation)this).B;
}
}
In use:
Adder add = new Adder();
// These members are not accessible:
// add.A = 2;
// add.B = 3;
// double result = add.GetResult();
// Cast to the interface type to access them:
IBinaryOperation add2 = add;
add2.A = 2;
add2.B = 3;
double result = add2.GetResult();
class MyClass : IInterfaceA, IInterfaceB
{
...
}
Here is an interface that extends two interfaces.
interface IInterfaceC : IInterfaceA, IInterfaceB
{
...
}
=== Шаблоны типов
public class GenericList<T>
{
void Add(T input) { }
}
=== Генераторы
public static IEnumerable<int> GetEven(IEnumerable<int> numbers){
foreach (int i in numbers){
if (i%2 == 0)
yield return i;
}
}
=== XML documentation system
public class Foo
{
/** <summary>A summary of the method.</summary>
* <param name="firstParam">A description of the parameter.</param>
* <remarks>Remarks about the method.</remarks> */
public static void Bar(int firstParam) {}
}
=== ...
Do use the using statement when working with objects that eat resources or implements IDisposable interface:
using (MemoryStream stream = new MemoryStream())
{
// do something
}
Try to avoid one-liner method implementation with curly braces like in the following:
public string Greeter(string name)
{
return $"Hello {name}!";
}
+1 Do use Expression-bodied (=>) implementation instead:
public string Greeter(string name) => $"Hello {name}!";
public struct Point { ... } // defines a “value” type
public class Pen { ... } // defines a “reference” type
=== ссылки
https://github.com/justinamiller/DotNet-Coding-Guidelines/blob/main/README.md
https://en.wikipedia.org/wiki/C_Sharp_syntax
Если чего-то всем нужного здесь не нашли, можно писать в комментариях.
Linux Bash если не подключается wifi
$ sudo rfkill list
0: phy0: Wireless LAN
Soft blocked: yes
Hard blocked: no
1: hci0: Bluetooth
Soft blocked: no
Hard blocked: no
$ sudo rfkill unblock 0
$ sudo ifconfig wlan0 up
После этого wifi подключился и заработал
