├── .vscode └── settings.json ├── CSharp ├── CSharpConsole.cs ├── Thread.cs ├── basic.cs ├── files.cs ├── linq.cs ├── mysql.cs ├── reflection.cs └── sockets │ └── socket.cs ├── D └── basic.d ├── README.md ├── SmallBasic ├── learn.sb └── smallbasic.sb ├── apache ├── .htaccess ├── index.php └── notes.txt ├── bash └── bash.sh ├── c++ ├── a.dat ├── basics.cpp ├── files.cpp ├── libs │ ├── ctime.cpp │ └── math.cpp └── oop.cpp ├── c └── main.c ├── dart ├── design_patters │ └── creational │ │ ├── builder.dart │ │ ├── singleto.dart │ │ └── singleton_factory.dart ├── files.dart ├── libs │ ├── convert.dart │ ├── datetime.dart │ ├── html.dart │ ├── http.dart │ ├── io.dart │ └── stream.dart ├── main.dart ├── server.dart └── stream.dart ├── docker ├── Dockerfile └── docker.txt ├── elixir └── basic.ex ├── file.txt ├── fun.py ├── git ├── git-flow.txt └── git.md ├── golang ├── array-slice-map.go ├── cuncurency.go ├── datetime.go ├── goroutine.go ├── gui │ └── fyne │ │ └── app.go ├── main.go ├── packages │ ├── database │ │ ├── mongodb.go │ │ ├── mysql.go │ │ └── redis.go │ ├── file.json │ ├── files.go │ ├── fmt.go │ ├── json.go │ ├── log.go │ ├── math.go │ ├── net_http │ │ └── main.go │ ├── os.go │ └── url.go └── socket │ ├── client.go │ └── server.go ├── jquery ├── img │ ├── slide1.jpg │ ├── slide2.jpg │ └── slide3.jpg ├── index.html ├── jquery.js └── slideshow.js ├── linux.txt ├── linux ├── laravel-permissions.txt └── vim.txt ├── mongodb └── mongodb.txt ├── mysql ├── example.txt ├── functions.txt ├── indexes.txt ├── mysql.txt ├── operators.txt └── tables.txt ├── perl └── perl.perl ├── php ├── array.php ├── cli.php ├── cookies.php ├── curl.php ├── database │ ├── crud │ │ ├── create.php │ │ ├── index.php │ │ └── update.php │ ├── mysqli.php │ ├── pdo.php │ └── sqlite3 │ │ ├── database.db │ │ └── sqlite3.php ├── date.php ├── design_patterns │ └── creational │ │ └── singleton.php ├── email.php ├── exception_handling.php ├── ext │ ├── bzip2.php │ ├── common_mark.php │ ├── ctype.php │ ├── curl.php │ ├── datastructure.php │ ├── datetime.php │ ├── dirs.php │ ├── ev.php │ ├── exec.php │ ├── exif.php │ ├── filter_data.php │ ├── finfo.php │ ├── ftp.php │ ├── gd.php │ ├── geo_ip.php │ ├── gettext.php │ ├── gmagick.php │ ├── gnupg.php │ ├── hash.php │ ├── hrtime.php │ ├── image_magick.php │ ├── json.php │ ├── lzf.php │ ├── mbstring.php │ ├── misc.php │ ├── mysqli.php │ ├── network.php │ ├── ob.php │ ├── openal.php │ ├── paraller.php │ ├── password_hash.php │ ├── phar.php │ ├── php_info.php │ ├── phpdbg.php │ ├── pspell.php │ ├── rar.php │ ├── reflection.php │ ├── seaslog.php │ ├── shmop.php │ ├── simplexml.php │ ├── sockets.php │ ├── sodium.php │ ├── spl.php │ ├── ssh2.php │ ├── stream.php │ ├── strings.php │ ├── ui.php │ ├── urls.php │ ├── vars.php │ ├── win32service.php │ ├── xdiff.php │ ├── xml.php │ ├── yaml.php │ └── zip.php ├── file.txt ├── files.php ├── flintstone │ ├── flintstone.php │ ├── users.db │ └── vendor │ │ └── flintstone │ │ ├── Cache │ │ ├── ArrayCache.php │ │ └── CacheInterface.php │ │ ├── Config.php │ │ ├── Database.php │ │ ├── Exception.php │ │ ├── Flintstone.php │ │ ├── Formatter │ │ ├── FormatterInterface.php │ │ ├── JsonFormatter.php │ │ └── SerializeFormatter.php │ │ ├── Line.php │ │ ├── Validation.php │ │ └── loader.php ├── functions.php ├── gd │ ├── captcha.php │ ├── gd.php │ └── gd2.php ├── headers.php ├── oop.php ├── output_buffering.php ├── php.php ├── reflections.php ├── regex.php ├── sessions.php ├── socket │ ├── client.php │ └── server.php ├── string.php ├── supper_globals.php ├── t.php ├── test.csv ├── upload.php └── validation-filters.php ├── postgresql └── basic.txt ├── python ├── mover.py ├── packages │ ├── __pycache__ │ │ ├── csv.cpython-311.pyc │ │ └── requests.cpython-39.pyc │ ├── asyncio.py │ ├── csv.csv │ ├── csv.py │ ├── os.py │ ├── prettytable.py │ ├── requests.py │ └── tkinter │ │ └── learn.py ├── python.py └── socket │ ├── client.py │ └── server.py ├── redis └── redis.txt ├── regex ├── Regular Expression.pdf └── regex.txt ├── ruby ├── basic.rb └── test.txt ├── rust └── rust.rs ├── selenium ├── php │ └── selenium.php └── python │ └── selenium.py ├── sfml └── cpp │ ├── basic.cpp │ ├── runner.sh │ ├── sample_audio.ogg │ ├── sfml.cpp │ └── simple_game.cpp ├── sqlserver └── sqlserver.txt ├── v └── vlang.v └── vb └── vb.vb /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp", 4 | "ostream": "cpp", 5 | "cstring": "cpp", 6 | "iosfwd": "cpp", 7 | "*.tcc": "cpp", 8 | "fstream": "cpp" 9 | } 10 | } -------------------------------------------------------------------------------- /CSharp/CSharpConsole.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CSharp 4 | { 5 | public class CSharpConsole 6 | { 7 | public static void Main(string[] args) 8 | { 9 | // Console.WriteLine("Hello World"); 10 | 11 | 12 | // Variables 13 | int num1 = 10; 14 | float num2 = 12.5f; 15 | string str = "Hello String"; 16 | string name; 17 | char c = 'c'; 18 | bool flag = true; 19 | 20 | // str = num1.ToString(); 21 | 22 | Console.WriteLine("Number 1: {0}, Number 2: {1}", num1, num2); 23 | 24 | // num1 = Convert.toInt32(num2); 25 | // num2 = Convert.toSingle(); toFloat 26 | 27 | // name = Console.ReadLine(); 28 | // c = char.Parse(Console.ReadKey()); // Convert.toChar() 29 | // c = char.toUpper(c); 30 | 31 | 32 | // Arrays 33 | int[] nums = new int[3]; 34 | nums[0] = 12; 35 | nums[1] = 22; 36 | nums[2] = 42; 37 | 38 | int[] nums2 = new int[] {1, 4, 6, 12, 41, 34, 14}; 39 | Console.WriteLine("Length Of numbs2 : {0}", nums2.Length); 40 | 41 | string[,] langs; 42 | langs = new string[,] { {"C#", "VB"}, {"PHP", "C"} }; 43 | 44 | const float PI = 3.1415f; 45 | 46 | decimal dec = 21312313M; 47 | 48 | 49 | int? nullNumber = null; 50 | Console.WriteLine(nullNumber??0); 51 | 52 | 53 | 54 | string fname = "Mani", lname = "Amani"; 55 | string fullname = string.Format("My name is {0} {1}", fname, lname); 56 | 57 | 58 | Console.WriteLine((string.Format("{0:yyyy / M / dd}", DateTime.Now))); 59 | 60 | 61 | 62 | 63 | 64 | Console.Readkey(); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /CSharp/Thread.cs: -------------------------------------------------------------------------------- 1 | using System -------------------------------------------------------------------------------- /CSharp/basic.cs: -------------------------------------------------------------------------------- 1 | public static class MyExtension 2 | { 3 | public static string toRial(this int value) 4 | { 5 | return value.ToString(value+" rial."); 6 | } 7 | 8 | public static string toShamsi(this DateTime value) 9 | { 10 | PersianCalender pc = new PersianCalender(); 11 | return pc.GetYear(value) + "/" + pc.GetMonth(value).ToString("00") + "/" + pc.GetDayOfMonth(value).ToString("00"); 12 | } 13 | 14 | 15 | // DateTime.Now.toShamsi(); 16 | 17 | } 18 | 19 | 20 | 21 | T Sum(T[] values) where T : INumber 22 | { 23 | T result = T.Zero; 24 | foreach(var T value in values) { 25 | result += value; 26 | } 27 | return result; 28 | } 29 | 30 | T Avg(T[] values) where T : INumber 31 | { 32 | var sum = Sum(values); 33 | var count = T.Zero; 34 | for(int i = 0; i < values.Length; i++) 35 | { 36 | count += T.One; 37 | } 38 | return sum/count; 39 | } 40 | 41 | 42 | var avg = 10.2; 43 | string JsonExample = $$""" 44 | { 45 | Total: {{ avg }} , 46 | Name: "Ali" 47 | } 48 | """; 49 | 50 | 51 | var byte[] utf8Sample = System.Text.Encoding.UTF8.GetBytes("ABC"); 52 | var byte[] utf8Sample2 = "ABC"u8; 53 | 54 | 55 | // delegates are pointer to methods 56 | 57 | 58 | delegate void dl1(int a, int b); 59 | 60 | static void sum(int n1, int n2) 61 | { 62 | // 63 | } 64 | 65 | static void minus(int n1, int n2) 66 | { 67 | // 68 | } 69 | 70 | 71 | dl1 d = new dl1(sum); 72 | d += minus; 73 | d(); 74 | 75 | 76 | delegate int deleTest(int a); 77 | 78 | deleTest d1 = delegate(int a) {return a + a}; 79 | 80 | deleTest d2 = (a) => a+a; 81 | 82 | 83 | 84 | delegate TResult deleGe(T1 a, T2 b); 85 | 86 | deleGe d1 = delegate(int a, double b) {return a / b}; 87 | d1(10, 3.15); 88 | 89 | // pre default delegates 90 | Func mFun = (x,y) => x / y; // Func must have return value 91 | 92 | Action mAct = x => Console.WriteLine(x); // Action have not return value 93 | 94 | Predicate myPre = x => x==5; // Predicate have one input and return type is bool 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /CSharp/files.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace Files 5 | { 6 | class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | FileStream fs = new FileStream("filename.txt", FileMode.Create, FileAccess.Write); 11 | StreamWrite sw = new StreamWrite(fs); 12 | sw.WriteLine("First line"); 13 | sw.Close(); 14 | fs.Close(); 15 | 16 | StreamReader sr = new StreamReader(fs); 17 | string c = sr.ReadLine(); 18 | sr.Close(); 19 | 20 | 21 | 22 | 23 | string text = "Hello from C#"; 24 | File.WriteAllText("filename.txt", text); 25 | string content = File.ReadAllText("filename.txt"); 26 | 27 | string content = File.ReadAllText('path'); 28 | 29 | 30 | FileInfo file = new FileInfo(@"test.txt"); 31 | Console.WriteLine("Full File Name: " + file.FullName); 32 | Console.WriteLine("File Name: " + file.Name); 33 | Console.WriteLine("CreationTime: " + file.CreationTime); 34 | Console.WriteLine("DirectoryName: " + file.DirectoryName); 35 | Console.WriteLine("Extension: " + file.Extension); 36 | Console.WriteLine("LastAccessTime: " + file.LastAccessTime); 37 | Console.WriteLine("LastWriteTime: " + file.LastWriteTime); 38 | 39 | 40 | // file.CopyTo(@"E:\test.txt", true); 41 | // file.MoveTo(@"E:\test.txt"); 42 | 43 | 44 | DirectoryInfo directory = new DirectoryInfo(@"E:\Files"); 45 | foreach (var item in directory.GetDirectories()) 46 | { 47 | Console.WriteLine("Directory {0}", item.Name); 48 | foreach (var itemFile in item.GetFiles()) 49 | { 50 | Console.WriteLine("---File: {0}", item.Name); 51 | } 52 | } 53 | 54 | 55 | DriveInfo[] drivers = DriveInfo.GetDrives(); 56 | foreach (var driver in drivers) 57 | { 58 | Console.WriteLine("Drive name: {0}", driver.Name); 59 | } 60 | 61 | Console.WriteLine("Ext: {0}", Path.GetExtension("Path.txt")); 62 | 63 | 64 | 65 | 66 | Console.WriteLine(Environment.CurrentDirectory); 67 | Console.WriteLine(Environment.UserName); 68 | Console.WriteLine(Environment.Is64BitOperatingSystem); 69 | Console.WriteLine(Environment.SystemDirectory); 70 | Console.WriteLine(Environment.NewLine); 71 | Console.WriteLine(Environment.OSVersion); 72 | 73 | Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); 74 | Console.WriteLine(Environment.Version.ToString()); 75 | 76 | 77 | string path = ""; 78 | StringBuilder sb = new StringBuilder(); 79 | 80 | foreach (var name in Directory.EnumerateFiles(path, "*.txt")) 81 | { 82 | using (StreamReader sr = new StreamReader(name)) 83 | { 84 | 85 | sb.AppendLine(name); 86 | sb.AppendLine(sr.ReadToEnd()); 87 | sb.AppendLine("------------------"); 88 | } 89 | } 90 | 91 | using (StreamWriter sw = new StreamWriter(path)) 92 | { 93 | sw.Write(sb.ToString()); 94 | } 95 | 96 | 97 | 98 | FileSystemWatcher fileSystemWatcher= new FileSystemWatcher(@"E:\"); 99 | 100 | fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_Created); 101 | 102 | fileSystemWatcher.IncludeSubdirectories= true; 103 | fileSystemWatcher.EnableRaisingEvents= true; 104 | 105 | 106 | private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e) 107 | { 108 | Console.WriteLine("Type: {0}", e.ChangeType); 109 | Console.WriteLine("Name: {0}", e.Name); 110 | } 111 | 112 | } 113 | 114 | } 115 | } -------------------------------------------------------------------------------- /CSharp/linq.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/CSharp/linq.cs -------------------------------------------------------------------------------- /CSharp/mysql.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/CSharp/mysql.cs -------------------------------------------------------------------------------- /CSharp/reflection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | Type t = typeof(int); 4 | t.GetMethods(); 5 | 6 | Type t2 = "String".GetType(); 7 | t2.Name // String 8 | t2.FullName // System.String 9 | 10 | -------------------------------------------------------------------------------- /CSharp/sockets/socket.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Sockets; 3 | 4 | 5 | 6 | var hostName = Dns.GetHostName(); 7 | 8 | 9 | IPHostEntity hostIps = Dns.Resolve(hostName); 10 | foreach(IPAddress ip in hostIps.AddressList) { 11 | Console.WriteLine(ip.ToString()); 12 | } 13 | 14 | 15 | 16 | IPAddress[] addresses = Dns.GetHostAddressed(Dns.GetHostName()); 17 | foreach(IPAddress ip in addresses) { 18 | if(ip.AddressFamily == AddressFamily.InterNetwork) { 19 | Console.WriteLine(ip.ToString()); 20 | } 21 | } 22 | 23 | 24 | 25 | 26 | IPAddress ip = IPAddress.Parse("192.168.1.10"); 27 | IPEndPoint ipNode = new IPEndPoint(ip, 5050); 28 | 29 | Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /D/basic.d: -------------------------------------------------------------------------------- 1 | import std.stdio; 2 | 3 | void main() 4 | { 5 | writeln("Hello World!"); 6 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Collection of usefull cheatsheets 2 | 3 | ### Add Your CheatSheets 4 | -------------------------------------------------------------------------------- /SmallBasic/learn.sb: -------------------------------------------------------------------------------- 1 | ' TextWindow.ForegroundColor = "Red" 2 | ' TextWindow.BackgroundColor = "White" 3 | ' TextWindow.WriteLine("Hello World!") 4 | 5 | ' TextWindow.Write("Enter your name: ") 6 | ' Name = TextWindow.Read() 7 | ' TextWindow.Write("Enter your age: ") 8 | ' Age = TextWindow.ReadNumber() 9 | ' TextWindow.WriteLine("Hello " + Name + " , " + Age + " years old" ) 10 | 11 | 12 | ' If Clock.Hour < 12 Then 13 | 'TextWindow.WriteLine("Good Morning") 14 | 'Else 15 | ' TextWindow.WriteLine("Good Evening") 16 | 'EndIf 17 | 18 | 'i = 1 19 | 'Start: 20 | 'TextWindow.WriteLine(i) 21 | 'i = i + 1 22 | 'If i <= 1000 Then 23 | ' Goto Start 24 | 'EndIf 25 | 26 | 'For i = 1 To 20 Step 2 27 | ' TextWindow.WriteLine(i) 28 | 'EndFor 29 | 30 | ' Arrays 31 | 32 | ' person["name"] = "Joun" 33 | ' person["age"] = 20 34 | ' TextWindow.WriteLine("person array has " + Array.GetItemCount(person) + " items.") 35 | 36 | ' Sub PrintDateAndTime() 37 | ' TextWindow.WriteLine("Date: " + Clock.Date) 38 | ' TextWindow.WriteLine("Time: " + Clock.Time) 39 | ' EndSub 40 | 41 | GraphicsWindow.Title = "First Window" 42 | GraphicsWindow.BackgroundColor = "Red" 43 | GraphicsWindow.Width = 600 44 | GraphicsWindow.Height = 600 45 | GraphicsWindow.CanResize = "False" 46 | GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() 47 | GraphicsWindow.PenWidth = 10 48 | GraphicsWindow.DrawLine(0, 100, 500, 200) 49 | GraphicsWindow.Show() 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /SmallBasic/smallbasic.sb: -------------------------------------------------------------------------------- 1 | TextWindow.WriteLine("Hello World"); 2 | TextWindow.Write("!"); -------------------------------------------------------------------------------- /apache/.htaccess: -------------------------------------------------------------------------------- 1 | Options All -Indexes 2 | 3 | 4 | RewriteEngine On 5 | RewriteBase /http://localhost:3000/htaccess/ 6 | RewriteRule ^index\.php - [L] 7 | RewriteCond %{REQUEST_FILENAME} !-f 8 | RewriteCond %{REQUEST_FILENAME} !-d 9 | RewriteRule . index.php [L] 10 | -------------------------------------------------------------------------------- /apache/index.php: -------------------------------------------------------------------------------- 1 | 3 | ServerName test.com 4 | DocumentRoot /var/www/html/test 5 | ErrorLog /var/log/httpd/test/error_log 6 | TransferLog /var/log/httpd/test/access_log 7 | 8 | 9 | 10 | ServerName sub.test.com 11 | DocumentRoot /var/www/html/sub 12 | 13 | 14 | in /etc/hosts: 15 | 127.0.0.1 test.com 16 | 127.0.0.1 sub.test.com 17 | 18 | in /etc/php.ini: 19 | cgi.fixpathinfo=0 20 | 21 | 22 | in /etc/php-fpm.d/www.conf 23 | listen = /var/run/php-fpm/php-fpm.sock 24 | 25 | listen.owner = nginx 26 | listen.group = nginx 27 | 28 | -------------------------------------------------------------------------------- /bash/bash.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | clear 4 | 5 | echo "Enter name: " 6 | read name 7 | echo "Hello $name" 8 | 9 | 10 | read -p "Enter age: " age 11 | 12 | if [ "$age" == "20" ]; then 13 | echo "Valid" 14 | elif [ "$age" -eq "22" ]; then # -ge gt eq lt le ne 15 | echo "Grate" 16 | else 17 | echo "Error" 18 | fi 19 | 20 | if [ -d "$HOME/directory" ]; then 21 | echo "exist" 22 | elif [ -f "$HOME/file.txt" ]; then 23 | echo "file exits" 24 | fi 25 | 26 | 27 | case "$age" in 28 | "20") 29 | echo "Valid" 30 | ;; 31 | "22") 32 | echo "Grater" 33 | ;; 34 | "18") 35 | echo "Less" 36 | ;; 37 | *) 38 | echo "Error" 39 | esac 40 | 41 | read -s -p "Enter Password: " password 42 | while [ "$password" != "1234" ]; do 43 | read -s -p "Enter Password" password 44 | done 45 | 46 | for number in {1..9};do 47 | echo $number 48 | done 49 | 50 | for ((i=0;i<=10;i++));do 51 | echo $i 52 | done 53 | 54 | IFS=":" 55 | name="ali:milad:reza" 56 | for name in name;do 57 | echo name 58 | done 59 | 60 | wget "url" 61 | if [ "$?" == "0"]; then 62 | notify-send "Ok" 63 | else 64 | notify-send "Error" 65 | fi 66 | 67 | [[ "one" == "one" ]] 68 | echo $? 69 | 70 | echo "$1 + $2 = " $(($1 + $2)) 71 | 72 | echo $# # args count 73 | $@ # all in seperate arg 74 | $* # all in one args 75 | 76 | 77 | ss="Programming" 78 | echo ${#ss} 79 | echo ${ss:3} 80 | echo ${ss:3:6} 81 | echo ${ss: -3} 82 | 83 | func (){ 84 | echo "Function" 85 | } 86 | 87 | func 88 | 89 | add () { 90 | echo "$1 + $2 = " $(($1 + $2)) 91 | } 92 | 93 | add 2 4 94 | 95 | result=`add 2 4 96 | 97 | # run exit when clearFunc run 98 | trap clearFunc exit 99 | 100 | 101 | while getopts "h:e:v" options ;do 102 | case "$options" in 103 | s) 104 | help_option="$OPTARG" 105 | ;; 106 | v) 107 | echo "version : 1.0.o" 108 | exit 109 | ;; 110 | esac 111 | done 112 | 113 | i=1 114 | while read f; do 115 | echo "Line $i: $f" 116 | ((i++)) 117 | done < file.txt 118 | 119 | echo -e '\033[34;42mColor Text\033[0m' 120 | # tput 121 | 122 | # touch {one,two,three}_{01..100} 123 | 124 | echo date +"%d-%m-%Y" 125 | 126 | printf "Name:\t%s\nID:\t%04d\n" "Ali" "20" 127 | 128 | # declare -i integer=120 129 | # readonly 130 | # declare -r e=300 131 | # declare -l lowerCase="lOweR" 132 | # declare -u lowerCase="lOweR" 133 | declare -A arr 134 | arr["name"]="Name" 135 | arr["id"]="200" 136 | for i in "${!arr[@]}" do 137 | echo "$i : ${arr[$i]}" 138 | done 139 | # result=$(ping -c 1 google.com) 140 | 141 | # echo $MACHTYPE 142 | 143 | -------------------------------------------------------------------------------- /c++/a.dat: -------------------------------------------------------------------------------- 1 | this is message 2 | this is line$ -------------------------------------------------------------------------------- /c++/basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int multiple(int); // prototype 9 | 10 | void swap(int &, int &); 11 | 12 | int strlength(const char *); 13 | void strconcat(char *, const char *); 14 | 15 | #define min(x, y) (x < y ? x : y) // macro 16 | 17 | template 18 | T maximum(T x, T y) 19 | { 20 | T max; 21 | if (x > y) 22 | max = x; 23 | else 24 | max = y; 25 | return max; 26 | } 27 | 28 | int main() 29 | { 30 | // cout<<"Hello"<>a; 35 | // cout<> Halve data 49 | 50 | // cout.width(5); 51 | // cout.fill('*'); 52 | // cout.setf(ios::left); // ios::right 53 | // cout<<'a'; 54 | 55 | // char ch; 56 | // int x; 57 | // for(ch='a'; ch<='z'; ch++) 58 | // { 59 | // x=ch; 60 | // cout< p -> a 108 | // int a=10; 109 | // int *p=&a; 110 | // int **pp=&p; 111 | // cout<<*p<s2: +1 182 | // cout<s2: +1 183 | 184 | // cout< (memset(s, 'g', 3)); // gggde 216 | // memcpy(s, s1, 1); 217 | // cout< (memmove(s, &s[1], 2)); //bccde 220 | 221 | // cout<>k; 255 | // strcpy(&s[k], &s[k+1]); // abdef 256 | // cout<h< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | /* 9 | END OF FILE (text = 1A or 26) (binary = ctrl+z) 10 | END OF LINE (text = CR/LF) 11 | */ 12 | 13 | // ifstream f1; 14 | // f1.open('a.dat', ios::in); 15 | // f1.close(); 16 | // ifstream f2("a.dat", ios::in); 17 | 18 | // ofstream f2; 19 | // f2.open("a.dat", ios::out); 20 | 21 | // fstream f3("a.dat", ios::in | ios::out) // ios::app, ios::ate, ios::binary, ios::trunc, 22 | 23 | // eof(); // is end of file? 24 | 25 | 26 | // char ch; 27 | // ofstream f1("a.dat"); // ios::binary 28 | // if(!f1) 29 | // exit(0); 30 | // cout<<"Enter message:\n"; 31 | // do{ 32 | // cin.get(ch); 33 | // f1.put(ch); 34 | // } while(ch != '$'); 35 | // f1.close(); 36 | 37 | // cout<<"output:\n"; 38 | // ifstream f2("a.dat"); 39 | // f2.get(ch); 40 | // while(!f2.eof()) 41 | // { 42 | // cout.put(ch); 43 | // f2.get(ch); 44 | // } 45 | 46 | // f2.close(); 47 | 48 | 49 | } -------------------------------------------------------------------------------- /c++/libs/ctime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | 9 | time_t now = time(0); 10 | cout << now<tm_mday; 16 | 17 | } -------------------------------------------------------------------------------- /c++/libs/math.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | cout< 2 | 3 | using namespace std; 4 | 5 | class SampleClass { 6 | private: 7 | int x; 8 | public: 9 | SampleClass() { 10 | cout<< "constructor"; 11 | } 12 | 13 | SampleClass(int a) { 14 | x = a; 15 | } 16 | // SampleClass(int a): x(a) 17 | // {} 18 | ~SampleClass() { 19 | cout<< "destructor"; 20 | } 21 | 22 | int f() { 23 | x=2; 24 | cout< 2 | 3 | int main() 4 | { 5 | printf("Hello World\n"); 6 | return 0; 7 | } -------------------------------------------------------------------------------- /dart/design_patters/creational/builder.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/dart/design_patters/creational/builder.dart -------------------------------------------------------------------------------- /dart/design_patters/creational/singleto.dart: -------------------------------------------------------------------------------- 1 | class Singleton 2 | { 3 | 4 | static Singleton? _instance; 5 | 6 | Singleton._(); // private constructor 7 | 8 | static Singleton getInstance() { 9 | if(_instance == null) { 10 | _instance = Singleton._(); 11 | } 12 | 13 | return _instance!; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /dart/design_patters/creational/singleton_factory.dart: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | static Singleton? _instance; 3 | 4 | Singleton._(); // private constructor 5 | 6 | factory Singleton.getInstance() { 7 | if (_instance == null) { 8 | _instance = Singleton._(); 9 | } 10 | 11 | return _instance!; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /dart/files.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | Directory directories = Directory.current; 5 | 6 | print(directories); 7 | } 8 | -------------------------------------------------------------------------------- /dart/libs/convert.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/dart/libs/convert.dart -------------------------------------------------------------------------------- /dart/libs/datetime.dart: -------------------------------------------------------------------------------- 1 | main() { 2 | // print(DateTime.now()); 3 | var currentData = DateTime.now(); 4 | 5 | print(currentData.year); 6 | print(currentData.weekday); 7 | print(currentData.month); 8 | print(currentData.day); 9 | print(currentData.hour); 10 | print(currentData.minute); 11 | print(currentData.second); 12 | 13 | var addDt = DateTime.now(); 14 | print(addDt.add(Duration(days: 5, hours: 5, minutes: 30))); 15 | 16 | var anotherDt = DateTime.now().subtract(Duration(days: 10, hours: 10)); 17 | print(addDt.isAfter(anotherDt)); // true 18 | 19 | var subDt = DateTime.now().subtract(Duration(days: 10, hours: 10)); 20 | print(addDt.isBefore(subDt)); // false 21 | 22 | var diffDt = addDt.difference(subDt); // 249:59:59.999000 23 | print(diffDt.inSeconds); 24 | print(diffDt.inHours); 25 | print(diffDt.inMinutes); 26 | print(diffDt.inDays); 27 | 28 | print(addDt.isAtSameMomentAs(anotherDt)); // false 29 | } 30 | -------------------------------------------------------------------------------- /dart/libs/html.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/dart/libs/html.dart -------------------------------------------------------------------------------- /dart/libs/http.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/dart/libs/http.dart -------------------------------------------------------------------------------- /dart/libs/io.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | 4 | void main() async 5 | { 6 | String name = stdin.readLineSync(); 7 | name.isEmpty ? stderr.writeln('Name Empty') : stdout.writeln("Hello ${name}"); 8 | 9 | // var dir = Directory('test').createSync(); 10 | // var dir2 = await Directory('test').createTemp(); 11 | 12 | // var systemTemp = Directory.systemTemp; 13 | // await for(var entity in systemTemp.list(recursive: true, followLinks: false)) { 14 | // print(entity.path); 15 | // } 16 | 17 | // File('test.txt').readAsString().then((String content) { 18 | // print(content); 19 | // }); 20 | 21 | // final file = File('test.txt'); 22 | // Stream lines = file.openRead() 23 | // .transform(utf8.decoder)// Decode bytes to UTF-8. 24 | // .transform(LineSplitter()); // Convert stream to individual lines. 25 | 26 | // await for (var line in lines) { 27 | // print('$line: ${line.length}'); 28 | // } 29 | 30 | // final file = await File('file.txt').writeAsString('this is content'); 31 | 32 | // var file = File('file.txt'); 33 | // var sink = file.openWrite(); 34 | // sink.write('Last Accessed: ${file.lastAccessedSync()}'); 35 | // sink.close(); 36 | 37 | 38 | } 39 | 40 | Future createDescriptions(Iterable objects) async { 41 | for (final object in objects) { 42 | try { 43 | var file = File('$object.txt'); 44 | if (await file.exists()) { 45 | var modified = await file.lastModified(); 46 | print( 47 | 'File for $object already exists. It was modified on $modified.'); 48 | continue; 49 | } 50 | await file.create(); 51 | await file.writeAsString('Start describing $object in this file.'); 52 | } on IOException catch (e) { 53 | print('Cannot create description for $object: $e'); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /dart/libs/stream.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:async'; 3 | import 'dart:convert'; 4 | 5 | void main(List args) async { 6 | // simpleStream(200000).listen((event) { 7 | // print("$event"); 8 | // }); 9 | 10 | // Stream stream = simpleStream(30000); 11 | // await for (var i in stream) { 12 | // File f = File('file.txt'); 13 | // IOSink sink = f.openWrite(mode: FileMode.append); 14 | // sink.add(utf8.encode("$i\n")); 15 | // await sink.flush(); 16 | // await sink.close(); 17 | // } 18 | 19 | File f = File('file.txt'); 20 | Stream> fStream = f.openRead(); 21 | fStream.transform(utf8.decoder).transform(LineSplitter()).listen((event) { 22 | print("$event"); 23 | }); 24 | } 25 | 26 | Stream simpleStream(int x) async* { 27 | for (int i = 0; i <= x; i++) { 28 | yield i; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /dart/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:collection'; 3 | 4 | void main() { 5 | print("Hello World!"); 6 | 7 | printDelayedString("Test"); 8 | // var list1 = [1, 20, 12, 30]; 9 | // print(list1.length); 10 | // print(list1[list1.length - 1]); // 30 11 | 12 | // print(DateTime.now()); 13 | 14 | // print("Enter your name: "); 15 | // String? name = stdin.readLineSync(); 16 | 17 | // String url = 'https://dart.dev/guides/libraries'; 18 | // var uri = Uri.parse(url); 19 | // print(uri.scheme); 20 | // print(uri.host); 21 | // print(uri.path); 22 | 23 | // stdout.writeln("Enter name: "); 24 | // String? name = stdin.readLineSync(); 25 | 26 | // int a = 10; 27 | // int b = 0; 28 | 29 | // try { 30 | // print(a ~/ b); 31 | // } on IntegerDivisionByZeroException catch (e) { 32 | // print(e.toString()); 33 | 34 | // print("zero"); 35 | // } 36 | 37 | 38 | } 39 | 40 | void printJadvalZarb() { 41 | for (int i = 1; i < 10; i++) { 42 | for (int j = 1; j < 10; j++) { 43 | int number = i*j; 44 | stdout.writeln(number.toString().padLeft(2)); 45 | if(j == 9){ 46 | stdout.write('\n'); 47 | } else { 48 | stdout.write(', '); 49 | } 50 | } 51 | } 52 | } 53 | 54 | Future printDelayedString(String str) async { 55 | await Future.delayed(Duration(seconds: 4)); 56 | stdout.writeln(str); 57 | } 58 | 59 | Future printDelayedString2(String str) { 60 | return Future.delayed(Duration(seconds: 2)).then((value) => stdout.writeln(str)); 61 | } 62 | -------------------------------------------------------------------------------- /dart/server.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() async { 4 | var server = await createServer(); 5 | await handleRequest(server); 6 | print("server ..."); 7 | } 8 | 9 | Future createServer() async { 10 | final address = InternetAddress.loopbackIPv4; 11 | const port = 8000; 12 | return await HttpServer.bind(address, port); 13 | } 14 | 15 | Future handleRequest(HttpServer server) async { 16 | await for(HttpRequest request in server) { 17 | request.response.write("Hello"); 18 | await request.response.close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dart/stream.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | class Numbers { 4 | int data = 1; 5 | 6 | StreamController streamController = StreamController(); 7 | 8 | Stream get stream => streamController.stream; 9 | 10 | Numbers() { 11 | Timer.periodic(Duration(seconds: 2), (timer) { 12 | streamController.sink.add(data); 13 | data++; 14 | }); 15 | } 16 | } 17 | 18 | startStream() { 19 | Numbers().stream.map((event) => "event: $event").listen((event) { 20 | print(event); 21 | }); 22 | } 23 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine 2 | 3 | # this is comment 4 | LABEL tag="1.0.0" 5 | 6 | RUN apk update && apk upgrade && apk add bash 7 | 8 | RUN ["mkdir", "/test"] 9 | 10 | 11 | 12 | EXPOSE 80 13 | 14 | -------------------------------------------------------------------------------- /docker/docker.txt: -------------------------------------------------------------------------------- 1 | docker run hello-world 2 | docker run hello-world command 3 | docker run -r image 4 | docker run -d image sleep 100 5 | # -d => run in background 6 | docker run image:tag 7 | 8 | docker run --rm hello-world // remove automatic when stopped 9 | -it // interactive 10 | --name // set the custom name for image 11 | 12 | docker run --name redis -p 6379:6379 --rm -v /tmp/data/redis:/data redis-server --appendonly yes 13 | 14 | docker run -p6379:6379 redis 15 | 16 | docker run 17 | 18 | docker run -it --name mname -m 500m --memory-swap 1G -cpuset-cpus="0 alpine 19 | 20 | docker pull image-name // get the image from hub 21 | 22 | docker images 23 | 24 | docker ps // list docker run 25 | docker ps -a // list all container run 26 | docker ps -l -n=2 // last containers 27 | docker ps -q // just show id's 28 | docker ps -q -a // just all id's 29 | docker ps -n 4 30 | docker ps -s 31 | docker ps -a --filter "name=test" 32 | docker ps -af status=exited 33 | 34 | docker stop $(docker ps -q) 35 | 36 | docker start CONTAINER_ID 37 | 38 | docker stop containerID 39 | 40 | docker attach CONTAINER_ID 41 | 42 | docker container log 43 | 44 | docker stats 45 | 46 | docker image 47 | docker image push 48 | docker image ls 49 | docker image history 50 | docker image inspect 51 | docker inspect image 52 | 53 | docker system prune 54 | 55 | docker rm containerID // remove docker stopped container 56 | 57 | docker container prune // remove all stopped containers 58 | 59 | docker rmi image // remove docker image 60 | // -f 61 | 62 | docker exec containerID command 63 | 64 | docker exec -it image-name command 65 | 66 | 67 | docker build -t imageName . 68 | 69 | docker search imageName 70 | 71 | docker create -it ubuntu:xenial bash 72 | 73 | docker cp CONTAINER_ID:/test_file test_file 74 | docker cp test_file CONTAINER_ID:/test_file 75 | 76 | docker image ls 77 | 78 | docker image history image:tag 79 | 80 | docker image inspect image:tag 81 | 82 | docker info 83 | 84 | docker pause containerID 85 | docker unpause containerID 86 | 87 | docker save image > image.tar 88 | 89 | docker load -i image.tar 90 | 91 | docker rm `docker images -a -q` 92 | 93 | 94 | docker volume create —-name my_volume 95 | docker volume ls 96 | docker volume inspect my_volume 97 | docker volume rm my_volume 98 | docker volume prune 99 | docker system prune 100 | 101 | docker container run --mount source=my_volume، target=/container/path/for/volume my_image 102 | type=bind, valoume, tmpfs 103 | 104 | 105 | 106 | useradd username 107 | usermod -aG docker username 108 | 109 | 110 | 111 | 112 | ctrl + p + q -> detach 113 | 114 | 115 | enable live-restore 116 | 117 | /etc/docker/daemon.json 118 | { 119 | "live-store":true 120 | } 121 | 122 | 123 | change storage driver: 124 | docker save -> push image -> change driver -> restart -> -------------------------------------------------------------------------------- /elixir/basic.ex: -------------------------------------------------------------------------------- 1 | list = [1, 2, 3, 4, 5] 2 | list ++ [ 6 ] # append to list 3 | newList = [ 0 | list] # prepend to list 4 | 5 | [1, 2, 3, 1] -- [ 2, 1, 3] # remove duplicate values 6 | 7 | td list # head of list -> 1 8 | tl list # tail of list -> 2, 3, 4, 5 9 | 10 | 11 | Enum.map(list, fn item -> 12 | item + 1 13 | end) 14 | -------------------------------------------------------------------------------- /file.txt: -------------------------------------------------------------------------------- 1 | This is first line -------------------------------------------------------------------------------- /fun.py: -------------------------------------------------------------------------------- 1 | def fun(x, y): 2 | if x<2 or y<4: 3 | return 2 4 | else: 5 | return 4 + fun(x-2,y-3) 6 | 7 | 8 | # print(fun(4,7)) // 10 9 | 10 | 11 | def fun2(c): 12 | if c<=2: 13 | return 1 14 | else: 15 | return fun2(c-2)+fun2(c-1) 16 | 17 | # print(fun2(7)) // 13 18 | 19 | 20 | def fun3(n): 21 | if n<=2: 22 | return n 23 | else: 24 | return fun3(n-1)+fun3(n-2)+fun3(n-3) 25 | 26 | print(fun3(5)) // 11 -------------------------------------------------------------------------------- /git/git-flow.txt: -------------------------------------------------------------------------------- 1 | git flow init 2 | 3 | 4 | git flow feature start feature_branch 5 | git flow feature finish feature_branch 6 | 7 | git flow release start 0.1.0 8 | git flow release finish '0.1.0' 9 | 10 | git flow hotfix start hotfix_branch 11 | git flow hotfix finish hotfix_branch -------------------------------------------------------------------------------- /git/git.md: -------------------------------------------------------------------------------- 1 | git config --global --edit 2 | 3 | git config --global --add user.name "test name" 4 | 5 | git config --global --unset user.name 6 | 7 | git config --global --unset-all user.name 8 | 9 | git config --global --list 10 | 11 | git config --list 12 | 13 | git help verb 14 | 15 | git verb --help 16 | 17 | git log --oneline 18 | 19 | git log --stat 20 | 21 | git log -4 22 | 23 | git log -p 24 | 25 | git log --author="user" 26 | 27 | git log --before="2020-06-01" --after="2020-06-05" 28 | 29 | git rm --cached file // remove file from stage 30 | 31 | git diff // un staged changes 32 | 33 | git diff --stat 34 | 35 | git blame file 36 | 37 | git blame -e file 38 | 39 | git blame -l file 40 | 41 | git blame -L 1,3 file 42 | 43 | git blame -L 2,+3 file 44 | 45 | git reset HEAD file // unstage file chnages 46 | 47 | git reset --soft id // checkout to commit and move changes to staging 48 | 49 | git reset --hard id // checkout to commit and delete changes 50 | 51 | git reset --mixed id // checkout to commit and move changes to working dir 52 | 53 | 54 | git clean -n 55 | 56 | git clean -f // remove all un tracked files 57 | 58 | git clean -df // remove all un tracked directories and contains files 59 | 60 | git revert commitId 61 | 62 | git checkout file // move to before state 63 | 64 | git checkout commitId 65 | 66 | git checkout master 67 | 68 | git tag 69 | 70 | git tag -a v0.1.1 -m "v0.1.1" 71 | 72 | git tag v0.1.1 -f -m "new message" 73 | 74 | git push origin tagName 75 | 76 | git push origin --tags 77 | 78 | git show commitId 79 | 80 | git rev-list HEAD 81 | 82 | git rev-list HEAD | wc -l 83 | 84 | git rev-list HEAD --count 85 | 86 | git rev-list feature ^master 87 | 88 | git rev-list 321313..642342 89 | 90 | git rev-list 321313..642342 -m 2 91 | 92 | git branch -m [new_branch_name] 93 | 94 | git grep word 95 | 96 | git grep word file 97 | 98 | git grep -c word 99 | 100 | git grep -l word 101 | 102 | git grep -m word 103 | 104 | git grep -e name -e family 105 | 106 | git grep --all-match -e name --and -e family 107 | 108 | 109 | sudo git push origin --delete edit_namespace 110 | -------------------------------------------------------------------------------- /golang/array-slice-map.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | // var a [5]int 7 | // a[2] = 20 8 | // fmt.Println(len(a)) 9 | // fmt.Println(cap(a)) 10 | 11 | // var b [3]string 12 | // b = [3]string{"One", "Two", "three"} 13 | // fmt.Println(b) 14 | 15 | // c := [2]int{1, 2} 16 | 17 | // for i := 0; i < len(a); i++ { 18 | // fmt.Println(a[i]) 19 | // } 20 | 21 | // languages := [3]string{ 22 | // "PHP", 23 | // "Go", 24 | // "C", 25 | // } 26 | 27 | //////////// Slice 28 | 29 | // s := make([]int, 3) 30 | 31 | // s2 := []string{"One", "Two", "three"} 32 | // s2 = append(s2, "C") 33 | 34 | // copy(empty, s2) 35 | 36 | ////////// Maps 37 | 38 | var languages = make(map[string]string) 39 | languages["Fa"] = "Farsi" 40 | languages["En"] = "English" 41 | languages["Fr"] = "French" 42 | // fmt.Println(languages) 43 | 44 | user := map[string]string{ 45 | "Name": "Ali", 46 | "Age": "23", 47 | } 48 | 49 | // delete(user, "Age") 50 | 51 | if v, ok := user["Email"]; ok { 52 | fmt.Println(v) 53 | } else { 54 | fmt.Println("Key not found") 55 | } 56 | 57 | for key, value := range languages { 58 | fmt.Printf("Key: %s : Value: %s \r\n", key, value) 59 | } 60 | 61 | // emptyMap := map[int][string]{} 62 | 63 | } 64 | -------------------------------------------------------------------------------- /golang/cuncurency.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | go fmt.Println("World") 10 | fmt.Println("Hello") 11 | time.Sleep(3 * time.Second) 12 | } 13 | -------------------------------------------------------------------------------- /golang/datetime.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | 10 | var weekday string = time.Now().Weekday().String() 11 | fmt.Print(weekday) 12 | 13 | switch time.Now().Weekday() { 14 | case time.Saturday, time.Sunday: 15 | fmt.Println("It's the weekend") 16 | default: 17 | fmt.Println("It's a weekday") 18 | } 19 | 20 | t := time.Now() 21 | switch { 22 | case t.Hour() < 12: 23 | fmt.Println("It's before noon") 24 | default: 25 | fmt.Println("It's after noon") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /golang/goroutine.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | func loop(name string) { 9 | for i := 1; i <= 10; i++ { 10 | fmt.Println(i, " => ", name) 11 | } 12 | } 13 | 14 | func main() { 15 | loop("Hello normal function") 16 | 17 | go loop("Hello goroutine function") 18 | 19 | fmt.Println("Number of goroutine in program: ", runtime.NumGoroutine()) 20 | } 21 | -------------------------------------------------------------------------------- /golang/gui/fyne/app.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fyne.io/fyne/v2/app" 5 | "fyne.io/fyne/v2/widget" 6 | ) 7 | 8 | func main() { 9 | app := app.New() 10 | 11 | w := app.NewWindow("Hello") 12 | w.SetContent(widget.NewLabel("Hello Fyne!")) 13 | 14 | w.ShowAndRun() 15 | } 16 | -------------------------------------------------------------------------------- /golang/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Post struct { 8 | Title, Body string 9 | Active bool 10 | Author 11 | } 12 | 13 | type Author struct { 14 | Email, Name string 15 | } 16 | 17 | // const APP string = "App" // Exported 18 | // const app string = "App" // Un exported 19 | 20 | func main() { 21 | // fmt.Print("Hello") 22 | // fmt.Println(" World!") 23 | 24 | // fmt.Printf("%d %s %f", 14, "String", 3.14) 25 | // fmt.Printf("10 type -> %T", 10) // int 26 | 27 | // time.Sleep(1 * time.Second) 28 | 29 | // fmt.Print("Enter your name: ") 30 | // var name string 31 | // i, err := fmt.Scanln(&name) 32 | // if err != nil { 33 | // fmt.Println(err) 34 | // return 35 | // } 36 | // fmt.Println("Your name: ", name) 37 | // fmt.Println(i) 38 | 39 | // string, float32, bool, int32 40 | // var a, a1 string 41 | // var b = "string" 42 | 43 | // c := 10 44 | 45 | // var ( 46 | // var1 = "value1" 47 | // var2 bool = true 48 | // ) 49 | 50 | // const constName = "value" 51 | // const PI float32 = 3.14 52 | 53 | // const ( 54 | // VERSION = "1" 55 | // ) 56 | 57 | // language := "C" 58 | // language2 := "Vuejs" 59 | // if language == "PHP" { 60 | // fmt.Println("PHP is cool") 61 | // } else if language == "Go" { 62 | // fmt.Println("Go is fun") 63 | // } else { 64 | // fmt.Println("Else ") 65 | // } 66 | 67 | // if n := 10; n <= 0 { 68 | // fmt.Print("True") 69 | // } 70 | 71 | // switch language { 72 | // case "PHP": 73 | // fmt.Print("PHP") 74 | // case "C": 75 | // fmt.Print("C") 76 | // fallthrough 77 | // default: 78 | // fmt.Print("D") 79 | // } 80 | 81 | // switch language:='JS'; langauge { 82 | // case 'JS': 83 | // fmt.Println('JS'); 84 | // } 85 | 86 | // switch { 87 | // case language == "Js": 88 | // switch { 89 | // case language2 == "Vuejs": 90 | // fmt.Print("Ok") 91 | // } 92 | // } 93 | 94 | // i := 1 95 | // for i <= 3 { 96 | // fmt.Println(i) 97 | // i = i + 1 98 | // } 99 | 100 | // for j := 7; j <= 9; j++ { 101 | // fmt.Println(j) 102 | // } 103 | 104 | // for { 105 | // fmt.Println("loop") 106 | // break 107 | // } 108 | 109 | // for n := 0; n <= 5; n++ { 110 | // if n%2 == 0 { 111 | // continue 112 | // } 113 | // fmt.Println(n) 114 | // } 115 | 116 | /// Map 117 | m := make(map[string]string) 118 | m["key"] = "value" 119 | 120 | ///// Struct 121 | 122 | // p := Post{} 123 | // p := new(Post) 124 | // p := Post{"Title New", "This is Good", true} 125 | // p := Post{Title: "Title New", Body: "This is Good", Active: true, Author: Author{"email", "name"}} 126 | // p.Title = "Test" 127 | // fmt.Println(p.Author.Email) 128 | 129 | // p.new() 130 | 131 | /////// Pointers 132 | 133 | // var x = 10 134 | // var y *int = &x // x address 135 | // fmt.Println(y) // 0xc000086000 136 | // fmt.Println(*y) // 10 137 | 138 | // v := 10 139 | // changeValue(&v) 140 | // fmt.Println(v) 141 | 142 | // testPanic() 143 | 144 | /////// Enums 145 | // type Format int 146 | // const ( 147 | // MP3 Format = iota 148 | // MP4 149 | // ) 150 | 151 | } 152 | 153 | func (p Post) new() { 154 | fmt.Println("new") 155 | } 156 | 157 | func changeValue(value *int) { 158 | *value = 1000 159 | } 160 | 161 | func hello(name string) { 162 | fmt.Println("Hello " + name) 163 | } 164 | 165 | func hello2(name string, family string) string { 166 | return fmt.Sprintf("Hello Dear, %s %s", name, family) 167 | } 168 | 169 | func add(x, y int) int { 170 | return x + y 171 | } 172 | 173 | func testPanic() { 174 | defer func() { 175 | if err := recover(); err != nil { 176 | fmt.Println("Panic handled") 177 | fmt.Println(err) 178 | } 179 | }() 180 | 181 | panic("Custom Panic") 182 | } 183 | -------------------------------------------------------------------------------- /golang/packages/database/mongodb.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/golang/packages/database/mongodb.go -------------------------------------------------------------------------------- /golang/packages/database/mysql.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | 6 | _ "github.com/go-sql-driver/mysql" 7 | ) 8 | 9 | type Person struct { 10 | Id int 11 | Name string 12 | } 13 | 14 | func main() { 15 | db, err := sql.Open("mysql", "") 16 | } 17 | -------------------------------------------------------------------------------- /golang/packages/database/redis.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/golang/packages/database/redis.go -------------------------------------------------------------------------------- /golang/packages/file.json: -------------------------------------------------------------------------------- 1 | { 2 | 3 | } -------------------------------------------------------------------------------- /golang/packages/files.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func checkError(err error) { 10 | if err != nil { 11 | fmt.Println(err) 12 | os.Exit(1) 13 | } 14 | } 15 | 16 | func main() { 17 | // bytes, err := ioutil.ReadFile("file.txt") 18 | // checkError(err) 19 | // fmt.Println(string(bytes)) 20 | 21 | file, err := os.Open("file.txt") 22 | checkError(err) 23 | // reader := bufio.NewReader(file) 24 | // checkError(err) 25 | // content, err := reader.Peek(2) 26 | // checkError(err) 27 | // fmt.Println(string(content)) 28 | 29 | scanner := bufio.NewScanner(file) 30 | scanner.Split(bufio.ScanWords) 31 | for scanner.Scan() { 32 | fmt.Println(scanner.Text()) 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /golang/packages/fmt.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Print("Hello") 7 | fmt.Println("World") 8 | 9 | var input int 10 | i, err := fmt.Scanln(&input) 11 | if err == nil { 12 | fmt.Println(err) 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /golang/packages/json.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type PostResponse struct { 4 | Title, Body string 5 | CreatedAt string 6 | } 7 | 8 | func main() { 9 | p = PostResponse{} 10 | json 11 | } 12 | -------------------------------------------------------------------------------- /golang/packages/log.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/golang/packages/log.go -------------------------------------------------------------------------------- /golang/packages/math.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("My favorite number is", rand.Intn(10)) 10 | } 11 | -------------------------------------------------------------------------------- /golang/packages/net_http/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | ) 7 | 8 | func main() { 9 | mux := http.DefaultServeMux 10 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 11 | 12 | }) 13 | 14 | http.ListenAndServe(":8080", nil) 15 | 16 | fmt.Println("Ok") 17 | } 18 | 19 | func handleTest(w http.ResponseWriter, r *http.Request) { 20 | if r.Method == "GET" { 21 | // w.Write() 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /golang/packages/os.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | 10 | // // Create , write simple file 11 | // file, err := os.Create("file.txt") 12 | // if err != nil { 13 | // fmt.Println(err) 14 | // os.Exit(1) 15 | // } 16 | // result, err := file.WriteString("This is first line") 17 | // if err != nil { 18 | // fmt.Println(err) 19 | // file.Close() 20 | // os.Exit(1) 21 | // } 22 | // fmt.Println(result, " bytes written.") 23 | // err = file.Close() 24 | // if err != nil { 25 | // fmt.Println(err) 26 | // os.Exit(1) 27 | // } 28 | 29 | // strings := []string{"Go", "Dart", "PHP"} 30 | // for _, v := range strings { 31 | // _, err = fmt.Fprintln(file, v) 32 | // if err != nil { 33 | // fmt.Println(err) 34 | // os.Exit(1) 35 | // } 36 | // } 37 | 38 | file, err := os.Open("file.txt") 39 | if err != nil { 40 | fmt.Println(err) 41 | os.Exit(1) 42 | } 43 | byt := make([]byte, 2) 44 | for { 45 | num, _ := file.Read(byt) 46 | fmt.Printf("%d byte , Content: $s \n", num, string(byt)) 47 | } 48 | // if _, err := os.Stat("file-exists2.file"); os.IsNotExist(err) { 49 | // fmt.Printf("File does not exist\n") 50 | // } 51 | 52 | // os.Rename(src, dst) 53 | } 54 | -------------------------------------------------------------------------------- /golang/packages/url.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/golang/packages/url.go -------------------------------------------------------------------------------- /golang/socket/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | conn, err := net.Dial("tcp", "127.0.0.1:5000") 12 | if err != nil { 13 | fmt.Println("Error") 14 | return 15 | } 16 | 17 | for { 18 | reader := bufio.NewReader(os.Stdin) 19 | fmt.Print("Text to send: ") 20 | text, _ := reader.ReadString('\n') 21 | 22 | fmt.Fprintf(conn, text+"\n") 23 | 24 | message, _ := bufio.NewReader(conn).ReadString('\n') 25 | fmt.Print("Mesage from server: " + message) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /golang/socket/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net" 7 | ) 8 | 9 | func main() { 10 | 11 | fmt.Println("Start Socket Service Listener on port : 5000") 12 | 13 | listener, _ := net.Listen("tcp", ":5000") 14 | 15 | conn, _ := listener.Accept() 16 | 17 | for { 18 | message, _ := bufio.NewReader(conn).ReadString('\n') 19 | fmt.Print("Message Received:", string(message)) 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /jquery/img/slide1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/jquery/img/slide1.jpg -------------------------------------------------------------------------------- /jquery/img/slide2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/jquery/img/slide2.jpg -------------------------------------------------------------------------------- /jquery/img/slide3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/jquery/img/slide3.jpg -------------------------------------------------------------------------------- /jquery/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Jquery 9 | 10 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /jquery/jquery.js: -------------------------------------------------------------------------------- 1 | // var jq = jQuery.noConflict(); 2 | // jq(window).width(); 3 | 4 | // $(document).ready(function () { 5 | // $('body').css("background-color", "red"); 6 | // }); 7 | 8 | $(function () { 9 | // $('body').css("background-color"); 10 | // $('body').css("background-color", "blue"); 11 | // $('body').css({ 12 | // "backgroundColor": "red", 13 | // "color": "blue" 14 | // }); 15 | 16 | // $("p").attr({"title": "p tag"}); 17 | // $("p").removeAttr("title"); 18 | 19 | // $('p').append(" Test"); 20 | 21 | // $('p').click(function() { 22 | // alert($(this).html()); 23 | // }); 24 | 25 | // $(window).height(); 26 | 27 | // $("#p1").hide(); 28 | // $("#p1").show(); 29 | 30 | // var elements = $("img"); 31 | // var index = elements.index($("#id1")); 32 | 33 | // $("p").each(function (index, elem) { 34 | // alert("This is " + index + " And " + elem.tagName); 35 | // }); 36 | 37 | 38 | // $("img").mouseenter(function () { 39 | // alert("Src: " + this.getAttribute("src")); 40 | // }); 41 | 42 | 43 | // $("p").add("div"); //$("p", "div"); 44 | 45 | 46 | // $("label").css("color", "red"); 47 | // $("label:even").css("font-size", "20px"); 48 | // $("label:even, .cell").css("background-color", "cyan"); 49 | // // same 50 | // $("label").css("color", "red").filter(":even").css("font-size", "20px").add(".cell").css("background-color", "cyan"); 51 | 52 | 53 | // $("tr:even").css("background-color", "#0ff"); 54 | // $("tr:odd").css("background-color", "#ddf"); 55 | // $("tr:first").css({ 56 | // "background-color": "blue", 57 | // "color": "white" 58 | // }); 59 | // $("tr:not(first-child)").hover(function () { 60 | // $(this).css("background-color", "red"); 61 | // }, function () { 62 | // $("tr:even:not(:first)").css("background-color", "#0ff"); 63 | // $("tr:odd").css("background-color", "#ddf"); 64 | // }); 65 | 66 | 67 | // $("#p1").append("Test"); 68 | // $("#p1").prepend("Test"); 69 | // $("#p1").append("Test"); 70 | // $("#p1").before("Test"); 71 | // $("#p1").remove("Test"); // return without event handler 72 | // $("#p1").detach("Test"); // return with event handler 73 | 74 | // $("input:radio[name=test]:checked").val(); 75 | // $("#textarea").val("Test"); 76 | // $("#form").serialize; 77 | 78 | // $("#dt").data("mydata"); // my value 79 | // $("#dt").data("mydata", 100); // 100 80 | // $("#dt").removeData("mydata"); 81 | 82 | // $(".container").css(["width", "height"]); 83 | // $(".container").css({"width": "+=50", "height":"+=100"}); 84 | 85 | 86 | // $("#checkbox").change(function () { 87 | // if ($(this).is(":checked")) 88 | // alert("checked"); 89 | // else 90 | // alert("not checked"); 91 | // }); 92 | 93 | 94 | // var resize; 95 | // $(window).resize(function () { 96 | // resize++; 97 | // var str = "The window resized " + resize + " times.
"; 98 | // str += " size is: " + $(this).width() + " height " + $(this).height() + "
"; 99 | // }).scroll(function () { 100 | // msg = $(this).scrollLeft() + $(this).scrollTop(); 101 | // }); 102 | 103 | }); 104 | 105 | 106 | /* 107 | Selectors: 108 | 109 | [class=c3] 110 | input[name*='nam'] 111 | p[id^='para] 112 | p[id$='para] 113 | a:first 114 | a:last 115 | div a:first-child 116 | div a:last-child 117 | p:even 118 | p:odd 119 | 120 | ul:nth-child(2) 121 | p:only-child 122 | p a:eq(2) 123 | p a:lt(2) 124 | p a:gt(2) 125 | 126 | span:empty 127 | 128 | div:has(p) 129 | 130 | :contains('jq') 131 | 132 | input:focus 133 | 134 | p:not(:empty) 135 | 136 | #form :enabled 137 | #form :disabled 138 | 139 | :selected 140 | :checked 141 | 142 | p:visible 143 | p:hidden 144 | 145 | div:animated 146 | 147 | div :header 148 | div :input 149 | 150 | :button 151 | 152 | 153 | */ -------------------------------------------------------------------------------- /jquery/slideshow.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | var canClick = true; 3 | var ul = $("#slider ul"); 4 | var first = ul.children().first().clone(); 5 | var last = ul.children().last().clone(); 6 | ul.prepend(last); 7 | ul.append(first); 8 | ul.css("left", "-600px"); 9 | 10 | $("#next").click(function (event) { 11 | event.preventDefault(); 12 | if (!canClick) 13 | return; 14 | else 15 | canClick = false; 16 | 17 | ul.css("transition", "2s"); 18 | ul.css("left", "-=600px"); 19 | setTimeout(function () { 20 | if(ul.position().left <-1800){ 21 | ul.css("transition", "0s").css("left", "-600px"); 22 | } 23 | canClick = true; 24 | clearInterval(interval); 25 | interval = setInterval(function() { 26 | $("#next").click(); 27 | }, 5000); 28 | }, 2000); 29 | }); 30 | }); -------------------------------------------------------------------------------- /linux.txt: -------------------------------------------------------------------------------- 1 | mtr -t 2 | -------------------------------------------------------------------------------- /linux/laravel-permissions.txt: -------------------------------------------------------------------------------- 1 | sudo chown -R www-data:www-data /path/to/your/laravel-directory 2 | sudo usermod -a -G www-data ubuntu 3 | sudo chgrp -R www-data storage bootstrap/cache 4 | sudo chmod -R ug+rwx storage bootstrap/cache 5 | 6 | sudo chown -R www-data:www-data /path/to/your/laravel/root/directory 7 | 8 | chmod -R 775 /path/to/your/project 9 | -------------------------------------------------------------------------------- /linux/vim.txt: -------------------------------------------------------------------------------- 1 | in normal mode / command mode: 2 | 3 | i = go to insert mode 4 | wq = write and quite 5 | 6 | w = got to start of next word 7 | e = got to end of next word 8 | b = got to start of last word 9 | 10 | r = replace one char 11 | 12 | o = open new line below and go to insert mode, O = open new line above 13 | 14 | 15 | 16 | j = down, k = up, l=right, h=left 17 | 18 | ctrl+f => page down, ctrl+b = page up 19 | 20 | linenumber+gg = go to linenumber ex: 2gg 21 | 22 | gg = goto up of file 23 | shift+g = goto end of file 24 | $ = goto end of line, ^ = goto start of line 25 | 26 | 5H go to 5th line from top of screen 27 | 5L go to 5th line to the end of screen 28 | 29 | x = delete current char 30 | 31 | d = delete ex: dw delete word, d& delete to end of line 32 | dd = delete current line 33 | 34 | p = paste last deleted text after cursor 35 | P = paste last deleted text before cursor 36 | 37 | xp = swap the chars 38 | 39 | 40 | 41 | in line mode: 42 | 43 | :linenumber = goto linenumber 44 | 45 | :/ search forward, :? search backward 46 | 47 | :$ = goto end of file 48 | 49 | :w new_file_name 50 | 51 | :e = reload file 52 | 53 | 54 | :set ruler = show position of cursor 55 | -------------------------------------------------------------------------------- /mongodb/mongodb.txt: -------------------------------------------------------------------------------- 1 | mongodb -------------------------------------------------------------------------------- /mysql/example.txt: -------------------------------------------------------------------------------- 1 | create table courses( 2 | id int unsigned auto_increment primary key, 3 | name varchar(30) not null, 4 | description varchar(250) not null, 5 | price int(10) not null, 6 | teacher_id int unsigned not null 7 | ); 8 | 9 | create table teachers( 10 | id int unsigned primary key auto_increment, 11 | phone varchar(12) not null unique, 12 | name varchar(30) not null, 13 | password varchar(30) not null, 14 | ); 15 | 16 | alter table courses add constraint fk_courseTeacher foreign key(teacher_id) references teachers(id); 17 | 18 | 19 | // joins 20 | 21 | select * from users cross join teachers; 22 | select * from users, teachers; 23 | 24 | 25 | select * from courses inner join teacher on course.teacher_id = teacher.id; 26 | select * from courses inner join teacher where course.teacher_id = teacher.id; 27 | 28 | 29 | select tbl1.id, tbl2.id from tbl1 cross join tbl2; 30 | 31 | 32 | select tbl1.id, tbl2.id from tbl1 left join tbl2 on tbl1.name = tbl2.name; -------------------------------------------------------------------------------- /mysql/functions.txt: -------------------------------------------------------------------------------- 1 | Math Functions: 2 | 3 | select abs(-5); // 5 4 | 5 | select sin(70), cos(80), tan(120),atan(60), atan(60, 80), asin(70), acos(150), cot(95); 6 | 7 | 8 | select hex(70), oct(20), bin(14); 9 | 10 | select degress(40); // digit in radian 11 | 12 | select radians(180), exp(6), floor(24), ln(4), log(4), log(4, 5), log2(10), log2(10, 30) ; 13 | 14 | select 20 div 5; 15 | 16 | select mod(30, 10), pi(), pow(10, 3), rand(), rand(10), round(4.8), sign(-1), sqrt(60), truncate(3.141516, 4); 17 | 18 | select greatest(1,4,5,6,12,41), least(2,14,5,13,5); 19 | 20 | 21 | 22 | Agregation Functions: 23 | 24 | select avg(Column) from table_name; 25 | select count(Column) from table_name; 26 | select min(Column) from table_name; 27 | select max(Column) from table_name; 28 | select sum(Column) from table_name; 29 | 30 | select std(Column) from table_name; 31 | select variance(Column) from table_name; 32 | 33 | 34 | 35 | Strings Functions: 36 | 37 | select ascii('c'), bit_lenght("String"), char(97, 100, 65); 38 | 39 | select concat("Hello ", "World"), concat_ws('_', "Hello", "World"); 40 | 41 | select char_length("string"), character_length("string"); 42 | 43 | select compress("string"), insert("string", 1, 2, "c"); 44 | 45 | select find_in_set('php', 'mysql,sqlite,java,php,python'); // 4 46 | 47 | select field('string','php', 'string', 'mysql'); // 2 48 | 49 | select instr('my favorite lang is php', 'php'); 50 | 51 | select lcase('PHP STRING'),ucase('sfd'), lower('STRING'), upper('fsdf'); 52 | 53 | select left('hello world',2), right('hello world',2); 54 | 55 | select length(), lpad('php', 10, 'J'), rpad('php', 10, 'J'); 56 | 57 | select locate('he', 'hello'),locate('he', 'hello', 2); 58 | 59 | rtrim(' mysql'), ltrim('my '), trim(' jf '); 60 | 61 | repeat('-',10); 62 | 63 | replace('hello world', 'hello', 'hi'); 64 | 65 | reverse('string'); 66 | 67 | strcmp('string', 'string'); 68 | 69 | substring('hello world', 3,4), mid('hello world', 3,4); 70 | 71 | 72 | # Date time 73 | 74 | select now(), curdate(), current_date(), curtime(), current_time(); 75 | 76 | date_add(now(), expr, type); 77 | types: 78 | year, month, week, day, hour, minute, second, microsecond, quarter 79 | select date_add(now(), interval 1 hour), date_sub(now(), interval 2 day); 80 | 81 | 82 | adddate(date(now())), 20), addtime('12:23:00', 02:00:00); 83 | 84 | hour(time(now())); 85 | 86 | minute(), second(), day(date(now())), month(), year(), week() 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /mysql/indexes.txt: -------------------------------------------------------------------------------- 1 | create index usr_index on users(name,email); 2 | 3 | create index usr_btree_index using btree on users(name, email); 4 | 5 | create index usr_hash_index using hash on users(name,email); 6 | 7 | create unique index unq_usr_index on users(email); 8 | 9 | create fulltext index ftxt_usr_index on users(name); 10 | 11 | show index from users; 12 | 13 | drop index usr_index on users; 14 | 15 | -------------------------------------------------------------------------------- /mysql/mysql.txt: -------------------------------------------------------------------------------- 1 | # Engines 2 | 3 | MyISAM: 4 | default engine in before mysql 5.5.5 5 | 6 | store every table data in three files: 7 | frm -> includes table schema 8 | myd -> includes data 9 | myi -> includes indexes 10 | 11 | 12 | Memory: 13 | Store data in memory 14 | 15 | 16 | 17 | 18 | # Data Types 19 | 20 | -- Numeric -- 21 | 22 | TINYINT: 23 | signed -> 128 to 127 24 | unsigned -> 0 to 255 25 | 26 | INT: 27 | signed -> -(2^31) to 2^31 28 | unsigned -> 0 to 2^32 29 | 30 | BIGINT: 31 | signed -> -(2^64) to 2^63 32 | unsigned -> 0 to 2^64 33 | 34 | FLAOT 35 | DOUBLE 36 | 37 | -- DATETIME -- 38 | 39 | DATE: 40 | 1000-01-01 to 9999-12-31 41 | 42 | TIME: 43 | 00:00:00 to 23:59:59 44 | 45 | DATETIME: 46 | 1000-01-01 00:00:00 to 9999-12-31 23:59:59 47 | 48 | TIMESTAMP: 49 | number in format -> YYYYMMDDHHMMSS 50 | 51 | 52 | -- STRINGS -- 53 | 54 | CHAR(M): 55 | string with M chars (M < 256) 56 | 57 | VARCHAR(M): 58 | string with M chars (M < 65536) 59 | 60 | TEXT: 61 | string with max len 65535 62 | 63 | BLOB: 64 | LIKE TEXT but case sensitive 65 | 66 | MEDIUMTEXT: 67 | string with 16 mg 68 | 69 | MEDIUMBLOB: 70 | LIKE MEDIUMTEXT but case sensitive 71 | 72 | LONGTEXT: 73 | string with 4 g 74 | 75 | LONGBLOB: 76 | LIKE LONGTEXT but case sensitive 77 | 78 | ENUM 79 | 80 | 81 | ////////////////////////// 82 | 83 | # Commands 84 | 85 | // all mysql commands finished by ; 86 | // database and table names in linux is sensitive 87 | 88 | show databases; 89 | 90 | create database database_name; 91 | 92 | create database if not exists database_name; 93 | 94 | use database_name; 95 | 96 | drop database if exists database_name; 97 | 98 | alter database database_name character set utf8 collate utf8_persian_ci; 99 | 100 | create table table_name ( 101 | Field1 types, 102 | Field2 types, 103 | ) ; 104 | 105 | show tables; 106 | 107 | alter table table_name rename new_name; 108 | 109 | alter table table_name add Coloumn type; 110 | 111 | alter table table_name drop coloumn Coloumn; 112 | 113 | alter table table_name modify Coloumn new_type; 114 | 115 | alter table table_name alter Coloumn1 set default 'Default value'; 116 | 117 | drop table if exists table_name; 118 | 119 | describe table_name; 120 | 121 | create temporary table table_name( 122 | Field1 types, 123 | Field2 types, 124 | ); 125 | 126 | drop temporary table table_name; 127 | 128 | 129 | 130 | 131 | INSERT INTO table_name ('Field1', 'Field2') 132 | VALUES ("Value1", "Value2"); 133 | 134 | INSERT INTO table_name VALUES ('Value1', 'Value2'); 135 | 136 | select * from table; 137 | 138 | select * from database.table; 139 | 140 | select * from tables limit 10; 141 | select * from tables limit 10, 30; 142 | 143 | select Coloumn1, Coloumn2, ... from database.table; 144 | 145 | select * from table_name where Coloumn < 200; 146 | select * from table_name where Coloumn < 200 order by ASC; // DESC 147 | 148 | select * from table_name order by Coloumn1 ASC, Coloumn2 DESC; 149 | 150 | select * from table_name where Coloumn1 between 100 and 200; 151 | 152 | select * from table_name where Coloumn1 > 100 and Coloumn2 in ("a", "b", "c"); 153 | 154 | select * from table_name where Coloumn1 is null; 155 | 156 | select * from table_name where Coloumn1 is not null; 157 | 158 | select * from table_name where Coloumn1 like '%t%'; 159 | 160 | select distinct Coloumn1 from table_name; 161 | 162 | select Coloumn1 as C1, Coloumn2 as C2 from table_name; 163 | 164 | select 10 + 5; // - * 165 | 166 | select Coloumn1, Coloumn2 + 10 as C2 from table_name; 167 | 168 | select @var := Coloumn1 from table_name ; 169 | select * from table_name where Coloumn2 > @tp; 170 | 171 | 172 | 173 | // usefull functions 174 | 175 | select avg(Coloumn) as average from table_name; 176 | 177 | // sum(); - min() - max() 178 | 179 | select count(*) as records from table_name; 180 | 181 | select concat(fname, ' ', lname) as fullname from table_name; 182 | 183 | length() // string byte size 184 | char_length() // string length size 185 | 186 | 187 | left(Coloumn, 10); - right(Coloumn, 4); // return n chars 188 | 189 | trim(); - rtrim() - ltrim(); 190 | 191 | substring(str, x, n); // start index is 1 192 | 193 | lower() upper() 194 | 195 | 196 | // Update 197 | 198 | update table_name set Coloumn = 'value'; 199 | 200 | update table_name set Coloumn = 'value' where Coloumn =1; 201 | 202 | delete from table_name where Coloumn1 == 1; 203 | 204 | delete from table_name; // delete all records 205 | truncate table table_name; // delete table and create new empty table 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | // Stored Procedure 217 | 218 | delimiter // 219 | 220 | create procedure GetAllUsers() 221 | begin 222 | select * from users; 223 | end 224 | // 225 | 226 | delimiter ; 227 | 228 | call GetAllUsers() 229 | 230 | 231 | ********** 232 | 233 | delimiter // 234 | 235 | create procedure GetUser(in userId int) 236 | begin 237 | select * from users where id=userId; 238 | end 239 | // 240 | 241 | delimiter ; 242 | 243 | ***** 244 | 245 | delimiter // 246 | 247 | create procedurer userCount(out total int) 248 | begin 249 | select count(id) into total from users; 250 | end 251 | // 252 | 253 | userCount(@total) 254 | select @total; 255 | 256 | 257 | drop procedure if exists GetUser; 258 | 259 | 260 | 261 | /// Triggers: 262 | 263 | delimiter // 264 | create trigger befor_users_update 265 | before update on users 266 | for each row 267 | begin 268 | insert into users_actions set action = 'update', user_id = old.user_id 269 | end // 270 | 271 | show triggers; 272 | 273 | 274 | 275 | /// Views: 276 | 277 | create view user_view as select name,email from users; 278 | 279 | select * from user_view; 280 | 281 | 282 | create or replace view user_view(userName, userEmail) as select name, email from users; 283 | 284 | 285 | 286 | /// Transactions: 287 | 288 | set autocommit=0; 289 | 290 | start transaction; 291 | 292 | insert into users(name) values("name"); 293 | insert into users(name) values("name2"); 294 | 295 | commit; 296 | 297 | 298 | 299 | 300 | /// Users: 301 | 302 | // privilages: create, drop, update, delete, insert, select, grant all 303 | 304 | create user 'username'@'localhost' identified by 'password'; 305 | 306 | grant all privilages on *.* to 'username'@'localhost'; 307 | 308 | flush privilages; 309 | 310 | 311 | grant create on database.table to 'username'@'localhost'; 312 | 313 | revoke create on database.table from 'username'@'localhost'; 314 | 315 | show grants for 'username'@'localhost'; 316 | 317 | show grants for current_user(); 318 | 319 | drop user 'username'; 320 | 321 | 322 | -------------------------------------------------------------------------------- /mysql/operators.txt: -------------------------------------------------------------------------------- 1 | select 10+4, 3*2, 4-1, 8/2, 16%3; 2 | 3 | update table_name set Column1= 2*2 where id=1; 4 | 5 | 6 | select 10 = 10, 5 <> 3, 1 < 2, 2 <= 3, 3 > 4, 4 >= 1, 4 != 4; 7 | 8 | select 5 between 1 and 10; // 1 9 | 10 | select ' ' is null; // 0 11 | select ' ' is not null; // 1 12 | 13 | select 'sql' like '%q%'; 14 | select 'sql' like 'sq_'; 15 | 16 | select 2 in (1,2,3,4,5); 17 | 18 | select 'mysql' regexp '^m*l$'; 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /mysql/tables.txt: -------------------------------------------------------------------------------- 1 | create table users( 2 | id int primary key, 3 | username varchar(30) unique not null, 4 | age int, 5 | check (age <= 8), 6 | active bool default true 7 | ); 8 | 9 | create table profile( 10 | id int primary key, 11 | user_id int, 12 | bio varchar(255), 13 | foreign key (user_id) references users(id) 14 | ); 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /perl/perl.perl: -------------------------------------------------------------------------------- 1 | use strict; 2 | 3 | # print "Hello World"; 4 | 5 | # print 10; 6 | # print 3.14; 7 | # print 010101; 8 | # print 0175; 9 | # print 0xaf; 10 | 11 | # datatypes: 12 | 13 | # arrays 14 | 15 | # scalars 16 | 17 | # hashes 18 | 19 | # strings 20 | 21 | 22 | # $var=10; 23 | # @arr=(1,2,3,4); 24 | # %myHash=("name","john"); 25 | 26 | # $myStr="Perl"; 27 | # print $myStr; 28 | # $myStr x=10; 29 | # print $myStr; 30 | 31 | $a="Programming"; 32 | print(length($a),"\n"); 33 | print(lc($a),"\n"); 34 | print(uc($a),"\n"); 35 | print(scalar reverse($a),"\n"); 36 | print(index($a, "o"), "\n"); 37 | print(substr($a, 0, 3), "\n"); 38 | 39 | 40 | # @numbers=(1,2,3); 41 | # # @names=("ali", "milad", "amir"); 42 | # print @numbers 43 | 44 | # @days=qw /sat sun mon tue wed the fri/; 45 | # print "$days"; 46 | 47 | print(sort(@days)); 48 | print(pop(@days)); 49 | print(push(@days, "fff")); 50 | 51 | # @nums=(1..9); 52 | 53 | # $count=scalar @nums; 54 | 55 | -------------------------------------------------------------------------------- /php/array.php: -------------------------------------------------------------------------------- 1 | "mon", "tue", 'wend', 'thu', 'fri', 'sat']; 12 | 13 | //////// 14 | $a = [ 15 | 'URL' => 'http://google.com', 16 | 'Name' => 'Google', 17 | 'Eamil' => 'Google@gmail.com' 18 | ]; 19 | 20 | $b = array( 21 | 'Username' => 'UGoogle', 22 | 'URL' => 'http://google.com', 23 | ); 24 | 25 | $c = array_merge($a, $b); 26 | 27 | echo '
';
 28 | echo '$c = ';
 29 | print_r($c);
 30 | echo '
'; 31 | 32 | ///////////// 33 | 34 | 35 | // Array Functions 36 | 37 | $nums = array(1,45,7,2,4,7,9,13); 38 | 39 | $nn = [ 40 | 'A' => 13, 41 | 'v' => 34, 42 | 'pi' => 3.14, 43 | 'name' => 'name', 44 | ]; 45 | 46 | $colors = ['red', 'blue', 'orange', 'pink', 'black', 'blue', 'red']; 47 | 48 | echo count($nums); 49 | 50 | echo sizeof($nums); 51 | 52 | array_slice($colors, 1, 4); 53 | 54 | list($red, $blue) = array_slice($color, 0,2); 55 | 56 | echo array_sum($nums); 57 | 58 | echo array_keys($nn); 59 | 60 | echo array_values($nn); 61 | 62 | echo isset($nn['A']); 63 | 64 | echo array_key_exists('a', $nn); 65 | 66 | echo array_search('pink', $colors); // pink 67 | echo array_search('green', $colors); // false 68 | 69 | echo array_unique($colors); 70 | 71 | in_array("search", $array); 72 | in_array("50", $array, true); 73 | 74 | array_search("search", $array); 75 | 76 | array_reverse(); 77 | 78 | array_merge(); 79 | 80 | array_push(); 81 | 82 | array_pop(); 83 | 84 | array_diff(); 85 | 86 | array_shift(); 87 | 88 | array_sum(); 89 | 90 | array_unique(); 91 | 92 | $callback = function($value, $key) { 93 | print("{$value}{$value}\n"); 94 | }; 95 | $person = ['name'=>'milad', 'age'=>20]; 96 | array_walk($person, $callback); 97 | 98 | 99 | // Array Sort Functions 100 | 101 | echo sort($colors); // first string next numbers 102 | 103 | echo sort($nums); 104 | 105 | echo rsort($nums); 106 | 107 | echo asort($nn); 108 | 109 | echo arsort($nn); 110 | 111 | echo ksort($nn); 112 | 113 | echo krsort($nn); 114 | 115 | // usort($arr, function () {}); 116 | 117 | // uasort(); 118 | 119 | // uksort(); 120 | 121 | natsort(); // netural sort 122 | 123 | natcasesort(); // scape alphabet 124 | 125 | $alphabet = 'abcdefghklmnopqrstu1234567890AVNDJSDFC'; 126 | $arrayAlphabet = str_split($alphabet); // string to array 127 | echo shuffle($nums); 128 | 129 | 130 | // Array Pointers 131 | 132 | $arr = [1,4,5,3,7,9,13]; 133 | echo current($arr); 134 | 135 | echo next($arr); 136 | 137 | echo current($arr); 138 | 139 | end($arr); 140 | 141 | key($arr); 142 | 143 | echo prev($arr); 144 | 145 | echo current($arr); 146 | 147 | reset($arr); 148 | 149 | echo current($arr); 150 | 151 | while(current($arr) !== false) { 152 | echo current($arr); 153 | next($arr); 154 | } 155 | 156 | list($key, $value) = each($arr); 157 | 158 | 159 | // range 160 | 161 | $numbers = range(1,9); 162 | $letters = range('a', 'z'); 163 | $revNumbers = range(9, 1); 164 | 165 | 166 | $ages = [ 167 | 'Person' => 'Age', 168 | 'Ali' => 30, 169 | 'Amir' => 20, 170 | 'Milad' => 25, 171 | 'Arash' => 19, 172 | 'Mehdi' => 15, 173 | ]; 174 | 175 | reset($ages); 176 | list($person, $age) = each($ages); 177 | echo("\n
{$person}
\n"); 178 | 179 | while(list($person, $age) = each($age)) { 180 | echo("{$person}{$age}\n"); 181 | } 182 | echo(""); 183 | -------------------------------------------------------------------------------- /php/cli.php: -------------------------------------------------------------------------------- 1 | set_charset("utf8"); 4 | ?> 5 | 6 | 7 | 8 | 9 | 10 | 11 | New User 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 36 | 37 | 38 | 39 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 54 | 55 |
Username
First name
Last name
status 31 | 35 |
gender 40 | 44 |
password
52 | 53 |
56 |
57 | 58 | -------------------------------------------------------------------------------- /php/database/crud/index.php: -------------------------------------------------------------------------------- 1 | set_charset("utf8"); 5 | 6 | if (isset($_GET['delete'])) { 7 | $deleteQuery = "DELETE FROM user_details WHERE `user_id` = {$_GET['delete']}"; 8 | $result = $connection->query($deleteQuery); 9 | $allQuery = "SELECT * from user_details LIMIT 50"; 10 | $result = $connection->query($allQuery); 11 | } else if (isset($_GET['insert'])) { 12 | $username = $_POST['username']; 13 | $fname = $_POST['fname']; 14 | $lname = $_POST['lname']; 15 | $status = $_POST['status']; 16 | $gender = $_POST['gender']; 17 | $password = $_POST['password']; 18 | 19 | $query = "INSERT INTO user_details (username, first_name, last_name, gender, `status`, `password`) VALUES ($username, $fname, $lname, $gender, $status, $password)"; 20 | $connection->query($query); 21 | $allQuery = "SELECT * from user_details LIMIT 50"; 22 | $result = $connection->query($allQuery); 23 | } else if (isset($_GET['update'])) { 24 | $username = $_GET['username']; 25 | $fname = $_GET['fname']; 26 | $lname = $_GET['lname']; 27 | $status = $_GET['status']; 28 | $gender = $_GET['gender']; 29 | $password = $_GET['password']; 30 | 31 | $query = "UPDATE user_details SET username=$username, first_name=$fname, last_name=$lname, 'status'=$status, gender=$gender, 'password'=$password WHERE 'user_id' = {$_GET['update']}"; 32 | $connection->query($query); 33 | $allQuery = "SELECT * from user_details LIMIT 50"; 34 | $result = $connection->query($allQuery); 35 | } else if (isset($_GET['search'])) { 36 | $search = $_GET['search']; 37 | $query = "SELECT * FROM user_details WHERE first_name LIKE '%$search%' OR last_name LIKE '%$search%'"; 38 | $result = $connection->query($query); 39 | } else { 40 | $query = "SELECT * FROM user_details LIMIT 50"; 41 | $result = $connection->query($query); 42 | } 43 | 44 | ?> 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | PHP CRUD Example 54 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | fetch_assoc()) { 146 | ?> 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 158 | 159 | 160 | 163 |
IDusernamefirst namelast namegenderstatusactions
155 | Update 156 | Delete 157 |
164 |
165 | 166 | 167 |
168 | 169 | New User 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /php/database/crud/update.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/php/database/crud/update.php -------------------------------------------------------------------------------- /php/database/mysqli.php: -------------------------------------------------------------------------------- 1 | set_charset('utf-8'); 6 | 7 | // mysqli_select_db($db_handle,$database_name); 8 | 9 | // mysqli_query($db_handle,$query) ; 10 | 11 | // mysqli_num_rows($result); 12 | 13 | // mysqli_fetch_array($result); 14 | 15 | // mysqli_close($db_handle); 16 | 17 | 18 | // $db_handle = mysqli_connect('localhost', 'root', '', 'learn') or exit("Unable to connect to MySQL: "); 19 | 20 | // echo $db_handle->host_info; 21 | 22 | // $query = "SELECT * FROM user_details where `username` like '%m%'"; 23 | // $result = $db_handle->query($query); 24 | 25 | // echo '
';
 26 | // print_r($result);
 27 | // echo '
'; 28 | 29 | // echo $result->num_rows . '
'; 30 | 31 | // // while($row = $result->fetch_assoc()){ 32 | // // echo($row['username']) . '
'; 33 | // // } 34 | 35 | // foreach($result->fetch_all(MYSQLI_ASSOC) as $row) { 36 | // echo $row['username'] . '
'; 37 | // } 38 | 39 | // // $query = "DELETE FROM user_details where `username` = 'mike28'"; 40 | // // $result = $db_handle->query($query); 41 | // // echo $db_handle->affected_rows . ' Record(s) Deleted.'; 42 | 43 | // $db_handle->close(); 44 | 45 | 46 | $connection = new mysqli("localhost", "root", "", "learn"); 47 | $stmt = $connection->stmt_init(); 48 | $query = "SELECT * FROM user_details WHERE username = ?"; 49 | $stmt->prepare($query); 50 | $username = "ross95"; 51 | $stmt->bind_param('s', $username); 52 | // b,d,i,s 53 | $stmt->bind_result($user_id, $username, $first_name, $last_name, $gender, $password, $status); 54 | 55 | $stmt->execute(); 56 | 57 | echo ""; 58 | while ($stmt->fetch()) { 59 | echo << 61 | 64 | EOS; 65 | } 66 | echo "
$user_id 62 | $username 63 |
"; 67 | 68 | // //if connection failed output error message 69 | // if (!mysqli_select_db($dbh,'my_personal_contacts')) 70 | 71 | // die("Unable to select database: " . mysqli_error()); 72 | // die("Unable to connect to MySQL: " . mysqli_error()); 73 | // //if selection fails output error message 74 | 75 | // $sql_stmt = "SELECT * FROM my_contacts"; 76 | 77 | // $result = mysqli_query($dbh,$sql_stmt); 78 | // //execute SQL statement 79 | 80 | // if (!$result) 81 | // //SQL select query 82 | // die("Database access failed: " . mysqli_error()); 83 | // //output error message if query execution failed 84 | 85 | // // get number of rows returned 86 | 87 | // $rows = mysqli_num_rows($result); 88 | // if ($rows) { 89 | 90 | // while ($row = mysqli_fetch_array($result)) { 91 | // echo 'ID: ' . $row['id'] . '
'; 92 | // echo 'Full Names: ' . $row['full_names'] . '
'; 93 | // echo 'Gender: ' . $row['gender'] . '
'; 94 | // echo 'Contact No: ' . $row['contact_no'] . '
'; 95 | // echo 'Email: ' . $row['email'] . '
'; 96 | // echo 'City: ' . $row['city'] . '
'; 97 | // echo 'Country: ' . $row['country'] . '

'; 98 | // } 99 | // } 100 | // mysqli_close($dbh); //close the database connection 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | // $dbh = mysqli_connect('localhost', 'root', 'melody'); 120 | // //connect to MySQL server if (!$dbh) 121 | 122 | // die("Unable to connect to MySQL: " . mysqli_error()); 123 | // //if connection failed output error message 124 | 125 | // if (!mysqli_select_db($dbh,'my_personal_contacts')) 126 | // die("Unable to select database: " . mysql_error()); 127 | // //if selection fails output error message 128 | 129 | // $sql_stmt = "INSERT INTO `my_contacts` (`full_names`,`gender`,`contact_no`,`email`,`city`,`country`)"; 130 | // $sql_stmt .= " VALUES('Poseidon','Mail','541',' poseidon @ sea . oc ','Troy','Ithaca')"; 131 | 132 | // $result = mysqli_query($dbh,$sql_stmt); //execute SQL statement 133 | 134 | // if (!$result) 135 | // die("Adding record failed: " . mysqli_error()); 136 | // //output error message if query execution failed echo "Poseidon has been successfully added to your contacts list"; 137 | 138 | // mysqli_close($dbh); //close the database connection 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | // $dbh = mysqli_connect('localhost', 'root', 'melody'); 149 | // //connect to MySQL server 150 | 151 | // if (!$dbh) 152 | // die("Unable to connect to MySQL: " . mysqli_error()); 153 | // //if connection failed output error message 154 | 155 | // if (!mysqli_select_db($dbh,'my_personal_contacts')) 156 | // die("Unable to select database: " . mysql_error()); 157 | // //if selection fails output error message 158 | 159 | // // $sql_stmt = "UPDATE `my_contacts` SET `contact_no` = '785',`email` = ' poseidon @ ocean . oc '; 160 | // // //SQL select query $sql_stmt .= " WHERE `id` = 5""; 161 | 162 | // $result = mysqli_query($dbh,$sql_stmt); 163 | // //execute SQL statement if (!$result) 164 | 165 | // die("Deleting record failed: " . mysqli_error()); 166 | // //output error message if query execution failed 167 | 168 | // echo "ID number 5 has been successfully updated"; 169 | // mysqli_close($dbh); //close the database connection 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | // $dbh = mysqli_connect('localhost', 'root', 'melody'); 180 | // //connect to MySQL server 181 | 182 | // if (!$dbh) 183 | // die("Unable to connect to MySQL: " . mysqli_error()); 184 | // //if connection failed output error message 185 | 186 | // if (!mysqli_select_db($dbh,'my_personal_contacts')) 187 | // die("Unable to select database: " . mysqli_error()); 188 | // //if selection failes output error message $id = 4; 189 | // //Venus's ID in the database 190 | 191 | // $sql_stmt = "DELETE FROM `my_contacts` WHERE `id` = $id"; 192 | // //SQL Delete query 193 | 194 | // $result = mysqli_query($dbh,$sql_stmt); 195 | // //execute SQL statement 196 | 197 | // if (!$result) 198 | // die("Deleting record failed: " . mysqli_error()); 199 | // //output error message if query execution failed 200 | 201 | // echo "ID number $id has been successfully deleted"; 202 | // mysqli_close($dbh); //close the database connection -------------------------------------------------------------------------------- /php/database/pdo.php: -------------------------------------------------------------------------------- 1 | setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 8 | 9 | // $sql_stmt = "SELECT VERSION()"; 10 | // $result = $pdo->query($sql_stmt); 11 | // $version = $result->fetch(); 12 | // echo 'Current mysql version: ' . $version[0] . PHP_EOL; 13 | 14 | 15 | $sql_stmt = "SELECT * FROM `user_details`"; 16 | $result = $pdo->query($sql_stmt); 17 | foreach ($result as $row) { 18 | echo ($row['username']) . '
'; 19 | } 20 | 21 | echo 'Row Count: ' . $result->rowCount(); 22 | 23 | 24 | } catch (PDOException $e) { 25 | echo $e->getMessage(); 26 | } 27 | 28 | // $dns = "mysql:host=localhost;dbname=learn;charset=utf8"; 29 | // $pdo = new PDO($dns, 'root', ''); 30 | // $query = "SELECT * WHERE user_details WHERE username = ?"; 31 | // $stmt = $pdo->prepare($query); 32 | 33 | // $stms->bindColoumn('UserId', $user_id); 34 | // $stms->bindColoumn('username', $username); 35 | 36 | // $params = ['username']; 37 | // $stmt->execute($params); -------------------------------------------------------------------------------- /php/database/sqlite3/database.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/php/database/sqlite3/database.db -------------------------------------------------------------------------------- /php/database/sqlite3/sqlite3.php: -------------------------------------------------------------------------------- 1 | query(" 6 | // CREATE TABLE IF NOT EXISTS users ( 7 | // id INTEGER PRIMARY KEY AUTOINCREMENT, 8 | // username TEXT NOT NULL 9 | // ); 10 | // "); 11 | 12 | // $db->query(" 13 | // INSERT INTO users ( 14 | // username 15 | // ) VALUES 16 | // ( 'admin' ), 17 | // ( 'writer' ), 18 | // ( 'editor') 19 | // ; 20 | // "); 21 | 22 | $users = $db->query(" 23 | SELECT * FROM users 24 | "); 25 | 26 | while(true) { 27 | 28 | $row = $users->fetchArray(SQLITE3_ASSOC); 29 | if(!$row) break; 30 | 31 | echo json_encode($row); 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /php/date.php: -------------------------------------------------------------------------------- 1 | jan 01 1970 4 | // January 19, 2038 -> 32-bit overflow 5 | 6 | // date($format, $timestamp); 7 | 8 | // echo time(); 9 | // echo date("Y/m/d"); -> 2020/12/05 10 | 11 | // echo date("y/m/d"); -> 20/12/05 12 | 13 | // echo date("Y M D"); -> 2020 Dec Sat 14 | // echo date("F"); -> December 15 | // echo date("l"); -> Saturday 16 | // echo date("N"); -> Current Day Number : 1(mon) - 7(sun) 17 | // echo date("w"); -> Current Day Number : 0(sun) - 6(sat) 18 | // echo date("W"); -> Current Week Number 19 | // echo date("t"); -> Current Month Number 20 | // echo date("z"); -> 339 : day of year 21 | // echo date("L"); -> is leap year 22 | 23 | 24 | 25 | // Time 26 | // echo date("g:i:s a"); -> 5:45:51 pm 27 | // date_default_timezone_set("Asia/Tehran"); 28 | // echo date("g:i:s a"); -> 9:15:51 pm 29 | // echo date("h:i:s a"); -> 09:15:51 pm 30 | // echo date("g:i:s A"); -> 9:15:51 PM 31 | // echo date("G:i:s A"); -> 17:48:29 PM 32 | 33 | // echo date('e'); -> Current Time Zone 34 | // echo date('P'); -> +00:00 35 | 36 | 37 | ////////////// Jalali Date/Time 38 | 39 | 40 | $timezone_identifiers = DateTimeZone::listIdentifiers(); 41 | 42 | foreach($timezone_identifiers as $key => $list){ 43 | 44 | echo $list . "
"; 45 | 46 | } 47 | 48 | date_default_timezone_set ( string $timezone_identifier ); 49 | echo "The time in " . date_default_timezone_get() . " is " . date("H:i:s"); 50 | 51 | date_default_timezone_set("Asia/Calcutta"); 52 | echo "The time in " . date_default_timezone_get() . " is " . date("H:i:s"); 53 | 54 | 55 | 56 | 57 | 58 | // echo time(); // timestamp 59 | // date("format", $timestamp); 60 | 61 | // mktime(1, 2, 3, 4, 5, 2006); // return timestamp 62 | 63 | // checkdate(10, 11, 10); 64 | // checkdate(2, 29, 2014); //false 65 | 66 | getdate($timestamp); 67 | /** 68 | * get a timestamp and return an asc array 69 | * minutes , mdate, mon, ydate, month 70 | */ 71 | 72 | fileatime(); 73 | 74 | filectime(); 75 | 76 | filemtime(); 77 | 78 | basename("path/to/file.txt"); // file.txt 79 | basename("path/to/file.txt", '.txt'); // file 80 | 81 | // dirname('path/to/file') // path/to 82 | 83 | -------------------------------------------------------------------------------- /php/design_patterns/creational/singleton.php: -------------------------------------------------------------------------------- 1 | 7 | // Cc: User2 8 | // X-Priority: 1 (Highest) 9 | // Content-Type: text/html 10 | // "; 11 | // mail("email@gmail.com", "Test Subject", "Hello", $headers); 12 | 13 | 14 | /////////////////// 15 | // PHPMailer 16 | 17 | -------------------------------------------------------------------------------- /php/exception_handling.php: -------------------------------------------------------------------------------- 1 | error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRICATED); 18 | 19 | ini_set('error_reporting', E_ALL); 20 | 21 | 22 | get_defined_vars(); 23 | get_defined_constants(); 24 | get_defined_functions(); 25 | 26 | try {} 27 | catch(Exception $e) {} 28 | finally {} -------------------------------------------------------------------------------- /php/ext/bzip2.php: -------------------------------------------------------------------------------- 1 | '; 8 | 9 | // echo "Filename: ". __FILE__ . '
'; 10 | // echo "Directory: ". __DIR__ . '
'; 11 | // echo "Directory: ". dirname(__FILE__) . '
'; 12 | // echo "Directory: ". dirname(__DIR__) . '
'; 13 | // echo "Directory: ". dirname(dirname(__DIR__)) . '
'; 14 | // echo "Basename File: ". basename(__FILE__) . '
'; 15 | // echo "Basename DIR: ". basename(__DIR__) . '
'; 16 | 17 | // $path_parts = pathinfo(__FILE__); // PATHINFO_EXTENSION, PATHINFO_BASENAME, PATHINFO_DIRNAME, PATHINFO_FILENAME 18 | // echo '
';
 19 | // print_r($path_parts);
 20 | // echo '
'; 21 | 22 | 23 | // $file = __DIR__ . '\\'. 'file.txt'; 24 | // echo $file; 25 | // echo '
';
 26 | // print_r(pathinfo($file));
 27 | // echo '
'; 28 | // if (file_exists($file)) 29 | // echo "exists"; 30 | // else 31 | // echo "no exists"; 32 | 33 | 34 | // is_dir(); 35 | // is_file(); 36 | // filesize(); 37 | // is_readable(); 38 | // is_writeable(); 39 | 40 | // touch('dir/text.txt'); 41 | 42 | // $path = __DIR__ . DIRECTORY_SEPARATOR; 43 | // $newDir = $path . 'newdir/2/images'; 44 | 45 | // function mkdir_if_not_exists($dir) { 46 | // if (!file_exists($dir)) { 47 | // mkdir($dir, 0777, true); 48 | // } 49 | // } 50 | 51 | // function rmdir_if_exists($dir) { 52 | // if (file_exists($dir)) { 53 | // rmdir($dir); 54 | // } 55 | // } 56 | 57 | 58 | 59 | 60 | // $path = dirname(dirname(__DIR__)); 61 | // $files = scandir($path, SCANDIR_SORT_ASCENDING); 62 | // // $files2 = array_diff($files, array('.'.'..')); 63 | 64 | // echo '
';
 65 | // print_r($files);
 66 | // echo '
'; 67 | 68 | 69 | // echo '

Contents:

'; 70 | // $dir = dirname(dirname(__DIR__)); 71 | // $handle = opendir($dir); 72 | // closedir($handle); 73 | 74 | // // echo $handle; 75 | // // var_dump($handle); 76 | 77 | // while(($item = readdir($handle)) !== false) { 78 | 79 | // if(in_array($item, ['.','..'])) continue; 80 | 81 | // $fullpath= $dir . '/' . $item; 82 | // if(is_dir($fullpath)) 83 | // $type = 'Directory'; 84 | // else 85 | // $type = 'File'; 86 | 87 | 88 | // echo '
';
 89 | //     print_r($item . $type);
 90 | //     echo '
'; 91 | // } 92 | 93 | 94 | // closedir($handle); 95 | 96 | 97 | // glob(pattern, flag); 98 | 99 | // copy('x.txt', 'x.txt.bak'); 100 | // rename('oldname','newname'); 101 | // unlink('path'); 102 | // rmdir('dir'); 103 | // echo getcwd(); 104 | // fseek($handle, $offset, $flag); // SEEK_SET | SEEK_CUR | SEEK_END 105 | // ftell($handle); 106 | // rewind($handle); 107 | 108 | // chmod(path, code); // Change Modification 109 | // chown(); // Change Owner 110 | // chgrp(); // Change Group 111 | 112 | // echo filegroup('file'); 113 | 114 | 115 | // $lines = file('https://google.com/'); 116 | // foreach($lines as $line) { 117 | // echo $line; 118 | // } 119 | 120 | 121 | // $file = __DIR__ . '\\' . 'file.txt'; 122 | // // $lines = file($file); 123 | // // foreach($lines as $line) { 124 | // // echo $line . '
'; 125 | // // } 126 | 127 | // $content = file_get_contents($file); 128 | // var_dump($content); 129 | 130 | // file_put_contents($file, '\r\nThis Thirth Line', FILE_APPEND); 131 | 132 | 133 | 134 | 135 | // $data = ['abc', 12, 'this is test']; 136 | // file_put_contents($file, serialize($data)); 137 | 138 | // $d = unserialize(file_get_contents($file)); 139 | 140 | // json_encode(); 141 | // json_decode(); 142 | 143 | 144 | /////////////// 145 | // $file = __DIR__ . '\\' . 'file.txt'; 146 | // $handle = fopen($file, 'r'); 147 | // if($handle === false) die("Thi file cannot be openned."); 148 | // $data = fread($handle, 6); 149 | // echo $data; 150 | 151 | // $line = fgets($handle); 152 | // echo $line; 153 | 154 | // fgetc(); 155 | // fgetcsv(); 156 | // fgets(); 157 | 158 | // file(); // return array contains lines 159 | // FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES 160 | 161 | // $bytes = readfile(); 162 | 163 | 164 | // while(true) { 165 | // $line = fgets($handle); 166 | // if( $line === false) break; 167 | // echo $line; 168 | // } 169 | 170 | 171 | // while(($line = fgets($handle)) !== false) { 172 | // if( $line === false) break; 173 | // echo $line; 174 | // } 175 | 176 | // header('Content-Type: text/txt'); 177 | // while(!feof($handle)) { 178 | // $line = fgets($handle); 179 | // $line = str_replace(['\r', '\n'], '', $line); 180 | // echo $line; 181 | // } 182 | 183 | // fclose($handle); 184 | 185 | 186 | 187 | 188 | ///////////////////////// Write File 189 | 190 | // $file = __DIR__ . '\\' . 'file.txt'; 191 | // $handle = fopen($file, 'w'); 192 | // if($handle === false) die("Thi file cannot be openned."); 193 | 194 | // $data = 'this new data'; 195 | // fwrite($handle, $data); 196 | // fputs($handle, 'f'); 197 | 198 | // fclose($handle); 199 | 200 | 201 | //////////////// Temp File 202 | 203 | // echo 'Temp Dir: '. sys_get_temp_dir() . '
'; 204 | 205 | // $handle = tmpfile(); 206 | // fwrite($handle, "Write Test"); 207 | // fseek($handle, 0); 208 | // echo fread($handle, 1024); 209 | // fclose($handle); 210 | 211 | // $dir = sys_get_temp_dir(); 212 | // $filename = tempnam($dir, 'px-'); 213 | // $filename2 =$dir . DIRECTORY_SEPARATOR . uniqid("TestPrefix-") . '.tmp'; 214 | 215 | // echo $filename; 216 | 217 | 218 | // if allow_url_fopen in php.init in on can open remote files 219 | 220 | ////////////////////////// CSV 221 | 222 | // $handle = fopen('test.csv', 'w'); 223 | 224 | // $arrValues = array( 225 | // 'name,age,email', 226 | // 'milad,19,milad@gmail.com', 227 | // 'ali,14,ali@gmail.com', 228 | // 'amir,24,amir@gmail.com', 229 | // 'mani,17,mani@gmail.com', 230 | // ); 231 | // foreach($arrValues as $line) { 232 | // fputcsv($handle, explode(',', $line)); 233 | // } 234 | 235 | // fclose($handle); 236 | 237 | //////// 238 | 239 | // $handle = fopen('test.csv', 'r') or die("Failed to create file"); 240 | 241 | // while($line = fgetcsv($handle, 0, ',')) { 242 | 243 | // } 244 | // fclose($handle); 245 | 246 | 247 | 248 | // $file_name_csv = "myscvfile.csv"; 249 | // $fp = fopen($file_name_csv, 'w'); 250 | 251 | // fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF)); 252 | // fputcsv($fp, array("firstName", "lastName")); 253 | 254 | // fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF)); 255 | // fputcsv($fp, array("Amir", "Shokri")); 256 | 257 | // fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF)); 258 | // fputcsv($fp, array("John", "Due")); 259 | 260 | // fclose($fp); 261 | 262 | -------------------------------------------------------------------------------- /php/flintstone/flintstone.php: -------------------------------------------------------------------------------- 1 | getcwd(), 10 | 'ext' => '.db', 11 | 'gzip' => false, 12 | 'cache' => true, 13 | 'formatter' => new JsonFormatter(), 14 | ]; 15 | 16 | $flintstone_users = new Flintstone('users', $options); 17 | 18 | $user1 = [ 19 | 'username' => 'admin', 20 | 'password' => '4321' 21 | ]; 22 | 23 | $flintstone_users->set('1', $user1); 24 | 25 | $flintstone_users->set('2', [ 26 | 'username' => 'writer', 27 | '1234' 28 | ]); 29 | 30 | // echo json_encode($flintstone_users->get('1')); 31 | 32 | // echo json_encode($flintstone_users->delete('1')); 33 | 34 | // echo json_encode($flintstone_users->getAll()); 35 | 36 | // var_export($flintstone_users->getKeys()); 37 | // echo count($flintstone_users->getKeys()); 38 | 39 | // var_export($flintstone_users->flush()); 40 | 41 | 42 | -------------------------------------------------------------------------------- /php/flintstone/users.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/php/flintstone/users.db -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Cache/ArrayCache.php: -------------------------------------------------------------------------------- 1 | cache); 20 | } 21 | 22 | /** 23 | * {@inheritdoc} 24 | */ 25 | public function get($key) 26 | { 27 | return $this->cache[$key]; 28 | } 29 | 30 | /** 31 | * {@inheritdoc} 32 | */ 33 | public function set($key, $data) 34 | { 35 | $this->cache[$key] = $data; 36 | } 37 | 38 | /** 39 | * {@inheritdoc} 40 | */ 41 | public function delete($key) 42 | { 43 | unset($this->cache[$key]); 44 | } 45 | 46 | /** 47 | * {@inheritdoc} 48 | */ 49 | public function flush() 50 | { 51 | $this->cache = []; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Cache/CacheInterface.php: -------------------------------------------------------------------------------- 1 | normalizeConfig($config); 27 | $this->setDir($config['dir']); 28 | $this->setExt($config['ext']); 29 | $this->setGzip($config['gzip']); 30 | $this->setCache($config['cache']); 31 | $this->setFormatter($config['formatter']); 32 | $this->setSwapMemoryLimit($config['swap_memory_limit']); 33 | } 34 | 35 | /** 36 | * Normalize the user supplied config. 37 | * 38 | * @param array $config 39 | * 40 | * @return array 41 | */ 42 | protected function normalizeConfig(array $config): array 43 | { 44 | $defaultConfig = [ 45 | 'dir' => getcwd(), 46 | 'ext' => '.dat', 47 | 'gzip' => false, 48 | 'cache' => true, 49 | 'formatter' => null, 50 | 'swap_memory_limit' => 2097152, // 2MB 51 | ]; 52 | 53 | return array_replace($defaultConfig, $config); 54 | } 55 | 56 | /** 57 | * Get the dir. 58 | * 59 | * @return string 60 | */ 61 | public function getDir(): string 62 | { 63 | return $this->config['dir']; 64 | } 65 | 66 | /** 67 | * Set the dir. 68 | * 69 | * @param string $dir 70 | * 71 | * @throws Exception 72 | */ 73 | public function setDir(string $dir) 74 | { 75 | if (!is_dir($dir)) { 76 | throw new Exception('Directory does not exist: ' . $dir); 77 | } 78 | 79 | $this->config['dir'] = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR; 80 | } 81 | 82 | /** 83 | * Get the ext. 84 | * 85 | * @return string 86 | */ 87 | public function getExt(): string 88 | { 89 | if ($this->useGzip()) { 90 | return $this->config['ext'] . '.gz'; 91 | } 92 | 93 | return $this->config['ext']; 94 | } 95 | 96 | /** 97 | * Set the ext. 98 | * 99 | * @param string $ext 100 | */ 101 | public function setExt(string $ext) 102 | { 103 | if (substr($ext, 0, 1) !== '.') { 104 | $ext = '.' . $ext; 105 | } 106 | 107 | $this->config['ext'] = $ext; 108 | } 109 | 110 | /** 111 | * Use gzip? 112 | * 113 | * @return bool 114 | */ 115 | public function useGzip(): bool 116 | { 117 | return $this->config['gzip']; 118 | } 119 | 120 | /** 121 | * Set gzip. 122 | * 123 | * @param bool $gzip 124 | */ 125 | public function setGzip(bool $gzip) 126 | { 127 | $this->config['gzip'] = $gzip; 128 | } 129 | 130 | /** 131 | * Get the cache. 132 | * 133 | * @return CacheInterface|false 134 | */ 135 | public function getCache() 136 | { 137 | return $this->config['cache']; 138 | } 139 | 140 | /** 141 | * Set the cache. 142 | * 143 | * @param mixed $cache 144 | * 145 | * @throws Exception 146 | */ 147 | public function setCache($cache) 148 | { 149 | if (!is_bool($cache) && !$cache instanceof CacheInterface) { 150 | throw new Exception('Cache must be a boolean or an instance of Flintstone\Cache\CacheInterface'); 151 | } 152 | 153 | if ($cache === true) { 154 | $cache = new ArrayCache(); 155 | } 156 | 157 | $this->config['cache'] = $cache; 158 | } 159 | 160 | /** 161 | * Get the formatter. 162 | * 163 | * @return FormatterInterface 164 | */ 165 | public function getFormatter(): FormatterInterface 166 | { 167 | return $this->config['formatter']; 168 | } 169 | 170 | /** 171 | * Set the formatter. 172 | * 173 | * @param FormatterInterface|null $formatter 174 | * 175 | * @throws Exception 176 | */ 177 | public function setFormatter($formatter) 178 | { 179 | if ($formatter === null) { 180 | $formatter = new SerializeFormatter(); 181 | } 182 | 183 | if (!$formatter instanceof FormatterInterface) { 184 | throw new Exception('Formatter must be an instance of Flintstone\Formatter\FormatterInterface'); 185 | } 186 | 187 | $this->config['formatter'] = $formatter; 188 | } 189 | 190 | /** 191 | * Get the swap memory limit. 192 | * 193 | * @return int 194 | */ 195 | public function getSwapMemoryLimit(): int 196 | { 197 | return $this->config['swap_memory_limit']; 198 | } 199 | 200 | /** 201 | * Set the swap memory limit. 202 | * 203 | * @param int $limit 204 | */ 205 | public function setSwapMemoryLimit(int $limit) 206 | { 207 | $this->config['swap_memory_limit'] = $limit; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Database.php: -------------------------------------------------------------------------------- 1 | [ 38 | 'mode' => 'rb', 39 | 'operation' => LOCK_SH, 40 | ], 41 | self::FILE_WRITE => [ 42 | 'mode' => 'wb', 43 | 'operation' => LOCK_EX, 44 | ], 45 | self::FILE_APPEND => [ 46 | 'mode' => 'ab', 47 | 'operation' => LOCK_EX, 48 | ], 49 | ]; 50 | 51 | /** 52 | * Database name. 53 | * 54 | * @var string 55 | */ 56 | protected $name; 57 | 58 | /** 59 | * Config class. 60 | * 61 | * @var Config 62 | */ 63 | protected $config; 64 | 65 | /** 66 | * Constructor. 67 | * 68 | * @param string $name 69 | * @param Config|null $config 70 | */ 71 | public function __construct(string $name, Config $config = null) 72 | { 73 | $this->setName($name); 74 | 75 | if ($config) { 76 | $this->setConfig($config); 77 | } 78 | } 79 | 80 | /** 81 | * Get the database name. 82 | * 83 | * @return string 84 | */ 85 | public function getName(): string 86 | { 87 | return $this->name; 88 | } 89 | 90 | /** 91 | * Set the database name. 92 | * 93 | * @param string $name 94 | * 95 | * @throws Exception 96 | */ 97 | public function setName(string $name) 98 | { 99 | Validation::validateDatabaseName($name); 100 | $this->name = $name; 101 | } 102 | 103 | /** 104 | * Get the config. 105 | * 106 | * @return Config 107 | */ 108 | public function getConfig(): Config 109 | { 110 | return $this->config; 111 | } 112 | 113 | /** 114 | * Set the config. 115 | * 116 | * @param Config $config 117 | */ 118 | public function setConfig(Config $config) 119 | { 120 | $this->config = $config; 121 | } 122 | 123 | /** 124 | * Get the path to the database file. 125 | * 126 | * @return string 127 | */ 128 | public function getPath(): string 129 | { 130 | return $this->config->getDir() . $this->getName() . $this->config->getExt(); 131 | } 132 | 133 | /** 134 | * Open the database file. 135 | * 136 | * @param int $mode 137 | * 138 | * @throws Exception 139 | * 140 | * @return SplFileObject 141 | */ 142 | protected function openFile(int $mode): SplFileObject 143 | { 144 | $path = $this->getPath(); 145 | 146 | if (!is_file($path) && !@touch($path)) { 147 | throw new Exception('Could not create file: ' . $path); 148 | } 149 | 150 | if (!is_readable($path) || !is_writable($path)) { 151 | throw new Exception('File does not have permission for read and write: ' . $path); 152 | } 153 | 154 | if ($this->getConfig()->useGzip()) { 155 | $path = 'compress.zlib://' . $path; 156 | } 157 | 158 | $res = $this->fileAccessMode[$mode]; 159 | $file = new SplFileObject($path, $res['mode']); 160 | 161 | if ($mode === self::FILE_READ) { 162 | $file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD); 163 | } 164 | 165 | if (!$this->getConfig()->useGzip() && !$file->flock($res['operation'])) { 166 | $file = null; 167 | throw new Exception('Could not lock file: ' . $path); 168 | } 169 | 170 | return $file; 171 | } 172 | 173 | /** 174 | * Open a temporary file. 175 | * 176 | * @return SplTempFileObject 177 | */ 178 | public function openTempFile(): SplTempFileObject 179 | { 180 | return new SplTempFileObject($this->getConfig()->getSwapMemoryLimit()); 181 | } 182 | 183 | /** 184 | * Close the database file. 185 | * 186 | * @param SplFileObject $file 187 | * 188 | * @throws Exception 189 | */ 190 | protected function closeFile(SplFileObject &$file) 191 | { 192 | if (!$this->getConfig()->useGzip() && !$file->flock(LOCK_UN)) { 193 | $file = null; 194 | throw new Exception('Could not unlock file'); 195 | } 196 | 197 | $file = null; 198 | } 199 | 200 | /** 201 | * Read lines from the database file. 202 | * 203 | * @return \Generator 204 | */ 205 | public function readFromFile(): \Generator 206 | { 207 | $file = $this->openFile(static::FILE_READ); 208 | 209 | try { 210 | foreach ($file as $line) { 211 | yield new Line($line); 212 | } 213 | } finally { 214 | $this->closeFile($file); 215 | } 216 | } 217 | 218 | /** 219 | * Append a line to the database file. 220 | * 221 | * @param string $line 222 | */ 223 | public function appendToFile(string $line) 224 | { 225 | $file = $this->openFile(static::FILE_APPEND); 226 | $file->fwrite($line); 227 | $this->closeFile($file); 228 | } 229 | 230 | /** 231 | * Flush the database file. 232 | */ 233 | public function flushFile() 234 | { 235 | $file = $this->openFile(static::FILE_WRITE); 236 | $this->closeFile($file); 237 | } 238 | 239 | /** 240 | * Write temporary file contents to database file. 241 | * 242 | * @param SplTempFileObject $tmpFile 243 | */ 244 | public function writeTempToFile(SplTempFileObject &$tmpFile) 245 | { 246 | $file = $this->openFile(static::FILE_WRITE); 247 | 248 | foreach ($tmpFile as $line) { 249 | $file->fwrite($line); 250 | } 251 | 252 | $this->closeFile($file); 253 | $tmpFile = null; 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Exception.php: -------------------------------------------------------------------------------- 1 | setDatabase($database); 45 | $this->setConfig($config); 46 | } 47 | 48 | /** 49 | * Get the database. 50 | * 51 | * @return Database 52 | */ 53 | public function getDatabase(): Database 54 | { 55 | return $this->database; 56 | } 57 | 58 | /** 59 | * Set the database. 60 | * 61 | * @param Database $database 62 | */ 63 | public function setDatabase(Database $database) 64 | { 65 | $this->database = $database; 66 | } 67 | 68 | /** 69 | * Get the config. 70 | * 71 | * @return Config 72 | */ 73 | public function getConfig(): Config 74 | { 75 | return $this->config; 76 | } 77 | 78 | /** 79 | * Set the config. 80 | * 81 | * @param Config $config 82 | */ 83 | public function setConfig(Config $config) 84 | { 85 | $this->config = $config; 86 | $this->getDatabase()->setConfig($config); 87 | } 88 | 89 | /** 90 | * Get a key from the database. 91 | * 92 | * @param string $key 93 | * 94 | * @return mixed 95 | */ 96 | public function get(string $key) 97 | { 98 | Validation::validateKey($key); 99 | 100 | // Fetch the key from cache 101 | if ($cache = $this->getConfig()->getCache()) { 102 | if ($cache->contains($key)) { 103 | return $cache->get($key); 104 | } 105 | } 106 | 107 | // Fetch the key from database 108 | $file = $this->getDatabase()->readFromFile(); 109 | $data = false; 110 | 111 | foreach ($file as $line) { 112 | /** @var Line $line */ 113 | if ($line->getKey() == $key) { 114 | $data = $this->decodeData($line->getData()); 115 | break; 116 | } 117 | } 118 | 119 | // Save the data to cache 120 | if ($cache && $data !== false) { 121 | $cache->set($key, $data); 122 | } 123 | 124 | return $data; 125 | } 126 | 127 | /** 128 | * Set a key in the database. 129 | * 130 | * @param string $key 131 | * @param mixed $data 132 | */ 133 | public function set(string $key, $data) 134 | { 135 | Validation::validateKey($key); 136 | 137 | // If the key already exists we need to replace it 138 | if ($this->get($key) !== false) { 139 | $this->replace($key, $data); 140 | return; 141 | } 142 | 143 | // Write the key to the database 144 | $this->getDatabase()->appendToFile($this->getLineString($key, $data)); 145 | 146 | // Delete the key from cache 147 | if ($cache = $this->getConfig()->getCache()) { 148 | $cache->delete($key); 149 | } 150 | } 151 | 152 | /** 153 | * Delete a key from the database. 154 | * 155 | * @param string $key 156 | */ 157 | public function delete(string $key) 158 | { 159 | Validation::validateKey($key); 160 | 161 | if ($this->get($key) !== false) { 162 | $this->replace($key, false); 163 | } 164 | } 165 | 166 | /** 167 | * Flush the database. 168 | */ 169 | public function flush() 170 | { 171 | $this->getDatabase()->flushFile(); 172 | 173 | // Flush the cache 174 | if ($cache = $this->getConfig()->getCache()) { 175 | $cache->flush(); 176 | } 177 | } 178 | 179 | /** 180 | * Get all keys from the database. 181 | * 182 | * @return array 183 | */ 184 | public function getKeys(): array 185 | { 186 | $keys = []; 187 | $file = $this->getDatabase()->readFromFile(); 188 | 189 | foreach ($file as $line) { 190 | /** @var Line $line */ 191 | $keys[] = $line->getKey(); 192 | } 193 | 194 | return $keys; 195 | } 196 | 197 | /** 198 | * Get all data from the database. 199 | * 200 | * @return array 201 | */ 202 | public function getAll(): array 203 | { 204 | $data = []; 205 | $file = $this->getDatabase()->readFromFile(); 206 | 207 | foreach ($file as $line) { 208 | /** @var Line $line */ 209 | $data[$line->getKey()] = $this->decodeData($line->getData()); 210 | } 211 | 212 | return $data; 213 | } 214 | 215 | /** 216 | * Replace a key in the database. 217 | * 218 | * @param string $key 219 | * @param mixed $data 220 | */ 221 | protected function replace(string $key, $data) 222 | { 223 | // Write a new database to a temporary file 224 | $tmpFile = $this->getDatabase()->openTempFile(); 225 | $file = $this->getDatabase()->readFromFile(); 226 | 227 | foreach ($file as $line) { 228 | /** @var Line $line */ 229 | if ($line->getKey() == $key) { 230 | if ($data !== false) { 231 | $tmpFile->fwrite($this->getLineString($key, $data)); 232 | } 233 | } else { 234 | $tmpFile->fwrite($line->getLine() . "\n"); 235 | } 236 | } 237 | 238 | $tmpFile->rewind(); 239 | 240 | // Overwrite the database with the temporary file 241 | $this->getDatabase()->writeTempToFile($tmpFile); 242 | 243 | // Delete the key from cache 244 | if ($cache = $this->getConfig()->getCache()) { 245 | $cache->delete($key); 246 | } 247 | } 248 | 249 | /** 250 | * Get the line string to write. 251 | * 252 | * @param string $key 253 | * @param mixed $data 254 | * 255 | * @return string 256 | */ 257 | protected function getLineString(string $key, $data): string 258 | { 259 | return $key . '=' . $this->encodeData($data) . "\n"; 260 | } 261 | 262 | /** 263 | * Decode a string into data. 264 | * 265 | * @param string $data 266 | * 267 | * @return mixed 268 | */ 269 | protected function decodeData(string $data) 270 | { 271 | return $this->getConfig()->getFormatter()->decode($data); 272 | } 273 | 274 | /** 275 | * Encode data into a string. 276 | * 277 | * @param mixed $data 278 | * 279 | * @return string 280 | */ 281 | protected function encodeData($data): string 282 | { 283 | return $this->getConfig()->getFormatter()->encode($data); 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Formatter/FormatterInterface.php: -------------------------------------------------------------------------------- 1 | assoc = $assoc; 17 | } 18 | 19 | /** 20 | * {@inheritdoc} 21 | */ 22 | public function encode($data): string 23 | { 24 | $result = json_encode($data); 25 | 26 | if (json_last_error() === JSON_ERROR_NONE) { 27 | return $result; 28 | } 29 | 30 | throw new Exception(json_last_error_msg()); 31 | } 32 | 33 | /** 34 | * {@inheritdoc} 35 | */ 36 | public function decode(string $data) 37 | { 38 | $result = json_decode($data, $this->assoc); 39 | 40 | if (json_last_error() === JSON_ERROR_NONE) { 41 | return $result; 42 | } 43 | 44 | throw new Exception(json_last_error_msg()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Formatter/SerializeFormatter.php: -------------------------------------------------------------------------------- 1 | preserveLines($data, false)); 13 | } 14 | 15 | /** 16 | * {@inheritdoc} 17 | */ 18 | public function decode(string $data) 19 | { 20 | return $this->preserveLines(unserialize($data), true); 21 | } 22 | 23 | /** 24 | * Preserve new lines, recursive function. 25 | * 26 | * @param mixed $data 27 | * @param bool $reverse 28 | * 29 | * @return mixed 30 | */ 31 | protected function preserveLines($data, bool $reverse) 32 | { 33 | $search = ["\n", "\r"]; 34 | $replace = ['\\n', '\\r']; 35 | 36 | if ($reverse) { 37 | $search = ['\\n', '\\r']; 38 | $replace = ["\n", "\r"]; 39 | } 40 | 41 | if (is_string($data)) { 42 | $data = str_replace($search, $replace, $data); 43 | } elseif (is_array($data)) { 44 | foreach ($data as &$value) { 45 | $value = $this->preserveLines($value, $reverse); 46 | } 47 | unset($value); 48 | } 49 | 50 | return $data; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Line.php: -------------------------------------------------------------------------------- 1 | line = $line; 20 | $this->pieces = explode('=', $line, 2); 21 | } 22 | 23 | public function getLine(): string 24 | { 25 | return $this->line; 26 | } 27 | 28 | public function getKey(): string 29 | { 30 | return $this->pieces[0]; 31 | } 32 | 33 | public function getData(): string 34 | { 35 | return $this->pieces[1]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /php/flintstone/vendor/flintstone/Validation.php: -------------------------------------------------------------------------------- 1 | "; 89 | 90 | if(!is_numeric($patternType) || $patternType < 0 || $patternType > 4) 91 | $patternType = 4; 92 | 93 | $pettern = $small_alphabet . $big_alphabet . $number . $characters; 94 | if($patternType == 1) 95 | $pettern = $small_alphabet; 96 | elseif($patternType == 2) 97 | $pattern = $small_alphabet . $big_alphabet; 98 | elseif($patternType == 3) 99 | $pattern = $small_alphabet . $big_alphabet . $number; 100 | elseif($patternType == 4) 101 | $pattern = $small_alphabet . $big_alphabet . $number . $characters; 102 | else 103 | $pattern = $small_alphabet . $big_alphabet . $number . $characters; 104 | 105 | for ($i = 0; $i < $length; $i++) { 106 | $n = rand(0, strlen($pettern) - 1); 107 | $result[$i] = $pettern[$n]; 108 | } 109 | 110 | return substr(implode('', $result), 0, $length); 111 | } 112 | 113 | } 114 | 115 | $strongPassword = new strongPassword(); 116 | echo "$strongPassword->randomText(5) :
" . $strongPassword->randomText(5) . "

"; 117 | echo "$strongPassword->randomText(20, 1) :
" . $strongPassword->randomText(20, 1) . "

"; 118 | echo "$strongPassword->randomText(30, 2) :
" . $strongPassword->randomText(30, 2) . "

"; 119 | echo "$strongPassword->randomText(40, 3) :
" . $strongPassword->randomText(40, 3) . "

"; 120 | echo "$strongPassword->randomText(50, 4) :
" . $strongPassword->randomText(50, 4) . "

"; 121 | -------------------------------------------------------------------------------- /php/gd/captcha.php: -------------------------------------------------------------------------------- 1 | 57 and $ascii < 65); 10 | $chars[$i] = chr($ascii); 11 | } 12 | 13 | $code = $chars[0] . $chars[1] . $chars[2] . $chars[3] . $chars[4]; 14 | $_SESSION['captcha'] = $code; 15 | $image = imagecreate(120, 40); 16 | $green = imagecolorallocate($image, 100, 255, 100); 17 | for($i=0; $i<5;$i++) { 18 | $angel = rand(-20,20); 19 | $size = rand(18, 22); 20 | $space = 22; 21 | $height = rand(25,33); 22 | $color = imagecolorallocate($image, rand(0,255), rand(0,100), rand(0,255)); 23 | imagefttext($image, $size, $angel, $i * $space + 5, $height, $color, "centaur.TTF", $chars[$i]); 24 | imageline($image, rand(0, 119), rand(0, 39), rand(0, 119), rand(0,39), $color); 25 | } 26 | 27 | imagepng($image); -------------------------------------------------------------------------------- /php/gd/gd.php: -------------------------------------------------------------------------------- 1 | =')) { 21 | // spl_autoload_register('myAutoloader'); 22 | // } else { 23 | // // function __autoload($className) { 24 | // // require("lib/$className"); 25 | // // } 26 | // } 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /php/output_buffering.php: -------------------------------------------------------------------------------- 1 | '; 70 | echo ' isset($num) ' . isset($var) . '.
'; 71 | echo ' is_int($num) ' . is_int($var) . '.
'; 72 | echo ' is_float($num) ' . is_float($var) . '.
'; 73 | echo ' is_numeric($num) ' . is_numeric($var) . '.
'; 74 | echo ' is_string($num) ' . is_string($var) . '.
'; 75 | echo ' is_array($num) ' . is_array($var) . '.
'; 76 | echo ' is_bool($num) ' . is_bool($var) . '.
'; 77 | echo ' is_object($num) ' . is_object($var) . '.
'; 78 | echo ' is_null($num) ' . is_null($var) . '.
'; 79 | echo ' empty($num) ' . empty($var) . '.
'; 80 | 81 | 82 | // Operators 83 | 84 | 85 | /* Arithmetic Operators 86 | 87 | Example Name Result 88 | +$a Identity Conversion of $a to int or float as appropriate. 89 | -$a Negation Opposite of $a. 90 | $a + $b Addition Sum of $a and $b. 91 | $a - $b Difference of $a and $b. 92 | $a * $b Multiplication Product of $a and $b. 93 | $a / $b Division Quotient of $a and $b. 94 | $a % $b Modulo Remainder of $a divided by $b. 95 | $a ** $b Exponentiation Result of raising $a to the $b'th power. 96 | 97 | */ 98 | 99 | echo (5 % 3)."\n"; // prints 2 100 | echo (5 % -3)."\n"; // prints 2 101 | echo (-5 % 3)."\n"; // prints -2 102 | echo (-5 % -3)."\n"; // prints -2 103 | 104 | 105 | /* Assignment Operators 106 | 107 | Example Same as... Description 108 | x = y x = y The left operand gets set to the value of the expression on the right 109 | x += y x = x + y Addition 110 | x -= y x = x - y Subtraction 111 | x *= y x = x * y Multiplication 112 | x /= y x = x / y Division 113 | x %= y x = x % y Modulus 114 | 115 | */ 116 | 117 | $a = 3; 118 | $a += 5; // sets $a to 8, as if we had said: $a = $a + 5; 119 | $b = "Hello "; 120 | $b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!"; 121 | 122 | 123 | /* Comparison Operators 124 | 125 | Operator Name Example Result 126 | == Equal $x == $y Returns true if $x is equal to $y 127 | === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type 128 | != Not equal $x != $y Returns true if $x is not equal to $y 129 | <> Not equal $x <> $y Returns true if $x is not equal to $y 130 | !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type 131 | > Greater than $x > $y Returns true if $x is greater than $y 132 | < Less than $x < $y Returns true if $x is less than $y 133 | >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y 134 | <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y 135 | <=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7. 136 | 137 | */ 138 | 139 | /* Increment / Decrement Operators 140 | 141 | Operator Name Description 142 | ++$x Pre-increment Increments $x by one, then returns $x 143 | $x++ Post-increment Returns $x, then increments $x by one 144 | --$x Pre-decrement Decrements $x by one, then returns $x 145 | $x-- Post-decrement Returns $x, then decrements $x by one 146 | 147 | */ 148 | 149 | /* Logical Operators 150 | 151 | Operator Name Example Result 152 | and And $x and $y True if both $x and $y are true 153 | or Or $x or $y True if either $x or $y is true 154 | xor Xor $x xor $y True if either $x or $y is true, but not both 155 | && And $x && $y True if both $x and $y are true 156 | || Or $x || $y True if either $x or $y is true 157 | ! Not !$x True if $x is not true 158 | 159 | */ 160 | 161 | /* String Operators 162 | 163 | Operator Name Example Result 164 | . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 165 | .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1 166 | 167 | */ 168 | 169 | 170 | /* Conditional Assignment Operators 171 | 172 | Operator Name Example Result 173 | ?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x. 174 | The value of $x is expr2 if expr1 = TRUE. 175 | The value of $x is expr3 if expr1 = FALSE 176 | ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x. 177 | The value of $x is expr1 if expr1 exists, and is not NULL. 178 | If expr1 does not exist, or is NULL, the value of $x is expr2. 179 | Introduced in PHP 7 180 | 181 | */ 182 | 183 | $x = ($a > 0) ? 1: 0; 184 | 185 | 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /php/reflections.php: -------------------------------------------------------------------------------- 1 | Guru', $text); 36 | 37 | echo $text; 38 | 39 | 40 | 41 | $my_email = "name@company.com"; 42 | if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/", $my_email)) { 43 | echo "$my_email is a valid email address"; 44 | } 45 | else 46 | { 47 | echo "$my_email is NOT a valid email address"; 48 | } 49 | -------------------------------------------------------------------------------- /php/sessions.php: -------------------------------------------------------------------------------- 1 | '; // e 10 | 11 | // echo strlen($str) . '
'; 12 | 13 | $strArr = str_split($str, 2); 14 | // echo '
';
 15 | // print_r($strArr);
 16 | // echo '
'; 17 | 18 | $hereDoc = <<'; 44 | // echo strtoupper($str) . '
'; 45 | // echo strrev($str) . '
'; 46 | 47 | // echo strpos($str, 'o') . '
'; 48 | // echo strrpos($str, 'o') . '
'; 49 | // echo stripos($str, 'o') . '
'; 50 | // echo strripos($str, 'o') . '
'; 51 | 52 | trim($str); 53 | rtrim($str); 54 | ltrim($str); 55 | 56 | 57 | $firstSpace = strpos($str, ' '); 58 | $secondSpace = strpos($str, ' ', $firstSpace + 1); 59 | 60 | // echo substr($str, 2, 5) . '
'; 61 | // echo substr($str, 2) . '
'; 62 | // echo substr($str, 3, -5) . '
'; 63 | 64 | str_replace("is", "was", $str); 65 | str_replace("is", "was", $str); 66 | 67 | 68 | substr_count($str, 'rl'); 69 | substr_count($str, 'rl', 3); 70 | substr_count($str, 'rl', 3, 5); 71 | 72 | substr_replace($str, 'new', 0); 73 | substr_replace($str, 'new', 0, 10); 74 | substr_replace($str, 'new', 0, 0); 75 | substr_replace($str, 'new', 3, 0); 76 | 77 | 78 | str_repeat('-', 10); 79 | 80 | // printf('This is str: %s', $str); 81 | // $r = sprintf('This is str: %s', $str); 82 | 83 | // $sf = '29 Esfand 1329'; 84 | // $res = sscanf($sf, '%d %s %d'); 85 | 86 | // list($day, $month, $year) = sscanf($sf, '%d %s %d'); 87 | 88 | // echo '
';
 89 | // print_r($res);
 90 | // echo '
'; 91 | 92 | 93 | $html = "

this is test html

"; 94 | htmlspecialchars($html); 95 | /* Second arg: ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES */ 96 | 97 | // htmlentities($html); 98 | 99 | strip_tags($html); // delete html tags from string 100 | // seconda args: tags that do not removed 101 | 102 | 103 | $url = 'http:://google.com'; 104 | urlencode($url); 105 | urldecode($url); 106 | 107 | rawurlencode($url); 108 | rawurldecode($url); 109 | 110 | // just different between urlencode and rawurlencode is space 111 | 112 | $path = "PHP is cool"; 113 | $pathEncoded = urlencode($path); 114 | $url = "https://google.com/?q=".$pathEncoded; 115 | 116 | 117 | $s = 'd,d2,d3'; 118 | explode(',', $s); 119 | explode(',', $s, 2); 120 | 121 | $a= ["c", "c1", "c2"]; 122 | implode(',', $a); -------------------------------------------------------------------------------- /php/supper_globals.php: -------------------------------------------------------------------------------- 1 | '; 5 | // print_r($_SERVER); 6 | echo ''; 7 | 8 | /* 9 | Array 10 | ( 11 | [DOCUMENT_ROOT] => C:\path\mycheatsheets 12 | [REMOTE_ADDR] => ::1 13 | [REMOTE_PORT] => 7981 14 | [SERVER_SOFTWARE] => PHP 7.4.9 Development Server 15 | [SERVER_PROTOCOL] => HTTP/1.1 16 | [SERVER_NAME] => localhost 17 | [SERVER_PORT] => 3000 18 | [REQUEST_URI] => /php/supper_globals.php 19 | [REQUEST_METHOD] => GET 20 | [SCRIPT_NAME] => /php/supper_globals.php 21 | [SCRIPT_FILENAME] => C:\path\mycheatsheets\php\supper_globals.php 22 | [PHP_SELF] => /php/supper_globals.php 23 | [HTTP_HOST] => localhost:3000 24 | [HTTP_CONNECTION] => keep-alive 25 | [HTTP_CACHE_CONTROL] => max-age=0 26 | [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 27 | [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36 28 | [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*//*;q=0.8,application/signed-exchange;v=b3;q=0.9 29 | [HTTP_SEC_FETCH_SITE] => none 30 | [HTTP_SEC_FETCH_MODE] => navigate 31 | [HTTP_SEC_FETCH_USER] => ?1 32 | [HTTP_SEC_FETCH_DEST] => document 33 | [HTTP_ACCEPT_ENCODING] => gzip, deflate, br 34 | [HTTP_ACCEPT_LANGUAGE] => fa-IR,fa;q=0.9,he-IL;q=0.8,he;q=0.7,tr-TR;q=0.6,tr;q=0.5,en-US;q=0.4,en;q=0.3 35 | [REQUEST_TIME_FLOAT] => 1606477552.7485 36 | [REQUEST_TIME] => 1606477552 37 | ) 38 | */ 39 | 40 | echo '__LINE__ = ' . __LINE__ . '
'; 41 | echo '__DIR__ = ' . __DIR__ . '
'; 42 | echo '__FILE__ = ' . __FILE__ . '
'; 43 | echo 'dirname(__FILE__) = ' . dirname(__FILE__) . '
'; 44 | 45 | func(); 46 | 47 | 48 | function func () { 49 | echo '__FUNCTION__ = ' . __FUNCTION__ . '
'; 50 | } 51 | 52 | /* 53 | __CLASS__ : The currnet Class 54 | __METHOD__ : The currnet Method of Class 55 | __NAMESPACE__ : The currnet Namespace 56 | __TRAIT__ : The currnet Trait 57 | 58 | */ 59 | echo '
';
60 | print_r($_GET);
61 | print_r($_POST);
62 | print_r($_REQUEST);
63 | echo '
'; 64 | 65 | echo 'Hello '. $_GET['name'] ; 66 | 67 | 68 | $text = 'i Like Php'; 69 | $encoded = urlencode($text); 70 | $decoded = urldecode($text); 71 | 72 | $tag = ' Link '; 73 | $a = htmlentities($text); 74 | $b = html_entity_decode($a); 75 | 76 | $c = htmlspecialchars($tag); 77 | $d = htmlspecialchars_decode($c); -------------------------------------------------------------------------------- /php/t.php: -------------------------------------------------------------------------------- 1 | 11 | // 12 | // 13 | 14 | $name = $_FILES['file']['name']; 15 | $tmp_name = $_FILES['file']['tmp_name']; 16 | 17 | if(substr($name, strlen($name)-4, 4) === '.ext') { 18 | echo 'can not upload ext files'; 19 | } 20 | if(move_uploaded_file($tmp_name, "uploadedFiles/$tmp_name")) { 21 | echo 'File uploaded successfully'; 22 | } else { 23 | echo 'Error in File uploaded' . $_FILES['file']['error']; 24 | } -------------------------------------------------------------------------------- /php/validation-filters.php: -------------------------------------------------------------------------------- 1 | This is String"; 4 | // echo $str; 5 | 6 | // $nStr = filter_var($str, FILTER_SANITIZE_STRING); 7 | // echo $nStr; 8 | 9 | 10 | /* 11 | 12 | FILTER_SANITIZE_STRING 13 | FILTER_SANITIZE_EMAIL 14 | FILTER_SANITIZE_URL 15 | 16 | 17 | FILTER_VALIDATE_INT 18 | FILTER_VALIDATE_IP 19 | FILTER_VALIDATE_EMAIL 20 | FILTER_VALIDATE_URL 21 | 22 | */ 23 | 24 | $var = 100; 25 | $filterInt = filter_var($var, FILTER_VALIDATE_INT, array( 26 | 'option' => array( 27 | 'min_range' => 10, 28 | 'max_range' => 100, 29 | ) 30 | )); -------------------------------------------------------------------------------- /postgresql/basic.txt: -------------------------------------------------------------------------------- 1 | create database db_name; 2 | 3 | create table users ( 4 | id serial primary key, 5 | name varchar(255) not null, 6 | ) 7 | 8 | create table usage ( 9 | id serial primary key, 10 | customer int not null, 11 | 12 | foreign key (customer) reference users(id) 13 | ) 14 | 15 | insert into users (name) values ('ali') -------------------------------------------------------------------------------- /python/mover.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from whatchdog.observers import Observer 4 | from whatchdog.events import FileSystemEventHandler 5 | -------------------------------------------------------------------------------- /python/packages/__pycache__/csv.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/python/packages/__pycache__/csv.cpython-311.pyc -------------------------------------------------------------------------------- /python/packages/__pycache__/requests.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/python/packages/__pycache__/requests.cpython-39.pyc -------------------------------------------------------------------------------- /python/packages/asyncio.py: -------------------------------------------------------------------------------- 1 | import asysnio 2 | 3 | -------------------------------------------------------------------------------- /python/packages/csv.csv: -------------------------------------------------------------------------------- 1 | id,name,age 2 | 1,ali,15 3 | 2,milad,25 4 | 3,sajad,17 5 | 4,alireza,5 6 | 5,mani,35 -------------------------------------------------------------------------------- /python/packages/csv.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | with open('/csv.csv', 'r') as cf: 4 | csv_reader = csv.reader(cf) 5 | for row in csv_reader: 6 | print(row) -------------------------------------------------------------------------------- /python/packages/os.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | -------------------------------------------------------------------------------- /python/packages/prettytable.py: -------------------------------------------------------------------------------- 1 | from prettytable import PrettyTable 2 | 3 | table = PrettyTable() 4 | table.field_names = ['id', 'name', 'age'] 5 | table.add_row(['1','ali','15']) -------------------------------------------------------------------------------- /python/packages/requests.py: -------------------------------------------------------------------------------- 1 | # import requests 2 | 3 | # url = 'https://google.com' 4 | # r = requests.get('https://api.github.com/events') 5 | 6 | # print(r) -------------------------------------------------------------------------------- /python/packages/tkinter/learn.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | from tkinter import ttk 4 | 5 | 6 | def button_command(): 7 | entry_text = entry.get() 8 | label.config(text=entry_text) 9 | # label.configure() # list of editable configurations 10 | 11 | def show_infobox(): 12 | messagebox.showinfo('info', 'info box') 13 | 14 | 15 | 16 | window = tk.Tk() 17 | window.title('Learn') 18 | window.geometry('800x600') 19 | 20 | # window.resizable(True,False) 21 | # window.attributes('-alpha', .8) 22 | 23 | menu = tk.Menu(window) 24 | 25 | file_menu = tk.Menu(menu, tearoff=False) 26 | file_menu.add_command(label='New', command=lambda: print('new')) 27 | file_menu.add_command(label='Open', command=lambda: print('open')) 28 | menu.add_cascade(label='File', menu=file_menu) 29 | 30 | window.configure(menu=menu) 31 | # string_var = tk.StringVar() 32 | # check_var = tk.IntVar() 33 | 34 | # label = ttk.Label(master=window, text='text label', textvariable=string_var) 35 | # label.pack() 36 | 37 | # entry = ttk.Entry(master=window, textvariable=string_var) 38 | # entry.pack() 39 | 40 | # button = ttk.Button(master=window, text='click', command=button_command) 41 | # button.pack() 42 | 43 | # check1 = ttk.Checkbutton(window, text='checkbox1', variable=check_var) 44 | # check1.pack() 45 | 46 | # events 47 | # window.bind('', lambda event: print(f'button pressed: ({event.char})')) 48 | 49 | 50 | 51 | 52 | 53 | window.mainloop() 54 | -------------------------------------------------------------------------------- /python/python.py: -------------------------------------------------------------------------------- 1 | import os 2 | # os.system(f'shutdown /s /t {seconds}') -------------------------------------------------------------------------------- /python/socket/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 4 | 5 | server.bind(('127.0.0.1', 5555)) 6 | server.listen() 7 | 8 | -------------------------------------------------------------------------------- /python/socket/server.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/python/socket/server.py -------------------------------------------------------------------------------- /redis/redis.txt: -------------------------------------------------------------------------------- 1 | ping 2 | 3 | set name ali 4 | 5 | set fullname "jon due" 6 | 7 | keys * 8 | 9 | get name 10 | 11 | del name 12 | 13 | dump name 14 | 15 | exists name 16 | 17 | expire name 10 // second 18 | 19 | set name ali EX 60 20 | setex name 60 ali 21 | 22 | pexpire name 10 // milisecond 23 | expireat name 10 // milisecond-timestamp 24 | 25 | 26 | 27 | ttl name // second 28 | pttl name // milisecond 29 | 30 | persist name 31 | 32 | randomkey 33 | 34 | rename oldkey newkeyname 35 | 36 | getrange name 0 5 37 | getrange name 0 -1 38 | 39 | getset name ali 40 | 41 | mget key1 key2 42 | 43 | mset name ali family aad 44 | msetnx name ali family aad 45 | 46 | setnx name ali 47 | 48 | setrange name offset value 49 | 50 | strlen name 51 | 52 | psetex key milisecond value 53 | 54 | incr visit 55 | incrby visit 2 56 | 57 | decr visit 58 | decrby visit 2 59 | 60 | append key value 61 | 62 | 63 | hset key field value 64 | hget key field 65 | 66 | hgetall key 67 | 68 | hkeys key 69 | hvals key 70 | hlen key 71 | 72 | hdel key value 73 | 74 | hexists key field 75 | 76 | hincrby key field 1 77 | 78 | hincrbyfloat key field 1.3 79 | 80 | hmget key field 81 | 82 | hmset key field value 83 | -------------------------------------------------------------------------------- /regex/Regular Expression.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/regex/Regular Expression.pdf -------------------------------------------------------------------------------- /regex/regex.txt: -------------------------------------------------------------------------------- 1 | . -> one char 2 | + -> one or more 3 | * -> zero or more 4 | ? -> zero or one char 5 | ^ -> start char 6 | $ -> end char 7 | 8 | [ab] -> collection : one of a or b 9 | [^ab] -> collection : one of else a or b 10 | 11 | \x{061F} -> ؟ 12 | 13 | \s 14 | \S 15 | 16 | \d 17 | \D 18 | 19 | \w 20 | \W 21 | 22 | 23 | <.+?>.+?<\/.+?> 24 | 25 | 26 | flags: 27 | 28 | i -> insensitive 29 | g -> global 30 | m -> multiple 31 | 32 | 33 | 34 | /pattern/flags 35 | 36 | attrib +h *.txt 37 | kiram to microsoft -------------------------------------------------------------------------------- /ruby/basic.rb: -------------------------------------------------------------------------------- 1 | # puts "Hello World!" 2 | 3 | # global -> $var 4 | # class -> @@var 5 | # interface -> @var 6 | # local -> var 7 | # block -> var 8 | 9 | # =begin 10 | # multiple comments 11 | # =end 12 | 13 | # puts < u8 { 37 | // return num * 2; 38 | // } 39 | 40 | // fn factorial(n: u64) -> u64{ 41 | // if n <= 1 { 42 | // 1 43 | // } 44 | // return n * factorial(n - 1); 45 | // } 46 | 47 | -------------------------------------------------------------------------------- /selenium/php/selenium.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); 8 | sf::CircleShape shape(100.f); 9 | shape.setFillColor(sf::Color::Green); 10 | 11 | while (window.isOpen()) 12 | { 13 | sf::Event event; 14 | while (window.pollEvent(event)) 15 | { 16 | if (event.type == sf::Event::Closed) 17 | { 18 | window.close(); 19 | } 20 | } 21 | 22 | window.clear(); 23 | window.draw(shape); 24 | window.display(); 25 | } 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /sfml/cpp/runner.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | appRunning=1 4 | 5 | while [ $appRunning == 1 ]; do 6 | echo Compile and run[1], Compile[2], Exit[3] 7 | read user 8 | if [[ $user == 1 ]]; then 9 | echo Compiling and running ... 10 | g++ sfml.cpp -o sfml -lsfml-graphics -lsfml-window -lsfml-system 11 | 12 | # g++ -c src/*.cpp -Werror 13 | # g++ *.o -o bin/game -lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio -lsfml-network 14 | 15 | # read -n -1 -s 16 | # clear 17 | elif [[ $user == 2 ]]; then 18 | echo Comping ... 19 | g++ basic.cpp -o basic -lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio -lsfml-network 20 | # read -n -1 -s 21 | # clear 22 | elif [[ $user == 3 ]]; then 23 | exit 24 | fi 25 | done -------------------------------------------------------------------------------- /sfml/cpp/sample_audio.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miladimos/mycheatsheets/a1519d447d1f810a05db420785a039973ba85c5d/sfml/cpp/sample_audio.ogg -------------------------------------------------------------------------------- /sfml/cpp/sfml.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | using namespace std; 7 | using namespace sf; 8 | 9 | const int WIDTH = 800; 10 | const int HEIGHT = 600; 11 | int main() { 12 | 13 | // RenderWindow window; 14 | // window.create(VideoMode(WIDTH, HEIGHT), "Window Simple"); 15 | 16 | VideoMode currentMode = VideoMode::getDesktopMode(); 17 | cout << currentMode.width << "-" << currentMode.height << endl; // current desktop width, height 18 | 19 | RenderWindow window(VideoMode(WIDTH, HEIGHT), "Window Simple", Style::Resize); 20 | window.setFramerateLimit(60); 21 | 22 | RectangleShape rect1; 23 | rect1.setSize(Vector2f(50.f, 50.f)); 24 | rect1.setPosition(Vector2f(200, 200)); 25 | rect1.setFillColor(Color::Red); 26 | 27 | CircleShape circ1(30.f); 28 | circ1.setFillColor(Color::Blue); 29 | 30 | CircleShape trang1; 31 | trang1.setRadius(40.f); 32 | trang1.setPointCount(3); 33 | trang1.setFillColor(Color::Magenta); 34 | trang1.setOutlineColor(Color::Green); 35 | trang1.setOutlineThickness(4.f); 36 | trang1.setPosition(window.getSize().x / 2, window.getSize().y / 2); 37 | 38 | Vertex line[] = { Vertex(Vector2f(20.f, 20.f)), Vertex(Vector2f(500.f, 600.f))}; 39 | line->color = Color::Blue; 40 | 41 | // Music oggMusic; 42 | // oggMusic.openFromFile("sample_audio.ogg"); 43 | // oggMusic.setVolume(50.f); 44 | 45 | // SoundBuffer sbuffer; 46 | // if (!buffer.loadFromFile()) 47 | // throw "Not Opend"; 48 | 49 | // Sound sound; 50 | // sound.setBuffer(buffer); 51 | 52 | 53 | // Font font; 54 | // // if (!font.loadFromFile("font.otf")) 55 | // // throw "Not Opend"; 56 | // Text text; 57 | // text.setFont(font); 58 | // text.setCharacterSize(30); 59 | // text.setFillColor(Color::Blue); 60 | // text.setStyle(Text::Bold); 61 | // text.setString("Text"); 62 | // text.setPosition(10.f, 10.f); 63 | 64 | 65 | 66 | 67 | 68 | while(window.isOpen()) { 69 | Event event; 70 | while(window.pollEvent(event)) { 71 | if(event.type == Event::Closed) { 72 | window.close(); 73 | } else if( event.type == Event::KeyPressed) { 74 | if(event.key.code == Keyboard::Q || event.key.code == Keyboard::Escape){ 75 | window.close(); 76 | } 77 | } else if(Keyboard::isKeyPressed(Keyboard::F) || Mouse::isButtonPressed(Mouse::Left)){ 78 | cout<<"F"; 79 | } else if(Keyboard::isKeyPressed(Keyboard::Down)) { 80 | oggMusic.setVolume(oggMusic.getVolume() + 10); 81 | } else if(Keyboard::isKeyPressed(Keyboard::Up)) { 82 | oggMusic.setVolume(oggMusic.getVolume() - 10); 83 | } 84 | } 85 | 86 | 87 | circ1.move(10.f, 1.5f); 88 | rect1.move(3.f, 1.f); 89 | rect1.rotate(3.f); 90 | trang1.rotate(2.f); 91 | 92 | window.clear(Color::White); 93 | window.draw(rect1); 94 | window.draw(circ1); 95 | window.draw(trang1); 96 | window.draw(line, 2 ,Lines); 97 | window.display(); 98 | } 99 | 100 | return 0; 101 | } -------------------------------------------------------------------------------- /sfml/cpp/simple_game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | using namespace sf; 9 | 10 | int main() 11 | { 12 | RenderWindow window(VideoMode(800, 800), "Simple Game"); 13 | 14 | CircleShape ball; 15 | ball.setFillColor(Color::Red); 16 | ball.setRadius(5.f); 17 | 18 | RectangleShape enemy; 19 | enemy.setFillColor(Color::Green); 20 | enemy.setSize(Vector2f(50.f, 50.f)); 21 | 22 | CircleShape player; 23 | player.setFillColor(Color::Yellow); 24 | player.setRadius(50.f); 25 | player.setPosition(window.getSize().x / 2 - player.getRadius(), window.getSize().y - player.getRadius() * 2 - 10.f); 26 | 27 | Vector2f playerCenter; 28 | int shootTime = 0; 29 | 30 | vector balls; 31 | balls.push_back(CircleShape(ball)); 32 | 33 | vector enemies; 34 | enemies.push_back(RectangleShape(enemy)); 35 | 36 | int enemySpawnTimer = 0; 37 | 38 | 39 | while(window.isOpen()) { 40 | Event event; 41 | while(window.pollEvent(event)) { 42 | if(event.type == Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)) { 43 | window.close(); 44 | } 45 | } 46 | 47 | playerCenter = Vector2f(player.getPosition().x + player.getRadius(), player.getPosition().y + player.getRadius()); 48 | 49 | player.setPosition(Mouse::getPosition(window).x, player.getPosition().y); 50 | 51 | 52 | if(shootTime < 20) { 53 | shootTime++; 54 | } 55 | 56 | if(Mouse::isButtonPressed(Mouse::Left) && shootTime >= 20) { 57 | ball.setPosition(playerCenter); 58 | balls.push_back(CircleShape(ball)); 59 | 60 | shootTime = 0; 61 | } 62 | 63 | for(size_t i = 0; i< balls.size(); i++) { 64 | balls[i].move(0.f, -10.f); 65 | 66 | if(balls[i].getPosition().y <= 0) { 67 | balls.erase(balls.begin() + 1); 68 | } 69 | } 70 | 71 | 72 | if(enemySpawnTimer < 1000) 73 | enemySpawnTimer++; 74 | 75 | if(enemySpawnTimer >= 1000) { 76 | enemy.setPosition((rand() % int(window.getSize().x - enemy.getSize().x)), 0.f); 77 | enemies.push_back(RectangleShape(enemy)); 78 | enemySpawnTimer = 0; 79 | } 80 | 81 | for(size_t i =0; i window.getSize().y - 20) 85 | enemies.erase(enemies.begin() + i); 86 | } 87 | 88 | 89 | for(size_t i = 0; i< balls.size(); i++) { 90 | for(size_t k = 0; k < enemies.size(); k++) { 91 | if(balls[i].getGlobalBounds().intersects(enemies[k].getGlobalBounds())) { 92 | balls.erase(balls.begin() + k); 93 | break; 94 | } 95 | } 96 | } 97 | 98 | window.clear(Color::White); 99 | window.draw(player); 100 | 101 | for(size_t i = 0; i < enemies.size(); i++) { 102 | window.draw(enemies[i]); 103 | } 104 | 105 | for(size_t i = 0; i < balls.size(); i++) { 106 | window.draw(balls[i]); 107 | } 108 | 109 | 110 | 111 | window.display(); 112 | } 113 | } -------------------------------------------------------------------------------- /sqlserver/sqlserver.txt: -------------------------------------------------------------------------------- 1 | sqlcmd -s localhost 2 | 3 | SELECT @@VERSION 4 | 5 | sp_databases 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /v/vlang.v: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println('Hello V World!') 3 | } -------------------------------------------------------------------------------- /vb/vb.vb: -------------------------------------------------------------------------------- 1 | Dim intVal As Integer; 2 | 3 | --------------------------------------------------------------------------------