投稿時間:2022-02-11 21:35:06 RSSフィード2022-02-11 21:00 分まとめ(38件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… CYRILL、「iPhone 13」シリーズ向けカラーブリックケース購入でもう1個貰えるバレンタインデーキャンペーンを開催中 https://taisy0.com/2022/02/11/151932.html cyrill 2022-02-11 11:27:24
python Pythonタグが付けられた新着投稿 - Qiita 私の記事まとめ https://qiita.com/seiji1997/items/3a8624fca50298e9e537 deeplearning 2022-02-11 20:56:20
Git Gitタグが付けられた新着投稿 - Qiita git管理下からはずす手順 https://qiita.com/tarian/items/e18f091658ac1ead1a3e 2022-02-11 20:31:10
Git Gitタグが付けられた新着投稿 - Qiita windowsにgit-filter-repoをインストールする https://qiita.com/error484/items/6d834f2b1de133eb1fc4 2022-02-11 20:29:39
Git Gitタグが付けられた新着投稿 - Qiita Gitのコミット絵文字prefix入力の辛さを改善する https://qiita.com/tfunato/items/9e4030ad1853dee2e6cb Gitのコミット絵文字prefix入力の辛さを改善する前提コミットメッセージにprefixを入れるのはいいぞ背景コミットメッセージのprefixに特定の文言を入れると、様々な良い効果が生まれ開発が捗る事が言われています。 2022-02-11 20:22:01
海外TECH Ars Technica Hundreds of e-commerce sites booby-trapped with payment card skimming malware https://arstechnica.com/?p=1833417 hackers 2022-02-11 11:15:24
海外TECH MakeUseOf Avoid Your No-Go Foods With These Food Scanner Apps https://www.makeuseof.com/food-scanner-apps/ dietary 2022-02-11 11:30:12
海外TECH MakeUseOf Use These 5 Ethereum Fee Calculators to Reduce Your Gas Fees https://www.makeuseof.com/ethereum-gas-fee-calculators/ prices 2022-02-11 11:30:12
海外TECH DEV Community What Is GitLab CI/CD And GitLab CI/CD Pipeline | GitLab CI/CD Tutorial | Part II https://dev.to/lambdatest/what-is-gitlab-cicd-and-gitlab-cicd-pipeline-gitlab-cicd-tutorial-part-ii-365a What Is GitLab CI CD And GitLab CI CD Pipeline GitLab CI CD Tutorial Part IIThis video explains what is Gitlab CI CD what is GitLab CI CD Pipeline and how to get started with GitLab CI CD Start FREE Testing Run Selenium Tests In GitLab CI GitLab CI makes the release process simple and easy averting last minute checks It allows seamless integration with cloud based tools like LambdaTest an online Selenium Grid of real browsers ensuring a seamless UI for web applications building a robust CI CD pipeline Want to get started with CICD Well here is a detailed CI CD Tutorial by LambdaTest answers the following What is a GitLab CI pipeline What is CI and CD in GitLab How do you create a GitLab CI CD pipeline How do you start GitLab 2022-02-11 11:52:36
海外TECH DEV Community 6 Tips and Tricks to avoid NullPointerException https://dev.to/prafful/6-tips-and-tricks-to-avoid-nullpointerexception-5dd Tips and Tricks to avoid NullPointerExceptionNull references have historically been a bad idea even Tony Hoare who invented null references calls it The Billion Dollar Mistake I call it my billion dollar mistake It was the invention of the null reference in At that time I was designing the first comprehensive type system for references in an object oriented language ALGOL W My goal was to ensure that all use of references should be absolutely safe with checking performed automatically by the compiler But I couldn t resist the temptation to put in a null reference simply because it was so easy to implement This has led to innumerable errors vulnerabilities and system crashes which have probably caused a billion dollars of pain and damage in the last forty years Charles Antony Richard Hoare OverviewNullPointerException can sometimes be frustrating It can break your application It could be difficult to find an actual issue from the production server logs In this article I will explain what is java lang NullPointerException Also we will see various tips and tricks that will help you in writing better code If you already have some idea about NullPointerException skip to the How to avoid NullPointerException section What is NullPointerException The NullPointerException is a runtime exception when a program tries to access an object with a null reference Or does any operation on a null object Here is a simple code snippet that throws java lang NullPointerException Here str is null any operations on it will throw NullPointerException The output if we try to run this code This was a trivial example imagine if our String str was given as an argument or in result set from a database call the application will break In the next section we will see some best practices to avoid NullPointerException How to avoid NullPointerException One of the famous ways to avoid java lang NullPointerException is to add null checks wherever plausible However this approach will make your code bloated with null something statements Here are some best practices that you can follow to make your code NullPointerException proof Using Optional ClassThe optional class feature was introduced in Java Here is an example that explains how you can leverage the Optional class feature to reduce NullPointerExceptions import java util Optional public class Example public static void main String args String str null Optional lt String gt strOpt Optional ofNullable str System out print strOpt orElse length prints Here strOpt orElse gives us an empty string when str is null otherwise it returns the original string Below are some more useful methods that can be used with the Optional class for different scenarios public boolean isPresent Returns true if there is a value present otherwise false public T get If a value is present in this Optional returns the value otherwise throws NoSuchElementException public T orElseGet Supplier lt extends T gt other Returns the value if present otherwise invoke other and return the result of that invocation To read more about the Optional class refer Optional Java Platform SE Using StringUtilsStringUtils handles null input Strings quietly Meaning if a null String is passed it does not throw NullPointerException It considers the null String as blank For using this in your project you may need to import StringUtils from Apache Commons Lang Bellow code demonstrate the null safety feature of StringUtils import org apache commons lang StringUtils public class Example public static void main String args String str null System out print StringUtils length str prints Some useful StringUtils method are as follows public static boolean isNotBlank CharSequence cs Checks if a CharSequence is not empty not null and not whitespace only public static boolean equals CharSequence cs CharSequence cs Compares two CharSequences returning true if they represent equal sequences of characters Returns true if both arguments are null Read more about StringUtils here Using Primitive DatatypesSince primitive datatypes can never be null Wherever possible try using int instead of Integer boolean instead of Boolean float instead of Float double instead of Double long instead of Long short instead of Short char instead of Character Calling equals on literalWhile comparing two Strings or elements of an enum it is always recommended to use a non null value at the left hand side Example public class Example public static void main String args String str null if abc equals str System out println true if str equals abc NullPointerException here System out println true Using Ternary OperatorUsing a ternary operator you can prevent your code from throwing NullPointerExceptions Here is how public class Example public static void main String args String str null System out println null str str length The above code will call length method only if str is not null hence preventing NullPointerException Throwing IllegalArgumentExceptionIt is always a best practice to throw an IllegalArgumentException if the argument is null or something that is not expected This may save hours of figuring out what went wrong Here is an example code that throws IllegalArgumentException when the argument passed is null public class Example public static void main String args String str null printStringLength str static void printStringLength String str if null str throw new IllegalArgumentException String str was null else System out println str length ConclusionOne of my favourite way of avoiding NullPointerException is by adding this statement null obj getSomething But we re mature developers we don t want to bloat our code with these null check statements imagine a code that looks like this if null obj amp amp null obj getSomething amp amp null obj getSomething fromHere amp amp null obj obj getSomething fromHere property do something with obj getSomething fromHere property Looks crazy right Trust me I ve written this in one of my applications to stop NullPointerExceptions However now we know how to avoid them in a better way Thank you for reading Do let me know in the comments what was the craziest thing you did for dealing with NullPointerExceptions 2022-02-11 11:50:06
海外TECH DEV Community Programmatic inspection of databases in Go using Atlas https://dev.to/ariga/programmatic-inspection-of-databases-in-go-using-atlas-4636 Programmatic inspection of databases in Go using AtlasDatabase inspection is the process of connecting to a database to extract metadata about the way data is structured inside it In this post we will present some use cases for inspecting a database demonstrate why it is a non trivial problem to solve and finally show how it can be solved using Atlas an open source package and command line tool written in Go that we are maintaining at Ariga As an infrastructure engineer I have wished many times to have a simple way to programmatically inspect a database Database schema inspection can be useful for many purposes For instance you might use it to create visualizations of data topologies or use it to find table columns that are no longer in use and can be deprecated Perhaps you would like to automatically generate resources from this schema such as documentation or GraphQL schemas or to use to locate fields that might carry personally identifiable information for compliance purposes Whatever your use case may be having a robust way to get the schema of your database is the foundation for many kinds of infrastructure applications When we started working on the core engine for Atlas we quickly discovered that there wasn t any established tool or package that could parse the information schema of popular databases and return a data structure representing it Why is this the case After all most databases provide some command line tool to perform inspection For example psql the standard CLI for Postgres supports the d command to describe a table postgres d users Table public users Column Type Collation Nullable Default id integer not null name character varying Indexes users pkey PRIMARY KEY btree id So what makes inspection a non trivial problem to solve In this post I will discuss two aspects that I think are interesting The first is the variance in how databases expose schema metadata and the second is the complexity of the data model that is required to represent a database schema How databases expose schema metadataMost of the SQL that we use in day to day applications is pretty standard However when it comes to exposing schemametadata database engines vary greatly in the way they work The way to retrieve information about things like available schemas and tables column types and their default values and many other aspects of the database schema lookscompletely different in each database engine For instance consider this query source which can be used to get the metadata about table columns from a Postgres database SELECT t table name t column name t data type t is nullable t column default t character maximum length t numeric precision t datetime precision t numeric scale t character set name t collation name t udt name t is identity t identity start t identity increment t identity generation col description to regclass table schema table name oid ordinal position AS comment t typtype t oidFROM information schema columns AS t LEFT JOIN pg catalog pg type AS t ON t udt name t typnameWHERE table schema AND table name IN s ORDER BY t table name t ordinal positionAs you can see while it s definitely possible to get the needed metadata information about the schema is stored in multiple tables in a way that isn t particularly well documented and often requires delving into the actual source code to understand fully Here s a query to get similar information from MySQL source SELECT TABLE NAME COLUMN NAME COLUMN TYPE COLUMN COMMENT IS NULLABLE COLUMN KEY COLUMN DEFAULT EXTRA CHARACTER SET NAME COLLATION NAME FROM INFORMATION SCHEMA COLUMNS WHERE TABLE SCHEMA AND TABLE NAME IN s ORDER BY ORDINAL POSITION While this query is much shorter you can see that it s completely different from the one we ran to inspect Postgres column metadata This demonstrates just one way in inspecting Postgres is difference from inspecting MySQL Mapping database schemas into a useful data structureTo be a solid foundation for building infrastructure inspection must produce a useful data structure that can betraversed and analyzed to provide insights in other words a graph representing the data topology As mentioned above such graphs can be used to create ERD entity relation diagram charts such as the schema visualizations on the Atlas Management UI Let s consider some aspects of database schemas that such a data structure should capture Databases are split into logical schemas Schemas contain tables and may have attributes such as default collation Tables contain columns indexes and constraints Columns are complex entities that have types that may be standard to the database engine and version orcustom data types that are defined by the user In addition Columns may have attributes such as default values that may be a literal or an expression it is important to be able to discern between now and now Indexes contain references to columns of the table they are defined on Foreign Keys contain references to column in other tables that may reside in other schemas and much much more To capture any one of these aspects boils down to figuring out the correct query for the specific database engine you are working with To be able to provide developers with a data structure that captures all of it and to do it well across different versions of multiple database engines we ve learned is not an easy task This is a perfect opportunity for an infrastructure project a problem that is annoyingly complex to solve and that if solved well becomes a foundation for many kinds of applications This was one of our motivations for creating Atlas GitHub an open source project that we maintain here at Ariga Using Atlas database schemas can be inspected to product Go structs representing a graph of the database schema topology Notice the many cyclic references that make it hard to print but very ergonomic to traverse amp schema Realm Schemas amp schema Schema Name test Tables amp schema Table Name users Schema amp schema Schema CYCLIC REFERENCE Columns amp schema Column Name id Type amp schema ColumnType Type amp schema IntegerType T int Unsigned false Null false PrimaryKey amp schema Index Unique false Table amp schema Table CYCLIC REFERENCE Attrs nil Parts amp schema IndexPart SeqNo Desc false C amp schema Column CYCLIC REFERENCE amp schema Table Name posts Schema amp schema Schema CYCLIC REFERENCE Columns amp schema Column Name id Type amp schema ColumnType Type amp schema IntegerType T int Unsigned false Null false amp schema Column Name author id Type amp schema ColumnType Type amp schema IntegerType T int Unsigned false Null true PrimaryKey amp schema Index Unique false Table amp schema Table CYCLIC REFERENCE Parts amp schema IndexPart SeqNo Desc false C amp schema Column CYCLIC REFERENCE ForeignKeys amp schema ForeignKey Symbol owner id Table amp schema Table CYCLIC REFERENCE Columns amp schema Column CYCLIC REFERENCE RefTable amp schema Table CYCLIC REFERENCE RefColumns amp schema Column CYCLIC REFERENCE OnDelete SET NULL Inspecting databases in Go using AtlasWhile Atlas is commonly used as a CLI tool all of Atlas s core engine capabilities are available as a Go module that you can use programmatically Let s get started with database inspection in Go To install Atlas use go get ariga io atlas master DriversAtlas currently supports three core capabilities for working with SQL schemas Inspection Connecting to a database and understanding its schema Plan Compares two schemas and produces a set of changes needed to reconcile the target schema to the sourceschema Apply creates concrete set of SQL queries to migrate the target database In this post we will dive into the inspection with Atlas The way inspection is done varies greatly between the different SQL databases Atlas currently has four supported drivers MySQLMariaDBPostgreSQLSQLiteAtlas drivers are built on top of the standard library database sql package To initialize the different drivers we need to initialize a sql DB and pass it to the Atlas driver constructor For example package tutorialimport database sql log testing github com mattn go sqlite ariga io atlas sql schema ariga io atlas sql sqlite func Test t testing T Open a connection to sqlite db err sql Open sqlite file example db cache shared amp fk amp mode memory if err nil log Fatalf failed opening db s err Open an atlas driver driver err sqlite Open db if err nil log Fatalf failed opening atlas driver s err do stuff with the driver InspectionAs we mentioned above inspection is one of Atlas s core capabilities Consider the Inspector interface in the sql schema package package schema Inspector is the interface implemented by the different database drivers for inspecting multiple tables type Inspector interface InspectSchema returns the schema description by its name An empty name means the attached schema e g SCHEMA in MySQL or CURRENT SCHEMA in PostgreSQL A NotExistError error is returned if the schema does not exists in the database InspectSchema ctx context Context name string opts InspectOptions Schema error InspectRealm returns the description of the connected database InspectRealm ctx context Context opts InspectRealmOption Realm error As you can see the Inspector interface provides methods for inspecting on different levels InspectSchema provides inspection capabilities for a single schema within a database server InspectRealm inspects the entire connected database server Each database driver for example MySQL Postgres or SQLite implements this interface Let s see how we can use this interface by inspecting a dummy SQLite database Continuing on the example from above package tutorialfunc TestInspect t testing T skipping driver creation ctx context Background Create an example table for Atlas to inspect err db ExecContext ctx create table example id int not null if err nil log Fatalf failed creating example table s err Open an atlas driver driver err sqlite Open db if err nil log Fatalf failed opening atlas driver s err Inspect the created table sch err driver InspectSchema ctx main amp schema InspectOptions Tables string example if err nil log Fatalf failed inspecting schema s err tbl ok sch Table example require True t ok expected to find example table require EqualValues t example tbl Name id ok tbl Column id require True t ok expected to find id column require EqualValues t amp schema ColumnType Type amp schema IntegerType T int An integer type specifically int Null false The column has NOT NULL set Raw INT The raw type inspected from the DB id Type The full source code for this example is available in the atlas examples repo And voila In this example we first created a table named example by executing a query directly against the database Next we used the driver s InspectSchema method to inspect the schema of the table we created Finally we made some assertions on the returned schema Table instance to verify that it was inspected correctly Inspecting using the CLIIf you don t want to write any code and just want to get a document representing your database schema you can always use the Atlas CLI to do it for you To get started head over to the docs Wrapping upIn this post we presented the Go API of Atlas which we initially built around our use case of building a new database migration tool as part of the Operational Data Graph Platform that we are creating here at Ariga As we mentioned in the beginning of this post there are a lot of cool things you can build if you have proper database inspection which raises the question what will you build with it Getting involved with AtlasFollow the Getting Started guide on theAtlas website Join our Discord Server Follow us on Twitter 2022-02-11 11:35:02
海外TECH DEV Community SDK Y APIS https://dev.to/leifermendez/sdk-y-apis-549i SDK Y APISEn el desarrollo de software moderno el SDK y la API son dos herramientas principales con las que te encontrarás con frecuencia Tienen mucho en común y a veces hay confusión sobre lo que hace cada una En esencia tanto el SDK como la API te permiten mejorar la funcionalidad de tu aplicación con relativa facilidad Para cumplir la promesa de cualquiera de ellas o de ambas y mejorar la experiencia tanto interna como de los usuarios finales es importante entender cómo funcionan ambas herramientas en el backend en quése diferencian y cómo contribuyen al proceso general de desarrollo Quées un SDK SDK significa kit de desarrollo de software También conocido como devkit El SDK es un conjunto de herramientas de construcción de software para una plataforma específica que incluye los bloques de construcción depuradores y a menudo un marco o grupo de bibliotecas de código como un conjunto de rutinas específicas de un sistema operativo SO Un SDK típico puede incluir algunos o todos estos recursos en su conjunto de herramientas Compilador Traduce de un lenguaje de programación al que se va a trabajarMuestras de código Ofrecen un ejemplo concreto de una aplicación o página webBibliotecas de código framework Proporcionan un atajo con secuencias de código que los programadores utilizarán repetidamenteHerramientas de prueba y análisis Proporcionan información sobre el rendimiento de la aplicación o el producto en entornos de prueba y producciónDocumentación Proporciona a los desarrolladores instrucciones que pueden consultar sobre la marchaDepuradores Ayudan a los equipos a detectar errores en su código para que puedan publicar un código que funcione como se espera A menudo el SDK incluye también al menos una API ya que sin ella las aplicaciones no pueden transmitir información ni trabajar juntas Cómo funciona un SDKLos SDK proporcionan una amplia colección de herramientas que permiten a los desarrolladores de software crear aplicaciones de software más rápidamente y de forma más estandarizada El desarrollo de aplicaciones móviles nativas en la nube por ejemplo aprovecha los SDK de iOS de Apple o los SDK de Android de Google para esa plataforma Para las aplicaciones a mayor escala como el software como servicio SaaS de las empresas y las aplicaciones de software de escritorio y web patentadas Microsoft proporciona el SDK NET de código abierto que se utiliza habitualmente La sencillez de un SDK es tan valiosa como las herramientas del kit El funcionamiento es el siguiente Compre descargue e instale el kit correspondiente a su plataforma por ejemplo piezas prefabricadas ejemplos e instrucciones Abre y aprovecha las API y todas las herramientas de desarrollo que necesites para crear una nueva aplicación empezando por el entorno de desarrollo integrado IDE Este es el espacio donde harás la codificación real y donde estátu compilador Utiliza las instrucciones la documentación los ejemplos de código y las herramientas de prueba para realizar la construcción lo que te daráa ti y a tu equipo una buena ventaja Casos de uso del SDKLos SDK de lenguajes de programación específicos como el JSON y el Java Developer Kit JDK se utilizan para desarrollar programas en esos lenguajes de una manera racionalizada y estandarizada Los SDK de análisis de Google y otros proporcionan datos sobre los comportamientos rutas y acciones de los usuarios Los SDK de monetización de Google Facebook y otros facilitan a los desarrolladores el despliegue de publicidad en sus aplicaciones existentes con el objetivo de generar ingresos Ventajas del SDKProporcionan acceso a los componentes e instrucciones para el desarrollo de software Un SDK para comercios por ejemplo que recoge todo lo que se desea en la aplicación favoritos carrito guardar para más tarde pago etc Integraciones más rápidas y fluidas Los SDKs simplifican los procesos estándar necesarios y proporcionan un fácil acceso a la información necesaria Ciclo de desarrollo más corto consiguiendo que los productos se desplieguen y lleguen al mercado de forma más eficiente Dado que un SDK estáconstruido para informar equipar y proporcionar atajos para el desarrollo los desarrolladores pueden centrarse en el desarrollo del producto que han planeado Asistencia y experiencia integradas No es necesario buscar respuestas o contratar a alguien para aumentar el equipo los SDK vienen precargados con experiencia en el código ya escrito y la documentación de apoyo incluida Control de costes Todo lo anterior le permite ceñirse mejor a un presupuesto establecido durante el desarrollo y después del despliegue Ahora vamos a ver cómo funciona ese intermediario la API ¿Quées una API API significa interfaz de programación de aplicaciones Tanto si funciona como una solución independiente como si estáincluida en un SDK una API facilita la comunicación entre dos plataformas Lo hace permitiendo que su software propietario sea aprovechado por desarrolladores de terceros Los desarrolladores pueden entonces permitir a sus propios usuarios utilizar indirectamente el servicio o los servicios proporcionados por la solución API También se puede pensar en una API como una especie de acuerdo entre dos partes La API no sólo permite el intercambio de información a la carta sino que estipula cómo debe intercambiarse esa información Dado que algunas API proporcionan la interfaz directamente los términos API e interfaz se utilizan a veces de forma intercambiable Para desglosarlo una API puede constar de dos cosas Las especificaciones técnicas y la documentación Esta información explica cómo tendráque integrar la API para utilizarla eficazmente La interfaz propiamente dicha Puedes acceder a ella directamente a través de una palabra clave en el caso de una API web o indirectamente desde una interfaz independiente en el caso de una API REST Algunas de las API más populares son las siguientesAPIs web que se utilizan para llegar a los navegadores y dispositivos web o como una aplicación propia de servicios web APIs SOAP que son una opción popular en casos de mayor privacidad y seguridad de los datos APIs abiertas o APIs públicas y APIs REST o RESTful que son una opción popular por su facilidad de uso y para maximizar el ancho de banda JSON RPC una opción para los casos en los que se necesitan llamadas asíncronas al servidor APIs personalizadas para conseguir la máxima agilidad con todas las partes móviles del desarrollo de software Quieres más contenido Aquíte dejo algunos enlaces donde comparto el contenido Youtube Todo sobre Angular Node JS y mucho másTelegram Canal donde compartimos dudas y complementamos nuestros conocimientosGithub Todo el código libre de los proyectosBlog Escribo cosas con más frecuencia cada semana Linkedin El canal profesional 2022-02-11 11:34:18
海外TECH DEV Community How to save power consumption in Linux https://dev.to/callepuzzle/how-to-save-power-consumption-in-linux-4a2e How to save power consumption in LinuxPowertop is a great tool to save battery power and with the help of another tool acpid to observe the acpi event and configure it automatically Acpid comes with predefined actions for triggered events By default these actions are defined in etc acpi handler shThe action “ac adapter has a default option logger ACPI action undefined So whether or not you are plugged in the ac you can see the log with journalctl fene msi root ACPI action undefined ACPI In this case you must to change the etc acpi handler sh with ac adapter case in ACPI Saving the changes and unplug the ac the following appears in the log ene msi root AC unplugedThe change works Now you can add the powertop commands This is my handler sh ac adapter case in ACPI case in powertop auto tune echo on gt sys bus usb devices power control USB USB Receiver Logitech echo enabled gt sys class net wlo device power wakeup echo enabled gt sys bus usb devices usb power wakeup echo enabled gt sys bus usb devices usb power wakeup echo enabled gt sys bus usb devices usb power wakeup echo enabled gt sys bus usb devices usb power wakeup echo enabled gt sys bus usb devices power wakeup echo enabled gt sys bus usb devices power wakeup echo enabled gt sys bus usb devices power wakeup logger AC unpluged echo disabled gt sys class net wlo device power wakeup echo disabled gt sys bus usb devices usb power wakeup echo disabled gt sys bus usb devices usb power wakeup echo disabled gt sys bus usb devices usb power wakeup echo disabled gt sys bus usb devices usb power wakeup echo disabled gt sys bus usb devices power wakeup echo disabled gt sys bus usb devices power wakeup echo disabled gt sys bus usb devices power wakeup logger AC pluged Remember this doesn t work if you start the laptop without an ac How do you solve it Inspired by the following post I created a new systemd unit usr lib systemd system acpid boot service Unit Description ACPI boot handleDocumentation man acpid Service Type oneshotExecStart usr local sbin acpi boot handle sh Install WantedBy multi user targetAnd the script usr local sbin acpi boot handle sh contains usr bin env bashset euo pipefailif acpi a grep on then onBit else onBit fi etc acpi handler sh ac adapter ACPI foo onBitIn this way you simulate the acpi action when the laptop starts In my case a MSI Modern the battery has hours more when all of the powertop options are enabled 2022-02-11 11:31:50
海外TECH DEV Community HTML5 Javascript Canvas : Rectangular Collision https://dev.to/spsoi/html5-javascript-canvas-rectangular-collision-4dl7 HTML Javascript Canvas Rectangular CollisionОтслеживаемпересечениеслева jsfiddle netfunction animate requestAnimationFrame animate c fillStyle AA c fillRect canvas width canvas height if mouse x gt canvas width обнаружениепересечениеслева console log Чпоньк red c fillStyle E c fillRect mouse x mouse y blue c fillStyle ABEA c fillRect canvas width canvas height Отрисуемдваквадратаjsfiddle netcanvas jscanvas document querySelector canvas let c canvas getContext d canvas width innerWidth canvas height innerHeight let mouse x innerWidth y innerHeight let colors c ECEFD FFFE FFF document addEventListener mousemove function event mouse x event clientX mouse y event clientY function animate requestAnimationFrame animate c fillStyle AA c fillRect canvas width canvas height c fillStyle E c fillRect mouse x mouse y c fillStyle ABEA c fillRect canvas width canvas height animate style csscanvas border px solid index html lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt link rel stylesheet href style css gt lt title gt Document lt title gt lt head gt lt body gt lt canvas id canvas width height gt lt canvas gt lt script src canvas js gt lt script gt lt body gt lt html gt 2022-02-11 11:31:17
海外TECH DEV Community 5 Web Designing mistakes that affect your SEO https://dev.to/technophilic78/5-web-designing-mistakes-that-affect-your-seo-81f Web Designing mistakes that affect your SEOYou have tirelessly worked on the design of your site whether You have added stunning images attractive themes and created beautiful designs Now you find that your website shows nowhere on the search engines You have applied every tactic but all of them were unsuccessful Your website design can be a significant reason you are not getting enough traffic Following are the top web designing mistakes that impact your SEO traffic Let us show you in detail Poor Navigation on your siteYou must have visited many websites where you get no clue of what to do next The primary concern for search engines while ranking a website is to find whether it is user friendly Even a smaller inconvenience on your website for your users can impact SEO performance When you partner with a website designing company in Lucknow you don t have to stress about the Navigation and other designing elements as they will take care of them Large size image and mediaThe biggest mistake website owners make is using heavy images and media files Having large size media files and images on your website directly impacts the page loading speed of your website Using high quality images and media files doesn t mean that you have to upload them at a quick rate If you have also made the same mistakes you can replace them with low size images and media files Like Technophilic the best website designing company in Lucknow offers extraordinary measures to improve your website performance Annoying Pop upsPop ups are excellent ways to generate more leads and conversions However if you use them to annoy your audience search engines Like Google will be more likely to reduce your search engine ranking Use pop ups to don t affect the user experience on your website Over usage of Pop ups can annoy or irritate your visitors resulting in low engagement and conversion rates A website designing company in Lucknow helps you get eye catching and engaging pop ups that will compel your audience to take a look Not Mobile responsiveDo you think your potential audience always uses a PC or laptop to avail services on your website If you feel you are losing great chances to rank on top of the SERPs the reason might be a non mobile responsive website If you have used great graphics for your website but are not optimized for mobile phones you lose great opportunities for more conversations Poorly used whitespacesWhitespaces are the most under appreciated factor in website designing The proper use of whitespaces makes your content look attractive and poor use of whitespace causes significant stress to the eyes of your audience and looks unattractive to engage their interest A website designing company in Lucknow takes good care of all these factors affecting the search engine rankings of a website 2022-02-11 11:30:47
海外TECH DEV Community Futuristic View on Android App Development https://dev.to/jamesnicholasjr/futuristic-view-on-android-app-development-5ffg Futuristic View on Android App Development of the mobile market is occupied by Android applications Awesome right That is the reason why businesses are rushing towards every top Android app development company in India to build their business applications This gives them a wider range of audience than before and creates enhanced brand awareness The rising demand for Android app development India in the modern era is because of the advent of advanced technological trends Android apps are adopting many advanced tech features which are very convenient and save a lot of time to the users Hence they are opting for Android applications the most Frameworks available for developing Android apps are also highly efficient and let the developers develop best in class applications Everything around Android is advantageous This is why it is believed the platform has a great future Given the increasing needs and never ending tech advancements the Android platform is here to stay and remains the leader of mobile app development Here are some of the futuristic Android app development solutions backed by advanced technologies which justify Android app development India has a bright future in the market Futuristic Android based Technical Solutions Instant Android ApplicationsInstant Android apps save a lot of time and do not need to be installed in order to check the app quality This lessens the time spent on installing the app for the app users thereby offering swift responses Many apps are liable to occupy a lot of space But in the case of instant apps it requires memory space on the devices the app is installed on Many eCommerce companies and game developers are getting highly benefited from these instant Android app development services These apps can be easily launched and the user doesn t have to go to the play store to install the same Artificial Intelligence and Machine Learning AI amp ML Recent advancements such as voice searches chatbots advanced analytics big data pricing automated processes etc are all serving the best and users are feeling comfortable using such utilities All of these features are backed by AI and ML They are the heart of modern digital solutions The introduction of these technologies in every Android app development company in India leads to improved customer services Here are the areas where the work can be eased Routine tasks can be automatedUser recommendations can be provided according to customer preferencesFilter configurations can be improvedPersonalized layoutsSpecial discounts Automated payment processesAI amp ML are very effective when combined and are expected to be the future of tech trend evolution Internet of Things IoT G will lead to the developed version of IoT From home to cities everything becomes smart i e smart homes and smart cities Android app development for IoT is going to be a great demand in and beyond Many Android app development India companies are already being benefited by the extended benefits of IoT technology in their app solutions Here are some of the technical solutions backed by IoT Smart fitness trackerHome sensorsSmart home gadgetsIndustrial production trackingLogistics and transportation Augmented Reality and Virtual Reality AR amp VR Augmented reality and virtual reality technologies are capable of transforming your Android apps into a whole new level of standardized solution The best example is Google maps which allows you to navigate easily from one place to another using virtual maps and real street views Also many leading furniture companies such as IKEA have come up with a virtual furniture setting feature that allows customers to check if a particular piece of furniture suits their place by packing them virtually Many businesses are coming forward to adopt these technologies and many sectors have already adopted these trends in their Android apps and are doing great Soon AR and VR will touch every possible niche in Android app development Blockchain TechnologyEvery fintech company is using blockchain technologies in recent times Blockchain technology combined with Android app development can reduce operating costs significantly improve app security offer secure transactions and back the exchange of data in a private and secure environment Top companies such as PayPal and Facebook are adopting blockchain trends slowly and FB is about to create its own cryptocurrency This technology is powerful enough to completely avoid unauthorized access breaches and hacks Many other Android app development companies in India are about to try their hand in this tech trend and will tailor solutions backed by Blockchain in the upcoming years Wrapping UpEvery Android app development company in India has a lot to offer businesses and developers looking to build a futuristic Android application With such efficient ranges of advancements in line with their upgrades the forthcoming Android tech world will flourish with newer technologies and features thereby giving people more than their expectations Pyramidion is a renowned mobile app development company holding experienced Android app developers To get started with our services connect with our experts soon 2022-02-11 11:28:10
海外TECH DEV Community Top 8 React Bootstrap Themes for Enthusiasts and Pros https://dev.to/flatlogic/top-8-react-bootstrap-themes-for-enthusiasts-and-pros-3c01 Top React Bootstrap Themes for Enthusiasts and Pros IntroductionBeauty is the removal of superfluities This statement by Michelangelo isn t only about aesthetics Masters of various professions have made similar statements And the ones who didn t often showed a similar attitude to their craft and life Empty spaces in a painting give weight to the parts that aren t empty Mechanisms with fewer moving parts break less Fewer components in software mean fewer things can go wrong In this article we ll talk about the best React Bootstrap templates and themes Both React and Bootstrap are frameworks that let you use existing functionality in your web applications Using them is the software analogy of fewer moving parts in a mechanism By using Bootstrap templates you trade some versatility for speed and reliable operation If you need components not supported by Bootstrap you ll want to use other solutions But when used right Bootstrap saves time and helps avoid potential compatibility issues To know what templates to choose and how to use them keep reading What You Need to Know About BootstrapWe ve written so much about React it s hard to find an article in our blog that doesn t have a paragraph on it Today we ll pay more attention to Bootstrap So what is Bootstrap In short Bootstrap is a FOSS Free and Open Source Software CSS framework It serves to develop a responsive cross platform front end with an emphasis on mobile platforms It also serves as a design templates library for interface components like typography forms navigation and more Bootstrap helps front end developers create gorgeous integration ready interfaces that are also design conscious But it has other uses besides building web apps from scratch Like integrating new design elements into your ReactJS project Bootstrap s ready made kit packages help you integrate these elements into your project Bootstrap ProsIntegrating Bootstrap into your project has many advantages Time EfficiencyHave you ever tried coding the traditional way using Notepad or a similar text editor If you have try and see the size of the files you wrote by hand Now compare that with the weight of a complete piece of software Now imagine how much time writing every line of code by hand will take Bootstrap libraries have functions and components you don t have to create from scratch Bootstrap doesn t need programming skills beyond the basics of HTML CSS JavaScript tandem If you know basic website design adding Bootstrap will be easy Additionally Bootstrap documents every component it contains ConsistencyTwitter programmers Mark Otto and Jacob Thornton developed Bootstrap in Their goal was a framework that eliminated any consistency issues If you create a project with Bootstrap it looks the way you intend on any platform and browser This fact helped Bootstrap become one of the top front end frameworks on the market today Conducive to TeamworkBootstrap is what you would call beginner friendly It is easy to learn and needs minimal training The detailed documentation that we have mentioned helps avoid any ambiguity If a new person joins your project s team they ll have no issue learning this framework and seamlessly joining the work process The Grid SystemWhen creating a page layout a good grid is necessary Bootstrap is divided into fluent and responsive website content columns It allows developers to create desktop specific elements by hiding them in the mobile version and vice versa And the predefined classes each component possesses also make the grid much easier and faster to understand ResponsivenessAs nowadays all the initial searches are run through mobile devices the website s responsiveness is as important as it ever was And guess which framework is all about creating mobile friendly websites That s right Bootstrap is Add that to the Grid System and you ll get a website that passes the required level of responsiveness with little effort Bootstrap ConsOf course Bootstrap has its downsides Let s make a rundown of all the things about Bootstrap you ll want to avoid It creates similar websitesWebsites and interfaces built with Bootstrap usually look fine with little that can go wrong or look out of place But Bootstrap s creators aimed for consistency above versatility and it shows Creating standardized interfaces is a different task from creating recognizable website designs Bootstrap s consistency comes at a cost of end results looking alike The more you use Bootstrap the more Bootstrap y everything will look It is possible to override and change style sheets manually but it kills a big part of why we use Bootstrap It can be heavyWe re used to devices getting thinner and lighter Perhaps that s why it s hard to wrap our heads around how heavy software has grown Bootstrap based projects are no exception Using Bootstrap often causes your web app to grow too heavy for casual mobile browsing This issue can be manually resolved but again this messes with the purpose of Bootstrap Learning CurveBootstrap s learning curve is less steep than for example Angular s Still it is there especially in the Grid and the component attribution department A beginner usually spends quite some time studying those before using Bootstrap casually Luckily it s a one time investment Bootstrap s documentation covers the newer version adaptation once you re familiar with it The Best Bootstrap Has to OfferBootstrap s best sides are of course the quickness and seamlessness of web development Especially for mobile devices On the other hand Bootstrap inflates the websites weight and makes any attempts at originality harder Should you use Bootstrap As is often the case the short answer is it varies Bootstrap has its pluses and minuses And it s your usage of it that determines which outweighs the other To give you a better idea of where to start we ve picked eight of our favorite React Bootstrap templates They vary in design and functions but we believe each one can be of interest Let us dive in Top React Bootstrap Templates ThemesComing up is our list of the best React Bootstrap Templates Material Dashboard ReactLinkLive PreviewPro Version Price Coming in at number one on our list is Material Dashboard React by Creative Tim As you can deduct from the name Material Dashboard React is not just a template but a fully functional Admin Dashboard with lots of cool features Let s give them a quick rundown Google s Material Design inspired designOver individual elements for your front end like buttons inputs navbars nav tabs cards alerts and many more Each of the elements mentioned above is customizable in colorExample Pages to get inspired by show to the potential clients or get a jump start on your developmentFull documentation built by the developersSo all in all we can describe Material Dashboard React as a reliable and beautifully made Bootstrap template If you want to lighten the process of web project creation give it a go Argon Dashboard ReactLinkLive PreviewPro Version Price At number two we have the Argon Dashboard React by Creative Tim This open source Bootstrap Dashboard contains over a hundred different components Choose and combine them as you wish Argon Dashboard React s every component has plenty of color variations that you can adjust with SASS files Many hover and focus variations are yours to experiment with At the same time there are example pages and detailed documentation There s enough guidance for you to learn the ropes So despite the hundred something components the Argon is easy to navigate Give it a try and see this balance of simplicity and versatility for yourself Shards Dashboards Lite ReactLinkLive DemoPrice Free The third entry on our list is Shards Dashboard Lite React by design revision Consider it a little treat we would like to add for all the lovers of free templates The first good thing about Shards Dashboard Lite is that it s free of charge but that s the first of many things Shards Lite is responsive and lightning fast It s built from scratch but follows all the best modern development practices That stands true for every template within the Shards Dashboard Lite React It has over a dozen custom components and more than a thousand and a half icons from FontAwesome and Material icon packs If you want to start with a free React Dashboard Template and see where to go next try Shards Dashboard Lite React It will probably be a while before you have to upgrade Light Blue React TemplateLinkLive PreviewPrice We take pride in the product that comes next The Light Blue React Template is Flatlogic s product and it s quite a heavy hitter Admin dashboards are our specialty and we spared no effort this time The Light Blue React can cover you as an admin dashboard a booking management system or an app for promo deals We paid a lot of attention to design too Light Blue s visuals are unobtrusive and well light If you plan to work with an interface for hours on end you want a subtle design that you barely notice is there Add customizable stylings and you ll have an idea of why you should try the Light Blue CoreUI Bootstrap Admin TemplateLinkLive PreviewPro Version Price to Built on Bootstrap and React js CoreUI is a simple template to handle CoreUI boasts mobile and cross browser compatibility But we can say the same about other templates on this list Likewise for the long term support What sets it apart is the dedicated support from developers If you face issues with CoreUI you can get qualified guidance from the people who wrote the damned thing CoreUI is a responsive cross browser template with lots of features and no requirements for your design skills Give it a try BizLandLinkLive PreviewPrice Free to Now we get to sixth place on our list which means we are about to talk about BizLand BizLand is a Bootstrap template that is most fitting for business and corporate projects BizLand helps manage consulting finance tax information insurance and more It has a slick “it s all about business design and vibe BizLand comes with all the features and components a good React Bootstrap template needs But the thing that made us love BizLand was the way it works React components improve the speed of development but often make the website slower That s not the case with BizLand The interface is fast and smooth so the user experience will be fantastic BizLand is responsive and functional comes with well commented code and its file structure is easy to deal with A definite catch of a Bootstrap template CreativeLinkLive PreviewPrice Free to One might nitpick and say that calling a template Creative can be ironically uncreative Nonetheless Creative more than deserves the seventh spot on our list as it is stylish and quite practical Creative contains a bunch of features SB Forms based working contact form and UX friendly navigation contribute to the consistent experience And the HTML markup and custom SASS layout make things intuitive Creative will be a great fit for your next Bootstrap based especially if it is a small business or a creative agency Coming Sssoon PageLinkLive PreviewPrice Free And now it is time to wrap up this list But we cannot do it without mentioning the last eighth entry which is Coming Sssoon Page Let s use your deductive abilities once again and with their help we can come to the conclusion that this light easy to use Bootstrap template is going to be most fitting when it comes to a project that is going to launch in some time in the future With the help of the Coming Sssoon Page you can create a beautiful and engaging page of this kind that can help you establish a following even before your project actually starts its life How to Create your React Dashboard TemplateIs this list a complete piece of guidance Not necessarily There s a legion of templates out there and we cannot give full credit to each one that deserves it Still we manage to try hundreds of templates and pick a few that stand out Some do so with their dependency others with their smooth operation But each item on the list is a solid piece of software that does its job But if none of them made an impression on you we have a solution creating your own Don t worry It s neither difficult nor time consuming Keep reading to know more You can also create your own React based Bootstrap looking template with the help of Flatlogic s Full Stack Web App Platform Here s how you do it Step Choose a name for your projectDespite perceived simplicity this step might as well be the hardest one as you will have to think of a name that can befit your project And also the other steps are even easier Step Choose a stack for your projectAs we are creating a React based template we need to choose the React option for the front end Backend and database can be entirely of your choosing Step Choose a design for your project Here we should say it is better to choose the Transparent variant as it is Bootstrap based Step Choose a schema for your projectThat is right you don t even have to spend time creating a schema yourself as there are ready made variants for you to choose from Step Review and generate your project Just assure yourself of your choices and press the «Create Project»button And what you will have on your hands is a brand new beautiful React based Bootstrap looking template ConclusionBootstrap is a tool that you should definitely try if you haven t already as you will find it greatly simplifies the not so easy process of web projects creation And that s it for today We hope that you ve enjoyed it as much as we did And as always have a nice day and feel free to read more of our articles Suggested articlesTop Bootstrap Dashboard Templates to Use Absolutely Free Noteworthy Bootstrap Admin Themes Made With the Latest Version of VueBootstrap vs Material UI Which One to Use for the Next Web App 2022-02-11 11:24:01
海外TECH DEV Community Not Only Metaverse. UX Trends 2022 https://dev.to/frontend_house/not-only-metaverse-ux-trends-2022-5df5 Not Only Metaverse UX Trends Hi Here we go with the Design Trends to watch out for in Paweł our Head of Design is presenting a list of the eight hottest UX and UI trends for Metaverse NFT Sure but not only Can t miss this video Enjoy You can also read the article at Frontend House 2022-02-11 11:19:10
海外TECH DEV Community Tutorial: Digital Signatures & NFT Allowlists https://dev.to/rounakbanik/tutorial-digital-signatures-nft-allowlists-eeb Tutorial Digital Signatures amp NFT Allowlists A Note on TerminologyA previous version of this article used the term whitelist instead of allowlist Although they refer to the same thing we have decided to update this article to use the latter in the interest of being more inclusive IntroductionCreating NFT allowlists has been by far the most requested topic in our developer community Therefore in this article we will cover the following topics Implementing allowlists on chain and their cost implicationsImplementing allowlists off chain using digital signaturesBy the end of this tutorial you should have an extremely good idea as to how to go about implementing allowlists in a secure and cost efficient way and in the process preventing unpleasant scenarios like gas wars DisclaimerThis article assumes that you have an intermediate knowledge of Solidity Hardhat and OpenZeppelin Contracts If some of these terms sound alien to you we strongly suggest you start here instead We also wanted to point out that not every NFT project requires an allowlist We recommend you think about implementing one only if you have an active and vibrant community and your projected demand for your NFTs far exceeds supply For of the projects out there this simply isn t true Therefore trying to implement allowlists will not only result in wastage of resources that could be spent elsewhere but could also backfire by repelling the few backers that your project has should you not be able to fill all slots Implementing Allowlists On ChainOn chain allowlists are secure and fairly easy to implement We will be using the NFT Collectible Contract from a previous tutorial as our base These are the following additions that we need to make to our contract A global mapping variable isAllowlistAddress that keeps track of all the addresses that have been allowlisted A function allowlistAddress that is callable only by the contract s owner and that can add one or more addresses to isAllowlistAddress mapping A preSale function that is very similar to the mintNfts function except that it only allows allowlisted addresses to mint at a pre sale price We can define the mapping variable as follows mapping address gt bool public isAllowlistAddress Next let s write a allowlisting function that allows the contract s owner to add a list of addresses to the aforementioned mapping Allowlist addressesfunction allowlistAddresses address calldata wAddresses public onlyOwner for uint i i lt wAddresses length i isAllowlistAddress wAddresses i true Finally let s write a preSale function that allows only allowlisted addresses to mint Presale mintsfunction preSale uint count public payable uint totalMinted tokenIds current uint preSalePrice ether uint preSaleMaxMint require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt preSaleMaxMint Cannot mint specified number of NFTs require msg value gt preSalePrice mul count Not enough ether to purchase NFTs require isAllowlistAddress msg sender Address is not allowlisted for uint i i lt count i mintSingleNFT isAllowlistAddress msg sender false Notice that this function is very similar to the mintNfts function that we already have in our contract We use a different price and mint limit for presale We also place an additional check to ensure only allowlisted addresses can mint Finally we remove the address from the allowlist to ensure that the wallet does not mint more than once Your final contract should look something like this SPDX License Identifier MITpragma solidity import openzeppelin contracts utils Counters sol import openzeppelin contracts access Ownable sol import openzeppelin contracts utils math SafeMath sol import openzeppelin contracts token ERC extensions ERCEnumerable sol contract NFTCollectible is ERCEnumerable Ownable using SafeMath for uint using Counters for Counters Counter Counters Counter private tokenIds mapping address gt bool public isAllowlistAddress uint public constant MAX SUPPLY uint public constant PRICE ether uint public constant MAX PER MINT string public baseTokenURI constructor string memory baseURI ERC NFT Collectible NFTC setBaseURI baseURI Allowlist addresses function allowlistAddresses address calldata wAddresses public onlyOwner for uint i i lt wAddresses length i isAllowlistAddress wAddresses i true function reserveNFTs public onlyOwner uint totalMinted tokenIds current require totalMinted add lt MAX SUPPLY Not enough NFTs left to reserve for uint i i lt i mintSingleNFT function baseURI internal view virtual override returns string memory return baseTokenURI function setBaseURI string memory baseTokenURI public onlyOwner baseTokenURI baseTokenURI Presale mints function preSale uint count public payable uint totalMinted tokenIds current uint preSalePrice ether uint preSaleMaxMint require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt preSaleMaxMint Cannot mint specified number of NFTs require msg value gt preSalePrice mul count Not enough ether to purchase NFTs require isAllowlistAddress msg sender Address is not allowlisted for uint i i lt count i mintSingleNFT isAllowlistAddress msg sender false function mintNFTs uint count public payable uint totalMinted tokenIds current require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt MAX PER MINT Cannot mint specified number of NFTs require msg value gt PRICE mul count Not enough ether to purchase NFTs for uint i i lt count i mintSingleNFT function mintSingleNFT private uint newTokenID tokenIds current safeMint msg sender newTokenID tokenIds increment function tokensOfOwner address owner external view returns uint memory uint tokenCount balanceOf owner uint memory tokensId new uint tokenCount for uint i i lt tokenCount i tokensId i tokenOfOwnerByIndex owner i return tokensId function withdraw public payable onlyOwner uint balance address this balance require balance gt No ether left to withdraw bool success msg sender call value balance require success Transfer failed The problem with on chain allowlistsThe implementation we ve used so far is secure and does exactly what it needs to do However this implementation is wildly inefficient The root cause of this is the allowlistAddresses function that can only be called by the contract s owner By its very design this contract expects the owner to populate the mapping with all possible allowlisted addresses Depending on the size of your allowlist this process could prove to be computationally intensive and extremely expensive You may be able to get away with this if you re operating on a sidechain like Polygon or Binance Smart chain but on Ethereum even modest sized allowlists will set you back by several thousands of dollars Fortunately it is possible to implement allowlists securely off chain without having to deal with extortionate gas fees We can achieve this using digital signatures Digital SignaturesDigital Signatures and public key cryptography are central to virtually everything that happens on a blockchains like Bitcoin and Ethereum We won t be covering how signatures work in this article we have a series on cryptography coming very soon Instead we will just acquire a black box understanding of how it works As most of you already know we interact with Ethereum using a wallet which is associated with two keys a public key or wallet address and a private key Using cryptography it is possible for a person to prove that s he holds the private key of a particular wallet address without revealing the key itself It should be obvious why this is very important If we couldn t initiate transactions using our private key without revealing said key the system would break down completely as there would be no way to authenticate yourself securely and trustlessly Digital cryptographic signatures allow us to accomplish the following The signer is able to sign a message using a private key and broadcast the signed message It is impossible to recover the private key by simply looking at the message and or the public key It is however possible to verify that the signer holds the correct private key using the public key or wallet address If this sounds a little magical it s because it is The feats possible by public key cryptography are nothing short of miraculous However as stated earlier we will cover this in detail in a future series With this basic understanding of how digital signatures work we can now propose the following system of implementing allowlists Create a centralized server and database that holds all the addresses that are allowlisted When a wallet tries to initiate a mint on your website send the wallet address to your server The server checks if the address has been allowlisted and if it has it signs the wallet address with a private key that is known only to the project s creator The server returns the signed message to the frontend client or website and this in turn is sent to the smart contract The contract s mint function verifies that the message sent was indeed signed by the wallet controlled by the owner If the verification succeeds minting is allowed The signed message is stored in a mapping to prevent it from being used more than once or by multiple wallets We will not be implementing a real server or using a real database in this article If this is something that you ve never done before taking a look at Express and Mongo tutorials would be a good place to start Signing MessagesIn your Hardhat project create a new file called allowlist js in the scripts folder We will be using the ethers library to sign our messages Let s allowlist Hardhat s default accounts to for this example const ethers require ethers const main async gt const allowlistedAddresses xcdcacdbeddcc xccdddbafabddedfabc xfbfebcfeefeb xdaafdbdcaafaaca xdabcccbafbdbadc const runMain async gt try await main process exit catch error console log error process exit runMain These are the only addresses that will be allowed to mint in the presale Let s use Account as the owner s wallet const owner xffdeaadffceabcfffb const privateKey xacbecaebaabdffbacbcbedefcaedbffff const signer new ethers Wallet privateKey console log signer address Run this script by running node scripts allowlist js in the terminal If all goes well the wallet address printed to the console should be the same as that assigned to owner Let s now sign a simple message and see how that works let message Hello World let signature await signer signMessage message console log signature Running this script will output a signed message xdd c In our case we will not be signing a message written in English Instead we will be signing the hash of a allowlisted wallet address which is nothing but a hash itself Ethers documentation recommends that we convert binary hash data into an array before signing it Let s sign the hash of the first allowlisted address from above Replace the code snippet above with the following Get first allowlisted addresslet message allowlistedAddresses Compute hash of the addresslet messageHash ethers utils id message console log Message Hash messageHash Sign the hashed addresslet messageBytes ethers utils arrayify messageHash let signature await signer signMessage messageBytes console log Signature signature Running this snippet will output xee cb as signature Therefore when a wallet issues a request to the server you server will need to do two things Check if the wallet is a part of allowlistedAddressesIf yes sign the hashed wallet address with the supplied private key and return the signature and the hashed wallet address Verifying SignaturesVerifying signatures is extremely simple using OpenZeppelin s ECDSA library Let s start with our base NFTCollectible sol contract again As a first step we will write a recoverSigner function that will take the hashed allowlisted wallet address and the signature as arguments and output the address of the signer function recoverSigner bytes hash bytes memory signature public pure returns address bytes messageDigest keccak abi encodePacked xEthereum Signed Message n hash return ECDSA recover messageDigest signature Let s open up a new Terminal and spin up a local instance of Ethereum using the following command npx hardhat nodeNext let s write code in allowlist js that compiles and deploys the contract to our local blockchain and calls the recoverSigner function const nftContractFactory await hre ethers getContractFactory NFTCollectible const nftContract await nftContractFactory deploy ipfs your cide code await nftContract deployed console log Contract deployed by signer address recover await nftContract recoverSigner messageHash signature console log Message was signed by recover toString Let s run this script using npx hardhat run scripts allowlist js network localhostIf all goes well you should see your console telling you that the message was signed by the same wallet that deployed the contract Amazing work We now have all the pieces we need to implement our preSale function and by extension allowlisting Let s define a mapping that will track if a particular signature has already been used to mint mapping bytes gt bool public signatureUsed Finally let s write our preSale function function preSale uint count bytes hash bytes memory signature public payable uint totalMinted tokenIds current uint preSalePrice ether uint preSaleMaxMint require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt preSaleMaxMint Cannot mint specified number of NFTs require msg value gt preSalePrice mul count Not enough ether to purchase NFTs require recoverSigner hash signature owner Address is not allowlisted require signatureUsed signature Signature has already been used for uint i i lt count i mintSingleNFT signatureUsed signature true Congratulations You have successfully implemented an allowlisting mechanism that works off chain but is just as secure as its on chain counterpart Here is the final contract SPDX License Identifier MITpragma solidity import openzeppelin contracts utils cryptography ECDSA sol import openzeppelin contracts utils Counters sol import openzeppelin contracts access Ownable sol import openzeppelin contracts utils math SafeMath sol import openzeppelin contracts token ERC extensions ERCEnumerable sol contract NFTCollectible is ERCEnumerable Ownable using SafeMath for uint using Counters for Counters Counter Counters Counter private tokenIds mapping bytes gt bool public signatureUsed uint public constant MAX SUPPLY uint public constant PRICE ether uint public constant MAX PER MINT string public baseTokenURI constructor string memory baseURI ERC NFT Collectible NFTC setBaseURI baseURI function reserveNFTs public onlyOwner uint totalMinted tokenIds current require totalMinted add lt MAX SUPPLY Not enough NFTs left to reserve for uint i i lt i mintSingleNFT function baseURI internal view virtual override returns string memory return baseTokenURI function setBaseURI string memory baseTokenURI public onlyOwner baseTokenURI baseTokenURI function recoverSigner bytes hash bytes memory signature public pure returns address bytes messageDigest keccak abi encodePacked xEthereum Signed Message n hash return ECDSA recover messageDigest signature function mintNFTs uint count public payable uint totalMinted tokenIds current require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt MAX PER MINT Cannot mint specified number of NFTs require msg value gt PRICE mul count Not enough ether to purchase NFTs for uint i i lt count i mintSingleNFT function preSale uint count bytes hash bytes memory signature public payable uint totalMinted tokenIds current uint preSalePrice ether uint preSaleMaxMint require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt preSaleMaxMint Cannot mint specified number of NFTs require msg value gt preSalePrice mul count Not enough ether to purchase NFTs require recoverSigner hash signature owner Address is not allowlisted require signatureUsed signature Signature has already been used for uint i i lt count i mintSingleNFT signatureUsed signature true function mintSingleNFT private uint newTokenID tokenIds current safeMint msg sender newTokenID tokenIds increment function tokensOfOwner address owner external view returns uint memory uint tokenCount balanceOf owner uint memory tokensId new uint tokenCount for uint i i lt tokenCount i tokensId i tokenOfOwnerByIndex owner i return tokensId function withdraw public payable onlyOwner uint balance address this balance require balance gt No ether left to withdraw bool success msg sender call value balance require success Transfer failed To summarize once again this is how pre sale minting would work A buyer visits your website connects wallet specifies the number of NFTs s he wants to mint and clicks on the Mint NFT button This initiates a request to your centralized server which checks if the address has been allowlisted If yes it sends back the hashed wallet address and the signature If no it returns an error Your website takes the aforementioned values and initiates a transaction to your smart contract on behalf of the user In the smart contract the preSale function verifies that the signature was indeed signed by you and allows minting to take place ConclusionThis is by far the most technical article we ve published so far If you ve understood major portions of what s going on then congratulations You are well on your way to becoming an expert Solidity developer If you find yourself struggling don t worry about it It may be a little hard to digest this in one go We would suggest you complement this article with alternate resources and tutorials on the topic We should also mention that digital signatures aren t the only way to achieve off chain allowlists It is possible to use Merkle trees to arrive at the same result We will be releasing an article on that sometime in the future If you have any questions or are stuck reach out to us on our Discord If you don t have questions come say hi to us on our Discord anyway Also if you liked our content we would be super grateful if you tweet about us follow us ScrappyNFTs and Rounak Banik and invite your circle to our Discord Thank you for your support About Scrappy SquirrelsScrappy Squirrels is a collection of randomly generated NFTs Scrappy Squirrels are meant for buyers creators and developers who are completely new to the NFT ecosystem The community is built around learning about the NFT revolution exploring its current use cases discovering new applications and finding members to collaborate on exciting projects with Join our community here 2022-02-11 11:17:12
海外TECH DEV Community Low Code Solutions In Amazon Web Services (AWS) https://dev.to/vishnuchandra007/low-code-solutions-in-amazon-web-services-aws-3j43 Low Code Solutions In Amazon Web Services AWS Low code has taken software development to the next level It is a visual approach that optimizes the entire development process to accelerate delivery Furthermore it enables companies to abstract and automate every step of the app lifecycle to streamline the deployment of various solutions This evolutionary approach has made developers lives so much easier and has enabled citizen developers to build applications without the assistance of professionals Bringing low code development in Amazon Web Services AWS the world s most comprehensive and broadly adopted cloud platform has enabled many users to build cloud apps rapidly Through this blog let us briefly get to know about AWS its benefits and its newly launched low code solution What is AWS As mentioned earlier Amazon Web Services AWS is the world s most popular cloud platform which offers more than fully featured services from data centers globally They have millions of customers including the fastest growing startups largest enterprises and leading government agencies that use AWS to lower costs increase agility and innovate speedily AWS provides significant benefits that include Functionality AWS has significantly more services and features within those services than any other cloud platform From infrastructure technologies like computers storage and databases to emerging technologies like machine learning and artificial intelligence data lakes and IoTs This provides a faster easier and more cost effective way to move your existing apps to the cloud and build more varying kinds of applications The largest community of customers and partnersAWS has the largest and most dynamic community including millions of active customers and partners globally The AWS Partner Network APN includes many systems integrators specializing in AWS services independent software vendors ISVs who adapt their technology to work on AWS Security AWS is designed to be the most flexible and secure cloud computing environment available today Its core infrastructure is built to satisfy the security requirements for the military global banks and other highly sensitive organizations Moreover it is backed by an intense set of cloud security tools and offers encryption of customer data stored by all AWS services Fastest pace of innovationWith AWS companies can leverage the latest technologies to experiment and innovate more quickly As a result it is continuously accelerating its pace of innovation to invent new technologies that are used to transform businesses Proven operational expertise AWS has unmatched experience maturity reliability security and performance that companies can rely upon for most of its app developments In addition with over years of delivering cloud services AWS has the most operational experience at a larger scale among any other cloud provider Low Code In AWS AWS recently launched Amplify Studio a new Figma connected low code service aimed to help developers quickly build cloud connected apps It is an extension of the existing AWS Amplify Service that focuses on building web and mobile apps but lacks Amplify s easy to use drag and drop interface In the Amplify Studio environment developers start with a data model adds content and authentication and then build a user experience using a third party collaborative design tool called Figma Furthermore it includes the Amplify Admin UI s backend configuring and managing capabilities which helps it to provide a unified interface that enables developers to build full stack applications faster One of the significant benefits of using Amplify Studio is that developers can focus on the core business logic that makes their app unique and different rather than spending a lot of time on UI styling Also the brand new Amplify UI library including its components and primitives is in preview further enhancing developer productivity Top Advantages Of Amplify StudioHere are the significant advantages of AWS s Amplify Studio Quickly create feature rich UIsDevelopers can easily create and customize the user interface of their apps using the visual interface and libraries of pre built UI components Quickly ship a full stack appDevelopers can complete a full stack app with just a few clicks by setting up their front end UI and corresponding backend on AWS Increase productivityUsers can automate the UI and infrastructure boilerplate code and focus more on their business logic Improve designer developer collaborationUsers can streamline the design handoff process and alleviate costly and time consuming errors Key Features Of Amplify StudioThe key features of Amplify Studio that make it a preferable option for low code development companies to build cloud based low code applications are as follows Configure an extensible app backendVisual backend builderDevelopers can use the visual development environment to define data models user authentications and file storage without relying on backend expertise Extend with AWS CDKUsing the AWS Cloud Development Kit CDK users can easily add AWS services not available within Amplify Studio Use with Amplify LibrariesUsers can connect mobile and web apps to backends created in AMplify Studio using Amplify Libraries for iOS Android Flutter React Native and Web JavaScript Accelerate UI app development Preview Pre built UI component library Users can select from a wide range of popular React components and marketing templates and customize them to fit their style guide Figma s design to code approach Users can seamlessly collaborate by importing Figma prototypes built by developers into Amplify Studio as clean React code Front to back configurationWith a few clicks users can visually bind the front end UI components in their layout to data sources in theri cloud connected app backend Manage and ship your appData file and user managementAmplify Studio lets team members manage users groups app content and files outside the AWS Management Console Deploy and host with Amplify HostingAmplify Studio can be used with Amplify Hosting to deploy and host any React Vue or Next js web app with built in continuous integration continuous deployment CI CD workflows testings pull request previews and custom domains Supports multiple environments Users can quickly test their changes in pre production environments before pushing them to production Conclusion Amplify Studio launched by AWS is an excellent tool for developing cloud based low code applications Though Amazon took a while to get to low code development the expertise and unique functionalities give us hope for better features and improvements in the future 2022-02-11 11:11:22
Apple AppleInsider - Frontpage News Xiaomi CEO aims match Apple for 'product and experience' https://appleinsider.com/articles/22/02/11/xiaomi-ceo-aims-match-apple-for-product-and-experience?utm_medium=rss Xiaomi CEO aims match Apple for x product and experience x The CEO of Chinese smartphone firm Xiaomi has announced an intention to compete fully with Apple s iPhone and described it as a war of life and death Xiaomi Mi i smartphonesXiaomi has previously outsold both Apple and Samsung in Europe Now however the company is aiming to focus on the top end of the market Read more 2022-02-11 11:29:59
海外TECH Engadget UK regulator accepts Google's updated proposal on browser cookie tracking https://www.engadget.com/googles-latest-privacy-sandbox-cookie-replacement-approved-by-uk-regulator-112527258.html?src=rss UK regulator accepts Google x s updated proposal on browser cookie trackingThe UK s Competition and Markets Authority CMA has accepted Google s latest plan to replace third party cookies from the Chrome Browser The regulator said that Google made legally binding commitments to address its concerns that the quot Privacy Sandbox quot would weaken competition and harm consumers nbsp Early in the CMA announced that it would investigate Google s plan to replace third party cookies with quot trust tokens quot It said that Google s plan quot could undermine the ability of publishers to generate revenue and undermine competition in digital advertising entrenching Google s market power quot It added that it received complaints from publishers and tech companies which alleged that Google may be quot abusing its dominant position quot nbsp While this is an important step we are under no illusions that our work is done We now move into a new phase where we will keep a close eye on Google as it continues to develop these proposals The CMA said that Google has promised to use a quot more transparent process than initially proposed quot It will now engage with third parties and publish test results and must address any issues raised by the CMA or third parties It will also not remove third party cookies quot until the CMA is satisfied that its competition concerns have been addressed quot nbsp In its own blog post on the matter Google said it would quot design develop and implement Privacy Sandbox with regulatory oversight and input from the CMA and the ICO quot It promised to apply the commitments globally not just in the UK as quot we believe that they provide a roadmap for how to address both privacy and competition concerns in this evolving sector quot Google wrote Last year Google delayed the rollout of third party cookies until mid rather than the timeline it originally set It admitted at the time that it quot needs more time across the ecosystem to get this right quot Google had originally proposed a cookie alternative called quot FLoC quot Federated Learning of Cohorts but announced last month that it was testing a replacement called Topics API nbsp 2022-02-11 11:25:27
ラズパイ Raspberry Pi Coding for kids: Art, games, and animations with our new beginners’ Python path https://www.raspberrypi.org/blog/coding-for-kids-art-games-animations-beginners-python-programming/ Coding for kids Art games and animations with our new beginners Python pathPython is a programming language that s popular with learners and educators in clubs and schools It also is widely used by professional programmers particularly in the data science field Many educators and young people like how similar the Python syntax is to the English language That s why Python is often the first text based language that The post Coding for kids Art games and animations with our new beginners Python path appeared first on Raspberry Pi 2022-02-11 11:04:21
ニュース BBC News - Home Cressida Dick: Search for new Met Police chief under way after resignation https://www.bbc.co.uk/news/uk-england-60345334?at_medium=RSS&at_campaign=KARANGA cressida 2022-02-11 11:06:46
ニュース BBC News - Home UK economy rebounds with 7.5% growth last year https://www.bbc.co.uk/news/business-60344573?at_medium=RSS&at_campaign=KARANGA omicron 2022-02-11 11:00:50
ニュース BBC News - Home Spain relaxes Covid restrictions for UK teenagers https://www.bbc.co.uk/news/business-60335735?at_medium=RSS&at_campaign=KARANGA negative 2022-02-11 11:28:29
ニュース BBC News - Home Russian figure skater's failed drug test confirmed https://www.bbc.co.uk/sport/winter-olympics/60329120?at_medium=RSS&at_campaign=KARANGA december 2022-02-11 11:13:23
ニュース BBC News - Home Labour MP Neil Coyle suspended over racist comment claim https://www.bbc.co.uk/news/uk-politics-60347836?at_medium=RSS&at_campaign=KARANGA british 2022-02-11 11:34:01
ニュース BBC News - Home Covid: Wales' mask and isolation laws could end in March https://www.bbc.co.uk/news/uk-wales-politics-60332835?at_medium=RSS&at_campaign=KARANGA legal 2022-02-11 11:48:20
ニュース BBC News - Home Underwater Photographer of the Year winner revealed https://www.bbc.co.uk/news/in-pictures-60334402?at_medium=RSS&at_campaign=KARANGA maldives 2022-02-11 11:36:52
ニュース BBC News - Home Marchant to start at 13 as England make eight changes to face Italy https://www.bbc.co.uk/sport/rugby-union/60347846?at_medium=RSS&at_campaign=KARANGA Marchant to start at as England make eight changes to face ItalyJoe Marchant will start at outside centre for England against Italy on Sunday in one of eight changes to the starting XV which lost to Scotland 2022-02-11 11:54:23
ニュース BBC News - Home 'It takes a brave team to look into that baggage' - how psychology united Jones' England https://www.bbc.co.uk/sport/rugby-union/60335747?at_medium=RSS&at_campaign=KARANGA x It takes a brave team to look into that baggage x how psychology united Jones x EnglandHow honesty sessions and the wisdom from Australia s hockey golds aim to build a stronger better England 2022-02-11 11:13:19
北海道 北海道新聞 日本ハム、打順抽選に3連続バント 練習試合、新庄采配に明確な意図 https://www.hokkaido-np.co.jp/article/644728/ 沖縄県名護市 2022-02-11 20:13:35
北海道 北海道新聞 立崎芙由子の39位が最高 バイアスロン・11日 https://www.hokkaido-np.co.jp/article/644746/ 芙由子 2022-02-11 20:10:00
北海道 北海道新聞 岩手の養鶏場で鳥インフルの疑い 簡易検査で陽性 https://www.hokkaido-np.co.jp/article/644745/ 高病原性鳥インフルエンザ 2022-02-11 20:10:00
北海道 北海道新聞 米長官、中ロ連携を批判 ウクライナ、五輪中も警戒 https://www.hokkaido-np.co.jp/article/644691/ 日本時間 2022-02-11 20:08:20
北海道 北海道新聞 みずほATM、また障害 保守点検で一時90カ所を休止 https://www.hokkaido-np.co.jp/article/644673/ 現金自動預払機 2022-02-11 20:06:10
北海道 北海道新聞 帯広市長選、自営業の西川氏出馬へ 現職と選挙戦 https://www.hokkaido-np.co.jp/article/644744/ 任期満了 2022-02-11 20:01:29

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)