diff --git a/LICENSE b/LICENSE
index d5ed795..f288702 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,21 +1,674 @@
-MIT License
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
-Copyright (c) 2021 @Fechin
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+ Preamble
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 2d04273..e3216a8 100644
--- a/README.md
+++ b/README.md
@@ -35,8 +35,8 @@ Reference provides cheat sheets for the following:
- [LaTeX](https://cheatsheets.zip/latex.html): This cheat sheet summarizes a reference list of [LaTeX](https://www.latex-project.org/) commonly used display math notation and some application examples of [KaTeX](https://katex.org/).
- [Rust](https://cheatsheets.zip/rust.html): The Rust quick reference cheat sheet that aims at providing help on writing basic syntax and methods.
- [C#](https://cheatsheets.zip/cs.html): C# quick reference cheat sheet that provides basic syntax and methods.
-- [Laravel](https://cheatsheets.zip/laravel.html): [Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP.
-This cheat sheet provides a reference for common commands and features for Laravel 8.
+- [Laravel](https://cheatsheets.zip/laravel.html): [Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP.
+ This cheat sheet provides a reference for common commands and features for Laravel 8.
- [Dart](https://cheatsheets.zip/dart.html): A Dart cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
- [JSON](https://cheatsheets.zip/json.html): This is a quick reference cheat sheet for understanding and writing JSON format configuration files.
- [Hook](https://cheatsheets.zip/hook.html): The [Hook](https://github.com/hook-lang/hook/) cheat sheet is a one-page reference sheet for the Hook programming language.
@@ -55,7 +55,7 @@ This cheat sheet provides a reference for common commands and features for Larav
- [Sass](https://cheatsheets.zip/sass.html): This is a quick reference cheat sheet that lists the most useful features of [SASS](https://sass-lang.com).
- [Go](https://cheatsheets.zip/go.html): This cheat sheet provided basic syntax and methods to help you using [Go](https://go.dev/).
- [Markdown](https://cheatsheets.zip/markdown.html): This is a quick reference cheat sheet to the Markdown syntax.
-- [Bash](https://cheatsheets.zip/bash.html): This is a quick reference cheat sheet to getting started with linux bash shell scripting.
+- [Bash](https://cheatsheets.zip/bash.html): This is a quick reference cheat sheet to getting started with Linux bash shell scripting.
@@ -64,10 +64,10 @@ This cheat sheet provides a reference for common commands and features for Larav
- [ChatGPT](https://cheatsheets.zip/chatgpt.html): This cheat sheet lists out prompts and tips from all over the world on how to use ChatGPT effectively
- [VSCode](https://cheatsheets.zip/vscode.html): This VSCode (Visual Studio Code) quick reference cheat sheet shows its keyboard shortcuts and commands.
-- [Mitmproxy](https://cheatsheets.zip/mitmproxy.html): [mitmproxy](https://mitmproxy.org/) is a free and open source interactive HTTPS proxy. This is a quick reference cheat sheet to the mitmproxy.
+- [Mitmproxy](https://cheatsheets.zip/mitmproxy.html): [Mitmproxy](https://mitmproxy.org/) is a free and open source interactive HTTPS proxy. This is a quick reference cheat sheet to the Mitmproxy.
- [XPath](https://cheatsheets.zip/xpath.html): This is an [XPath](https://en.wikipedia.org/wiki/XPath) selectors cheat sheet, which lists commonly used XPath positioning methods and CSS selectors
- [Emacs](https://cheatsheets.zip/emacs.html): [Emacs](https://www.gnu.org/software/emacs) is the extensible, customizable, self-documenting real time display text editor.
-This reference was made for Emacs 27.
+ This reference was made for Emacs 27.
- [Emmet](https://cheatsheets.zip/emmet.html): [Emmet](https://emmet.io/) is a web-developer’s toolkit for boosting HTML & CSS code writing, which allows you to write large HTML code blocks at speed of light using well-known CSS selectors.
- [RegEX](https://cheatsheets.zip/regex.html): A quick reference for regular expressions (regex), including symbols, ranges, grouping, assertions and some sample patterns to get you started.
- [Vim](https://cheatsheets.zip/vim.html): A useful collection of [Vim](http://www.vim.org/) 8.2 quick reference cheat sheets to help you learn vim editor faster.
@@ -86,19 +86,19 @@ This reference was made for Emacs 27.
- [Netstat](https://cheatsheets.zip/netstat.html): This quick reference cheat sheet provides various for using netstat command.
- [Screen](https://cheatsheets.zip/screen.html): This is a quick reference guide cheat sheet for the screen command.
- [Awk](https://cheatsheets.zip/awk.html): This is a one page quick reference cheat sheet to the [GNU awk](https://www.gnu.org/software/gawk/manual/gawk.html), which covers commonly used awk expressions and commands.
-- [Find](https://cheatsheets.zip/find.html): This is a quick reference list of cheat sheet for linux find command, contains common options and examples.
+- [Find](https://cheatsheets.zip/find.html): This is a quick reference list of cheat sheet for Linux find command, contains common options and examples.
- [Sed](https://cheatsheets.zip/sed.html): [Sed](https://www.gnu.org/software/sed/manual/sed.html) is a stream editor, this sed cheat sheet contains sed commands and some common sed tricks.
- [Cron](https://cheatsheets.zip/cron.html): [Cron](https://en.wikipedia.org/wiki/Cron) is most suitable for scheduling repetitive tasks. Scheduling one-time tasks can be accomplished using the associated at utility.
- [Git](https://cheatsheets.zip/git.html): This cheat sheet summarizes commonly used Git command line instructions for quick reference.
- [Grep](https://cheatsheets.zip/grep.html): This cheat sheet is intended to be a quick reminder for the main concepts involved in using the command line program grep and assumes you already understand its usage.
-- [Netcat](https://cheatsheets.zip/nc.html): This cheat sheet provides various for using Netcat on both Linux and Unix.
+- [Netcat](https://cheatsheets.zip/nc.html): This cheat sheet provides various for using netcat on both Linux and Unix.
- [Taskset](https://cheatsheets.zip/taskset): This quick reference cheat sheet for tasket command.
Python
-- [Numpy](https://cheatsheets.zip/numpy.html): [NumPy](https://numpy.org/) is the fundamental package for scientific computing with Python. This cheat sheet is a quick reference for NumPy beginners.
+- [NumPy](https://cheatsheets.zip/numpy.html): [NumPy](https://numpy.org/) is the fundamental package for scientific computing with Python. This cheat sheet is a quick reference for NumPy beginners.
@@ -107,7 +107,7 @@ This reference was made for Emacs 27.
- [Neo4j](https://cheatsheets.zip/neo4j.html): A Neo4j cheat sheet with getting started resources and information on how to query the database with Cypher.
- [PostgreSQL](https://cheatsheets.zip/postgres.html): The [PostgreSQL](https://www.postgresql.org/docs/current/) cheat sheet provides you with the common PostgreSQL commands and statements.
-- [Redis](https://cheatsheets.zip/redis.html): This is a [redis](https://redis.io/) quick reference cheat sheet that lists examples of redis commands
+- [Redis](https://cheatsheets.zip/redis.html): This is a [Redis](https://redis.io/) quick reference cheat sheet that lists examples of redis commands
- [MySQL](https://cheatsheets.zip/mysql.html): The SQL cheat sheet provides you with the most commonly used SQL statements for your reference.
@@ -127,7 +127,7 @@ This reference was made for Emacs 27.
- [Slack](https://cheatsheets.zip/slack.html): A visual cheat-sheet for the 62 keyboard shortcuts found in Slack
- [SoundCloud](https://cheatsheets.zip/soundcloud.html): A visual cheat-sheet for the 22 keyboard shortcuts found on SoundCloud
- [Twitter](https://cheatsheets.zip/twitter.html): A visual cheat-sheet for the 26 keyboard shortcuts found on Twitter
-- [Android Studio](https://cheatsheets.zip/android-studio.html): A visual cheat-sheet for the 130 keyboard shortcuts found in the Andriod Studio software
+- [Android Studio](https://cheatsheets.zip/android-studio.html): A visual cheat-sheet for the 130 keyboard shortcuts found in the Android Studio software
- [Github](https://cheatsheets.zip/github.html): A visual cheat-sheet for the 80 keyboard shortcuts found on Github.com
- [Shopify](https://cheatsheets.zip/shopify.html): A visual cheat-sheet for the 50 keyboard shortcuts found on the Shopify website
- [Zoom](https://cheatsheets.zip/zoom.html): A visual cheat-sheet for the 32 keyboard shortcuts found in Zoom. These shortcuts are for MacOS, for Windows visit /zoom-windows.
@@ -203,7 +203,7 @@ This reference was made for Emacs 27.
- [HTML Characters Entities](https://cheatsheets.zip/html-char.html): This cheat sheet is a complete list of HTML entities with their numbers and names. Also included is a full list of ASCII characters that can be represented in HTML.
- [ISO 639-1 Language Code](https://cheatsheets.zip/iso-639-1.html): This is a list of the ISO language codes that conform to the ISO 639-1 standard, it provide reference for multi-language website.
- [Resolutions](https://cheatsheets.zip/resolutions.html): This cheat sheet lists screen sizes, viewport size and CSS media queries for popular Phones, Tablets, Laptops and Watches
-- [HTTP Status Code](https://cheatsheets.zip/http-status-code.html): The http status codes cheat sheet. a quick reference to every HTTP status code.
+- [HTTP Status Code](https://cheatsheets.zip/http-status-code.html): The http status codes cheat sheet. A quick reference to every HTTP status code.
- [Emoji](https://cheatsheets.zip/emoji.html): Some of the emoji codes are not super easy to remember, so here is a little cheat sheet.
- [CheatSheets](https://cheatsheets.zip/quickref.html): This is the magic syntax variant manual that you can use on CheatSheets.zip, It's a good practice for contributors.
- [MIME types](https://cheatsheets.zip/mime.html): This cheat sheet lists some common MIME types for the Web. You can look in the [IANA/MIME Media Types registry](http://www.iana.org/assignments/media-types/index.html) which contains all registered MIME types.
diff --git a/source/_posts/django.md b/source/_posts/django.md
new file mode 100644
index 0000000..d3b1440
--- /dev/null
+++ b/source/_posts/django.md
@@ -0,0 +1,1738 @@
+---
+title: Django
+date: 2024-05-15 10:12:25
+background: bg-[#1e3e2e]
+tags:
+ - python
+ - web
+categories:
+ - Programming
+intro: |
+ A Django cheat sheet.
+plugins:
+ - copyCode
+---
+
+### Contents
+
+- [Start New Django Project](#start-a-new-django-project)
+- [Project Config](#project-config)
+- [Create Data Model](#create-data-model)
+- [Field Lookups](#field-lookups)
+- [Admin Panel](#admin-panel)
+- [Routing](#routing)
+- [Static Route & Customize Admin Panel](#static-route-and-customize-admin-panel)
+- [Function Based Views](#function-based-views)
+- [Class Based Views](#class-based-views)
+- [Django Template](#django-template)
+- [Create custom template tags and filters](#create-custom-template-tags-and-filters)
+- [Creating custom Context Processor](#creating-custom-context-processor)
+- [Model Managers and Querysets](#model-managers-and-querysets)
+- [Form (forms.py)](#form)
+- [Flash Mssages](#flash-messages)
+- [User Model (pre-created)](#user-model)
+- [Authentication Configure](#authentication-configure)
+- [Create Custom Accounts Model](#create-custom-accounts-model)
+- [Send Email](#send-email)
+- [Signals](#signals)
+- [Seed](#seed)
+- [Environment Variables](#environment-variables)
+- [Asynchronous Task with Django Celery Redis](#asynchronous-task-with-django-celery-redis)
+
+#### Start a New Django Project
+
+```python
+# Create et access project folder
+~$ mkdir project_name
+~$ cd project_name
+
+# Create Python virtual env
+~$ python3 -m venv venv
+
+# Activate virtual env
+~$ source venv/bin/activate
+
+# If you want to deactivate virtual env
+~$ deactivate
+
+# Install django (~= same as 4.2.*)
+~$ pip install django~=4.2.0
+
+# New django project (from project_name folder)
+~$ django-admin startproject config
+
+# Create app (from project_name folder)
+~$ python manage.py startapp app_name
+```
+
+#### Migration:
+
+Django create a database table for each models present in your app using thoses commands:
+
+- Makemigrations: Create a file under app_name/migrations with the database structure to create
+
+```python
+~$ python manage.py makemigrations
+```
+
+- Migrate: Will read the migrations files and create the actual database and tables
+
+```python
+~$ python manage.py migrate
+```
+
+#### Create superuser for authenficiation/admin panel
+
+```python
+~$ python manage.py createsuperuser
+```
+
+#### Start server
+
+```python
+~$ python manage.py runserver => ex. http://127.0.0.1:8000
+```
+
+#### Requirements
+
+```python
+# Create a requirements file that contain all your projet dependencies
+~$ pip freeze > requirements.txt
+
+# Install your project requirements (if a requirements file exist)
+~$ pip install -r requirements.txt
+```
+
+#### Other commands
+
+```python
+# Django shell (Run projet code direclty)
+~$ python manage.py shell
+
+# example of code to run in the shell:
+ >>> from app_name.models import User
+ >>> user1 = User.objects.first()
+
+# Prepare static folders for production
+~$ python manage.py collectstatic
+
+# Take all data from app blog and export in json
+~$ python manage.py dumpdata blog > myapp.json
+
+# Take all data in json file and import in app data table
+~$ python manage.py loaddata myapp.json
+
+# To Create or Update a message file for Translation, run this command
+~$ django-admin makemessages -l de
+# Updating message files
+~$ django-admin compilemessages
+```
+
+## Project config
+
+```python
+# Add app to settings.py
+INSTALLED_APPS = [
+ … ,
+ 'app_name.apps.App_nameConfig',
+ ]
+
+# App templates folder
+create folder appfolder/templates/appname
+
+# Project templates folder:
+create folder projectname/templates
+
+# settings.py template config
+Project templates settings.py:
+ TEMPLATES = [
+ { …
+ 'DIRS': [BASE_DIR / 'templates'],
+ … }
+
+# Create Static folder:
+project_name\static\
+
+# Static folder (settings.py):
+STATIC_URL = '/static/'
+STATICFILES_DIRS = [ BASE_DIR / 'static' ]
+STATIC_ROOT = 'static_root'
+# Media folder (settings.py):
+MEDIA_URL = '/media/'
+STATICFILES_DIRS = (
+ (BASE_DIR / 'static'),
+)
+MEDIA_ROOT = BASE_DIR / 'media'
+
+# To use PostgresSQL
+# pip install psycopg2
+# settings.py
+DATABASE = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.postgresql',
+ 'NAME': 'blog',
+ 'USER': 'admin',
+ 'PASSWORD': '123456',
+ 'HOST': 'localhost',
+ 'PORT': '5432'
+ }
+ }
+
+TIME_INPUT_FORMATS = [
+ '%H:%M:%S', # '14:30:59'
+ '%H:%M', # '14:30'
+]
+
+DATE_FORMAT = "Y/M/d"
+
+# locale for Translations
+LANGUAGES = [
+ ('en', 'English'),
+ ('de', 'German'),
+]
+
+LOCALE_PATHS = (
+ BASE_DIR / 'locale',
+)
+
+# CK Editor Configuration
+CKEDITOR_UPLOAD_PATH = 'uploads/'
+CKEDITOR_RESTRICT_BY_USER = True
+CKEDITOR_BROWSE_SHOW_DIRS = True
+CKEDITOR_ALLOW_NONIMGE_FILES = True
+CKEDITOR_IMAGE_BACKEND = "pillow"
+CKEDITOR_CONFIGS = {
+ 'default': {
+ 'toolbar': 'full',
+ }}
+
+# SSL
+# If you have an SSL certificate
+SECURE_SSL_REDIRECT = True
+# cookies will only be sent via HTTPS connections
+SESSION_COOKIE_SECURE = True
+CSRF_COOKIE_SECURE = True
+```
+
+## Create Data Model:
+
+Theses models can be created as database tables with the migrations commands
+
+```python
+# models.py
+# The id fields is automaticly created by Django
+# for each model that why it's not show below
+from django.db import models
+
+class Customer(models.Model)
+ name = models.Charfield('Customer', max_length=120)
+ age = models.IntegerField()
+ note = models.TextField(blank=True, null = True)
+ email = models.EmailField(max_length=255, blank=True, null=True)
+ credit = models.FloatField(blank=True)
+ is_active = models.BooleanField(default=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ img = models.ImageField(upload_to ='uploads/')
+ # Select Field (return value, display value)
+ TYPE_CHOICES = (
+ ('Customer', 'Customer'),
+ ('Supplier', 'Supplier'),
+ ('Student', 'Student'),
+ )
+ type = models.CharField(choices=TYPE_CHOICES)
+
+ class Meta:
+ verbose_name = "Customer"
+ verbose_name_plural = "Customers"
+
+ def __str__(self): # Model string representation
+ return self.name
+
+ # the URL that points to a resource or page on your website
+ def get_absolute_url(self):
+ return reverse("customer_detail", kwargs={"pk": self.pk})
+```
+
+#### Relationship between models
+
+```python
+# One-to-Many: (use double quotes if the entity is not yet declare) ex. "Supplier"
+supplier = models.ForeignKey(Supplier, blank=True, null=True, on_delete=models.CASCADE,related_name="supplierother")
+
+# on_delete can be set to models.CASCADE, models.ST_DEFAULT or models.SET_NULL
+# The related_name attribute specifies the name of the reverse relation from the supplier model back to your model
+
+# Many-to-Many:
+tags = models.ManyToManyField(Tag, blank=True)
+
+# One to One
+User = models.OneToOneField(User, on_delete=models.CASCADE)
+
+# Overwrite save method
+def save(self, (*args, **kwargs):
+ if not self.slug:
+ self.slug = slugify(self.title)
+ super().save(*args, **kwargs)
+```
+
+## Field Lookups
+
+In Django, the `field__lookuptype` syntax is used to perform lookups on fields in queries. The `field` represents the name of the field you want to perform the lookup on, and `lookuptype` represents the type of lookup you want to perform.
+
+For example, let's say you have a model called `Book` with a field called `title` . You can use the `field__lookuptype` syntax to perform different types of lookups on the `title` field.
+
+Here are a few examples:
+
+```python
+
+# 1. Exact Match Lookup:
+Book.objects.filter(title__exact='Python Tricks')
+# 2. Case-insensitive Lookup:
+Book.objects.filter(title__iexact='python tricks')
+# 3. Contains Lookup:
+Book.objects.filter(title__contains='Python')
+# 4. Startswith Lookup:
+Book.objects.filter(title__startswith='Python')
+# 5. Endswith Lookup:
+Book.objects.filter(title__endswith='Tricks')
+```
+
+### Field Lookups Reference
+
+A list of all field look up keywords:
+
+| **Keyword** | **Description** |
+| ------------ | ------------------------------------------------ |
+| contains | Contains the phrase |
+| icontains | Same as contains, but case-insensitive |
+| date | Matches a date |
+| day | Matches a date (day of month, 1-31) (for dates) |
+| endswith | Ends with |
+| iendswith | Same as endswidth, but case-insensitive |
+| exact | An exact match |
+| iexact | Same as exact, but case-insensitive |
+| in | Matches one of the values |
+| isnull | Matches NULL values |
+| gt | Greater than |
+| gte | Greater than, or equal to |
+| hour | Matches an hour (for datetimes) |
+| lt | Less than |
+| lte | Less than, or equal to |
+| minute | Matches a minute (for datetimes) |
+| month | Matches a month (for dates) |
+| quarter | Matches a quarter of the year (1-4) (for dates) |
+| range | Match between |
+| regex | Matches a regular expression |
+| iregex | Same as regex, but case-insensitive |
+| second | Matches a second (for datetimes) |
+| startswith | Starts with |
+| istartswith | Same as startswith, but case-insensitive |
+| time | Matches a time (for datetimes) |
+| week | Matches a week number (1-53) (for dates) |
+| week_day | Matches a day of week (1-7) 1 is Sunday |
+| iso_week_day | Matches a ISO 8601 day of week (1-7) 1 is Monday |
+| year | Matches a year (for dates) |
+| iso_year | Matches an ISO 8601 year (for dates) |
+
+## Admin Panel:
+
+Every Django projects come with an Admin Panel that can be open at /admin url (ex: localhost:8000/admin)
+To display the model in the Admin panel register the model in the app_name/admin.py file
+For each models you can specify the fields you want to use
+
+```python
+from django.contrib import admin
+from app_name.models import Blog
+
+# Custom model Admin (admin.py):
+@admin.register(Blog) # Register app
+class BlogAdmin(admin.ModelAdmin)
+ fields = ("title", "description") # Fields to use for add/edit/show page
+ list_display = ("title", "description") # fields to display in search page
+ list_display_links = ("title",) # fields that will be a link in search page
+ ordering = ("date_created",) # Ordering allowed in the search page
+ search_fields = ("title", "description") # Search fields allowed in the search page
+ list_filter =("title",) # define list filters that appear in the right sidebar
+```
+
+## Routing:
+
+Django routing info is store in project_folder/urls.py file
+
+```python
+from django.contrib import admin
+from django.urls import path, include
+
+urlpatterns = [
+ path('admin/', admin.site.urls), # pre-created admin urls routes
+ path('', include('app_name.urls')) # include your app urls
+]
+```
+
+the 'include()' method allow to link another urls.py file created in your app folder (app_name/urls.py)
+
+
+```python
+from django.urls import path
+from app_name import views
+
+urlpatterns = [
+ path('posts', views.index, name='posts.index'),
+ path('posts/create/', views.create, name='posts.create',
+ path('posts//', views.show, name='posts.show'),
+ path('posts//edit/', views.edit, name='posts.edit'),
+ path('posts//delete/', views.delete, name='posts.delete'),
+ path('posts///', views.status, name='posts.status'), # two arguments
+]
+```
+
+## Static Route and Customize Admin Panel
+
+Header and Title admin panel & Custom 404,500,503 Template
+
+```python
+# add in project/urls.py
+from django.contrib import admin
+from django.conf import settings
+from django.conf.urls.static import static
+
+urlpatterns = [ ... ]
+
+if settings.DEBUG == True:
+ urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+
+# Customize Admin Panel Header & Title
+admin.site.site_header = _('Administrator Control Panel')
+admin.site.site_title = _('Administrator Control Panel')
+admin.site.index_title = _('Wellcome to Control Panel')
+
+# Costomize 404 Template page
+handler404 = 'app_name.views.handler404'
+handler500 = 'app_name.views.handler500'
+handler503 = 'app_name.views.handler503'
+```
+
+## Function Based Views
+
+```python
+# views.py
+from django.shortcuts import render, redirect
+from app_name.models import Post
+from app_name.forms import PostForm
+
+def index(request):
+ # Get all Posts
+ posts = Post.objects.all()
+
+ # Render app template with context
+ return render(request, 'appfolder/index.html', {'posts': posts})
+
+def show(request, id):
+ post = Post.objects.get(id=id)
+ return render(request, 'appfolder/show.html', {'post': post})
+
+def create(request):
+ form = PostForm(request.POST or None)
+ if form.is_valid():
+ # optionally we can access form data with form.cleaned_data['first_name']
+ post = form.save(commit=False)
+ post.user = request.user
+ post.save()
+ return redirect('/posts')
+
+ return render(request, 'appfolder/create.html', {'form': form)
+
+def edit(request, id):
+ post = Post.objects.get(id=id)
+ form = PostForm(request.POST or None, instance=post)
+ if form.is_valid():
+ form.save()
+ return redirect('/posts')
+
+ return render(request, 'appfolder/edit.html', {'form': form)
+
+def delete(request, id):
+ post = Post.objects.get(id=id)
+ post.delete()
+ return redirect('/posts')
+
+def status(request, id, state):
+ post = Post.objects.get(id=id, state=state)
+ return redirect('appfolder/status.html', {'post': post})
+```
+
+## Class Based Views
+
+```python
+from django.views.generic import TemplateView, ListView, DetailView,
+ CreateView, UpdateView, DeleteView
+
+class LandingPageView(TemplateView):
+ template_name = 'landing.html'
+
+ # Optional: Change context data dict
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+ context['title'] = 'Landing Page'
+ return context
+
+
+class PostsListView(ListView):
+ queryset = Post.objects.all()
+ # Optional
+ # context_object_name = "posts" (default: post_list)
+ # template_name = 'posts.html' (default: posts/post_list.html)
+
+
+class PostsDetailView(DetailView):
+ model = Post # object var in template
+ # Optional
+ # template_name = 'post.html' (default: posts/post_detail.html)
+
+
+class PostsCreateView(CreateView):
+ form_class = PostForm
+ template_name = 'posts/post_create.html' # no default value
+
+ def get_success_url(self):
+ return reverse('posts-list')
+
+ # Optional: Overwrite form data (before save)
+ def form_valid(self, form):
+ if self.request.user.is_authenticated:
+ from.instance.author = self.request.user
+ return super().form_valid(form)
+
+
+class PostsUpdateView(UpdateView):
+ model = Post
+ form_class = PostForm
+ template_name = 'posts/post_update.html'
+
+ def get_success_url(self):
+ return reverse('post-list')
+
+ # Optional: Change context data dict
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+ context['submit_text'] = 'Update'
+ return context
+
+
+class PostsDeleteView(DeleteView):
+ model = Post
+ template_name = 'posts/post_delete.html'
+ success_url = reverse_lazy('posts-list')
+
+# Urls.py route declaration
+path('/update/', PostsUpdateView.as_view(), name='post-update')
+```
+
+## Django Template
+
+Templates are store in project_folder/templates or in your app_folder/templates/app_name/\*.html
+
+```python
+{% extends 'base.html' %}
+{% block content %}
+{% endblock %}
+
+{% include 'partials/header.html' %}
+
+# include template with One or More Parameters
+{% include 'body.html' with key1=value1 key2=value2 %}
+
+{% if user.username = 'Mike' %}
+
Hello Admin
+{% elif user.username = 'john' %}
+
Hello John Doe
+{% else %}
+
Hello User
+{% endif %}
+
+{% for product in products %}
+
product number: {{ forloop.counter0 }}
+
The product name is {{ product }}
+{% endfor %}
+
+# Access to the variable in the template
+{{ var_name }}
+
+# Template variables formating
+{{ title | lower }}
+{{ blog.post | truncatwords:50 }}
+{{ order.date | date:"D M Y" }}
+{{ list_items | slice:":3" }}
+{{ total | default:"nil" }}
+
+# Current path (ex. posts/1/show)
+{{ request.path }}
+
+# URL by name with param
+{% url 'posts.delete' id=post.id %}
+
+# Use static in template:
+{% load static %}
+{% static 'css/main.css' %}
+
+# Define the variable in the template
+{% with name="World" %}
+
+
Hello {{ name }}!
+
+{% endwith %}
+```
+
+## Create custom template tags and filters
+
+For example, if your custom tags/filters are in a file called `basetags.py`, your app layout might look like this:
+
+```
+app_name/
+└─── templatetags/
+ └─── basetags.py
+ __init__.py
+ models.py
+ views.py
+```
+
+- And in your template you would use the following:
+
+```python
+{% load basetags %}
+```
+
+- the module must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered. So, near the top of your module, put the following:
+
+#### Writing custom template filters
+
+Custom filters are Python functions that take one or two arguments:
+The value of the variable (input) – not necessarily a string.
+The value of the argument – this can have a default value, or be left out altogether.
+For example, in the filter `{{ var|foo:"bar" }}`, the filter foo would be passed the variable var and the argument "bar".
+
+The Library.filter() method takes two arguments:
+The name of the filter – a string.
+The compilation function – a Python function (not the name of the function as a string).
+You can use register.filter() as a decorator instead:
+
+```python
+# basetags.py
+from django import template
+
+register = template.Library()
+
+@register.filter(name="cut")
+def cut(value, arg):
+ """Removes all values of arg from the given string"""
+ return value.replace(arg, "")
+
+# Most filters don’t take arguments. In this case, leave the argument out of your function
+@register.filter()
+def lower(value): # Only one argument.
+ """Converts a string into all lowercase"""
+ return value.lower()
+
+
+@register.simple_tag
+def to_class_name(object):
+ return str(object.__class__.__name__)
+
+# Template
+# And here’s an example of how that filter would be used in Template:
+{{ somevariable | cut:"0" }}
+
+# Put the result of simple tag into a variable
+{% to_class_name object as objectmodel %}
+
Model Class Name: {{ objectmodel }}
+```
+
+## Creating custom Context Processor
+
+1. Anywhere, create a context_processors.py file
+
+```
+project_name
+└───app_name
+ ├───...
+ └───context_processors.pyy
+```
+
+2. Create a function in context_processors.py that accepts a HttpRequest object as an argument and returns a dictionary
+A context processor is just a function that accepts an HttpRequest object as an argument and returns a dictionary. Like this:
+
+```python
+# app_name/context_processors.py
+def site_email(request):
+ return { 'site_email' : 'example@gmail.com' }
+```
+
+3. Add this to your context_processors setting in settings.py (at the bottom for security reasons)
+
+```python
+ TEMPLATES = [
+ { …
+ 'OPTIONS': {
+ 'context_processors': [
+ …
+ 'app_name.context_processors.site_email', # <- New context processor here
+ …
+ ],
+ … },
+
+# Now be able to access the 'site_email' template variable on every single django template across your whole site.
+```
+
+## Model Managers and Querysets
+
+Model manager allow model database reads and writes
+
+```python
+# One line create and save
+Article.objects.create(name='Item 1', price=19.95)
+
+# Read all
+Article.objects.all()
+
+# Create
+user = User.objects.first()
+article = Article(user=user, name='Item 1', price=19.95)
+
+# Save
+article.save()
+
+# Read one
+Article.objects.get(id=1)
+
+# Select Related (to avoid n+1 query)
+posts = Post.objects.select_related('user', 'category').all()
+
+# Read or render a 404 not found page
+from django.shortcuts import get_object_or_404
+article = get_object_or_404(Article, id=512)
+
+# Filter
+Article.objects.filter(model='dyson', name__icontains='dyson') # __icontains
+Article.objects.filter(year__gt=2016) # __gt = greater than
+Article.objects.filter(year__lt=2001) # __lt = less than
+
+# Filter on relationship sub model field
+Article.objects.get(user__username='mike')
+
+# Ordering
+Article.objects.order_by('name') # ascending
+Article.objects.order_by('-name') # descending
+
+# Slicing return first
+Article.objects.all().order_by('name')[0]
+
+# Slicing return last
+Article.objects.all().order_by('-name')[0]
+
+# Slicing limit/offset
+Article.objects.all().order_by('name')[1..10]
+
+# Updating
+article = Article.objects.first()
+article.name = 'new name'
+article.save()
+
+# One line update
+Article.objects.filter(id=4).update(name='new name')
+
+# Deleting
+article = Article.objects.first()
+article.delete()
+
+# One line delete
+article.objects.get(id=1).delete()
+
+# Delete all
+Article.objects.all().delete()
+
+# Set ForeignKey field value
+model1 = Model(name='dyson')
+article.model = model1
+
+# Get ForeignKey value
+article1.model.name
+model1.article_set.all()
+
+# Add Many-to-Many
+article1.tags.add(tag1)
+article1.tags.all()
+tag1.articles_set.all()
+```
+
+## Form
+
+In HTML, a form is a collection of elements inside `` that allow a visitor to do things like enter text, select options, manipulate objects or controls, and so on, and then send that information back to the server.
+
+```python
+# app_name/forms.py
+from django import forms
+class ArticleForm(forms.Form):
+ name = forms.Charfield(max_length=100)
+ description = forms.Charfield(blank=True, null = True)
+
+
+# Model Form
+from django.forms import ModelForm
+from app_name.models import Article
+class ArticleForm(ModelForm):
+ class Meta:
+ model = Article
+ fields = ['name', 'description', 'price'] # Use '__all__' for all fields
+ widgets = {
+ 'name': forms.TextInput(attrs={'class': 'form-control'}),
+ }
+ labels = {
+ 'name': 'First Name',
+ }
+ error_messages = {
+ 'name': {'required': 'This field is required',},
+ }
+ help_texts = {
+ 'name': 'Enter Your First Name',
+ }
+
+
+# Render form in template
+
+
+# Bootstrap (pip install django-crispy-forms + installed_apps: 'crispy_forms')
+{% load crispy_forms_tags %}
+{{ form|crispy }}
+{{ form.email|as_crispy_field }}
+
+# crispy-tailwind
+pip install crispy-tailwind
+
+# settings.py
+CRISPY_ALLOWED_TEMPLATE_PACKS = 'tailwind'
+CRISPY_TEMPLATE_PACK = 'tailwind'
+
+# template usage
+{% load tailwind_filters %}
+{{ form|crispy}}
+```
+
+#### Form validation
+
+```python
+# forms.py
+from django.core.exceptions import ValidationError
+
+# field validation
+def clean_first_name(self):
+ data = self.cleaned_data['first_name']
+ if data = 'Mike':
+ raise ValidationError('Your name must not be Mike')
+ return data
+
+# form validation
+def clean(self):
+ first_name = self.cleaned_data['first_name']
+ last_name = self.cleaned_data['last_name']
+ if first_name + last_name = 'MikeTaylor':
+ raise ValidationError('Your name must not be Mike Taylor')
+```
+
+## Flash messages
+
+```python
+messages.success(request, 'Login successful')
+messages.error(request, 'Login error')
+
+# Message tags
+# debug, info, success, warning and error
+
+# Display flash in template
+{% if messages %}
+ {% for message in messages %}
+ {% message %}
+ {% message.tags %}
+```
+
+## User Model
+
+User Model (pre-created)
+
+```python
+# Get a reference to Django pre-created User model
+from django.contrib.auth import get_user_model
+
+User = get_user_model()
+
+# Or if you want to custom user model
+from django.contrib.auth.models import AbstractUser
+
+class User(AbstractUser):
+ # add custom fields and methods
+
+# To make Django use that model go to settings.py and add: AUTH_USER_MODEL = 'app_name.User'
+```
+
+## Authentication Configure
+
+#### Authentication : LoginView
+
+```python
+# LoginView is already pre-created by Django
+from django.contrib.auth.views import LoginView
+
+# Add a url to reach that view
+path('login/', LoginView.as_view(), name='login')
+
+# By default the LoginView will try to open a template name 'registration/login.html' and send a login form with it.
+
+# Create a template under registration/login.html
+{% extends "base.html" %}
+{% block content %}
+
+{% endblock content %}
+
+# When user click the Login button, the LoginView will try to authenticate the user with the form username ans password.
+
+# If successful il will then login the user and redirect to LOGIN_REDIRECT_URL specified in your settings.py
+```
+
+#### Authentication : LogoutView
+
+```python
+# LogoutView is already pre-created by Django
+from django.contrib.auth.views import LogoutView
+
+# Add a url to reach that view
+path('logout/', LoginView.as_view(), name='logout')
+
+# Include a link in a template
+ href="{% url 'logout' %}">Logout
+
+# After link is execute, the user will be logout and redirect to LOGOUT_REDIRECT_URL specified in your settings.py
+```
+
+#### Authentication : SignupView
+
+```python
+# Create a SignupView (that view is not created by default)
+# import sinupview form pre-created by Django
+from django.contrib.auth.forms import UserCreationForm
+from django.views.generic import CreateView
+
+class SignupView(CreateView):
+ template_name = 'registration/signup.html'
+ form_class = UserCreationForm
+
+ def get_success_url(self):
+ return reverse("login")
+
+
+# Create template: registration/signup.html
+{% extends "base.html" %}
+{% block content %}
+
+{% endblock content %}
+
+# Add a url to reach that view
+from posts.views import SignupView
+
+path('signup/', SignupView.as_view(), name='signup')
+
+# Optional: Customize the UserCreationForm
+# (forms.py)
+from django.contrib.auth import get_user_model
+from django.contrib.auth.forms import UserCreationForm
+
+User = get_user_model()
+class CustomUserCreationForm(UserCreattionForm):
+ class Meta:
+ model = User
+ fields = ['username']
+ fields_classes = {'username': UsernameField}
+```
+
+#### Optional pre-created Authentication routes
+
+```python
+# urls.py
+urlpatterns += path('', include('django.contrib.auth.urls'))
+# /login, /lougout, /signup, etc.
+```
+
+#### Template Authentication helpers
+
+```python
+# Authentication links
+Login
+Signup
+Logout
+
+# Check if user login
+{% if request.user.is_authenticated %}
+ Logged in as: {{ request.user.username }}
+{% endif %}
+```
+
+#### Authorization: LoginRequiredMixin and login_required
+
+```python
+from django.contrib.auth.mixins import LoginRequiredMixin
+
+# Restrict views to auth user only (views.py)
+class PostsCreateView(LoginRequiredMixin, generic.CreateView):
+ ...
+ ...
+
+
+from django.contrib.auth.decorators import login_required
+
+@login_required(login_url='/login')
+def search_page(request):
+ ...
+ ...
+```
+
+#### Manual Authentication , Login and Logout
+
+```python
+from django.contrib.auth import authenticate, login
+
+def login_page(request):
+ if request.method == "POST":
+ username = request.POST.get("username")
+ password = request.POST.get("password")
+ user = authenticate(request, username=username, password=password)
+ if user is not None:
+ login(request, user)
+ return redirect("index")
+
+return render(request, "registration/login.html", {})
+
+
+def logout_page(request):
+ logout(request)
+ return redirect("index")
+```
+
+#### User Change password
+
+```python
+# set_password will hash the password
+user.set_password('raw password')
+```
+
+## Create Custom Accounts Model
+
+```python
+~$ python manage.py startapp accounts
+```
+
+```python
+# Add accounts app to settings.py
+INSTALLED_APPS = [ … ,
+ 'accounts.apps.AccountsConfi', ]
+.
+.
+.
+AUTH_USER_MODEL = 'accounts.User'
+```
+
+```python
+# accounts/models.py
+from django.db import models
+from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
+
+class UserManager(BaseUserManager):
+ def create_user(self, username, email, password=None, **extra_fields):
+ if not username:
+ raise ValueError('Users must have an username')
+ if not email:
+ raise ValueError('Users must have an email')
+
+ user = self.model(email=email, **extra_fields)
+ user.set_password(password)
+ user.save(using=self._db)
+ return user
+
+ def create_superuser(self, username, email, password=None, **extra_fields):
+ extra_fields.setdefault('is_staff', True)
+ extra_fields.setdefault('is_superuser', True)
+ extra_fields.setdefault('is_active', True)
+
+ user = self.create_user(username, email, password=password, **extra_fields)
+ user.save(using=self._db)
+ return user
+
+
+class User(AbstractBaseUser, PermissionsMixin):
+ username = models.CharField(verbose_name='Username', max_length=255, unique=True)
+ email = models.EmailField(verbose_name='email', max_length=255, unique=True)
+ phone = models.BigIntegerField(verbose_name='Phone Number', unique=True, blank=True, null=True)
+ is_active = models.BooleanField(default=True, verbose_name="is_active")
+ is_staff = models.BooleanField(default=False, verbose_name="is_staff")
+ is_superuser = models.BooleanField(default=False, verbose_name="is_superuser")
+
+ objects = UserManager()
+
+ # We can use any field for username
+ USERNAME_FIELD = 'username' # or 'email' or 'phone'
+ REQUIRED_FIELDS = ['username', 'email']
+
+ def __str__(self):
+ return self.username
+
+ class Meta:
+ verbose_name = "User"
+ verbose_name_plural = "Users"
+```
+
+```python
+# accounts/forms.py
+from django import forms
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.core.exceptions import ValidationError
+from accounts.models import User
+from django.utils.translation import gettext_lazy as _
+
+
+class UserCreationForm(forms.ModelForm):
+ password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
+ password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone', 'is_active', 'is_staff')
+
+ def clean_password2(self):
+ password1 = self.cleaned_data.get("password1")
+ password2 = self.cleaned_data.get("password2")
+ if password1 and password2 and password1 != password2:
+ raise ValidationError("Passwords don't match")
+ return password2
+
+ def save(self, commit=True):
+ user = super().save(commit=False)
+ user.set_password(self.cleaned_data["password1"])
+ if commit:
+ user.save()
+ return user
+
+
+class UserChangeForm(forms.ModelForm):
+ password = ReadOnlyPasswordHashField()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone', 'is_active', 'is_staff')
+
+ def clean_password(self):
+ return self.initial["password"]
+
+
+class LoginForm(forms.Form):
+ email = forms.CharField(
+ widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), label='Email')
+ password = forms.CharField(
+ widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}),label='Password')
+
+
+class RegisterForm(forms.ModelForm):
+ password1 = forms.CharField(label='Password', widget=forms.PasswordInput(
+ attrs={'class': 'form-control'}))
+ password2 = forms.CharField(label='Password confirmation',
+ widget=forms.PasswordInput(attrs={'class': 'form-control'}))
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone')
+
+ widgets = { # Optional
+ 'username': forms.TextInput(attrs={'class': 'form-control'}),
+ 'email': forms.EmailInput(attrs={'class': 'form-control'}),
+ 'phone': forms.NumberInput(
+ attrs={'class': 'form-control', 'type': 'tel', 'maxlength': '11',
+ 'minlength': '11', 'onkeypress': 'return isNumber(event)', 'required': 'false'})}
+
+ def clean_password2(self):
+ password1 = self.cleaned_data.get("password1")
+ password2 = self.cleaned_data.get("password2")
+ if password1 and password2 and password1 != password2:
+ raise ValidationError("Passwords don't match")
+ else:
+ return password2
+
+ def save(self, commit=True):
+ user = super().save(commit=False)
+ user.set_password(self.cleaned_data["password1"])
+ if commit:
+ user.save()
+ return user
+
+class EditProfileForm(forms.ModelForm):
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone')
+
+
+class ChangePassword(forms.Form):
+ password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput(
+ attrs={'class': 'form-control', 'placeholder': 'Password'}))
+ password2 = forms.CharField(label=_('Password confirmation'),
+ widget=forms.PasswordInput(
+ attrs={'class': 'form-control', 'placeholder': 'Re-Enter Password'}))
+
+ def clean_password2(self):
+ password1 = self.cleaned_data.get("password1")
+ password2 = self.cleaned_data.get("password2")
+ if password1 and password2 and password1 != password2:
+ raise ValidationError("Passwords don't match")
+ else:
+ return password2
+```
+
+```python
+# accounts/admin.py
+from django import forms
+from django.contrib import admin
+from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.core.exceptions import ValidationError
+from django.contrib.auth.models import Group
+from accounts.models import User
+
+
+class UserCreationForm(forms.ModelForm):
+ password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
+ password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone')
+
+ def clean_password2(self):
+ # Check that the two password entries match
+ password1 = self.cleaned_data.get("password1")
+ password2 = self.cleaned_data.get("password2")
+ if password1 and password2 and password1 != password2:
+ raise ValidationError("Passwords don't match")
+ return password2
+
+ def save(self, commit=True):
+ user = super().save(commit=False)
+ user.set_password(self.cleaned_data["password1"])
+ if commit:
+ user.save()
+ return user
+
+
+class UserChangeForm(forms.ModelForm):
+ password = ReadOnlyPasswordHashField()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'phone', 'password', 'is_active', 'is_staff')
+
+
+class UserAdmin(BaseUserAdmin):
+ form = UserChangeForm
+ add_form = UserCreationForm
+ list_display = ('username', 'email', 'is_active', 'is_staff', 'is_superuser')
+ list_editable = ('is_staff', 'is_active')
+ list_filter = ('is_staff', 'groups')
+ fieldsets = (
+ (None, {'fields': ( 'username', 'email', 'phone', 'password')}),
+ ('Permissions', {'fields': ('is_staff',)}),
+ ('Group Permissions', {
+ 'fields': ('is_active', 'is_superuser', 'groups', 'user_permissions'),
+ })
+ )
+ add_fieldsets = (
+ (None, {
+ 'classes': ('wide',),
+ 'fields': ('username', 'email', 'phone', 'password1', 'password2'),
+ }),
+ ('Group Permissions', {
+ 'fields': ('is_active', 'is_superuser', 'groups', 'user_permissions'),
+ })
+ )
+ search_fields = ('username', 'email', 'phone')
+ ordering = ('username', 'email', 'phone')
+ filter_horizontal = ('groups', 'user_permissions',)
+
+
+admin.site.register(User, UserAdmin)
+# unregister the Group model from admin.
+# admin.site.unregister(Group)
+```
+
+```python
+# accounts/urls.py
+from django.urls import path
+from accounts import views
+
+app_name = 'accounts'
+urlpatterns = [
+ path('login/', views.userLogin, name='login'),
+ path('register/', views.userRegister, name='register'),
+ path('logout/', views.LogoutPage, name='logout')
+]
+```
+
+```python
+# accounts/views.py
+from django.shortcuts import render, redirect
+from django.contrib.auth import login, logout, authenticate
+from django.contrib.auth.decorators import login_required
+from django.utils.translation import gettext_lazy as _
+from accounts.forms import LoginForm, RegisterForm
+from django.contrib import messages
+from accounts.models import User
+
+
+def userRegister(request):
+ form = RegisterForm()
+ if request.method == 'POST':
+ form = RegisterForm(request.POST)
+ if form.is_valid():
+ cd = form.cleaned_data
+ if not User.objects.filter(email=cd['username']).exists():
+ if not User.objects.filter(email=cd['email']).exists():
+ user = User.objects.create_user(
+ username=cd['username'], phone=cd['phone'], email=cd['email'], password=cd['password1'])
+ user.save()
+ login(request, user)
+ messages.success(request, _("You successfully registered a user"), extra_tags="success")
+ return redirect('app_name:home')
+ else:
+ messages.error(request, _("This Email is exists"), extra_tags="warning")
+ else:
+ messages.error(request, _("This Username is exists"), extra_tags="warning")
+ else:
+ import json
+ er = json.loads(form.errors.as_json())
+ for e in er:
+ messages.error(request, er[e][0]['message'], 'warning')
+ return render(request, 'accounts/register.html', {'form': form})
+
+
+def userLogin(request):
+ if not request.user.is_active:
+ if request.method == 'POST':
+ form = LoginForm(request.POST)
+ if form.is_valid():
+ cd = form.cleaned_data
+ if User.objects.filter(username=cd['username']).exists():
+ user = authenticate(request, username=cd['username'], password=cd['password'])
+ if user is not None:
+ login(request, user)
+ messages.success(request, _("logged in successfully"), extra_tags="success")
+ return redirect('app_name:home')
+ else:
+ messages.error(request, _("your username Or Password is wrong"), extra_tags="warning")
+ else:
+ messages.error(request, _("No account created with this username"), extra_tags="warning")
+ return redirect('accounts:login')
+ else:
+ messages.error(request, _("Please enter your information correctly"), extra_tags="warning")
+ else:
+ form = LoginForm()
+ return render(request, 'accounts/login.html', {'form': form})
+ else:
+ return redirect('app_name:home')
+
+
+@login_required()
+def LogoutPage(request):
+ logout(request)
+ messages.success(request, _("You Logged Out successfully"), extra_tags="success")
+ return redirect('app_name:home')
+```
+
+## Send Email
+
+```python
+# settings.py
+EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
+
+# Send email function
+from django.core.email import send_mail
+
+send_mail(
+ subject = "A new post has been created",
+ messsage = "Go to the web site to see the detail",
+ from_email = "test@test.com",
+ recipient_list = ["test2@text.com"]
+)
+```
+
+## Signals
+
+```python
+# models.py
+from django.db.models.signals import post_save, pre_save
+
+def post_user_created_signal(sender, instance, created, **kwargs):
+ if created:
+ UserProfile.objects.create(user=instance)
+
+# Launch the post_user_create_singal method if User model is save
+post_save.connect(post_user_created_signal, sender=User)
+```
+
+## Seed
+
+```python
+from app_name.models import Product, Category
+from django.shortcuts import HttpResponse
+from faker import Faker
+
+
+def seed(request):
+ Product.objects.all().delete()
+ Category.objects.all().delete()
+
+ category = Category()
+ category.name = "Sports"
+ category.save()
+
+ category = Category()
+ category.name = "Home"
+ category.save()
+
+ fake = Faker()
+ for _ in range(100):
+ product = Product()
+ product.name = fake.unique.word()
+ product.short_description = fake.sentence()
+ product.main_picture = fake.image_url()
+ product.price = fake.random_digit() * 10
+ product.category = Category.objects.order_by('?').first()
+ product.save()
+
+ return HttpResponse('Seeded')
+```
+
+## Environment Variables
+
+#### .env key/value file
+
+```python
+$ pip install python-decouple
+```
+
+##### Create a file name '.env' in the root folder of your project
+
+```python
+SECRET_KEY = 'your secret key'
+ALLOWED_HOST = 127.0.0.1
+```
+
+##### In settings.py change security related settings to point to the .env file
+
+```python
+from decouple import config
+
+SECRET_KEY = config('SECRET_KEY')
+ALLOWED_HOST = config('ALLOWED_HOST')
+```
+
+## Asynchronous Task with Django Celery Redis
+
+Celery is a distributed task queue that can collect, record, schedule, and perform tasks outside of your main program.
+
+##### Step 1: Install Celery Using pip
+
+```python
+~$ pip install celery # pip install celery[redis]
+```
+
+##### Step 2. Add celery.py File in Your Project Module
+
+```python
+# your_project/celery.py
+import os
+from celery import Celery
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE','your_project_name.settings')
+app = Celery('your_project_name')
+app.config_from_object('django.conf:settings', namespace='CELERY')
+app.autodiscover_tasks()
+
+@app.task(bind=True)
+def debug_task(self):
+ print(f'Request: {self.request!r}')
+```
+
+##### Step 3: Import the Celery App to Django
+
+To ensure that the Celery app is loaded when Django starts, add the following code into the `__init__.py` file that sits on the project module beside on settings.py file.
+
+```python
+# your_project/__init__.py
+from .celery import app as celery_app
+
+__all__ = ('celery_app',)
+```
+
+##### Step 4: Download and Run Redis as a Celery ‘broker’
+
+```python
+~$ redis-server
+```
+
+You can test that Redis is working properly by typing this into your terminal:
+
+```python
+~$ redis-cli ping
+```
+
+> Redis should reply with PONG - try it!
+
+##### Step 5: Add Redis as a Dependency in the Django Project:
+
+```python
+~$ pip install redis
+```
+
+##### step 6: Celery Stuff Configure to the Django Settings File
+
+Once Redis is up, add the following code to your settings.py file and use celery-result
+
+```python
+~$ pip install django-celery-results
+```
+
+> This extension enables you to store Celery task results using the Django ORM.
+> It defines a single model (`django_celery_results.models.TaskResult`) used to store task results, and you can query this database table like any other Django model.
+
+```python
+INSTALLED_APPS = [
+ … ,
+ 'django_celery_results',
+ ]
+
+BROKER_URL = 'redis://localhost:6379'
+CELERY_RESULT_BACKEND = 'redis://localhost:6379'
+CELERY_ACCEPT_CONTENT = ['application/json']
+CELERY_TASK_SERIALIZER = 'json'
+CELERY_RESULT_SERIALIZER = 'json'
+CELERY_TIMEZONE = TIME_ZONE
+CELERY_RESULT_BACKEND = 'django-db'
+CELERY_CACHE_BACKEND = 'django-cache'
+
+CACHES = {
+ 'default': {
+ 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
+ 'LOCATION': 'redis://localhost:6379/1',
+ "OPTIONS": {
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
+ }
+ }
+}
+```
+
+##### That’s it! You should now be able to use Celery with Django
+
+Test that the Celery worker is ready to receive tasks:
+
+```python
+~$ celery -A your_project_name worker -l info
+```
+
+> The most important task is: Always run a worker is needed to execute the celery task if any error throws from Redis like this:
+
+```python
+AttributeError: 'str' object has no attribute 'items'
+```
+
+- the solution is: you have to use Redis old version
+
+#### Add a New Task to the Celery Step by Step:
+
+##### Step 1: Add tasks.py File to Your Django App.
+
+```python
+# app_name/tasks.py
+from celery import shared_task
+from celery.decorators import task
+from time import sleep
+
+
+@task(name='my_first_task')
+def my_first_task(duration):
+ sleep(duration)
+ return('first_task_done')
+
+@shared_task
+def test_func():
+ for i in range(10):
+ print(i)
+ return 'End_OK'
+
+@shared_task
+def adding(x, y):
+ time.sleep(10)
+ result = x + y
+ return result
+```
+
+##### Step 2: Assign Task to the Celery.
+
+You need to assign a task to the celery. To assign this task you need to call this function with something different. celery gives us two methods `delay()` and `apply_async()` to call task.
+
+```bash
+# Normal function call in python
+~$ my_first_task()
+
+# add task to the celery with function call
+~$ my_first_task.delay()
+```
+
+> you can send argument to the function using the delay method.
+> To check celery on the action open a separate tab of the terminal then go to the project directory (activate environment if you are using one) and run this command again
+
+```bash
+~$ celery -A your_project_name worker -l info
+```
+
+##### Create a View in your App
+
+```python
+# app_name/views.py
+from django.http import HttpResponse
+from app_name.tasks import my_first_task, test_func, adding
+
+def index(request):
+ my_first_task.delay(10)
+ result = adding.delay(x=4, y=5)
+ return HttpResponse(f'response done. {result}')
+
+def test(request):
+ test_func.delay()
+ return HttpResponse("Done")
+```
+
+##### Then call the view from your app URL
+
+```python
+# app_name/urls.py
+from django.urls import path
+from app_name.views import index, test
+urlpatterns = [
+ path('celery-index/', index, name='celery_index_url'),
+ path('celery-test/', test, name='celery_test_url'),
+]
+```
+
+### Celery In Production Using Supervisor on Linux Server Step by Step:
+
+#### Step 1: Install Supervisor on Ubuntu Server
+
+```bash
+~$ sudo apt-get install supervisor
+```
+
+#### Step 2: Add .conf File in Supervisor
+
+```bash
+~$ sudo nano /etc/supervisor/conf.d/app_name.conf
+```
+
+> app_name can be anything you like, it should be similar to your project name.
+
+#### Step 3: Add some Configure in app_name.conf
+
+```bash
+[program:your_app_name]
+command=/path/to/env/bin/celery worker -A your_project_name --loglevel=INFO
+directory=/path/to/workflow/your_project_name/
+user=www-data
+autostart=true
+autorestart=true
+stdout_logfile=/path/to/workflow/your_project_name/logs/celeryd.log
+redirect_stderr=true
+```
+
+> let's describe the configure file:
+
+```bash
+[program:your_app_name]
+#The name of your supervisord program
+
+command=/path/to/env/bin/celery worker -A your_project_name --loglevel=INFO
+#Set full path to celery program if using virtualenv
+
+directory=/path/to/workflow/your_project_name/
+#The directory to your Django project
+
+user=www-data
+#The web server has to be run under a specific user. That user must exist.
+
+autostart=true
+#If true, this program will start automatically when supervisord is started
+
+autorestart=true
+#May be one of false, unexpected, or true. If false, the process will never be autorestarted. If unexpected, the process will be restart when the program exits with an exit code that is not one of the exit codes associated with this process’ configuration (see exitcodes). If true, the process will be unconditionally restarted when it exits, without regard to its exit code.
+
+stdout_logfile=/path/to/workflow/your_project_name/logs/celeryd.log
+#Put process stdout output in this file
+
+redirect_stderr=true
+#If true, cause the process’ stderr output to be sent back to supervisord on its stdout file descriptor (in UNIX shell terms, this is the equivalent of executing /the/program 2>&1).
+```
+
+#### Step 4: Inform Configuration to the Server
+
+After adding a new program, we should run the following two commands, to inform the server to reread the configuration files and to apply any changes.
+
+```python
+~$ sudo supervisorctl reread
+~$ sudo supervisorctl update
+```
+
+#### Managing Supervisor App
+
+```bash
+~$ sudo supervisorctl
+```
+
+You will be greeted with a list of the registered processes. You will see a process called `your_app_name` with a `RUNNING` status.
+
+```bash
+your_app_name RUNNING pid 6853, uptime 0:22:30
+supervisor>
+```
+
+Type `help` for a list of available commands.
+
+```bash
+supervisor> help
+default commands (type help ):
+=====================================
+add exit open reload restart start tail
+avail fg pid remove shutdown status update
+clear maintail quit reread signal stop version
+```
+
+In a nutshell, we can `start`, `stop` and `restart` programs bypassing the program name as an argument to the respective command.
+We can also take a look at the program output with the `tail` command.
+Once you are finished, you can `quit`.
+
+```bash
+~$ supervisor> quit
+```
diff --git a/source/_posts/go.md b/source/_posts/go.md
index 3f3cfb8..ad7fdf3 100644
--- a/source/_posts/go.md
+++ b/source/_posts/go.md
@@ -1006,8 +1006,64 @@ func main() {
var r Shape = Rectangle{Length: 3, Width: 4}
fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
}
+
+```
+Go generics {.cols-2}
+-------------
+
+
+### example 1
+```go
+// comparable represents types that can be compared.
+type comparable interface {
+ int | float64 | string
+}
+
+// Max returns the maximum of two comparable values.
+func Max[T comparable](a, b T) T {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func main() {
+ // Find the maximum of two integers.
+ maxInt := Max(10, 20)
+ fmt.Println("Max integer:", maxInt)
+
+ // Find the maximum of two floats.
+ maxFloat := Max(3.14, 2.71)
+ fmt.Println("Max float:", maxFloat)
+
+ // Find the maximum of two strings.
+ maxString := Max("apple", "banana")
+ fmt.Println("Max string:", maxString)
+}
+
```
+### example 2
+```go
+
+// Pair[T, U] represents a generic pair of values.
+type Pair[T, U any] struct {
+ First T
+ Second U
+}
+
+func main() {
+ pair := Pair[int, string]{First: 42, Second: "hello"}
+
+ fmt.Println("First:", pair.First)
+ fmt.Println("Second:", pair.Second)
+
+ // Print the types of the values in the pair.
+ fmt.Println("Type of First:", reflect.TypeOf(pair.First))
+ fmt.Println("Type of Second:", reflect.TypeOf(pair.Second))
+}
+
+```
Miscellaneous
-------------
@@ -1037,6 +1093,8 @@ Miscellaneous
- import
- return
- var
+- iota
+
{.cols-3 .marker-none}
### Operators and punctuation
diff --git a/source/_posts/http-status-code.md b/source/_posts/http-status-code.md
index e8fc37c..4ac62f2 100644
--- a/source/_posts/http-status-code.md
+++ b/source/_posts/http-status-code.md
@@ -3,21 +3,21 @@ title: HTTP Status Code
background: bg-[#3b7dc0]
date: 2020-12-26 16:09:09
tags:
- - response
- - server
+ - response
+ - server
categories:
- - Other
+ - Other
intro: |
- The http status codes cheat sheet. a quick reference to every HTTP status code.
+ The HTTP status codes cheat sheet. A quick reference to every HTTP status code.
plugins:
- - tooltip
+ - tooltip
---
HTTP Status code
-----------
-### Means
+### Means
- [1xx: Informational](#1xx-information){data-tooltip="It means the request has been received and the process is continuing."}
- [2xx: Success](#2xx-successful){data-tooltip="It means the action was successfully received, understood, and accepted."}
@@ -26,20 +26,20 @@ HTTP Status code
- [5xx: Server Error](#5xx-server-error){data-tooltip="It means the server failed to fulfill an apparently valid request."}
-
### 2xx. Successful {.row-span-2}
* [200: OK](https://tools.ietf.org/html/rfc7231#section-6.3.1){data-tooltip="The request is OK."}
-* [201: Created](https://tools.ietf.org/html/rfc7231#section-6.3.2){data-tooltip="The request is complete, and a new resource is created ."}
+* [201: Created](https://tools.ietf.org/html/rfc7231#section-6.3.2){data-tooltip="The request is complete, and a new resource is created."}
* [202: Accepted](https://tools.ietf.org/html/rfc7231#section-6.3.3){data-tooltip="The request is accepted for processing, but the processing is not complete."}
* [203: Non-Authoritative Information](https://tools.ietf.org/html/rfc7231#section-6.3.4){data-tooltip="The information in the entity header is from a local or third-party copy, not from the original server."}
* [204: No Content](https://tools.ietf.org/html/rfc7231#section-6.3.5){data-tooltip="A status code and a header are given in the response, but there is no entity-body in the reply."}
* [205: Reset Content](https://tools.ietf.org/html/rfc7231#section-6.3.6){data-tooltip="The browser should clear the form used for this transaction for additional input."}
* [206: Partial Content](https://tools.ietf.org/html/rfc7233#section-4.1){data-tooltip="The server is returning partial data of the size requested. Used in response to a request specifying a Range header. The server must specify the range included in the response with the Content-Range header."}
+* [207: Multi-Status](https://tools.ietf.org/html/rfc4918#section-11.1){data-tooltip="Provides status for multiple independent operations."}
+* [208: Already Reported](https://tools.ietf.org/html/rfc5842#section-7.1){data-tooltip="Used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly."}
+* [226: IM Used](https://tools.ietf.org/html/rfc3229#section-10.4.1){data-tooltip="The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance."}
-
-
-### 4xx. Client Error {.row-span-3}
+### 4xx. Client Error {.row-span-3}
* [400: Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1){data-tooltip="The server did not understand the request."}
* [401: Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1){data-tooltip="The requested page needs a username and a password."}
* [402: Payment Required](https://tools.ietf.org/html/rfc7231#section-6.5.2){data-tooltip="You can not use this code yet."}
@@ -50,38 +50,39 @@ HTTP Status code
* [407: Proxy Authentication Required](https://tools.ietf.org/html/rfc7235#section-3.2){data-tooltip="You must authenticate with a proxy server before this request can be served."}
* [408: Request Timeout](https://tools.ietf.org/html/rfc7231#section-6.5.7){data-tooltip="The request took longer than the server was prepared to wait."}
* [409: Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8){data-tooltip="The request could not be completed because of a conflict."}
-* [410: Gone](https://tools.ietf.org/html/rfc7231#section-6.5.9){data-tooltip="The requested page is no longer available ."}
-* [411: Length Required](https://tools.ietf.org/html/rfc7231#section-6.5.10){data-tooltip="The "Content-Length" is not defined. The server will not accept the request without it ."}
+* [410: Gone](https://tools.ietf.org/html/rfc7231#section-6.5.9){data-tooltip="The requested page is no longer available."}
+* [411: Length Required](https://tools.ietf.org/html/rfc7231#section-6.5.10){data-tooltip="The "Content-Length" is not defined. The server will not accept the request without it."}
* [412: Precondition Failed](https://tools.ietf.org/html/rfc7232#section-4.2){data-tooltip="The pre condition given in the request evaluated to false by the server."}
* [413: Payload Too Large](https://tools.ietf.org/html/rfc7231#section-6.5.11){data-tooltip="The server will not accept the request, because the request entity is too large."}
-* [414: URI Too Long](https://tools.ietf.org/html/rfc7231#section-6.5.12){data-tooltip="The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information ."}
-* [415: Unsupported Media Type](https://tools.ietf.org/html/rfc7231#section-6.5.13){data-tooltip="The server will not accept the request, because the mediatype is not supported ."}
+* [414: URI Too Long](https://tools.ietf.org/html/rfc7231#section-6.5.12){data-tooltip="The server will not accept the request, because the URL is too long. Occurs when you convert a "post" request to a "get" request with a long query information."}
+* [415: Unsupported Media Type](https://tools.ietf.org/html/rfc7231#section-6.5.13){data-tooltip="The server will not accept the request, because the media type is not supported."}
* [416: Range Not Satisfiable](https://tools.ietf.org/html/rfc7233#section-4.4){data-tooltip="The requested byte range is not available and is out of bounds."}
* [417: Expectation Failed](https://tools.ietf.org/html/rfc7231#section-6.5.14){data-tooltip="The expectation given in an Expect request-header field could not be met by this server."}
+* [421: Misdirected Request](https://tools.ietf.org/html/rfc7540#section-9.1.2){data-tooltip="The request was directed at a server that is not able to produce a response."}
* [426: Upgrade Required](https://tools.ietf.org/html/rfc7231#section-6.5.15){data-tooltip="The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."}
+* [428: Precondition Required](https://tools.ietf.org/html/rfc6585#section-3){data-tooltip="The origin server requires the request to be conditional."}
+* [429: Too Many Requests](https://tools.ietf.org/html/rfc6585#section-4){data-tooltip="The user has sent too many requests in a given amount of time."}
+* [431: Request Header Fields Too Large](https://tools.ietf.org/html/rfc6585#section-5){data-tooltip="The server is unwilling to process the request because its header fields are too large."}
* [451: Unavailable For Legal Reasons](https://datatracker.ietf.org/doc/html/rfc7725#section-3){data-tooltip="This status code indicates that the server is denying access to the resource as a consequence of a legal demand."}
-
-
-
### 1xx. Information
* [100: Continue](https://tools.ietf.org/html/rfc7231#section-6.2.1){data-tooltip="Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request."}
* [101: Switching Protocols](https://tools.ietf.org/html/rfc7231#section-6.2.2){data-tooltip="The server switches protocol."}
* [102: Processing](https://tools.ietf.org/html/rfc2518#section-10.1){data-tooltip="An interim response used to inform the client that the server has accepted the complete request, but has not yet completed it."}
-
-
+* [103: Early Hints](https://tools.ietf.org/html/rfc8297){data-tooltip="Indicates to the client that the server is likely to send a final response with the header fields included in the informational response."}
### 3xx. Redirection
-* [300: Multiple Choices](https://tools.ietf.org/html/rfc7231#section-6.4.1){data-tooltip="A link list. The user can select a link and go to that location. Maximum five addresses ."}
-* [301: Moved Permanently](https://tools.ietf.org/html/rfc7231#section-6.4.2){data-tooltip="The requested page has moved to a new url ."}
-* [302: Found](https://tools.ietf.org/html/rfc7231#section-6.4.3){data-tooltip="The requested page has moved temporarily to a new url ."}
-* [303: See Other](https://tools.ietf.org/html/rfc7231#section-6.4.4){data-tooltip="The requested page can be found under a different url ."}
+* [300: Multiple Choices](https://tools.ietf.org/html/rfc7231#section-6.4.1){data-tooltip="A link list. The user can select a link and go to that location. Maximum five addresses."}
+* [301: Moved Permanently](https://tools.ietf.org/html/rfc7231#section-6.4.2){data-tooltip="The requested page has moved to a new URL."}
+* [302: Found](https://tools.ietf.org/html/rfc7231#section-6.4.3){data-tooltip="The requested page has moved temporarily to a new URL."}
+* [303: See Other](https://tools.ietf.org/html/rfc7231#section-6.4.4){data-tooltip="The requested page can be found under a different URL."}
* [304: Not Modified](https://tools.ietf.org/html/rfc7232#section-4.1){data-tooltip="This is the response code to an If-Modified-Since or If-None-Match header, where the URL has not been modified since the specified date."}
* [305: Use Proxy](https://tools.ietf.org/html/rfc7231#section-6.4.5){data-tooltip="The requested URL must be accessed through the proxy mentioned in the Location header."}
* [306: Unused](https://tools.ietf.org/html/rfc7231#section-6.4.6){data-tooltip="This code was used in a previous version. It is no longer used, but the code is reserved."}
-* [307: Temporary Redirect](https://tools.ietf.org/html/rfc7231#section-6.4.7){data-tooltip="The requested page has moved temporarily to a new url."}
+* [307: Temporary Redirect](https://tools.ietf.org/html/rfc7231#section-6.4.7){data-tooltip="The requested page has moved temporarily to a new URL."}
+* [308: Permanent Redirect](https://tools.ietf.org/html/rfc7538#section-3){data-tooltip="The request and all future requests should be repeated using another URI."}
### 5xx. Server Error
@@ -91,4 +92,8 @@ HTTP Status code
* [503: Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4){data-tooltip="The request was not completed. The server is temporarily overloading or down."}
* [504: Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5){data-tooltip="The gateway has timed out."}
* [505: HTTP Version Not Supported](https://tools.ietf.org/html/rfc7231#section-6.6.6){data-tooltip="The server does not support the "http protocol" version."}
-
+* [506: Variant Also Negotiates](https://tools.ietf.org/html/rfc2295#section-8.1){data-tooltip="Transparent content negotiation for the request results in a circular reference."}
+* [507: Insufficient Storage](https://tools.ietf.org/html/rfc4918#section-11.5){data-tooltip="The server is unable to store the representation needed to complete the request."}
+* [508: Loop Detected](https://tools.ietf.org/html/rfc5842#section-7.2){data-tooltip="The server detected an infinite loop while processing the request."}
+* [510: Not Extended](https://tools.ietf.org/html/rfc2774#section-7){data-tooltip="Further extensions to the request are required for the server to fulfill it."}
+* [511: Network Authentication Required](https://tools.ietf.org/html/rfc6585#section-6){data-tooltip="The client needs to authenticate to gain network access."}
diff --git a/source/_posts/kotlin.md b/source/_posts/kotlin.md
index b4701bd..38cd111 100644
--- a/source/_posts/kotlin.md
+++ b/source/_posts/kotlin.md
@@ -378,7 +378,7 @@ then, true || evaluates to false and eventually returns true
```kotlin
var studied = true
-var well Rested = true
+var wellRested = true
if (wellRested) {
println("Good luck today!")
diff --git a/source/_posts/latex.md b/source/_posts/latex.md
index 242bfde..2072fea 100644
--- a/source/_posts/latex.md
+++ b/source/_posts/latex.md
@@ -248,7 +248,7 @@ preview | method | preview | method | preview | method | preview | method
:- | :- | :- | :-
:- | :- | :- | :-
| Correct: | `\tan(at-n\pi)` | `KaTeX:\rightarrow` | `KaTeX:\tan(at-n\pi)`|
-| Incorrect: | `tan(at-n\pi)` | `katex:\rightarrow` | `KaTeX:tan(at-n\pi)` | {.left-align}
+| Incorrect: | `tan(at-n\pi)` | `KaTeX:\rightarrow` | `KaTeX:tan(at-n\pi)` | {.left-align}
### Logic and Set Theory{.col-span-3}
diff --git a/source/_posts/mysql.md b/source/_posts/mysql.md
index 1e94cec..9a413e9 100644
--- a/source/_posts/mysql.md
+++ b/source/_posts/mysql.md
@@ -558,7 +558,7 @@ ON t(c3,c4)
Drop an index
```sql
-DROP INDEX idx_name;
+DROP INDEX idx_name ON t;
```
diff --git a/source/_posts/openssl.md b/source/_posts/openssl.md
new file mode 100644
index 0000000..e7ba48a
--- /dev/null
+++ b/source/_posts/openssl.md
@@ -0,0 +1,328 @@
+---
+title: OpenSSL
+date: 2020-11-25 18:28:43
+icon: icon-style
+background: bg-emerald-600
+tags:
+categories:
+- Linux Command
+intro: |
+ This is a reference of commands to use to interact with electronic certificates
+plugins:
+- copyCode
+---
+
+## Private Key {.cols-2}
+
+### Print out the private key details
+
+```bash
+openssl rsa -check -text -in privateKey.key
+```
+
+### Print out the hashes of the private key
+
+```bash
+openssl rsa -noout -modulus -in privateKey.key | openssl md5
+openssl rsa -noout -modulus -in privateKey.key | openssl sha1
+openssl rsa -noout -modulus -in privateKey.key | openssl sha256
+openssl rsa -noout -modulus -in privateKey.key | openssl sha512
+```
+
+### Change password
+
+```bash
+openssl rsa -aes256 -in privateKey.key -out newPrivateKey.key
+```
+
+### List available elliptic curves
+
+```bash
+openssl ecparam -list_curves
+```
+
+### Create elliptic curve private key with a specific curve
+
+```bash
+openssl ecparam -name secp521r1 -genkey -noout -out privateKey.key
+```
+
+## Certificate {.cols-2}
+
+### Print out the hashes of the certificate
+
+```bash
+openssl x509 -noout -modulus -in certificate.crt | openssl md5
+openssl x509 -noout -modulus -in certificate.crt | openssl sha1
+openssl x509 -noout -modulus -in certificate.crt | openssl sha256
+openssl x509 -noout -modulus -in certificate.crt | openssl sha512
+```
+
+Or, alternatively:
+
+```bash
+openssl x509 -noout -fingerprint -in certificate.crt
+openssl x509 -noout -fingerprint -sha256 -in certificate.crt
+```
+
+### Print out the content of the certificates
+
+```bash
+openssl x509 -in certificate.crt -noout -text|more
+```
+
+### Print out specific fields of the certificates
+
+```bash
+openssl x509 -noout -subject certificate.crt
+openssl x509 -noout -issuer certificate.crt
+openssl x509 -noout -dates certificate.crt
+```
+
+### Inspect server certificates
+
+```bash
+echo | openssl s_client -servername www.openssl.org -connect \
+www.openssl.org:443 2>/dev/null | openssl x509 -noout -text|more
+echo | openssl s_client -servername imap.arcor.de -connect \
+imap.arcor.de:993 2>/dev/null | openssl x509 -noout -text|more
+```
+
+### Verify certificates
+
+**OK**
+
+```bash
+openssl verify -verbose -x509_strict -CAfile \
+issuer.crt Test\ Haeschen\ 1.crt
+```
+Result:
+```bash
+Test Haeschen 1.crt: OK
+```
+
+**Corrupted** ([for example](https://security.stackexchange.com/questions/60804/creating-an-x-509-certificate-with-an-invalid-signature))
+
+```bash
+openssl verify -verbose -x509_strict -CAfile \
+issuer.crt Test\ Haeschen\ 1_corrupted.crt
+```
+Result:
+```bash
+C = DE, ST = Thueringen, L = Rudolstadt, O = Damaschkestr. 11, OU = Arbeitszimmer, CN = Test Haeschen 1
+error 7 at 0 depth lookup: certificate signature failure
+error Test Haeschen 1_corrupted.crt: verification failed
+40270500477F0000:error:0200008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding:../crypto/rsa/rsa_pk1.c:75:
+40270500477F0000:error:02000072:rsa routines:rsa_ossl_public_decrypt:padding check failed:../crypto/rsa/rsa_ossl.c:598:
+40270500477F0000:error:1C880004:Provider routines:rsa_verify:RSA lib:../providers/implementations/signature/rsa_sig.c:774:
+40270500477F0000:error:06880006:asn1 encoding routines:ASN1_item_verify_ctx:EVP lib:../crypto/asn1/a_verify.c:217:
+```
+
+## S/Mime {.cols-2}
+
+### create signature
+
+```bash
+openssl smime -sign -in msg.txt -text -out msg.p7s \
+-signer certificate.crt -inkey privateKey.key
+```
+
+
+### Verify signature
+
+```bash
+openssl smime -verify -in msg.p7s -CAfile chain.pem
+```
+
+
+## CRL {.cols-2}
+
+### Print out the contents of the CRL
+
+```bash
+openssl crl -inform DER -noout -text -in crl/cacrl.der
+openssl crl -inform PEM -noout -text -in crl/cacrl.pem
+```
+
+## PKCS#12 {.cols-2}
+
+### Display contents
+
+```bash
+openssl pkcs12 -info -in digitalIdentity.p12
+```
+
+### Create from certificate and private key
+
+```bash
+openssl pkcs12 -export -in certificate.cert \
+-inkey privateKey.key -out digitalIdentity.p12
+```
+
+### Extract private key
+
+```bash
+openssl pkcs12 -in digitalIdentity.p12 -out privateKey.key
+```
+
+### Convert to PEM
+
+```bash
+openssl pkcs12 -in digitalIdentity.p12 -out digitalIdentity.pem
+```
+
+## TSA {.cols-2}
+
+### Display query
+
+```bash
+openssl ts -query -in query.tsq -text
+```
+
+### Display reply
+
+```bash
+openssl ts -reply -in reply.tsr -text
+```
+
+### Verify reply
+
+```bash
+openssl ts -verify -in reply.tsr -data data.dat -CAfile chain.pem
+```
+
+### Extract token from reply
+
+```bash
+openssl ts -reply -in reply.tsr -token_out -out token.tk
+```
+
+### Extract certificates from token
+
+```bash
+openssl pkcs7 -inform DER -in token.tk -print_certs -noout -text
+```
+
+## CSR {.cols-2}
+
+### Create from existing key
+
+```bash
+openssl req -new -key privateKey.key -out my.csr
+```
+
+This can of course be a RSA key or one based on an elliptic curve. Available curves can be listed using
+
+```bash
+openssl ecparam -list_curves
+```
+
+Afterwards you chose one of the curves and create a private key like so:
+
+```bash
+openssl ecparam -name secp521r1 -genkey -noout \
+-out privateKey.key
+```
+
+### Display
+
+```bash
+openssl req -in my.csr -noout -text
+```
+
+## HTTPS {.cols-2}
+
+### Dump Certificates PEM encoded
+```bash
+openssl s_client -showcerts -connect www.example.com:443
+```
+
+## STARTTLS {.cols-2}
+
+### Dump Certificates PEM encoded
+```bash
+openssl s_client -showcerts -starttls imap \
+-connect mail.domain.com:139
+```
+
+## S/MIME verification {.cols-2}
+
+### Possible outcomes
+
+Message was tampered with (return code 4):
+
+```bash
+Verification failure
+140485684135232:error:2E09A09E:CMS routines:CMS_SignerInfo_verify_content:verification failure:../crypto/cms/cms_sd.c:847:
+140485684135232:error:2E09D06D:CMS routines:CMS_verify:content verify error:../crypto/cms/cms_smime.c:393:
+```
+
+Message signature not trusted (return code 4):
+
+```bash
+Verification failure
+140146111432000:error:2E099064:CMS routines:cms_signerinfo_verify_cert:certificate verify error:../crypto/cms/cms_smime.c:252:Verify error:unable to get local issuer certificate
+```
+
+Message not signed (return code 2):
+
+```bash
+Error reading S/MIME message
+140701208487232:error:0D0D40CD:asn1 encoding routines:SMIME_read_ASN1:invalid mime type:../crypto/asn1/asn_mime.c:469:type: multipart/alternative
+```
+
+Validation successful (return code 0):
+
+```bash
+Verification successful
+```
+
+### Verify the validity of an email message
+
+```bash
+openssl cms -verify -in some_email_message.eml
+```
+
+### Verify the validity of an email message explicitly specifying trust
+
+```bash
+openssl cms -verify -in some_email_message \
+-CAfile trust_anchor-crt
+```
+
+### Signed and encrypted messages need to be decrypted first:
+
+Note: the P12 file holding the digital identity must be pem-encoded! (see above)
+
+```bash
+openssl cms -decrypt -out decrypted_email_message \
+-inkey p12.pem -in some_encrypted_email_message
+```
+
+## Raw {.cols-2}
+
+### See the raw structure of an ASN.1 file (only for DER encoded files)
+
+```bash
+openssl asn1parse -in mysterious_file.pem
+```
+
+### With a bit more detail
+
+```bash
+openssl asn1parse -dump -strictpem -in mysterious_file.pem
+```
+
+## Some resources with useful OpenSSL commands
+
+* [OpenSSL command cheatsheet](https://www.freecodecamp.org/news/openssl-command-cheatsheet-b441be1e8c4a/)
+* [21 OpenSSL Examples to Help You in Real-World](https://geekflare.com/openssl-commands-certificates/)
+* [The Most Common OpenSSL Commands](https://www.sslshopper.com/article-most-common-openssl-commands.html)
+* [OpenSSL Quick Reference Guide](https://www.digicert.com/ssl-support/openssl-quick-reference-guide.htm)
+* [openssl_commands.md](https://gist.github.com/webtobesocial/5313b0d7abc25e06c2d78f8b767d4bc3)
+* [OpenSSL Essentials: Working with SSL Certificates, Private Keys and CSRs](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
+* [OpenSSL tips and tricks](https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art030)
+* [Checking A Remote Certificate Chain With OpenSSL ](https://langui.sh/2009/03/14/checking-a-remote-certificate-chain-with-openssl/)
+* [OpenSSL: how to extract certificates and token status from RFC3161 timestamping reply?](https://stackoverflow.com/questions/66044640/openssl-how-to-extract-certificates-and-token-status-from-rfc3161-timestamping)
+* [Steps to generate CSR for SAN certificate with openssl](https://www.golinuxcloud.com/openssl-subject-alternative-name/)
+* [Howto add a Subject Alternative Name extension into a Certificate Signing Request](https://support.microfocus.com/kb/doc.php?id=3522065)
diff --git a/source/_posts/react.md b/source/_posts/react.md
index 7743c74..db3c2d0 100644
--- a/source/_posts/react.md
+++ b/source/_posts/react.md
@@ -382,4 +382,189 @@ export default function Weather(props) {
}
}
```
-Note: Make sure to import Axios first to your project.
\ No newline at end of file
+Note: Make sure to import Axios first to your project.
+
+
+HOOKS
+------------
+
+### useState Hook
+
+```javascript
+import React, { useState } from "react";
+
+function Counter() {
+ const [count, setCount] = useState(0);
+
+ return (
+
+
Count: {count}
+
+
+ );
+}
+
+export default Counter;
+```
+Note: The useState Hook is a built-in React Hook that allows functional components to manage local state. It provides a way to declare state variables and update them within a functional component.
+Example code illustrating how to use it
+
+
+### Multiple State Variable Declaration
+
+```javascript
+import React, { useState } from "react";
+
+function Counter() {
+ const [count, setCount] = useState(0);
+ const [name, setName] = useState("");
+ const [isCompleted, setIsCompleted] = useState(false);
+
+ const handleIncrement = () => {
+ setCount(count + 1);
+ };
+
+ const handleNameChange = (event) => {
+ setName(event.target.value);
+ };
+
+ const toggleCompletion = () => {
+ setIsCompleted(!isCompleted);
+ };
+
+ return (
+
+
Count: {count}
+
+
+
+
+
+
+ );
+}
+
+export default Counter;
+```
+Note: You can declare multiple state variables using the useState Hook by calling it multiple times in a functional component. Each call to useState manages a separate piece of state.
+
+### Input State Management
+
+```javascript
+import { useState } from "react";
+
+function FormExample() {
+ const [formData, setFormData] = useState({name: "",email: "",message: ""});
+
+ const handleChange = (event) => {
+ const { name, value } = event.target;
+ setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
+ };
+
+ const handleSubmit = (event) => {
+ event.preventDefault();
+ alert(`Name: ${formData.name}, Email: ${formData.email}, Message: ${formData.message}`
+ );
+};
+
+ return (
+
+ );
+}
+
+export default FormExample;
+```
+
+### useEffect Hook
+
+```javascript
+import React, { useState, useEffect } from "react";
+
+function Timer() {
+ const [seconds, setSeconds] = useState(0);
+
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setSeconds((prevSeconds) => prevSeconds + 1);
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, []);
+
+ return
Seconds: {seconds}
;
+}
+
+export default Timer;
+```
+Note: The useEffect Hook in React is used for performing side effects in functional components. It allows you to execute code based on component lifecycle events like mounting, updating, and unmounting.
+
+### Fetch API using useEffect
+
+```javascript
+import React, { useState, useEffect } from "react";
+import axios from "axios";
+
+function UserList() {
+ const [users, setUsers] = useState([]);
+
+ useEffect(() => {
+ axios.get("https://jsonplaceholder.typicode.com/users")
+ .then(response => {
+ setUsers(response.data);
+ })
+ .catch(error => {
+ console.error("Error fetching users:", error);
+ });
+ }, []);
+
+ return (
+
+
User List
+
+ {users.map(user => (
+
{user.name}
+ ))}
+
+
+ );
+}
+
+export default UserList;
+```
+Note: Make sure to import Axios first to your project.
+
+### Custom Hook creation useLocalStorage
+
+```javascript
+import { useState, useEffect } from "react";
+
+function useLocalStorage(key, initialValue) {
+ const [value, setValue] = useState(() => {
+ const storedValue = localStorage.getItem(key);
+ return storedValue !== null ? JSON.parse(storedValue) : initialValue;
+ });
+
+ useEffect(() => {
+ localStorage.setItem(key, JSON.stringify(value));
+ }, [key, value]);
+
+ return [value, setValue];
+}
+
+export default useLocalStorage;
+```
+Note: Custom Hooks are reusable functions in React that contain logic shared across multiple components. They allow you to extract stateful logic from components into standalone functions.
\ No newline at end of file
diff --git a/source/_posts/ruby.md b/source/_posts/ruby.md
new file mode 100644
index 0000000..13f972a
--- /dev/null
+++ b/source/_posts/ruby.md
@@ -0,0 +1,2254 @@
+---
+title: Ruby
+date: 2024-04-25 09:50:25
+background: bg-red-500
+tags:
+ - script
+ - interpret
+categories:
+ - Programming
+intro: |
+ The [Ruby](https://www.ruby-lang.org/) cheat sheet is a one-page reference sheet for the Ruby programming language.
+plugins:
+ - copyCode
+---
+
+Getting Started
+---------------
+
+### Install
+
+```bash
+# Debian, Ubuntu
+$ sudo apt-get install ruby-full
+# Windows
+$ winget install RubyInstallerTeam.Ruby
+$ brew install ruby # macOS
+$ docker run -it --rm ruby:latest # Docker
+```
+
+### What is Gemfile and Gemfile.lock {.row-span-2}
+
+- [Gemfile](https://bundler.io/v2.3/man/gemfile.5.html) Is the Bundler (also gem) configuration file that contains the project's gem list (dependencies)
+
+```ruby
+# Specify gem in the Gemfile in the project root directory
+ruby '3.1.2'
+
+source 'https://rubygems.org'
+gem 'nokogiri'
+gem 'rack', '~>3.0.10'
+gem 'rspec', :require => 'spec'
+```
+
+Install all gems in Gemfile
+
+```bash
+$ bundle install
+```
+
+Solve the problem of Gemfile.lock inconsistency between mac for development and linux for production
+
+```bash
+bundle lock --add-platform x86_64-linux
+```
+
+### Install a specific version of a specific ruby gem
+
+```bash
+$ gem install bundler -v 2.4.20
+$ gem install minitest -v 5.22.3
+```
+
+### Update gems using Bundler
+
+```bash
+# Updating a single gem using Bundler
+$ bundle update nokogiri
+# Use Bundler to update each gem in the Gemfile
+$ bundle update
+```
+
+### Comment {.row-span-1}
+
+```ruby
+# This is a single line comments.
+=begin
+Multi-line
+Comment
+=end
+puts "Hello world!" # Inline comments for code
+```
+
+### reserved words {.col-span-1}
+
+
+Reserved words | Description
+:-|-
+| `__ENCODING__` | The script encoding of the current file
+| `__LINE__` | The line number of this keyword in the current file
+| `__FILE__` | The path of the current file
+| `BEGIN` | Code enclosed in { } is run before the program is run
+| `END` | Code enclosed in { } is run at the end of the program
+| `alias` | Create an alias for an existing method, operator, or global variable
+| `and` | Logical AND operator
+| `begin` | Begin a block of code
+| `break` | Terminate a loop
+| `case` | Compare an expression with matching `when` clauses, terminated with `end`
+| `class` | Define a class
+| `def` | define a function/method
+| `defined?` | Check if a variable or function exist
+| `do` | Start a block of code, terminated with the `end` keyword
+| `else` | Execute the following code if previous conditions are not met
+| `elsif` | Alternative condition for if expressions
+| `end` | End blocks of code starting with keywords like `begin`, `class`,`def`,`do`,`if`, etc.
+| `ensure` | Always execute at the end of a block
+| `false` | Logical boolean value false
+| `for` | Start a `for` loop
+| `if` | Execute the code block `if` the condition is `true`
+| `in` | Used with `for` loop
+| `module` | Define a module
+| `next` | jump to the point before the evaluation of the loop condition
+| `nil` | Stand for null, invalid, or always false
+| `not` | Logical NOT opearator
+| `or` | Logical OR opearator
+| `redo` | Jump back to the loop condition evaluation
+| `rescue` | Evaluate expressions after an exception is raised
+| `retry` | Repeat method calls when called outside `rescue`, jump to the top of the block when called inside `rescue`
+| `return` | Return a value from a method or block
+| `self` | Refer to the current object
+| `super` | Call the same-named method in the superclass
+| `then` | Used as a separator with`if`,`unless`,`when`,`case`,`rescue`
+| `true` | Logical boolean value true
+| `undef` | Undefine methods/functions within the current class
+| `until` | Execute the code block until the condition is false
+| `when` | Begin a clause under a `case` statement
+| `while` | Execute the code block while the condition is true
+| `yield` | Execute the code block passed to a method
+
+
+
+### Operator {.row-span-7}
+
+#### Logical Operators
+
+- `and`
+- `or`
+- `not`
+- `&&`
+- `||`
+- `!`
+
+#### Bit operators
+
+- `&`
+- `|`
+- `^`
+- `~`
+- `<<`
+- `>>`
+
+#### Arithmetic operators
+
+- `+`
+- `-`
+- `*`
+- `/`
+- `%`
+- `**`
+
+#### Comparison operator
+
+- `==`
+- `!=`
+- `>`
+- `<`
+- `>=`
+- `<=`
+- `<=>`
+- `===`
+- `eql?`
+- `equal?`
+
+#### Operator examples
+
+```bash
+# Addition
+1 + 1 #=> 2
+# Subtraction
+2 - 1 #=> 1
+# Multiplication
+2 * 2 #=> 4
+# Division
+10 / 5 #=> 2
+17 / 5 #=> 3, not 3.4
+17 / 5.0 #=> 3.4
+# Exponentiation
+2 ** 2 #=> 4
+3 ** 4 #=> 81
+# Modulus (remainder of division)
+8 % 2 #=> 0 (8 / 2 = 4; no remainder)
+10 % 4 #=> 2 (10 / 4 = 2 remainder 2)
+a = 10
+b = 20
+a == b #=> false
+a != b #=> true
+a > b #=> false
+a < b #=> true
+a >= b #=> false
+a <= b #=> true
+
+# Comparison operators
+a <=> b #=> -1
+c = 20
+c <=> b #=> 0
+c <=> a #=> 1
+# Equality used in when clauses for case statements
+(1...10) === 5 #=> true
+# True if the receiver and the argument have the same type and equal values
+1.eql?(1.0) #=> false
+c = a + b #=> 30
+c += a #=> 40
+c -= a #=> 30
+c *= a #=> 300
+c /= a #=> 30
+c %= a #=> 3
+c **= a #=> 59049
+
+# Ruby parallel assignment
+a = 10
+b = 20
+c = 30
+a, b, c = 10, 20, 30
+# Ruby bitwise operators
+a = 60
+b = 13
+# & Binary AND operator copies a bit to the result if it exists in both operands.
+a & b #=> 12
+# | Binary OR operator copies a bit if it exists in either operand.
+a | b #=> 61
+# ^ Binary XOR operator copies a bit if it is set in one operand but not both.
+a ^ b #=> 49
+# ~ Binary Ones Complement is unary and has the effect of 'flipping' bits.
+~a
+# << Binary Left Shift Operator. The left operand's value is moved
+# left by the number of bits specified by the right operand.
+a << 2
+# >> Binary Right Shift Operator. The left operand's value is moved
+# right by the number of bits specified by the right operand.
+a >> 2
+
+# Ruby logical operators
+a and b #=> true.
+a or b #=> true.
+a && b #=> true.
+(a || b) #=> true.
+!(a && b) #=> false.
+not(a && b) #=> false.
+# Ruby ternary operator
+# ? :
+# If condition is true ? Then value X : Otherwise value Y
+a == 10 ? puts 'Right' : puts 'Wrong'
+# Ruby range operators
+# .. Creates a range from the start point to the end point (inclusive)
+1..10 #=> Creates a range from 1 to 10 (inclusive of 1 and 10)
+# ... Creates an exclusive range from the start point to the end point
+1...10 #=> Creates an exclusive range from 1 to 10
+```
+
+### Operator precedence table
+
+From highest to lowest, this is the precedence table for ruby. High precedence operations happen before low precedence operations.
+
+- !, ~, unary +
+- **
+- unary -
+- *, /, %
+- +, -
+- <<, >>
+- &
+- |, ^
+- >, >=, <, <=
+- <=>, ==, ===, !=, =~, !~
+- &&
+- ||
+- .., ...
+- ?, :
+- modifier-rescue
+- =, +=, -=, etc.
+- defined?
+- not
+- or, and
+- modifier-if, modifier-unless, modifier-while, modifier-until
+- { } blocks
+
+### Variables and scope {.col-span-2}
+
+| - | - | - | - |
+|------|-------|---------|-------------|
+| Name | Scope | Example | Explanation |
+| `[a-z]` or `_` | Local | `count = 10` or `_count = 10` | Local variables must be initialized |
+| `@` | Instance variable | `@id = []` | Instance variables have a "nil" value before initialization |
+| `@@` | Class variable | `@@name = []` | Class variables must be initialized |
+| `$` | Global variable | `$version = "0.8.9"` | Global variables have a "nil" value before initialization |
+| `[A-Z]` | Constant | `PI = 3.14` | Constant variables must be initialized, you can change constants, but you will receive a warning |
+
+
+There are five different types of variables. The first character determines the range
+To read in deap about variables check
+[User Guide](https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/) cap 19,20,21,22,23
+[Pre-Defined Variables and Constants](https://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/variable.html)
+
+
+### Check the scope of a variable
+
+```ruby
+defined? count
+"local-variable"
+defined? @id
+"instance-variable"
+defined? @@name
+"class variable"
+defined? $version
+"global-variable"
+defined? PI
+"constant"
+```
+
+### Data Types {.col-span-2}
+
+| - | - | - | - |
+|:--------|:-----------------------------|:------------------------------------------|:--------------|
+| Type | Example | Class | Documentation |
+| `Integer` | a = 17 | a.class > Integer a.class.superclass > Numeric | [#]((https://ruby-doc.org/3.3.1/Integer.html)) |
+| `Float` | a = 87.23 | a.class > Float a.class.superclass > Numeric | [#](https://ruby-doc.org/3.3.1/Float.html) |
+| `String` | a = "Hello universe" | a.class > String | [#](https://ruby-doc.org/3.3.1/String.html) |
+| `Array` | a = [12, 34] | a.class > Array | [#](https://ruby-doc.org/3.3.1/Array.html) |
+| `Hash` | a = {type: "tea", count: 10} | a.class > Hash | [#](https://ruby-doc.org/3.3.1/Hash.html) |
+| `Boolean` | a = false a = true | a.class > FalseClass a.class > TrueClass | [TrueClass](https://ruby-doc.org/3.3.1/TrueClass.html) [FalseClass](https://ruby-doc.org/3.3.1/FalseClass.html) |
+| `Symbol` | a = :status | a.class > Symbol | [#](https://ruby-doc.org/3.3.1/Symbol.html) |
+| `Range` | a = 1..3 | a.class > Range | [#](https://ruby-doc.org/3.3.1/Range.html) |
+| `Nil` | a = nil | a.class > NilClass | [#](https://ruby-doc.org/3.3.1/NilClass.html) |
+
+[further reading](https://www.digitalocean.com/community/tutorials/understanding-data-types-in-ruby)
+
+### Check data type
+
+```ruby
+# Both are synonyms
+a = 37
+a.kind_of? Integer
+# true
+a.is_a? Integer
+# true
+```
+
+### Symbol
+
+```ruby
+week_days = {sunday: 11, monday: 222}
+```
+
+### Integer useful methods
+
+```ruby
+2.even?
+# true
+3.even?
+# false
+```
+
+### Range
+
+`..` Used to create inclusive ranges
+
+```ruby
+range = 1..10
+range.to_a
+# output => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+```
+
+`...` Used to create exclusive ranges
+
+```ruby
+range = 1...10
+range.to_a
+# output => [1, 2, 3, 4, 5, 6, 7, 8, 9]
+```
+some useful methods
+
+Method name | Output
+:----------- | -----
+`cover?` | `(1..5).cover?(5)` => `true`
+`end` | `('a'..'z').end` => `"z"`
+`first` | `(1..5).first` => `1`
+`first(3)` | `('A'..'Z').first(2)` => `["A", "B"]`
+`eql?` | `((0..2).eql?(0..5)` => `false`
+
+### Using `step` in Range
+
+```ruby
+(1..20).step(2) { |number| puts "#{number}"}
+# output
+# 1
+# 3
+# 5
+# 7
+# 9
+# 11
+# 13
+# 15
+# 17
+# 19
+```
+
+Ruby Flow control
+---
+
+### if
+
+```ruby
+num = 2
+puts 'two' if num == 2
+```
+
+If the condition is true, execute the code
+
+### if elsif else
+
+```ruby
+temp = 19
+if temp >= 25
+ puts "hot"
+elsif temp < 25 && temp >= 18
+ puts "normal"
+else
+ puts "cold"
+end
+# output => normal
+```
+
+### unless
+
+```ruby
+# Unless contrary to if , evaluates when the statement is false
+name = "rob"
+# if name != "bob"
+unless name == "bob"
+ puts "hello stranger"
+else
+ puts "hello bob"
+end
+# output => hello stranger
+num = 6
+puts 'not two' unless num == 2
+# output => not two
+```
+
+### case {.row-span-2}
+
+```ruby
+# case returns the value of the last expression executed
+case input
+# Check for an integer, 19
+when 19
+ puts "It's 19"
+ # 检查一个确切的字符串,“Zaman”
+when "Zaman"
+ puts "Hi Zaman"
+when 7..11
+ puts "It's between 7 and 11"
+ # Check multiple values, "coffee"
+when "tea", "coffee"
+ puts "Happy days"
+end
+```
+
+### case( short syntax )
+
+```ruby
+case input
+ when 19 then puts "It's 19"
+end
+```
+
+### case( Optional failure )
+
+```ruby
+case input
+ when 19 then puts "It's 19"
+else
+ puts "It's not 19"
+end
+```
+
+### case( Get return value )
+
+```ruby
+marks = 86
+result = case marks
+ when 0..49 then "Fail"
+ when 50..64 then "Pass"
+ when 65..74 then "Credit"
+ when 75..84 then "Distinction"
+ when 85..100 then "High Distinction"
+ else "Invalid marks"
+ end
+
+puts result
+# High Distinction
+```
+
+String
+---
+
+### String interpolation
+
+```ruby
+name = "World"
+puts "Hello #{name}"
+puts "The total is #{1+1}"
+# "the total is 2"
+```
+
+String interpolation allows you to combine strings together
+
+### Extract substring
+
+```ruby
+string = "abc123"
+string[0,3]
+# "abc"
+string[3,3]
+# "123"
+string[0..-2]
+# "abc12"
+#remove or replace the substring
+string[0..2] = ""
+puts string
+# "123"
+```
+
+A substring is a small part of a string, which is useful if you only want that specific part, like the beginning, middle, or end
+
+### Convert a string to lowercase or uppercase
+
+```ruby
+"HELLO World".downcase # "hello world"
+"hello worlD".upcase # "HELLO WORLD"
+"hEllo wOrlD".capitalize # "Hello world"
+"hEllo WOrlD".swapcase # "HeLLO woRLd"
+```
+
+### useful methods {.col-span-3}
+
+| Function Name | Output | Note |
+|:--------------|:-------|:-----|
+| length or size | `"HELLO World".length` => `11` `"HELLO World".size` => `11` | Returns the length of the string |
+| reverse | `"hello worlD".reverse` => `"Dlrow olleh"` | Returns the reversed string |
+| include? other_str | `"hEllo wOrlD".include? "w"` => `true` | Returns true if the string or character exists, otherwise returns false |
+| gsub(pattern, replacement) | `"hEllo wOrlD".gsub(" ", "_")` => `"hEllo_wOrlD"` | gsub or global substitute replaces one or more strings with the provided string |
+| gsub(pattern, hash) | `"organization".gsub("z", 'z' => 's')` => `"organisation"` | gsub or global substitute replaces one or more strings with the provided hash |
+| gsub(pattern) { |match| block} | `"Price of the phone is 1000 AUD".gsub(/\d+/) { |s| '$'+s }` `"Price of the phone is $1000 AUD"` | gsub or global substitute replaces one or more strings with the provided block |
+| strip | `" hEllo WOrlD ".strip` `"hEllo WOrlD"` | It will remove (trim) any leading and trailing characters: null (“\x00”), horizontal tab (“\t”), newline (\n), vertical tab (“\v”), form feed (f), carriage return(\r), space (" ") |
+| prepend | `a = "world" a.prepend("hello ")` `"hello world"` | Adds the string before another string |
+| insert | `a = "hello" a.insert(a.length, " world")` `"hello world"` | Inserts the string at a specific position |
+| start_with? | `string = "ruby programming"` `string.start_with? "ruby"` `true` | Checks if the string starts with a specific prefix |
+| end_with? | `string = "ruby programming"` `string.end_with? "ruby"` `false` | Checks if the string ends with a specific prefix |
+| delete_suffix | `string = "sausage is expensive"` `string.delete_suffix(" is expensive")` `"sausage"` | Deletes the suffix from the string |
+| delete_prefix | `string = "sausage is expensive"` `string.delete_prefix("sausage")` `" is expensive"` | Deletes the prefix from the string |
+| split | `string = "a b c d" string.split` `["a", "b", "c", "d"]` | Converts the string into an array of characters |
+| join | `arr = ['a', 'b', 'c'] arr.join` => `"abc"` | Converts an array into a string |
+| to_i | `a = "49" a.to_i` => `49` | Converts the string into an integer |
+| chop | `"abcd?".chop("?")` => `"abcd"` | Deletes the last character from the string |
+| count | `str = "aaab" str.count("a")` `3` | Counts the characters in the string |
+| to_f | `a = "49"` `a.to_f` `49.0` | Converts the string into a floating point number |
+| to_sym | `a = "key"` `a.to_sym` `:key` | Converts the string into a symbol |
+| match | `"abcd?".match(/ab/)` => `#` | Converts the pattern into a regular expression and calls its match method on the string |
+| empty? | `"hello".empty?` => `false` | Returns true if the length of the string is zero |
+| squeeze | `"Booook".squeeze` => `"Bok"` | Returns a copy of the string where runs of the same character are replaced by a single character |
+| * | `puts "Ruby " * 4` => `Ruby Ruby Ruby Ruby` | Returns the concatenation of multiple copies of self |
+| + | `"sammy " + "shark"` => `"sammyshark"` | Returns the concatenation of self and the given other string |
+| eql? | `s = 'foo'` => `true` `s.eql?('foo')` => `true` | Returns true if the objects have the same length and content; false otherwise |
+
+
+Methods
+---
+
+### Declare a method {.row-span-3}
+
+```ruby
+def method_name(parameter1, parameter2)
+ puts "#{parameter1} #{parameter2}"
+ parameter1 + parameter2
+end
+```
+---
+
+```ruby
+res = method_name(20, 10)
+# output => 30
+def method_name(parameter1, parameter2)
+ puts "#{parameter1} #{parameter2}"
+ return parameter1 + parameter2
+end
+# output => 30
+```
+
+### Call method
+
+```ruby
+res = method_name(parameter1, parameter2)
+# Methods can be called without parentheses
+res = method_name parameter1, parameter2
+```
+
+### Class method {.row-span-4}
+
+Class methods are class-level methods. There are multiple ways to define class methods
+
+```ruby
+class Mobile
+ def self.ring
+ "ring ring ring..."
+ end
+end
+
+Mobile.ring
+```
+---
+
+```ruby
+class Mobile
+ def Mobile.ring
+ "ring ring ring..."
+ end
+end
+Mobile.ring
+```
+---
+
+```ruby
+class Mobile
+ class << self
+ def ring
+ "ring ring ring..."
+ end
+ end
+end
+Mobile.ring
+```
+
+Class methods are instance methods of class objects. When a new class is created, an object of type "Class" is initialized and assigned to a global constant (in this case Mobile)
+
+```ruby
+Mobile = Class.new do
+ def self.ring
+ "ring ring ring..."
+ end
+end
+Mobile.ring
+```
+
+```ruby
+Mobile = Class.new
+class << Mobile
+ def ring
+ "ring ring ring..."
+ end
+end
+Mobile.ring
+```
+
+### Use another parameter as default value
+
+```ruby
+def method_name(num1, num2 = num1)
+ return num1 + num2
+end
+res = method_name(10)
+# output => 20
+```
+
+### Define default values for method parameters
+
+```ruby
+def method_name(parameter1, parameter2, type = "ADD")
+ puts "#{parameter1} #{parameter2}"
+ return parameter1 + parameter2 if type == "ADD"
+ return parameter1 - parameter2 if type == "SUB"
+end
+res = method_name(20, 10)
+# output => 30
+```
+
+### Pass variable length arguments to method parameters
+
+```ruby
+def method_name(type, *values)
+ return values.reduce(:+) if type == "ADD"
+ return values.reduce(:-) if type == "SUB"
+end
+numbers = [2, 2, 2, 3, 3, 3]
+res = method_name("ADD", *numbers)
+# output => 15
+res = method_name("SUB", *numbers)
+# output => -11
+# Or you can provide a value like this
+res = method_name("ADD", 2, 2, 2, 3, 3, 3)
+# output => 15
+```
+
+### Modify object
+
+```ruby
+a = ["Drama", "Mystery", "Crime",
+"Sci-fi", "Disaster", "Thriller"]
+a.sort
+puts a
+# We did not modify the object
+# Drama
+# Mystery
+# Crime
+# Sci-fi
+# Disaster
+# Thriller
+a.sort!
+puts a
+# Modify object
+# Crime
+# Disaster
+# Drama
+# Mystery
+# Sci-fi
+# Thriller
+```
+
+When you want to modify the object, use `!` after the method
+
+### Boolean method
+
+In ruby, methods ending with a question mark (?) are called boolean methods, which return `true` or `false`
+
+```ruby
+"some text".nil?
+# false
+nil.nil?
+# true
+```
+
+You can have your own boolean method
+
+```ruby
+def is_vowel?(char)
+ ['a','e','i','o','u'].include? char
+end
+is_vowel? 'a'
+# true
+is_vowel? 'b'
+# false
+```
+
+Blocks
+---
+
+### Block example
+
+```ruby
+# return value
+def give_me_data
+ data = yield
+ puts "data = #{data}"
+end
+give_me_data { "Big data" }
+# output => data = Big data
+```
+
+The code between `do` and `end` (for multiple lines) or curly braces `{` and `}` (for a single line) is called a block, and they can define multiple parameters between two pipes `( |arg1, arg2|)`
+
+### Single line block
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.each { |s| puts s }
+# puts s = block body
+# |s| = block arugments
+```
+
+### Multi-line block
+
+```ruby
+salary.each do |s|
+ a = 10
+ res = a * s
+ puts res
+end
+# Block
+# a = 10
+# res = a * s
+# puts res
+# block parameters
+# |s|
+```
+
+Blocks can be passed as method parameters or associated with method calls. block returns the last evaluated statement
+
+### Implicitly passing a block
+
+```ruby
+def give_me_data
+ puts "I am inside give_me_data method"
+ yield
+ puts "I am back in give_me_data method"
+end
+
+give_me_data { puts "Big data" }
+
+# output
+# I am inside give_me_data method
+# Big data
+# I am back in give_me_data method
+```
+
+### Called multiple times
+
+```ruby
+def give_me_data
+ yield
+ yield
+ yield
+end
+
+give_me_data { puts "Big data" }
+
+# output
+# Big data
+# Big data
+# Big data
+```
+
+### Called with block parameters
+
+```ruby
+def give_me_data
+ yield 10
+ yield 100
+ yield 30
+end
+
+give_me_data { |data| puts "Big data #{data} TB" }
+
+# output
+# Big data 10 TB
+# Big data 100 TB
+# Big data 30 TB
+```
+
+### Called with multiple block parameters
+
+```ruby
+def give_me_data
+ yield "Big data", 10, "TB"
+ yield "Big data", 100, "GB"
+ yield "Big data", 30, "MB"
+end
+
+give_me_data { |text, data, unit| puts "#{text} #{data} #{unit}" }
+
+# output
+# Big data 10 TB
+# Big data 100 GB
+# Big data 30 MB
+```
+
+### Block will attempt to return from the current context
+
+```ruby
+give_me_data
+ puts "I'm inside the give_me_data method"
+end
+
+def test
+ puts "I'm inside the test method"
+ give_me_data { return 10 } # Code returns from here
+ puts "I am back in test method"
+end
+
+return_value = test
+
+# output
+# I'm inside the test method
+# I'm inside the give_me_data method
+# 10
+```
+
+### Pass the block explicitly by using the & parameter
+
+```ruby
+def give_me_data(&block)
+ block.call
+ block.call
+end
+
+give_me_data { puts "Big data" }
+
+# output
+# Big data
+# Big data
+```
+
+### Check if block is given
+
+```ruby
+def give_me_data
+ yield
+end
+
+give_me_data
+
+# output
+# LocalJumpError: no block given (yield)
+```
+
+### Ways to handle exceptions and make blocks optional
+
+```ruby
+def give_me_data
+ return "no block" unless block_given?
+ yield
+end
+
+give_me_data { puts "Big data" }
+give_me_data
+
+# output
+# Big data
+```
+
+Procs
+---
+
+### Procs
+
+```ruby
+p = Proc.new { puts "Hello World" }
+
+def give_me_data(proc)
+ proc.call
+end
+
+give_me_data p
+
+# output
+# Hello World
+```
+
+proc is like a block that can be stored in a variable
+
+### any parameter {.col-span-2}
+
+```ruby
+p = Proc.new { |count| "Hello World " * count }
+
+def give_me_data(proc)
+ proc.call 5, 2
+end
+
+give_me_data p
+
+# output
+# "Hello World Hello World Hello World Hello World Hello World "
+```
+
+### proc will attempt to return from the current context
+
+```ruby
+p = Proc.new { return 10 }
+p.call
+# output
+LocalJumpError: unexpected return
+```
+
+### Cannot return from top-level context
+
+```ruby
+def give_me_data
+ puts "I'm inside the give_me_data method"
+ p = Proc.new { return 10 }
+ p.call # Code returns from here
+ puts "I am back in give_me_data method"
+end
+
+return_value = give_me_data
+puts return_value
+
+# output
+# I'm inside the give_me_data method
+# 10
+```
+
+Lambdas
+----
+
+### Declare a lambda{.row-span-2}
+
+```ruby
+l = lambda { puts "Hello World" }
+# shorthand
+l = -> { puts "Hello World" }
+# transfer lambda
+l.call
+# output => Hello World
+```
+
+There are multiple ways to call a lambda
+
+```ruby
+l.()
+l[]
+```
+
+### strict arguments
+
+```ruby
+l = -> (count) { "Hello World " * count }
+l.call 5
+# output
+# "Hello World Hello World Hello World Hello World Hello World "
+l.call 5, 2
+# output
+wrong number of arguments (given 2, expected 1)
+```
+
+### declare a lambda in block {.row-span-2}
+
+```ruby
+def give_me_data
+ puts "I am inside give_me_data method"
+ l = -> { return 10 }
+ l.call
+ puts "I am back in give_me_data method"
+end
+
+return_value = give_me_data
+puts return_value
+
+# output
+# I am inside give_me_data method
+# I am back in give_me_data method
+# nil # because puts return nil
+```
+
+### lambdas are returned from the lambda itself, just like regular methods
+
+```ruby
+l = -> { return 10 }
+l.call
+
+# output => 10
+```
+
+Array
+---
+
+### Initialize an empty array
+
+```ruby
+array = Array.new #=> []
+# or
+array = []
+```
+
+### Array containing objects of different types
+
+```ruby
+array = [1, "two", 3.0]
+#=> [1, "two", 3.0]
+```
+
+### Fill array with initial size and default objects {.row-span-2}
+
+```ruby
+numbers = Array.new(3)
+#=> [nil, nil, nil]
+numbers = Array.new(3, 7)
+#=> [7, 7, 7]
+numbers = Array.new(3, true)
+#=> [true, true, true]
+numbers = []
+numbers.fill(7, 0..2) #=> [7, 7, 7]
+```
+
+### array of different hashes {.col-span-2}
+
+```ruby
+array_with_hashes = Array.new(2) { {} } #=> [{}, {}]
+array_with_hashes[0][:name] = "Bob"
+array_with_hashes[0][:id] = 10 #=> [{:name=>"Bob", :id=>10}, {}]
+```
+
+### Two-dimensional array
+
+```ruby
+temperature_data = [
+ ["A908", 38],
+ ["A909", 37],
+ ["A910", 38],
+ ]
+temperature_data[0] #=> ["A908", 38]
+temperature_data[0][0] #=> "A908"
+temperature_data[0][1] #=> 38
+```
+
+### array index
+
+```ruby
+str_array = [
+ "This", "is", "a", "small", "array"
+]
+str_array[0] #=> "This"
+str_array[1] #=> "is"
+str_array[4] #=> "array"
+```
+
+### negative index
+
+```ruby
+str_array = [
+ "This", "is", "a", "small", "array"
+]
+# Index -1 represents the last element
+str_array[-1] #=> "array"
+# Index -2 represents the second to last element
+str_array[-2] #=> "small"
+str_array[-6] #=> nil
+```
+
+### array method at
+
+```ruby
+str_array = [
+ "This", "is", "a", "small", "array"
+]
+
+puts str_array.at(0) #=> "This"
+```
+
+### Range acquisition
+
+```ruby
+arr = [1, 2, 3, 4, 5, 6]
+arr[100] #=> nil
+arr[-3] #=> 4
+arr[2, 3] #=> [3, 4, 5]
+arr[1..4] #=> [2, 3, 4, 5]
+arr[1..-3] #=> [2, 3, 4]
+```
+
+### Array method fetch
+
+```ruby
+arr = ['a', 'b', 'c', 'd', 'e', 'f']
+arr.fetch(100)
+#=> IndexError: Index outside array bounds 100:-6...6
+arr.fetch(100, "oops") #=> "oops"
+```
+
+Out of bounds, give default value
+
+### Get array elements
+
+```ruby
+arr = [1, 2, 3, 4, 5, 6]
+
+arr.first # first value => 1
+arr.last # last value => 6
+# take Returns the first n elements
+arr.take(3) #=> [1, 2, 3]
+# drop after n elements have been deleted
+arr.drop(3) #=> [4, 5, 6]
+```
+
+### Add value to end of array push
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.push(11)
+#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+numbers.push(12, 13, 14)
+#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
+```
+
+### Delete the value at the end of the array pop
+
+```ruby
+num_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+num_array.pop #=> 10
+num_array
+#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+```
+
+
+### Add value to beginning of array unshift
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.unshift(0)
+#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.unshift(-3, -2, -1)
+#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+```
+
+### Retrieve and simultaneously delete the first element shift
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.shift #=> 1
+numbers
+#=> [2, 3, 4, 5, 6, 7, 8, 9, 10]
+```
+
+### Remove element at specific index delete_at
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.delete_at(2) #=> 4
+numbers
+#=> [2, 3, 5, 6, 7, 8, 9, 10]
+```
+
+### Remove a specific element anywhere in an array
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.delete(2) #=> 2
+numbers #=> [3, 5, 6, 7, 8, 9, 10]
+```
+
+### Insert value at given index insert {.row-span-2}
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.insert(0, 0)
+#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.insert(0, -3, -2, -1)
+#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+
+numbers.insert(-1, 12, 13, 14)
+#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]
+numbers.insert(-4, 11)
+#=> [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
+```
+
+### A block to fill the array with values
+
+```ruby
+numbers = Array.new(10) { |n| n = n * 2 }
+#=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
+```
+
+### Filling arrays becomes easier
+
+```ruby
+numbers = Array(100..110)
+#=> [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
+
+# Or we can convert the range to an array
+(100..110).to_a
+#=> [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
+```
+
+### Remove nil value from array
+
+```ruby
+arr = ['foo', 0, nil, 'bar', 7, nil]
+arr.compact #=> ['foo', 0, 'bar', 7]
+arr #=> ['foo', 0, nil, 'bar', 7, nil]
+arr.compact! #=> ['foo', 0, 'bar', 7]
+arr #=> ['foo', 0, 'bar', 7]
+```
+
+### Remove duplicates uniq
+
+```ruby
+arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
+arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
+arr # => [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
+arr.uniq! #=> [2, 5, 6, 556, 8, 9, 0, 123]
+arr #=> [2, 5, 6, 556, 8, 9, 0, 123]
+```
+
+### Check if a value exists in an array(`include?`)
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+planets.include? "Mars"
+# output => true
+planets.include? "Pluto"
+# output => false
+```
+
+### Get array size
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+planets.size
+# output => 8
+planets.length
+# output => 8
+```
+You can use size or length, both are synonyms
+
+### clear array
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.clear
+# output => []
+```
+
+### Get the first element of the array
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers[0]
+# or
+numbers.first
+# output => 1
+```
+
+### Get the last element of the array
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers[-1]
+# or
+numbers.last
+# output => 10
+```
+
+### Merge two arrays
+
+```ruby
+a = ["tom", "mot", "otm"]
+b = [2, 3, 5]
+a.zip(b)
+# output
+# [["tom", 2], ["mot", 3], ["otm", 5]]
+```
+
+### Sort array {.row-span-3}
+
+```ruby
+primes = [7, 2, 3, 5]
+sorted_primes = primes.sort
+puts "#{sorted_primes}"
+# output => [2, 3, 5, 7]
+```
+or in-place sort
+```ruby
+primes = [7, 2, 3, 5]
+primes.sort!
+puts "#{primes}"
+# output => [2, 3, 5, 7]
+```
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+planets.sort
+# output
+# ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Saturn", "Uranus", "Venus"]
+planets.sort_by { |p| p }
+# output
+# ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Saturn", "Uranus", "Venus"]
+planets.sort_by { |p| p.length }
+# output
+# ["Mars", "Earth", "Venus", "Saturn", "Uranus", "Neptune", "Jupiter", "Mercury"]
+```
+
+### Get maximum value from array
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.max_by { |p| p }
+# output => 7
+```
+
+### Get array elements using range {.row-span-2}
+
+```ruby
+# numbers[start..end], both index are inclusive
+puts numbers[0..3]
+# 1
+# 2
+# 3
+# 4
+# numbers[start..end], end index is exclusive
+puts numbers[0...3]
+# 1
+# 2
+# 3
+# or numbers[start..length]
+puts numbers[0, 1]
+# 1
+```
+
+### Get the first n elements of the array
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.take(3)
+# [7, 2, 3]
+```
+
+### access element
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.fetch(3)
+# 5
+# Fetch will throw an error if the element does not exist
+primes.fetch(10)
+# (index 10 outside of array bounds: -4...4)
+# or get an default value
+primes.fetch(10, -1)
+# -1
+```
+
+### Delete first n elements
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.drop(3)
+# [5]
+```
+
+### Delete the first element
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.shift
+# [2, 3, 5]
+```
+
+### Remove last element
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.pop
+# [7, 2, 3]
+```
+
+### Delete element with index
+
+```ruby
+primes = [7, 2, 3, 5]
+primes.delete_at(-1)
+# [7, 2, 3]
+```
+
+### Remove all occurrences of elements
+
+```ruby
+primes = [7, 2, 3, 5, 5]
+primes.delete(5)
+# [7, 2, 3]
+```
+
+### each {.row-span-3}
+
+```ruby
+# When you have single line blocks
+salary = [399, 234, 566, 533, 233]
+salary.each { |s| puts s }
+# output
+# 399
+# 234
+# 566
+# 533
+# 233
+```
+
+When you have a multi-line block, you can replace the curly braces `{}` with `do` and `end`
+
+```ruby
+salary.each do |s|
+ a = 10
+ res = a * s
+ puts res
+end
+# output
+# 3990
+# 2340
+# 5660
+# 5330
+# 2330
+```
+
+Or you can do the same thing using braces {} and semicolon as separator instead of newline
+
+```ruby
+salary.each { |s| a = 10 ; res = a * s ; puts res }
+```
+
+### each_with_index
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.each_with_index { |value, index| puts "#{index} #{value}" }
+# output
+# 0 399
+# 1 234
+# 2 566
+# 3 533
+# 4 233
+```
+
+### each_index
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.each_index { |i| puts i}
+# output
+# 0
+# 1
+# 2
+# 3
+# 4
+```
+
+### map
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.map { |s| s * 10 }
+# return
+# [3990, 2340, 5660, 5330, 2330]
+# On the other hand, each returns the original value
+salary = [399, 234, 566, 533, 233]
+salary.each { |s| s * 10 }
+# return
+# [399, 234, 566, 533, 233]
+```
+
+### collect
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.collect { |s| s > 400 }
+# output
+# [false, false, true, true, false]
+```
+
+### for
+
+```ruby
+for value in [2, 3, 5, 7]
+ puts value
+end
+```
+
+### each_with_object {.col-span-2}
+
+```ruby
+colors = [
+ {color: "red", count: 3}, {color: "red", count: 5}, {color: "black", count: 4}
+]
+colors.each_with_object(Hash.new(0)) { |color, hash| hash["color_"+color[:color]] = color[:color].upcase; hash["count_"+color[:color]] += color[:count] }
+# output
+{"color_red"=>"RED", "count_red"=>8, "color_black"=>"BLACK", "count_black"=>4}
+
+[1, 2, 3].each_with_object(0) { |number, sum| sum += number}
+# output
+# 0
+# Because 0 is immutable, and since the initial object is 0, the method returns 0
+```
+
+### while
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+index = 0
+while index < planets.size
+ puts "#{planets[index]}"
+ index += 1
+end
+```
+---
+
+```ruby
+a = 1
+star = '*'
+while a <= 10
+ puts star
+ star += '*'
+ a += 1
+end
+```
+
+### do while
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+index = 0
+loop do
+ puts "#{planets[index]}"
+ index += 1
+ break if planets[index] == "Mars" or index > planets.size
+end
+```
+
+### until
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+index = planets.size - 1
+until index < 0
+ puts "#{planets[index]}"
+ index -= 1
+end
+```
+
+```ruby
+a = 1
+star = '*'
+until star.length > 10
+ puts star
+ star += '*'
+ a += 1
+end
+```
+
+### times
+
+```ruby
+10.times { puts "#{rand(1..100)}"}
+# output
+# will print 10 random numbers
+```
+
+Just because you can doesn't mean you should iterate over an array like this
+
+```ruby
+data_sample = [2, 3, 5, 7]
+data_sample.size.times { |index| puts "#{data_sample[index]}" }
+# output
+# 2
+# 3
+# 5
+# 7
+```
+
+### upto
+
+```ruby
+data_sample = [2, 3, 5, 7]
+0.upto((data_sample.size - 1) / 2) { |index| puts "#{data_sample[index]}" }
+# output
+# 2
+# 3
+```
+
+### downto
+
+```ruby
+data_sample = [2, 3, 5, 7]
+(data_sample.size - 1).downto(data_sample.size / 2) { |index| puts "#{data_sample[index]}" }
+# output
+# 7
+# 5
+```
+
+
+### step {.row-span-2}
+
+```ruby
+1.step(20, 2) { |number| puts "#{number}"}
+# output
+# 1
+# 3
+# 5
+# 7
+# 9
+# 11
+# 13
+# 15
+# 17
+# 19
+```
+
+---
+
+```ruby
+19.step(1, -2) { |number| puts "#{number}"}
+# output
+# 19
+# 17
+# 15
+# 13
+# 11
+# 9
+# 7
+# 5
+# 3
+# 1
+```
+
+### inject {.row-span-2}
+
+```ruby
+numbers = [2, 2, 2, 2, 2]
+numbers.inject{ |res, n| res + n }
+# The output is the sum of all numbers
+# If no initial value is set for res, the first element of the array is used as the initial value of res.
+#10
+# Now set the value of res to 11
+numbers = [2, 2, 2, 2, 2]
+numbers.inject(11) { |res, n| res + n }
+# so 11 + 2, 13 + 2, 15 + 2, 17 + 2 and 19 + 2
+# 21
+# using symbol
+numbers = [2, 2, 2, 2, 2]
+numbers.inject(:+)
+# output
+# 10
+```
+
+Use initial values and symbols
+
+```ruby
+numbers = [2, 2, 2, 2, 2]
+numbers.inject(11, :+)
+# output
+# 21
+```
+
+### reduce
+
+```ruby
+numbers = [2, 2, 2, 2, 2]
+numbers.reduce(11, :+)
+# output
+# 21
+```
+
+### detect
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+planets.detect { |name| name.start_with?("E") and name.end_with?("h") }
+# output
+# Earth
+salary = [399, 234, 566, 533, 233]
+salary.detect { |s| s > 1000 }
+# output
+# nil
+```
+
+
+### find
+
+```ruby
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+planets.find { |name| name.start_with?("E") and name.end_with?("h") }
+# output
+# Earth
+```
+
+
+### select
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.select { |n| n % 2 == 0 }
+# Now you have an even array
+# [2, 4, 6, 8, 10]
+# If there are no values that satisfy your logic, return an empty array
+[1, 1, 1].select { |n| n % 2 == 0 }
+# no even numbers
+# []
+```
+
+
+### reject
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.reject { |n| n % 2 == 0 }
+# Reject if the number is even, so now we have an odd array
+# [1, 3, 5, 7, 9]
+```
+
+
+### keep_if
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.keep_if { |n| n % 2 == 0 }
+# numbers Array contains only even numbers
+# [2, 4, 6, 8, 10]
+```
+
+
+### delete_if
+
+```ruby
+numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+numbers.delete_if { |n| n % 2 == 0 }
+# numbers Array contains only odd numbers
+# [1, 3, 5, 7, 9]
+```
+
+
+### drop_while
+
+```ruby
+numbers = [1, 2, 3, 1, 2, 3, 0]
+numbers.drop_while { |n| n < 3 }
+# is 3 less than 3, returns false, so delete 1, 2
+# [3, 1, 2, 3, 0]
+```
+
+
+### reverse_each
+
+```ruby
+words = %w[first second third fourth fifth sixth]
+str = ""
+words.reverse_each {|word| str += "#{word} "}
+p str #=> "sixth fifth fourth third second first "
+```
+
+
+boolean enumerable method
+---
+
+### boolean enumerable method {.row-span-2}
+
+| Name | When to use |
+|:---------|-----------------------------------------------------|
+| `all?` | When you want to check if all elements meet your condition |
+| `any?` | When you want to check if at least one item meets your condition |
+| `one?` | When you want to check if one element meets your requirement |
+| `none?` | When you want to check if no item meets your condition, the opposite of? |
+| `empty?` | When you want to check if an object is empty |
+| `include?` | When you want to check if an element exists in the object |
+
+
+### all?
+
+```ruby
+[2, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
+# true
+[1, 4, 6, 8, 10].all? { |num| num % 2 == 0 }
+# false
+```
+
+### any?
+
+```ruby
+[1, 3, 5, 7, 10].any? { |num| num % 2 == 0 }
+# true
+[1, 3, 5, 7, 19].any? { |num| num % 2 == 0 }
+# false
+```
+
+### one?
+
+```ruby
+[1, 3, 2, 5, 7].one? { |num| num % 2 == 0 }
+# true
+[1, 3, 2, 5, 4].one? { |num| num % 2 == 0 }
+# false
+```
+
+### none?
+
+```ruby
+[1, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
+# true
+[2, 3, 5, 7, 9].none? { |num| num % 2 == 0 }
+# false
+```
+
+### empty?
+
+```ruby
+[].empty?
+# true
+[1, 3, 5, 7, 9].empty?
+# false
+```
+
+Combination method
+---
+
+### Combination method {.row-span-2}
+
+- `&` Returns a new array containing each element found in array and array other_array; duplicates are omitted; use eql? to compare items
+- `intersection` Returns a new array containing each element found in self and all given arrays other_arrays; duplicates are omitted; use eql? to compare items
+- `+` Returns an array containing all elements of self followed by all elements of the given array
+- `-` Returns an array containing all elements of self not found in the given array
+- `union` Returns an array containing all elements of self and all elements of the given array, with duplicates removed
+- `difference` Returns an array containing all elements of self not found in any given array
+- `product` self Returns or produces all combinations of elements from self and the given array
+
+### &
+
+```ruby
+[0, 1, 2, 3] & [1, 2] # => [1, 2]
+[0, 1, 0, 1] & [0, 1] # => [0, 1]
+```
+
+### intersection
+
+```ruby
+[0, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3])
+# => [0, 1]
+[0, 0, 1, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3])
+# => [0, 1]
+```
+
+### +
+
+```ruby
+a = [0, 1] + [2, 3]
+a # => [0, 1, 2, 3]
+```
+
+### -
+
+```ruby
+[0, 1, 1, 2, 1, 1, 3, 1, 1] - [1]
+# => [0, 2, 3]
+[0, 1, 2, 3] - [3, 0]
+# => [1, 2]
+[0, 1, 2] - [4]
+# => [0, 1, 2]
+```
+
+### union
+
+```ruby
+[0, 1, 2, 3].union([4, 5], [6, 7])
+# => [0, 1, 2, 3, 4, 5, 6, 7]
+[0, 1, 1].union([2, 1], [3, 1])
+# => [0, 1, 2, 3]
+[0, 1, 2, 3].union([3, 2], [1, 0])
+# => [0, 1, 2, 3]
+```
+
+### difference
+
+```ruby
+[0, 1, 1, 2, 1, 1, 3, 1, 1].difference([1])
+# => [0, 2, 3]
+[0, 1, 2, 3].difference([3, 0], [1, 3])
+# => [2]
+[0, 1, 2].difference([4])
+# => [0, 1, 2]
+```
+
+### product
+
+```ruby
+a = [0, 1, 2]
+a1 = [3, 4]
+p = a.product(a1)
+p.size # => 6 # a.size * a1.size
+p # => [[0, 3], [0, 4], [1, 3], [1, 4], [2, 3], [2, 4]]
+```
+
+
+Loops
+---
+
+### while loop
+
+```ruby
+# variable count
+count = 4
+# using while loop
+# here conditional is count i.e. 4
+while count >= 1
+ # statements to be executed
+ puts "Ruby Cheatsheet"
+ count = count - 1
+ # while loop ends here
+end
+```
+
+output
+
+```
+Ruby Cheatsheet
+Ruby Cheatsheet
+Ruby Cheatsheet
+Ruby Cheatsheet
+```
+
+### for loop
+
+```ruby
+# loop using range as expression
+text = "Ruby Cheatsheet"
+# using for loop with the range
+for count in 1..5 do
+ puts text
+end
+```
+
+output
+
+```
+Ruby Cheatsheet
+Ruby Cheatsheet
+Ruby Cheatsheet
+Ruby Cheatsheet
+Ruby Cheatsheet
+```
+
+### do..while loop
+
+```ruby
+# starting of do..while loop
+loop do
+ puts "Ruby Cheatsheet"
+ val = '7'
+ # using boolean expressions
+ if val == '7'
+ break
+ end
+ # ending of ruby do..while loop
+end
+```
+
+output
+
+```
+Ruby Cheatsheet
+```
+
+### until loop
+
+```ruby
+var = 7
+# here do is optional
+until var == 11 do
+ # code to be executed
+ puts var * 10
+ var = var + 1
+ # here loop ends
+end
+```
+
+output
+
+```
+70
+80
+90
+100
+```
+
+### Break out of loop
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.each do |s|
+ break if s == 566
+ puts s
+end
+# output
+# 399
+# 234
+```
+
+By using the `break` keyword
+
+### skip within loop
+
+```ruby
+salary = [399, 234, 566, 533, 233]
+salary.each do |s|
+ next if s == 533
+ puts s
+end
+# output
+# 399
+# 234
+# 566
+# 233
+```
+
+By using next keyword
+
+### Repeat current iteration
+
+```ruby
+data = [456, 3000]
+retry_count = 0
+status = "network failure"
+sum = 0
+data.each do |d|
+ if retry_count == 3
+ status = "connection established"
+ retry_count = 0
+ redo
+ elsif status == "network failure" and retry_count < 5
+ puts "network failure #{retry_count}"
+ retry_count += 1
+ redo
+ elsif status == "connection established"
+ puts d
+ sum += d
+ end
+end
+# output of sum
+# 3456
+```
+
+### Start the cycle again
+
+```ruby
+numbers = [2, 2, 44, 44]
+sum = 0
+begin
+ numbers.each do |s|
+ if rand(1..10) == 5
+ puts "hi 5, let's do it again!"
+ sum = 0
+ raise "hi 5"
+ end
+ puts s
+ sum += s
+ end
+rescue
+ retry
+end
+```
+
+Classes
+---
+
+### Classes Example {.row-span-2}
+
+```ruby
+class Person
+ # when you create a new object, it looks for a method named initialize and executes it, like a constructor in java
+ # def initialize(name, number)
+ # @name = name
+ # @number = number
+ # end
+ # instance variable
+ # @name
+ # class variable
+ # @@count
+ # attr_accessor acts as a getter and setter for the following instance attributes
+ attr_accessor :name, :number
+ # class variable must be initialized
+ @@count = 0
+ def self.count
+ @@count
+ end
+ def self.count=(count)
+ @@count = count
+ end
+ def initialize
+ @@count += 1
+ end
+end
+# create an instance of the Person class
+p1 = Person.new
+# set attributes of the Person class
+p1.name = "Yukihiro Matsumoto"
+p1.number = 9999999999
+# get attributes of the Person class
+puts "#{p1.name}"
+puts "#{p1.number}"
+puts "#{Person.count}"
+# Yukihiro Matsumoto
+# 9999999999
+# 1
+p2 = Person.new
+p2.name = "Yukihiro Matsumoto"
+p2.number = 9999999999
+# get attributes of the Person class
+puts "#{p2.name}"
+puts "#{p2.number}"
+puts "#{Person.count}"
+# Yukihiro Matsumoto
+# 9999999999
+# 2
+# set class variable
+Person.count = 3
+puts "#{Person.count}"
+# 3
+```
+
+### Inherit a class
+
+```ruby
+class Person
+ attr_accessor :name, :number
+end
+# Inherit methods and properties from parent class using < symbol
+class Student < Person
+ attr_accessor :id
+end
+s = Student.new
+s.name = "James Bond"
+s.number = 700
+s.id = 678
+puts "#{p.name}"
+James Bond
+puts "#{p.number}"
+700
+puts "#{p.id}"
+678
+```
+
+### Check instance type
+
+```ruby
+class Vehicle; end
+class Car < Vehicle; end
+class Audi < Car; end
+car = Car.new
+car.instance_of? Vehicle
+false
+car.instance_of? Car
+true
+car.instance_of? Audi
+false
+a = 7
+a.instance_of? Integer
+true
+a.instance_of? Numeric
+false
+```
+
+Returns true if the object is an instance of the given class and not a subclass or superclass
+
+### Print all method names of a class
+
+```ruby
+puts (String.methods).sort
+# Exclude methods inherited from Object class
+puts (String.methods - Object.public_instance_methods).sort
+```
+
+### Check if a class has a specific method
+
+```ruby
+String.respond_to?(:prepend)
+true
+String.respond_to?(:append)
+false
+```
+
+See Also
+---
+
+- [Ruby](https://www.ruby-lang.org/en/) _(ruby-lang.org)_
+- [Ruby Cheatsheet](https://github.com/lifeparticle/Ruby-Cheatsheet) _(github.com)_
\ No newline at end of file
diff --git a/source/_posts/rust.md b/source/_posts/rust.md
index 3a97580..458781c 100644
--- a/source/_posts/rust.md
+++ b/source/_posts/rust.md
@@ -277,7 +277,7 @@ println!("Share {cs} for developers");
```rust
// Creating an empty string object
-let my_string = String::new;
+let my_string = String::new();
// Converting to a string object
let S_string = a_string.to_string()
diff --git a/source/_posts/selenium.md b/source/_posts/selenium.md
new file mode 100644
index 0000000..ff8ac28
--- /dev/null
+++ b/source/_posts/selenium.md
@@ -0,0 +1,156 @@
+---
+title: Selenium
+date: 2024-05-04 19:50:01
+background: bg-[#d33731]
+tags:
+ - automation
+ - testing
+categories:
+ - Programming
+intro: |
+ This cheat sheet is a crash course for Selenium beginners and help to get the idea about the basic concepts of Selenium.
+---
+
+## Getting Started
+
+### Initialize Browser Drivers {.row-span-2}
+
+| Browser | Syntax |
+| --------- | --------------------------------------- |
+| `Chrome` | WebDriver driver = new ChromeDriver(); |
+| `Edge` | WebDriver driver = new EdgeDriver(); |
+| `Firefox` | WebDriver driver = new FirefoxDriver(); |
+| `Safari` | WebDriver driver = new SafariDriver(); |
+
+{.show-header .left-text}
+
+### Selenium Locators {.col-span-2}
+
+| Locator | Syntax |
+| ----------------- | --------------------------------------------- |
+| `className` | driver.findElement(By.className (“key”)) |
+| `cssSelector` | driver.findElement(By.cssSelector(key")) |
+| `id ` | driver.findElement(By.id(key")) |
+| `linkText` | driver.findElement(By.linkText(key")) |
+| `name` | driver.findElement(By.name(“key")) |
+| `partialLinkText` | driver.findElement(By.partialLinkText(“key")) |
+| `tagName ` | driver.findElement(By.tagName (“key”)) |
+| `xpath` | driver.findElement(By.xpath(“key")) |
+
+{.show-header .left-text}
+
+### Navigate to URL
+
+```shell script
+driver.get("https://www.example.com");
+```
+
+### Close all browser windows
+
+```shell script
+driver.quit();
+```
+
+### Close the current browser window
+
+```shell script
+driver.close();
+```
+
+### Navigation {.col-span-2}
+
+| Description | Syntax |
+| ------------------------------- | ------------------------------------------------ |
+| `Navigate to a new URL` | driver.navigate().to("https://www.newsite.com"); |
+| `Go forward to the next page` | driver.navigate().forward(); |
+| `Go back to the previous page ` | driver.navigate().back(); |
+| `Refresh the current page` | driver.navigate().refresh(); |
+
+{.show-header .left-text}
+
+### Frame Handling {.col-span-2}
+
+| Description | Syntax |
+| --------------------------------- | ----------------------------------- |
+| `Switch to a frame` | driver.switchTo().frame("frameId"); |
+| `Switch back to the main content` | driver.switchTo().defaultContent(); |
+
+{.show-header .left-text}
+
+### Alerts/Pop-Ups
+
+```shell script
+Alert alert = driver.switchTo().alert();
+
+// Used to click on the ‘OK’ button of the alert.
+alert.accept();
+
+// Used when the ‘Cancel’ button is clicked in the alert box.
+alert.dismiss();
+
+// Used to send text to an alert
+alert.sendKeys("text");
+
+// Used to capture the alert message.
+alert().getText();
+
+```
+
+### Mouse and Keyboard Actions {.col-span-2}
+
+```shell script
+Actions actions = new Actions(driver);
+
+// Shifts the mouse pointer to the center of the element and click on it
+actions.moveToElement(element).click().build().perform();
+
+// Performs double click on the element
+actions.doubleClick(element).perform();
+
+// Drags the element from one point and drops to another
+actions.dragAndDrop(source, target).perform();
+
+// Sends a series of keys to the element
+actions.sendKeys(element, "text").perform();
+
+```
+
+### Page Information {.col-span-1}
+
+```shell script
+// Get the page title
+driver.getTitle();
+
+// Get the current page URL
+driver.getCurrentUrl();
+
+// Get the entire page source code
+driver.getPageSource();
+
+```
+
+### Waits {.col-span-3}
+
+```shell script
+// Explicit Wait :- These are conditional waits can be applied to satisfy a particular condition
+WebDriverWait wait = new WebDriverWait(driver, 10);
+wait.until(ExpectedConditions.elementToBeClickable(element));
+```
+
+```shell script
+// Implicit Wait :- Once the command is run, Implicit Wait remains for the entire duration for which the browser is open.
+driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
+```
+
+```shell script
+// Fluent Wait :- Fluent Wait in Selenium marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
+FluentWait wait = new FluentWait(driver);
+//Specify the timeout of the wait
+wait.withTimeout(5000, TimeUnit.MILLISECONDS);
+//Specify polling time
+wait.pollingEvery(250, TimeUnit.MILLISECONDS);
+//Specify what exceptions to ignore
+wait.ignoring(NoSuchElementException.class)
+//This is how we specify the condition to wait on.
+wait.until(ExpectedConditions.alertIsPresent());
+```
diff --git a/source/_posts/terraform.md b/source/_posts/terraform.md
new file mode 100644
index 0000000..914107c
--- /dev/null
+++ b/source/_posts/terraform.md
@@ -0,0 +1,434 @@
+---
+title: Terraform
+date: 2024-4-18
+background: bg-[#7f48be]
+tags:
+ - container
+ - virtual
+categories:
+ - Programming
+intro: |
+ This is a quick reference cheat sheet for [Terraform](https://docs.docker.com/get-started/).
+plugins:
+ - copyCode
+---
+
+## HCL Syntax:
+
+```
+(Block Name) (Resource Type) (Resource Name)
+ | | |
+ ▽ ▽ ▽
+ resource "aws_instance" "my_aws_server" {
+ --
+ ami = "ami-1251351351513" |<--(Arguments)
+ instance_type = "t2.micro" |
+ --
+
+}
+
+```
+### Variable Types
+
+1. Simple types: number, string, bool, null.
+
+2. Complex types:
+ Collection types: list, map, set
+ Structural types: `object({ = , ...})`, `tuple([, ...])`
+
+Order of Precedence:
+defaults < env vars < terraform.tfvars file < terraform.tfvars.json file < .auto.tfvars < command line (-var & -var-file)
+
+```
+variable "" {
+ description = ""
+ type =
+ default =
+}
+
+# type string
+variable "aws_region" {
+ description = "AWS Region"
+ type = string
+ default = "us-east-1"
+}
+
+# type list(string)
+variable "azs" {
+ description = "AZs in the Region"
+ type = list(string)
+ default = [ "us-east-1a", "us-east-1b", "us-east-1c"]
+}
+
+# type map
+variable "amis" {
+ type = map(string)
+ default = {
+ "eu-west-1" = "ami-0fdke15151513145",
+ "us-east-1" = "ami-0d17359173587519"
+ }
+}
+
+# type object
+variable "egress_dsg" {
+ type = object({
+ from_port = number
+ to_port = number
+ protocol = string
+ cidr_blocks = list(string)
+ })
+ default = {
+ from_port = 0,
+ to_port = 65365,
+ protocol = "tcp",
+ cidr_blocks = ["100.0.0.0/16", "200.0.0.0/16", "0.0.0.0/0"]
+ }
+}
+```
+
+## Meta-Arguments
+
+### Loops
+count, for_each, [for( o in var.list: o.id])
+
+```
+# creating multiple EC2 instances using count
+resource "aws_instance" "server" {
+ ami = "ami-06ec8443c2a35b0ba"
+ instance_type = "t2.micro"
+ count = 3 # creating 3 resources
+}
+
+# declaring a variable
+variable "users" {
+ type = list(string)
+ default = ["demo-user", "admin1", "john"]
+}
+
+# creating IAM users using for_each
+resource "aws_iam_user" "test" {
+ for_each = toset(var.users) # converts a list to a set
+ name = each.key
+}
+
+# A for expression creates a complex type value by transforming another complex type value.
+variable "names" {
+ type = list
+ default = ["som", "john", "mary"]
+}
+
+output "show_names" {
+ # similar to Python's list comprehension
+ value = [for n in var.names : upper(n)]
+}
+
+output "short_upper_names" {
+ # filter the resulting list by specifying a condition:
+ value = [for name in var.names : upper(name) if length(name) > 7]
+}
+```
+
+### Splat
+
+`Splat(var.list[*].id)`
+
+```
+# Launch an EC2 instance
+resource "aws_instance" "server" {
+ ami = "ami-05cafdf7c9f772ad2"
+ instance_type = "t2.micro"
+ count = 3
+}
+
+output "private_addresses"{
+ value = aws_instance.server[*].private_ip # splat expression
+}
+```
+
+### depends_on
+
+if two resources depends on each other, depends_on specifies that dependency to enforce ordering
+```
+resource "aws_iam_role_policy" "example" {
+ name = "example"
+ role = "s3 access"
+ policy = jsonencode({
+ "Statement" = [{
+ "Action" = "s3:*",
+ "Effect" = "Allow",
+ }],
+ })
+}
+
+resource "aws_instance" "my_server" {
+ ami = "ami-a255235"
+ instance_type = "t2.micro"
+
+ iam_instance_profile = aws_iam_instance_profile.my_server
+
+ depends_on = [
+ aws_iam_role_policy.example,
+ ]
+```
+
+### lifecycle
+
+A set of meta arguments to control behavior specific resources
+```
+resources "aws_instance" "server" {
+ ami = "ami-a1b3414"
+ instance_type = "t2.micro"
+
+ lifecycle {
+ create_before_destroy = true
+ ignore_changes = [
+ # Some resources have metadata
+ # modified automatically outside of TF
+
+ tags
+ ]
+ }
+}
+```
+
+### Conditionals
+
+`condition ? true_val : false_val`
+
+### Built-In functions
+
+| Function | Result |
+| ------------------------------------------------|-------------------------|
+| `max(5, 10, 9)` | 12 |
+| `min(5, 10, 9)` | 5 |
+| `format("There are %d servers", 4)` | There are 4 lights |
+| `join("," ["foo", "bar", "baz"])` | foo,bar,baz |
+| `split(",", "foo,bar,baz")` | `["foo", "bar", "baz"]` |
+| `replace("hi world", "/w.*d/", "mom"` | hi mom |
+| `substr("hello world", 1, 4)` | ello |
+| `lookup({a="lol", b="sad"}, "a", "what?")` | lol |
+| `lookup({a="lol", b="sad"}, "c", "what?")` | what? |
+| `slice(["a", "b", "c", "d"], 1, 3)` | `["b", "c"]` |
+| `timestamp()` | "2022-04-02T05:52:48Z" |
+| `cidr("10.1.2.240/28", 1)` | 10.1.2.241 |
+| `cidr("10.1.2.240/28", 14)` | 10.1.2.254 |
+
+
+### Provider block
+
+Details of the provider(s) being used. Includes information like access mechanisms, regional options, profile touse etc.
+
+```
+provider "aws" {
+ region = "us-east-1"
+}
+
+# Additional provider config reference as `aws.west`.
+provider "aws" {
+ alias = "west"
+ region = "us-west-2"
+}
+```
+
+### Requiring Providers
+```
+terraform {
+
+ # required_providers block specifies source and version
+ required_providers {
+ aws = {
+ source = "hashicorp/aws" # where to find the provider
+ version = "5.8.0" # which version of the provider is needed for this config
+ }
+ }
+}
+```
+### Locals block
+
+A local value assigns a name to an expression, so you can use the name multiple times within a module instead of repeating the expression
+```
+locals {
+ service_name = "forum"
+ owner = "Community Team"
+}
+
+# once local declared you can reference it
+locals {
+ common_tags = {
+ Service = local.service_name
+ Owner = local.owner
+```
+
+### Output block
+
+```
+output "api_base_url" {
+ value = "https://${aws_instance.example.private_dns}:8433/"
+
+ # The EC2 instance must have an encrypted root volume.
+ precondition {
+ condition = data.aws_ebs_volume.example.encrypted
+ error_message = "The server's root volume is not encrypted."
+ }
+
+ # output can be marked as containing sensitive
+ sensitive = true # output can be marked as containing sensitive
+}
+```
+
+### Data block
+
+Data sources that can be queried (cloud provider, local list, etc.)
+
+```
+data "aws_ami" "example" {
+ most_recent = true
+
+ owners = ["self"]
+ tags = {
+ Name = "app-server"
+ Tested = "true"
+ }
+}
+```
+
+### Modules
+
+```
+module "myec2" {
+ source = "../modules/ec2"
+
+ # module inputs
+ ami_id = var.ami_id
+ instance_type = var.instance_type
+ servers = var.servers
+}
+```
+
+### Backends
+
+A backend defines where Terraform stores its state data files.
+
+Available backends: local(default), remote, azurerm, consul, cos, gcs, http, Kubernetes, oss, pg, s3
+```
+terraform {
+ backend "remote" {
+ organization = "example_corp"
+
+ workspaces {
+ name = "my-app-prod"
+ }
+ }
+}
+```
+
+### Resource Addressing
+
+| Example | Description |
+| ------------------------------------------------- | ----------------------- |
+| `[module path][resource info` | Resource path syntax |
+| `module.[optional] module index` | Module path syntax |
+| `resource_type.user_defined_name[optional index]` | Resource spec syntax |
+| `.` | List all images |
+| `var.` | Input Variable |
+| `local.` | Locals |
+| `module.` | Child module outputs |
+| `data..` | Data blocks |
+| `path.module` | Location of expresssion |
+| `path.root` | Root Module location |
+| `terraform.workspace` | Current workspace |
+---
+## Terraform CLI
+
+Create/Edit TF config file -> init -> plan -> validate -> apply -> destroy
+
+### Initialization
+```sh
+terraform init [options]
+
+ -upgrade # Install latest module & provider versions
+ -reconfigure # reconfigure backend, ignoring any saved config
+ -backend=false # Disable backend & use previous Initialization
+ -migrate-state # reconfigure backend & attempt to migrate any existing state
+```
+### Planning
+
+Generates & review an execution plan
+```sh
+terraform plan [options]
+
+ -var 'user=john' # set value for input vars in the root module of config
+ -var-file=filename # load var values from the given file
+ -input=true # ask for input for vars if not directly set
+ -out=path # write a plan file to given path. can be used as input for "apply"
+ -refresh-only # verifies remote object consistency without proposing actions to undo changes done outside TF
+ -destroy # create plan to destroy all objects currenly managed
+ -target=resource # target planning to given resouce & its dependencies only.
+
+terraform plan -refresh-only # updates state to match changes made outside of TF. Good for drift detection
+
+```
+### Validation
+```sh
+terraform validate # Validates the config files for errors
+
+```
+
+### Apply
+
+Executes changes to infra
+```sh
+terraform apply [options]
+
+ -auto-approve # skip interactive approval of plan before applying
+ -replace # force replacement of a particular resource instance
+ -var 'foo=bar' # set a value for input vars in the root module of config
+ -var-file=filename # load var values from the given file
+ -parallelism=n # limit the no of concurrent operations. Default=10
+
+terraform apply -auto-approve var-file=web-dev.tfvars
+terraform apply -replace="aws_instance.server"
+terraform plan -refresh-only # Updates statefile to accept changes made manually.
+```
+
+### Destroy
+
+Destroy (deletes) Terraform managed infra. Same as `terraform apply -destroy `
+
+```sh
+terraform destroy [options]
+
+ -auto-approve # skip interactive approval before destroying
+ -target # limits destroy to only given resource & its dependencies
+
+
+terraform destroy -target aws_vpc.my_vpc -auto-approve
+```
+
+# Miscellaneous
+
+```sh
+terraform state show aws_instance.my_vm
+terraform state pull > my_terraform.tfstate
+terraform state mv aws_iam_role.my_ssm_role
+terraform state list
+terraform state rm aws_instance.my_server
+
+terraform import aws_instance.new_server i-243abc
+sudo apt install graphviz
+terraform graph | dot -Tpng > graph.png
+```
+
+# Logging
+log levels = TRACE > DEBUG > INFO > WARN > ERROR
+
+```sh
+export TF_LOG_CORE=TRACE # enable core logging
+export TF_LOG_PROVIDER=TRACE # enable provider logging
+export TF_LOG_PATH=logs.txt # to persist logs
+```
+
+# Also See
+
+- [Docs](https://developer.hashicorp.com/terraform/language)
+- [Good FCC Article](https://www.freecodecamp.org/news/terraform-certified-associate-003-study-notes/)
diff --git a/source/assets/icon/nim.svg b/source/assets/icon/nim.svg
index 38b29b1..f005ad2 100644
--- a/source/assets/icon/nim.svg
+++ b/source/assets/icon/nim.svg
@@ -1,2 +1,4 @@
-
-
\ No newline at end of file
+
+
diff --git a/source/assets/icon/ruby.svg b/source/assets/icon/ruby.svg
new file mode 100644
index 0000000..45e591d
--- /dev/null
+++ b/source/assets/icon/ruby.svg
@@ -0,0 +1,3 @@
+
\ No newline at end of file
diff --git a/themes/coo/source/css/style.tailwindcss b/themes/coo/source/css/style.tailwindcss
index b92f6a3..69e4ec9 100644
--- a/themes/coo/source/css/style.tailwindcss
+++ b/themes/coo/source/css/style.tailwindcss
@@ -28,6 +28,28 @@ html.scrollbar {
scroll-padding-top: 20px;
}
+/***Scrollbars***/
+:root.dark {
+ color-scheme: dark;
+}
+
+/* Restrict changes to mouse users */
+@media (pointer: fine) {
+ ::-webkit-scrollbar {
+ @apply bg-slate-200 w-2 h-2 rounded-lg
+ }
+ ::-webkit-scrollbar-thumb {
+ @apply bg-slate-300 rounded-lg
+ }
+
+ :root.dark ::-webkit-scrollbar {
+ @apply bg-slate-700
+ }
+ :root.dark ::-webkit-scrollbar-thumb {
+ @apply bg-slate-500
+ }
+}
+
.max-container {
max-width: 1320px;
@apply mx-auto p-3;